branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/main | <file_sep>import numpy as np
from scipy.sparse import issparse, csc_matrix, csr_matrix, dia_matrix
import scipy.sparse.linalg as spla
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from boundaryCond import Dirichlet, Neuman
"""
------------------------------------------------------------------------------------
Some auxiliary useful functions
fem_solver - solves linear system with Dirichlet or Neuman (enforced) boundary conditions
plot_sol - plots solution, 1d or 2d
plot_piecewise - makes piecewise plot of 1d solution (for P0 elts)
------------------------------------------------------------------------------------
"""
def get_solver(name):
""" returns the correct solver passed as string arg to fem solver """
name = name.lower()
if name == 'cg':
return spla.cg
elif name == 'gmres':
return spla.gmres
elif name =='minres':
return spla.minres
else:
raise ValueError('Invalid solver argument.')
#--------------------------------------------------------------------------------------#
def inc_dirichlet(bcs, n_dofs):
""" help incorporate enforced Dirichlet bc
Input:
bcs - Dirichlet boundary conditions
n_dofs - total number of DOFs in function space
Output:
u - initialized solution vector
dirichlet_nodes - unique node numbers of nodes where bc is enforced
"""
# initialize solution vector
u = np.zeros(n_dofs)
# put unique Dirichlet nodes here
dirichlet_nodes = np.array([], dtype=int)
# inc bc in solution vector and save nodes
for bc in bcs:
unique_nodes = bc.unique_dof_nos() # unique node numbers in this bc
new_nodes = np.setdiff1d(unique_nodes, dirichlet_nodes) # new nodes not in previous bc
u[new_nodes] += bc.assemble()[new_nodes] # update solution vector
dirichlet_nodes = np.concatenate((dirichlet_nodes, new_nodes))
return u, dirichlet_nodes
#--------------------------------------------------------------------------------------#
def inc_neuman(bcs, n_dofs):
""" help incorporate enforced Neuman bc
Input:
bcs - Neuman boundary conditions
n_dofs - total number of DOFs in function space
Output:
u - initialized solution vector
neuman_edges - unique edge numbers of edges where bc is enforced
"""
# initialize solution vector
u = np.zeros(n_dofs)
# put unique Neuman edges here
neuman_edges = np.array([], dtype=int)
for bc in bcs:
edges = bc.unique_dof_nos()
u += bc.assemble()
neuman_edges = np.concatenate((neuman_edges, edges))
return u, neuman_edges
#--------------------------------------------------------------------------------------#
def fem_solver(fs, A, rhs, *bcs, **kw):
"""
Solve linear system Au = rhs with specified Dirichlet or Neuman boundary conditions (optional)
Input:
fs - function space
A - linear system (sparse if not mixed, dense if mixed)
rhs - right hand side vector
bcs - Dirichlet (for lagrange elt) or Neuman (for RT elt) boundary conditions (optional)
kw:
info - print some information about linear system (condition number, size and rank)
solver - name of linear solver to be used (default: spsolve)
tol - tolerance of iterative method (default: 1e-06)
P - preconditioner for iterative method (default: none)
Output:
u - solution vector, if not mixed
(m_1,u_1),...,(m_n,u_n) - if mixed (i.e. tuples of FE number and solution vector)
"""
# get kw
info = kw.pop('info',False); solver_name = kw.pop('solver', None); tol = kw.pop('tol', 1e-06); # P = kw.pop('P',None)
x0 = kw.pop('x0', None)
if len(bcs) != 0: # <------------------------------- incorporate boundary conditions (if any)
# separate Dirichlet and Neuman boundary conditions
neuman = []; dirichlet = []
for bc in bcs:
if isinstance(bc,Dirichlet):
dirichlet.append(bc)
else:
neuman.append(bc)
# assemble Dirichlet (for Lagrange element)
if dirichlet == []:
uD = np.zeros(fs.n_dofs()); dirichlet_node_nos = np.array([],dtype=int)
else:
# get updated solution vector and unique dof numbers
uD, dirichlet_node_nos = inc_dirichlet(dirichlet, fs.n_dofs())
# assemble Neuman (for RT element)
if neuman == []:
uN = np.zeros(fs.n_dofs()); neuman_edge_nos = np.array([],dtype=int)
else:
# get updated solution vector and unique dof numbers
uN, neuman_edge_nos = inc_neuman(neuman, fs.n_dofs())
u = uD + uN
enforced_dof_nos = np.concatenate((dirichlet_node_nos, neuman_edge_nos)) # unique dof numbers of enforced dofs
free_dofs = np.setdiff1d(range(fs.n_dofs()), enforced_dof_nos) # unique dof numbers of free dofs
n_free_dofs = len(free_dofs) # number of free nodes
# convert linear system to dense (if needed)
if issparse(A):
A = A.todense()
# modify linear system
A_free = A[free_dofs.reshape(n_free_dofs, 1), free_dofs]
rhs = rhs - csc_matrix(A).dot(u)
# # set up preconditioner (if needed)
# if P is not None:
# M_x = lambda x: spla.spsolve(csc_matrix(P[free_dofs.reshape(n_free_dofs, 1), free_dofs]), x)
# M = spla.LinearOperator((n_free_dofs, n_free_dofs), M_x)
# else:
# M = None
# print condition number
if info:
print "Condition number of matrix: ", np.linalg.cond(A_free)
print "Rank of matrix: ", np.linalg.matrix_rank(A_free)
print "Shape of matrix: ", A_free.shape
# solve
if solver_name is None:
u[free_dofs] = spla.spsolve(csr_matrix(A_free), rhs[free_dofs])
else:
solver = get_solver(solver_name)
if x0 is not None:
x0 = x0[free_dofs]
u[free_dofs], temp = solver(csc_matrix(A_free), rhs[free_dofs], x0=x0, tol=tol, maxiter=A_free.shape[0])
print temp
assert temp == 0, 'Iterative solver, {}, failed to converge.'.format(solver_name)
else: # <--------------------------------------------- no boundary conditions
# print condition number
if info:
print "Condition number of matrix: ", np.linalg.cond(A)
print "Rank of matrix: ", np.linalg.matrix_rank(A_free)
print "Shape of matrix: ", A_free.shape
# # set up preconditioner (if needed)
# if P is not None:
# M_x = lambda x: spla.spsolve(csc_matrix(P), x)
# M = spla.LinearOperator(P.shape, M_x)
# else:
# M = None
# solve
if solver_name is None:
u = spla.spsolve(csc_matrix(A), rhs)
else:
solver = get_solver(solver_name)
# u, temp = solver(csc_matrix(A), rhs, M=M, tol=tol)
u, temp = solver(csc_matrix(A), rhs, x0=x0, tol=tol)
assert temp == 0, 'Iterative solver, {}, failed to converge.'.format(solver_name)
# return solution vector(s)
if fs.mixed():
us = []; n0 = 0; n = 0
for j in xrange(fs.n_FE()):
n += fs.n_dofs(j)
us.append((j,u[n0:n]))
n0 = n
return us
else:
return u
#--------------------------------------------------------------------------------------#
def plot_sol(fs, u, u_ex=None, **kw):
""" makes a plot of u on the mesh the function space is built on
Input:
fs - function space
u - solution vector (values to be plotted)
u_ex - exact solution (callable)
kw:
contour - True if contour plot, else 3D plot (default: True)
name - name of figure (default: Plotting)
"""
# get kwargs
contour = kw.pop('contour', True); name = kw.pop('name', 'Plotting')
# get solution vector
if isinstance(u, tuple):
assert fs.mixed(), 'Wrong format of solution vector, space is not mixed.'
m = u[0]; u = u[1]
else:
m = 0
# set up figure
if u_ex is None:
fig = plt.figure(num=name)
else:
fig = plt.figure(figsize=(12,6), num=name)
# get plotting points from function space
coords = fs.dof_to_cn(m)
X = coords[:,0]; Y = coords[:,1]
# plot solution
if fs.mesh.dim() == 2:
if u_ex is None:
if not contour: # 3D plot
ax = fig.gca(projection='3d')
ax.plot_trisurf(X, Y, u, linewidth=0.2, antialiased=True, cmap=plt.cm.Spectral)
else: # contour plot
plot = plt.tricontourf(X,Y,u,100)
CB = plt.colorbar(plot, shrink=0.8, extend='both')
plt.title("computed solution")
plt.xlabel('x'); plt.ylabel('y')
plt.xticks([]); plt.yticks([])
else:
U_ex = [u_ex(c) for c in coords]
if not contour: # 3D plot
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.plot_trisurf(X, Y, u, linewidth=0.2, antialiased=True, cmap=plt.cm.CMRmap)
plt.title("computed solution")
plt.xticks([]); plt.yticks([])
plt.xlabel('x'); plt.ylabel('y')
ax = fig.add_subplot(1, 2, 2, projection='3d')
ax.plot_trisurf(X, Y, U_ex, linewidth=0.2, antialiased=True, cmap=plt.cm.CMRmap)
plt.title("exact solution")
plt.xticks([]); plt.yticks([])
plt.xlabel('x'); plt.ylabel('y')
else: # contour plot
plt.subplot(121)
plot = plt.tricontourf(X,Y,u,100)
CB = plt.colorbar(plot, shrink=0.8, extend='both')
plt.title("computed solution")
plt.xticks([]); plt.yticks([])
plt.xlabel('x'); plt.ylabel('y')
plt.subplot(122)
plot = plt.tricontourf(X,Y,U_ex,100)
CB = plt.colorbar(plot, shrink=0.8, extend='both')
plt.title("exact solution")
plt.xticks([]); plt.yticks([])
plt.xlabel('x'); plt.ylabel('y')
else: # dim = 1
if u_ex is None:
plt.plot(X, u)
plt.title("computed solution")
plt.xlabel('x')
plt.ylabel('y')
else:
plt.subplot(121)
plt.plot(X, u)
plt.title("computed solution")
plt.xlabel('x')
plt.ylabel('y')
U_ex = [u_ex(c) for c in coords]
plt.subplot(122)
plt.plot(X, U_ex)
plt.title("exact solution")
plt.xlabel('x')
plt.ylabel('y')
plt.show()
#--------------------------------------------------------------------------------------#
def plot_piecewise(u, nodes, u_ex=None, name=''):
""" makes a piecewise plot of 1D solution
Input:
u - computed solution
mesh - 1d mesh
u_ex - exact solution (optional)
name - name of figure """
assert np.allclose(nodes[:,1],0), 'Piecewise plotting only for 1 dim.'
nodes = nodes[:,0]
# set up figure
if name == '':
name = 'Plot piecewise constant in 1D'
fig = plt.figure(num=name)
x = np.linspace(0,1,101)
vertices = np.unique(mesh.vertices()) # <------- fix this line
n_v = len(vertices)
plt.plot(x, np.piecewise(x, [(x >= vertices[n]) & (x <= vertices[n+1]) for n in xrange(n_v-1)], u))
# evaluate exact solution at nodes
if u_ex is not None:
U_ex = []
for p in x:
U_ex.append(u_ex([p]))
plt.plot(x, U_ex)
plt.legend(('computed','exact'))
else:
plt.legend('computed')
plt.show()
#--------------------------------------------------------------------------------------#
if __name__ == '__main__':
def piecewise_test(n=10):
""" test piecewise plotting """
from meshing import UnitIntMesh
from functionSpace import FunctionSpace
from finiteElement import FiniteElement
u_ex = lambda x: 4*x[0]*(1.-x[0]) # exact solution
mesh = UnitIntMesh(n) # 1d mesh
fs = FunctionSpace(mesh, FiniteElement('lagrange', 0)) # P0 function space
# assemble
A = fs.mass()
rhs = fs.rhs(u_ex)
# solve with homogenous Dirichlet bc
u = fem_solver(fs, A, rhs)
plot_piecewise(u, fs.dof_to_coords(), u_ex)
#piecewise_test()
<file_sep>import numpy as np
from finiteElement import Element
class Space:
"""Function space class
Input:
mesh - mesh it is built on
deg
gauss - degree of Gaussian quadrature (optional, default is 4)
"""
def __init__(self, mesh, deg=None, gauss=4):
# try to get degree from mesh or set to 1 (piecewise linear)
if deg is None:
try:
deg = mesh.deg()
except AttributeError:
deg = 1
# set data
self.mesh = mesh
self.__deg = deg
self.__gauss = gauss
self.__fe = Element(deg, gauss)
def assemble(self, derivative, c=None, cond=False):
"""Assemble linear system
Input:
c - coefficient (variable or constant), can be tensor valued if appropriate
derivative - True if derivative of shape function
cond - True if condition number is calculated and printed
Output:
A - stiffness/mass matrix (dense)"""
A = np.zeros((self.mesh.n_dofs(), self.mesh.n_dofs())) # initialize global assembly matrix
# loop over elements
for vc, dc, d in zip(self.mesh.elt_to_vcoords(),\
self.mesh.elt_to_dofcoords(),\
self.mesh.elt_to_dofs()):
self.__fe.set_data(vc, dc) # give element data to FE
elt_assemble = self.__fe.assemble(c, derivative) # element assembly
A[np.array([d]).T, d] += elt_assemble # add to global assembly
if cond:
from numpy.linalg import cond
print("Condition number of {} matrix: {}".format("stiffness" if derivative else "mass", cond(A)))
return A
def stiffness(self, c=None, cond=False):
"""Assemble stiffness matrix"""
return self.assemble(True, c, cond)
def mass(self, c=None, cond=False):
"""Assemble mass matrix"""
return self.assemble(False, c, cond)
def rhs(self, f):
"""Assemble "right hand side" load vector
Input:
f - function (or constant)
Output:
load vector
"""
rhs = np.zeros(self.mesh.n_dofs())
if f == 0:
return rhs
else:
# loop over elements
for vc, dc, d in zip(self.mesh.elt_to_vcoords(),\
self.mesh.elt_to_dofcoords(),\
self.mesh.elt_to_dofs()):
self.__fe.set_data(vc, dc) # give element data to FE
rhs[d] += self.__fe.assemble_rhs(f)
return rhs
def norm(self, u, f=None, p=2):
"""calculate norm of, ||u|| or of ||u - f||
Input:
u - vector of values at nodes"""
norm = 0
# loop over elements
for vc, dc, d in zip(self.mesh.elt_to_vcoords(),\
self.mesh.elt_to_dofcoords(),\
self.mesh.elt_to_dofs()):
self.__fe.set_data(vc, dc) # give element data to FE
norm += self.__fe.norm(u[d], f=f, p=p)
return np.power(norm,1./p)
#--------------------------------------------------------------------------------------#
if __name__ == '__main__':
import math
from meshing import RectangleMesh
def dirichlet_ex(data, n=16, deg=1, gauss=4, diag='r', plot=True, cond=False):
""" Poisson w/ homogenous Dirichlet bc in 2D
"""
from scipy.sparse import issparse, csc_matrix, csr_matrix, dia_matrix
import scipy.sparse.linalg as spla
import matplotlib.pyplot as plt
#print("\nPoissin eq. w/ Dirichlet bc in 2D")
# data
mesh = RectangleMesh(nx=n,ny=n,deg=deg,diag=diag)
f = data["rhs"]; u_ex = data["u_ex"]
# assemble
fs = Space(mesh, deg, gauss=gauss)
A = fs.stiffness(cond=cond)
rhs = fs.rhs(f)
bedge_to_dofs = mesh.bedge_to_dofs()
enforced_dof_nos = np.unique(np.ravel(bedge_to_dofs))
free_dofs = np.setdiff1d(range(mesh.n_dofs()), enforced_dof_nos)
n_free_dofs = len(free_dofs)
# solution vector
u = np.zeros(mesh.n_dofs())
U_ex = u_ex(mesh.dof_to_coords())
u[enforced_dof_nos] = U_ex[enforced_dof_nos]
# modify linear system and solve
A_free = A[free_dofs.reshape(n_free_dofs, 1), free_dofs]
rhs = rhs - csc_matrix(A).dot(u)
u[free_dofs] = spla.spsolve(csc_matrix(A_free), rhs[free_dofs])
# plot solution
X,Y = mesh.dof_to_coords().T
if plot:
#tri = Triangulation(X, Y, elt_to_vertex)
fig = plt.figure(figsize=plt.figaspect(0.5))
ax1 = fig.add_subplot(1, 2, 1, projection='3d')
ax1.plot_trisurf(X, Y, U_ex, cmap=plt.cm.Spectral)
ax1.set_title("Exact")
#ax1.set_xlim(0, 1)
#ax1.set_ylim(0, 1)
#ax1.set_zlim(np.min(U_ex), np.max(U_ex))
ax2 = fig.add_subplot(1, 2, 2, sharez=ax1, sharey=ax1, sharex=ax1, projection='3d')
ax2.plot_trisurf(X, Y, u, cmap=plt.cm.Spectral) #triangles=tri.triangles, cmap=plt.cm.Spectral)
ax2.set_title("Numerical")
#ax2.set_zlim(0, 1)
plt.show()
return fs.norm(u,f=u_ex)
#--------------------------------------------------------------------------------------#
def neuman_ex(n=16, deg=1, gauss=4, diag='r', plot=True):
""" Poisson w/ homogenous Neuman bc in 2D
ill conditioned -> use CG
- P1 conv rate: ~ 4
"""
from scipy.sparse import issparse, csc_matrix, csr_matrix, dia_matrix
import scipy.sparse.linalg as spla
import matplotlib.pyplot as plt
print("\nNeuman ex2 in 2D")
# data
mesh = RectangleMesh(nx=n,ny=n,deg=deg,diag=diag)
pi = math.pi
f = lambda x: pi*(np.cos(pi*x[:,0]) + np.cos(pi*x[:,1]))
u_ex = lambda x: (np.cos(pi*x[:,0]) + np.cos(pi*x[:,1]))/pi
# assemble
fs = Space(mesh, deg, gauss)
A = fs.stiffness(cond=True)
rhs = fs.rhs(f)
# solve
#u, info = spla.cg(csr_matrix(A), rhs)
#print("CG successful") if info == 0 else print("No convergence")
u = spla.spsolve(csr_matrix(A), rhs)
X,Y = mesh.dof_to_coords().T
if plot:
#tri = Triangulation(X, Y, elt_to_vertex)
fig = plt.figure(figsize=plt.figaspect(0.5))
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.plot_trisurf(X, Y, u, cmap=plt.cm.Spectral) #triangles=tri.triangles, cmap=plt.cm.Spectral)
ax.set_title("Numerical")
#ax.set_zlim(0, 1)
ax = fig.add_subplot(1, 2, 2, projection='3d')
ax.plot_trisurf(X, Y, u_ex(mesh.dof_to_coords()), cmap=plt.cm.Spectral)
ax.set_title("Exact")
#ax.set_zlim(0, 1)
plt.show()
#--------------------------------------------------------------------------------------#
def dirichlet_data(n):
from math import pi
rhs = [lambda x: 32.*(x[:,0]*(1.-x[:,0]) + x[:,1]*(1.-x[:,1])),
-6,
lambda x: 2*pi*pi*np.sin(pi*x[:,0])*np.cos(pi*x[:,1]),
lambda x: -2*(x[:,0]**2 - x[:,0] + x[:,1]**2 - x[:,1] + 0.5),
lambda x: -6*(x[:,0] + x[:,1])]
u_ex = [lambda x: 16.*x[:,0]*(1.-x[:,0])*x[:,1]*(1.-x[:,1]),
lambda x: 1 + np.power(x[:,0],2) + 2*np.power(x[:,1],2),
lambda x: np.sin(pi*x[:,0])*np.cos(pi*x[:,1]),
lambda x: np.power((x[:,0]-0.5),2) * np.power((x[:,1]-0.5),2),
lambda x: np.power(x[:,0],3) + np.power(x[:,1],3)]
return {"rhs": rhs[n], "u_ex": u_ex[n]}
#--------------------------------------------------------------------------------------#
def conv_test(ex_no=0, deg=1, gauss=4, diag="r"):
e = []; r = ["-"]; j = 0
print("Convergence test for Poisson equation with Dirichlet boundary condition:")
print("\t- deg: ", deg, ", gauss: ", gauss, ", diag: ", diag, "\n")
print("--------------------")
template = "{0:<5}{1:<10}{2:<30}"
print(template.format("res","error","rate"))
print("--------------------")
e_prev = 0
for n in [4,8,16,32,64]:
e = dirichlet_ex(dirichlet_data(ex_no), n=n, deg=deg, gauss=gauss, diag=diag, plot=False)
r = e_prev/e
if r == 0:
r = "-"
else:
r = round(r,2)
print(template.format(n,round(e,4),r))
e_prev = e
conv_test(ex_no=4, deg=1, gauss=4, diag="l")
#neuman_ex(n=16, deg=1, gauss=4, diag='r', plot=True)<file_sep>"""
Generate lagrange data for regular triangular mesh
"""
import numpy as np
def regular_mesh_data(box, res, deg, diag):
"""Lagrange DOF data for regular triangular mesh
Input:
box - bounding box ([start_x,end_x],[start_y,end_y])
res - number of divisions of x and y intervals (nx,ny)
deg - degree of Lagrange DOFs
diag - diagonal to the left or right
Output:
node_to_coords - node number to coordinates (for deg=1 nodes are element vertices)
elt_to_nodes - element number to node numbers
"""
# check valid data
assert len(box) == len(res), 'Incompatible box and res arguments.'
if len(box)!= 2:
raise ValueError('Invalid box and res arguments.')
# check valid diagonal arg
diag = diag.lower()
assert diag in {'left','l','right','r'}, 'Invalid diagonal argument.'
x = box[0]; y = box[1] # bounding box
nx = res[0]; ny = res[1] # number of cells in each direction (2 elts per cell)
nx_dofs = deg*nx+1; ny_dofs = deg*ny+1 # number of vertex in x and y directions
n_dofs = nx_dofs*ny_dofs # total number of vertex
n_elts = 2*nx*ny # total number of elements
n_boundary_edges = 2*nx + 2*ny # total number of boundary edges
# assemble node_to_coords
# numbered from bottom left, then right, then one up start from left again
xx = np.linspace(x[0],x[1],nx_dofs)
yy = np.linspace(y[0],y[1],ny_dofs)
node_to_coords = []
# loop over dofs
for iy in range(ny_dofs):
for ix in range(nx_dofs):
node_to_coords.append([xx[ix], yy[iy]])
assert len(node_to_coords) == n_dofs, 'Assembly of vertex_to_coords failed.'
# assemble elt_to_nodes
# numbering follows cell numbering (bottom left to right, one up, left to right etc.)
# lower elt in cell comes before upper elt
# anti-clockwise numbering of vertexes (start from bottom left)
elt_to_nodes = []
# boundary edge to node numbers (divided in four groups corresponding to sides of rectangle)
bottom = []; top = []; right = []; left = []
# loop over cells
for iy in range(ny):
for ix in range(nx):
# dofs in current cell as matrix
dofs_in_cell = np.array([[nx_dofs*(deg*iy + i) + deg*ix + j \
for j in range(deg+1)] for i in range(deg,-1,-1)])
# extract dofs in the upper and lower element
if diag in {"right","r"}:
# når diag=r så er øverste element riktig fortegn
dofs_in_cell = np.fliplr(dofs_in_cell)
# lower element
elt_to_nodes.append(dofs_in_cell[np.tril_indices(deg+1)])
# upper element
elt_to_nodes.append(np.flip(dofs_in_cell[np.triu_indices(deg+1)]))
if ix == 0: left.append(dofs_in_cell[:,-1])
if ix == nx-1: right.append(dofs_in_cell[:,0])
else:
# når diag=l så er nederste element riktig fortegn
# lower element
elt_to_nodes.append(dofs_in_cell[np.tril_indices(deg+1)])
# upper element
elt_to_nodes.append(np.flip(dofs_in_cell[np.triu_indices(deg+1)]))
if ix == 0: left.append(dofs_in_cell[:,0])
if ix == nx-1: right.append(dofs_in_cell[:,-1])
#elt_to_nodes.append(dofs_in_cell[np.tril_indices(deg+1)])
#elt_to_nodes.append(dofs_in_cell[np.triu_indices(deg+1)])
if iy == 0: bottom.append(dofs_in_cell[-1,:])
if iy == ny-1: top.append(dofs_in_cell[0,:])
assert len(elt_to_nodes) == n_elts, "Assembly of elt_to_vertex failed."
assert len(bottom+left+top+right) == n_boundary_edges, "Assembly of boundary failed."
boundary = {"bottom": np.array(bottom),
"left": np.array(left),
"top": np.array(top),
"right": np.array(right)}
return np.array(node_to_coords, dtype=float), np.array(elt_to_nodes, dtype=int), boundary
def triangle_mesh_data(nx, ny):
"""Lagrange DOF data for regular mesh of reference triangle, i.e.,
triangle with vertices {(0,0), (0,1), (1,0)}
Input:
res - number of divisions of x and y intervals (nx,ny)
Output:
vertex_to_coords - node number to coordinates (for deg=1 nodes are element vertices)
elt_to_vertex - element number to node numbers
"""
nx_vertex = nx+1; ny_vertex = ny+1 # number of vertex in x and y directions
n_vertex = nx_vertex*ny_vertex # total number of vertex
n_elts = nx*ny # total number of elements
# assemble vertex_to_coords
# numbered from bottom left, then right, then one up start from left again
xx = np.linspace(0,1,nx_vertex)
yy = np.linspace(0,1,ny_vertex)
vertex_to_coords = []
# loop over vertexes
for iy in range(ny_vertex):
for ix in range(nx_vertex-iy):
vertex_to_coords.append([xx[ix], yy[iy]])
vertex_to_coords = np.array(vertex_to_coords, dtype=float)
#assert len(vertex_to_coords) == n_vertex, 'Assembly of vertex_to_coords failed.'
# assemble elt_to_vertex
# numbering follows cell numbering (bottom left to right, one up, left to right etc.)
# lower elt in cell comes before upper elt
# anti-clockwise numbering of vertexes (start from bottom left)
elt_to_vertex = []
# loop over cells
for iy in range(ny):
for ix in range(nx-iy):
# vertexes of cell (ix,iy), from bottom left, anti-clockwise
v0 = sum([nx_vertex - iiy for iiy in range(iy)]) + ix
v1 = v0+1
v2 = v0+nx_vertex-iy
v3 = v2+1
elt_to_vertex.append([v0, v1, v2])
if ix < nx - iy - 1:
elt_to_vertex.append([v1, v3, v2])
elt_to_vertex = np.array(elt_to_vertex, dtype=int)
assert len(elt_to_vertex) == n_elts, 'Assembly of elt_to_vertex failed.'
return vertex_to_coords, elt_to_vertex<file_sep>import numpy as np
class Dirichlet:
""" class for implementing enforced Dirichlet boundary conditions for Lagrange element
Input:
fs - function space
g - funciton (or constant) on the boundary
names - names for boundary dictionary (default: entire boundary)
kw:
m - number of FE in case of mixed space (default: 0)
"""
def __init__(self, fs, g, *names, **kw):
""" assembles Dirichlet boundary condition for Lagrange element,
given by function (or constant) g on the boundary.
parts of boundary can be specified according to names in boundary dictionary """
m = kw.pop('m', 0)
assert fs.fe.method(m) == 'lagrange', 'This class is only for implementing Dirichlet BC for Lagrange element.'
# get data from function space
dnode_nos_m = fs.ext_dof_nos(*names, m=m) # local dirichlet node numbers
node_to_coords = fs.dof_to_cn(m) # node number to coords matrix
# assemble boundary condition
bc = np.zeros(fs.n_dofs()) # initialize boundary condition
dnode_nos = dnode_nos_m + sum([fs.n_dofs(j) for j in xrange(m)]) # global dirichlet node numbers
if callable(g):
bc[dnode_nos] = [g(node_to_coords[n]) for n in dnode_nos_m]
else:
bc[dnode_nos] = g
self.__unique_dof_nos = dnode_nos
self.__bc = bc
self.__m = m
def m(self):
""" return method number """
return self.__m
def unique_dof_nos(self):
""" return list of all node number involved in this bc """
return self.__unique_dof_nos
def assemble(self):
""" assemble boundary condition """
return self.__bc
class Neuman:
""" class for implementing Neuman boundary conditions for Raviart-Thomas element
Input:
fs - function space
g - funciton (or constant) on the boundary
names - names for boundary dictionary (default: entire boundary)
kw:
m - number of FE in case of mixed space (default: 0)
"""
def __init__(self, fs, g, *names, **kw):
""" assembles Neuman boundary conditions for Raviart-Thomas element,
given by function (or constant) g on the boundary.
parts of boundary can be specified according to names in boundary dictionary """
m = kw.pop('m', 0)
assert fs.fe.method(m) == 'rt', 'This class is only for implementing Neuman BC for RT element.'
# assemble boundary condition
if g == 0:
bc = np.zeros(fs.n_dofs())
else:
bc = fs.assemble_boundary(g, *names, m=m, dirichlet=False)
# get unique edge nos
neuman_dof_nos = fs.ext_dof_nos(*names, m=m) + sum([fs.n_dofs(j) for j in xrange(m)])
self.__m = m
self.__bc = bc
self.__unique_dof_nos = neuman_dof_nos
def m(self):
""" return method number """
return self.__m
def unique_dof_nos(self):
""" return list of all node number involved in this bc """
return self.__unique_dof_nos
def assemble(self):
""" assemble boundary condition """
return self.__bc
<file_sep># FEMpy
Solve elliptic/parabolic partial differential equations using the Fintie Element Method.
Written in python3 using Numpy ans Scipy
<file_sep>import numpy as np
from numpy.linalg import norm
from gaussquad import gaussPts
from shapefuncs import ShapeFunctions
def get_args(*args):
""" get args input for Element class """
method = []; deg = []
if len(args) == 0:
# default is Lagrange of degree 1
deg.append(1); method.append('lagrange')
elif all(map(lambda x: isinstance(x,list), args)):
# if args is as lists of methods and degrees
if all(map(lambda x: isinstance(x,int), args[0])):
deg = args[0]; method = args[1]
else:
deg = args[1]; method = args[0]
elif all(map(lambda x: isinstance(x,tuple), args)):
# if args is as method-degree tuples
for a in args:
if isinstance(a[0],int):
deg.append(a[0]); method.append(a[1])
else:
deg.append(a[1]); method.append(a[0])
else:
# if just method and tuple
if isinstance(args[0],int):
deg.append(args[0]); method.append(args[1])
else:
deg.append(args[1]); method.append(args[0])
# check if valid number of degrees and methods and return
assert len(method) == len(deg), 'Invalid input.'
return method, deg
#--------------------------------------------------------------------------------------#
def affine_map(vertices):
""" affine transformation F : K_ref -> K, where F(x) = a x + b, for x in K_ref
Input:
vertices - local vertices to coordinate matrix
Output:
B, b, det (2D: meas = |det|/2, 1D: meas = |det|)
"""
if len(vertices) == 3:
tmp1 = vertices[1] - vertices[0]
tmp2 = vertices[2] - vertices[0]
a = np.array([tmp1, tmp2]).T
a_inv = np.linalg.inv(a)
det = np.linalg.det(a)
b = vertices[0]
else:
tmp1 = (vertices[1] - vertices[0])/2
tmp2 = 2*np.ones(2)
a = np.array([tmp1, tmp2]).T
#a_inv = np.linalg.inv(a)
a_inv = None
det = np.linalg.det(a)
b = (vertices[0] + vertices[1])/2
return a, a_inv, det, b
#--------------------------------------------------------------------------------------#
class Element:
""" Finite Element class
Input:
method - finite element method (string)
deg - degree of finite element method (int)
or (deg, method) - tuples
"""
def __init__(self, *args):
# get args input
method, deg = get_args(*args)
# check if mixed elt
if len(method) > 1:
self.__mixed = True
else:
self.__mixed = False
# check if valid methods
method = map(lambda x: x.lower(), method)
for m in method:
assert any(map(lambda x: x == m, ['lagrange', 'rt'])), 'Invalid method: {}.'.format(m)
# set data
m_keys = []
for j in xrange(len(method)):
m_keys.append((deg[j], method[j]))
self.__m_keys = m_keys
self.__initialized = False
def initialized(self):
""" return True if element is initialized """
return self.__initialized
def mixed(self):
""" True if mixed finite element """
return self.__mixed
def m_keys(self, m=None):
""" return all or m'th degree/method tuples, e.g. (1,'lagrange') """
if m is None:
return self.__m_keys
else:
return self.__m_keys[m]
def method(self, m=None):
""" returns finite element method """
if m is None:
return [k[1] for k in self.m_keys()]
else:
return self.m_keys(m)[1]
def deg(self, m=None):
""" returns degree """
if m is None:
return [k[0] for k in self.m_keys()]
else:
return self.m_keys(m)[0]
def initialize(self, dim, gauss):
""" initialize finite element
Input:
dim - spatial dimension of finite element
gauss - degree of Gaussian quadrature
"""
sfns = {}; n_dofs = {}
for k in self.__m_keys:
if k not in sfns.keys():
if k == (0,'lagrange'):
sf = None; nd = 1
elif k == (0,'rt'):
sf = None; nd = 3
else:
sf = ShapeFunctions(k[0], dim); nd = sf.n_dofs()
sfns[k] = sf; n_dofs[k] = nd
self.__dim = dim
self.__gauss = gauss
self.__sfns = sfns
self.__n_dofs = n_dofs
self.__initialized = True
def n_dofs(self, m=0):
""" return number of dofs """
return self.__n_dofs[self.m_keys(m)]
def set_data(self, vertices, signs=None):
""" set local vertex to coordinate matrix (and local edge to sign matrix if RT element) """
assert len(vertices)-1 == self.__dim, 'Number of vertices and dimension mismatch.'
# initialize affine transform
a, a_inv, det, b = affine_map(vertices)
self.__a = a
self.__a_inv = a_inv
self.__det = det
self.__b = b
# set data
self.__vertices = vertices
self.__signs = signs
def measure(self):
""" returns measure of element (area in 2d, length in 1d) """
return abs(self.__det)/self.__dim
def map_to_elt(self, xi):
""" maps ref coord xi to global coord x """
return np.dot(self.__a, xi) + self.__b
def map_to_ref(self, x):
""" maps global coord x to local coord xi of reference element """
return np.linalg.solve(self.__a, x - self.__b)
def integrate(self, f, **kw):
""" integrate (global) function f over element
Input:
f - function to be integrated (callable or constant)
kw:
gauss - degree of Gaussian quadrature (default: same as element)
Output:
integral
"""
if callable(f):
# get quadrature points and weights
xw = np.array(gaussPts(kw.pop('gauss',self.__gauss), self.__dim))
nq = xw.shape[0] # number of quad points
qweights = xw[:,2] # quad weights
qpoints = xw[:,:2] # quad points
# calculate and return integrals
return sum([ f( self.map_to_elt(qpoints[n]) )*qweights[n] for n in xrange(nq) ])*self.measure()*(self.__dim/2.)
else:
return f*self.measure()
def jacobi(self):
""" return Jacobi matrix of transformation x -> xi, i.e. dxi/dx """
if self.__dim == 2:
return self.__a_inv
else:
return 2./self.measure()
def eval(self, n, x, m=0):
""" evaluate shape function at global coord x
Input:
n - n'th shape function to be evaluated
x - global coord
m - m'th FE
"""
k = self.__m_keys[m]
if k == (0,'lagrange'):
return 1.
elif k == (0,'rt'):
e = norm(self.__vertices[(n+1)%3] - self.__vertices[(n+2)%3]) # measure of edge
return self.__signs[n]*e*(x - self.__vertices[n])/(2*self.measure())
else: # lagrange of order 1,2 or 3
xi = self.map_to_ref(x)
return self.__sfns[k].eval(n, xi, derivative=False)
def deval(self, n, x, m=0):
""" evaluate shape function derivative at global coord x
Input:
n - n'th shape function to be evaluated
x - global coord
m - m'th method
"""
k = self.__m_keys[m]
if k == (0,'lagrange'):
raise ValueError('No derivative of P0 shape functions.')
elif k == (1,'lagrange'):
if self.__dim == 2:
v1 = self.__vertices[(n+1)%3]; v2 = self.__vertices[(n+2)%3]
return np.array([ v1[1] - v2[1], v2[0] - v1[0] ])/abs(self.__det)
else: # dim = 1
return pow(-1,n+1)*1/self.measure()
elif k == (0,'rt'):
e = norm(self.__vertices[(n+1)%3] - self.__vertices[(n+2)%3]) # measure of edge
return self.__signs[n]*e/self.measure()
else: # lagrange of order 2 or 3
xi = self.map_to_ref(x)
return np.dot(self.__sfns[k].eval(n, xi, derivative=True), self.jacobi())
def evaluate(self, n, x, derivative=False, m=0):
""" evaluate shape functions """
if derivative:
return self.deval(n, x, m)
else:
return self.eval(n, x, m)
def assemble_stress(self, d1=0, d2=0, c=None):
""" Assemble parts of stress tensor (for element), i.e. (partial_x phi_i, partial_y phi_j)
*only call this for P1 elements in 2D*
Input:
d1 - partial deriv for row index (0 for x, 1 for y)
d2 - partial deriv for column index (0 for x, 1 for y)
"""
v0, v1, v2 = self.__vertices
# rows are gradients of phi
phis = np.array([[ v1[1] - v2[1], v2[0] - v1[0] ],\
[ v2[1] - v0[1], v0[0] - v2[0] ],\
[ v0[1] - v1[1], v1[0] - v0[0] ]])
A = np.tensordot(phis[:,d1], phis[:,d2], 0)
if c is None:
return A/(4*self.measure())
else:
return A*self.integrate(c)/(self.__det**2)
def assemble_P0_div(self, c=None):
""" Assemble mixed piecewise const and div of vector P1, i.e. (q, dx u1) or (q, dy u2)
*only call this for P1 elements in 2D*
Input:
d - partial deriv (0 for dx, 1 for dy)
c - coefficient
"""
v0, v1, v2 = self.__vertices
# rows are gradients of phi
phis = np.array([[ v1[1] - v2[1], v2[0] - v1[0] ],\
[ v2[1] - v0[1], v0[0] - v2[0] ],\
[ v0[1] - v1[1], v1[0] - v0[0] ]])
if c is None:
return phis[:,0]/2, phis[:,1]/2
else:
return phis[:,0]*self.integrate(c)/abs(self.__det), phis[:,1]*self.integrate(c)/abs(self.__det)
def assemble_P0_P0(self, c=None):
""" efficient assembly of element mass matrix for P0 element """
if c is None:
return np.array([[self.measure()]])
elif not callable(c):
return c*np.array([[self.measure()]])
else: # callable c
return np.array([[self.integrate(c)]])
def assemble_dP1_dP1(self, c=None):
""" efficient assembly of element stiffness matrix for P1 element """
if self.__dim == 1:
temp = np.array([[1., -1.],\
[-1., 1.]])/self.measure()
if c is None:
return temp
elif not callable(c):
return c*temp
else: # callable c
return self.integrate(c)*temp/self.measure()
else: # dim = 2
if c is None:
E = self.__vertices[[1, 2, 0],:] - self.__vertices[[2, 0, 1],:]
return np.dot(E,E.T)/(4*self.measure())
elif not callable(c): # possibly tensor coeff
v0, v1, v2 = self.__vertices
phi1 = np.array([ v1[1] - v2[1], v2[0] - v1[0] ])
phi2 = np.array([ v2[1] - v0[1], v0[0] - v2[0] ])
phi3 = np.array([ v0[1] - v1[1], v1[0] - v0[0] ])
return np.array([[np.dot(c,phi1).dot(phi1), np.dot(c,phi1).dot(phi2), np.dot(c,phi1).dot(phi3)],\
[np.dot(c,phi2).dot(phi1), np.dot(c,phi2).dot(phi2), np.dot(c,phi2).dot(phi3)],\
[np.dot(c,phi3).dot(phi1), np.dot(c,phi3).dot(phi2), np.dot(c,phi3).dot(phi3)]])/(4*self.measure())
else: # callable c, possibly tensor valued
v0, v1, v2 = self.__vertices
phi1 = np.array([ v1[1] - v2[1], v2[0] - v1[0] ])/abs(self.__det)
phi2 = np.array([ v2[1] - v0[1], v0[0] - v2[0] ])/abs(self.__det)
phi3 = np.array([ v0[1] - v1[1], v1[0] - v0[0] ])/abs(self.__det)
a11 = self.integrate(lambda x: np.dot(c(x), phi1).dot(phi1))
a12 = self.integrate(lambda x: np.dot(c(x), phi1).dot(phi2))
a13 = self.integrate(lambda x: np.dot(c(x), phi1).dot(phi3))
a21 = self.integrate(lambda x: np.dot(c(x), phi2).dot(phi1))
a22 = self.integrate(lambda x: np.dot(c(x), phi2).dot(phi2))
a23 = self.integrate(lambda x: np.dot(c(x), phi2).dot(phi3))
a31 = self.integrate(lambda x: np.dot(c(x), phi3).dot(phi1))
a32 = self.integrate(lambda x: np.dot(c(x), phi3).dot(phi2))
a33 = self.integrate(lambda x: np.dot(c(x), phi3).dot(phi3))
return np.array([[a11, a12, a13],\
[a21, a22, a23],\
[a31, a32, a33]])
def assemble_dRT0_P0(self, c=None):
""" efficient assembly of element RT0-P0 matrix """
e1 = norm(self.__vertices[1] - self.__vertices[2])*self.__signs[0]
e2 = norm(self.__vertices[2] - self.__vertices[0])*self.__signs[1]
e3 = norm(self.__vertices[0] - self.__vertices[1])*self.__signs[2]
if c is None:
return np.array([[e1,e2,e3]]).T
elif not callable(c):
return c*np.array([[e1,e2,e3]]).T
else: # callable c
return self.integrate(c)*np.array([[e1,e2,e3]]).T/self.measure()
def assemble_flux_product(self, w, c=None):
""" assemble product of fluxes """
assert self.__m_keys[0] == (0,'rt') and self.__m_keys[1] == (0,'lagrange'), 'Must be mixed space.'
A = np.zeros(3)
if c is None:
for j in xrange(3):
if not callable(w):
f = lambda x: np.dot(w[0]*self.eval(0,x), self.eval(j,x)) \
+ np.dot(w[1]*self.eval(1,x), self.eval(j,x)) \
+ np.dot(w[2]*self.eval(2,x), self.eval(j,x))
A[j] = self.integrate(f)
else: # callable w
A[j] = self.integrate(lambda x: np.dot(w(x), self.eval(j,x)))
elif callable(c):
for j in xrange(3):
f = lambda x: np.dot(w[0]*self.eval(0,x), np.dot(c(x),self.eval(j,x))) \
+ np.dot(w[1]*self.eval(1,x), np.dot(c(x),self.eval(j,x))) \
+ np.dot(w[2]*self.eval(2,x), np.dot(c(x),self.eval(j,x)))
A[j] = self.integrate(f)
else:
for j in xrange(3):
f = lambda x: np.dot(w[0]*self.eval(0,x), np.dot(c,self.eval(j,x))) \
+ np.dot(w[1]*self.eval(1,x), np.dot(c,self.eval(j,x))) \
+ np.dot(w[2]*self.eval(2,x), np.dot(c,self.eval(j,x)))
A[j] = self.integrate(f)
return np.array([A])
def assemble(self, c=None, derivative=[False,False], m=0, n=0):
"""
integrate shape function products over this element
Input:
c - coefficient (variable or constant) can be tensor valued if 2D
derivative - True if derivative of shape function evaluated
m, n - methods
Output:
A - matrix of integrals
"""
if self.__m_keys[m] == (0,'rt') and self.__m_keys[n] == (0,'lagrange') and derivative == [True,False]:
return self.assemble_dRT0_P0(c)
elif self.__m_keys[m] == (0,'lagrange') and self.__m_keys[n] == (0,'rt') and derivative == [False,True]:
return self.assemble_dRT0_P0(c).T
elif m == n and self.__m_keys[m] == (0,'lagrange') and derivative == [False,False]:
return self.assemble_P0_P0(c)
elif m == n and self.__m_keys[m] == (1,'lagrange') and derivative == [True,True]:
return self.assemble_dP1_dP1(c)
else:
A = np.zeros((self.n_dofs(m), self.n_dofs(n)))
for i in xrange(self.n_dofs(m)):
for j in xrange(self.n_dofs(n)):
if c is None:
A[i,j] = self.integrate(lambda x: np.dot(self.evaluate(i,x,derivative[0],m),\
self.evaluate(j,x,derivative[1],n)))
elif not callable(c):
A[i,j] = self.integrate(lambda x: np.dot(np.dot(c, self.evaluate(i,x,derivative[0],m)),\
self.evaluate(j,x,derivative[1],n)))
else: # callable c
A[i,j] = self.integrate(lambda x: np.dot(np.dot(c(x), self.evaluate(i,x,derivative[0],m)),\
self.evaluate(j,x,derivative[1],n)))
return A
def rhs(self, f, m=0):
""" assemble element right hand side """
if self.__m_keys[m] == (0,'lagrange'):
if callable(f):
return np.array([self.integrate(f)])
else: # not callable
return np.array([f*self.measure()])
else:
if callable(f):
return np.array([self.integrate( lambda x: np.dot(f(x), self.eval(n,x,m)) ) for n in xrange(self.n_dofs(m))])
else:
return np.array([self.integrate(lambda x: self.eval(n,x,m))*f for n in xrange(self.n_dofs(m))])
def __mul__(self, other):
""" multiplication of two elements. They should be defined on same mesh """
method = self.method() + other.method(); deg = self.deg() + other.deg()
return Element(method, deg)
#--------------------------------------------------------------------------------------#
if __name__ == '__main__':
from meshing import UnitSquareMesh
fe = Element()
fe.initialize(2, 4)
#vs = np.array([[0,0], [1,0], [0,1]])
#fe.set_data(vs)
mesh = UnitSquareMesh(8,8)
for j in xrange(mesh.n_elts()):
vs = mesh.elt_to_vcoords(j)
fe.set_data(vs)
print "\n--------- element {} ------------".format(j)
print "measure: ", fe.measure()
print "det: ", fe._Element__det
for v in vs:
print fe.true_deval(0,v), fe.deval(0,v), fe.eval(0,v)
print fe.true_deval(1,v), fe.deval(1,v), fe.eval(1,v)
print fe.true_deval(2,v), fe.deval(2,v), fe.eval(2,v), "\n"
# assert np.allclose(fe.true_deval(0,v) - fe.deval(0,v),0)
# assert np.allclose(fe.true_deval(1,v) - fe.deval(1,v),0)
# assert np.allclose(fe.true_deval(2,v) - fe.deval(2,v),0)
stress = fe.assemble_stress()
<file_sep>import numpy as np
import math
from lagrange_data import regular_mesh_data, triangle_mesh_data
#--------------------------------------------------------------------------------------#
"""
def regular_mesh_data(box, res, diag):
Data for regular triangular mesh
Input:
box - bounding box ([start_x,end_x],[start_y,end_y])
res - number of divisions of x and y (nx,ny)
diag - diagonal to the left or right
Output:
vertex_to_coords - vertex number to coordinates
elt_to_vertex - element number to vertex numbers
# check valid data
assert len(box) == len(res), 'Incompatible box and res arguments.'
if len(box)!= 2:
raise ValueError('Invalid box and res arguments.')
# check valid diagonal arg
diag = diag.lower()
assert diag in {'left','l','right','r'}, 'Invalid diagonal argument.'
x = box[0]; y = box[1] # bounding box
nx = res[0]; ny = res[1] # number of cells in each direction (2 elts per cell)
nx_vertex = nx+1; ny_vertex = ny+1 # number of vertex in x and y directions
n_vertex = nx_vertex*ny_vertex # total number of vertex
n_elts = 2*nx*ny # total number of elements
# assemble vertex_to_coords
# numbered from bottom left, then right, then one up start from left again
xx = np.linspace(x[0],x[1],nx_vertex)
yy = np.linspace(y[0],y[1],ny_vertex)
vertex_to_coords = []
# loop over vertexes
for iy in range(ny_vertex):
for ix in range(nx_vertex):
vertex_to_coords.append([xx[ix], yy[iy]])
vertex_to_coords = np.array(vertex_to_coords, dtype=float)
assert len(vertex_to_coords) == n_vertex, 'Assembly of vertex_to_coords failed.'
# assemble elt_to_vertex
# numbering follows cell numbering (bottom left to right, one up, left to right etc.)
# lower elt in cell comes before upper elt
# anti-clockwise numbering of vertexes (start from bottom left)
elt_to_vertex = []
# loop over cells
for iy in range(ny):
for ix in range(nx):
# vertexes of cell (ix,iy), from bottom left, anti-clockwise
v0 = iy*nx_vertex+ix; v1 = v0+1
v2 = v0+nx_vertex; v3 = v2+1
if diag in {'right', 'r'}:
elt_to_vertex.append([v0, v1, v3])
elt_to_vertex.append([v0, v3, v2])
else:
elt_to_vertex.append([v0, v1, v2])
elt_to_vertex.append([v1, v3, v2])
elt_to_vertex = np.array(elt_to_vertex, dtype=int)
assert len(elt_to_vertex) == n_elts, 'Assembly of elt_to_vertex failed.'
return vertex_to_coords, elt_to_vertex
"""
def plot_mesh(vertex_to_coords, elt_to_vertex, dof_to_coords, bdofs, title, figsize, grid, savefig):
"""Plots trianglular mesh with or without DOFs indicated
Input:
vertex_to_coords - vertex number to coordinates
elt_to_vertex - element number to vertex number
dof_to_coords - DOF number to coordinate
bdofs - numbers of boundary DOFS
title - title of figure
figsize - size of figure
grid - True if grid lines are shown
savefig - file name in case of saved figure
"""
import matplotlib.pyplot as plt
# initialize figure
plt.figure(figsize=figsize)
# plot mesh
x = vertex_to_coords[:,0]; y = vertex_to_coords[:,1]
plt.gca().set_aspect("equal")
plt.triplot(x, y, elt_to_vertex, "g-", linewidth=2)
# plot DOFs
if dof_to_coords is not None:
idofs = np.setdiff1d(range(dof_to_coords.shape[0]),bdofs)
dof_x = dof_to_coords[idofs,0]; dof_y = dof_to_coords[idofs,1]
plt.plot(dof_x,dof_y,"go",markersize=10)
if bdofs is not None:
dof_x = dof_to_coords[bdofs,0]; dof_y = dof_to_coords[bdofs,1]
plt.plot(dof_x,dof_y,"bo",markersize=10)
# set title
if title is None:
if dof_to_coords is None:
plt.title("Triangular mesh.")
else:
plt.title("Triangular mesh with DOFs.")
else:
plt.title(title)
plt.xlabel("x")
plt.ylabel("y")
# gridlines
plt.grid(grid)
# save figure
if savefig is not None:
plt.savefig(savefig)
plt.show()
#--------------------------------------------------------------------------------------#
class Mesh:
"""Triangular mesh
Input:
vertex_to_coords - vertex number to coordinates, i.e., np.array([[x, y]], float)
elt_to_vertex - element number to vertex numbers, i.e., np.array([[v0, v1, v2]], int)
dof_data, optional e.g.,
dof_to_coords - DOF number to coordinates, i.e., np.array([[x, y]], float)
elt_to_dofs - element number to DOF numbers, i.e., np.array([[dof_1,...,dof_n]], int)
"""
def __init__(self, vertex_to_coords, elt_to_vertex):
# set data
self.__vertex_to_coords = vertex_to_coords
self.__elt_to_vertex = elt_to_vertex
self.__dof_data = {}
self.__boundary_data = {}
def n_elts(self):
""" return number of elements in mesh """
return self.__elt_to_vertex.shape[0]
def n_vertices(self):
""" return number of vertices in mesh """
return self.__vertex_to_coords.shape[0]
def n_edges(self):
""" return number of edges (Eulers formula) """
return self.n_elts() + self.n_vertices() - 1
def vertex_to_coords(self, n=None):
"""Get vertex number to coordinates (global or of vertex n) """
if n is None:
return self.__vertex_to_coords
else:
return self.__vertex_to_coords[n,:]
def elt_to_vertex(self, n=None):
""" get elt number to vertex numbers (global or of elt n) """
if n is None:
return self.__elt_to_vertex
else:
return self.__elt_to_vertex[n,:]
def elt_to_vcoords(self, n=None):
"""return element number to vertex coords, or vertex coords of element n
i.,e, n_eltsx3x2 or 3x2 array """
if n is None:
return self.__vertex_to_coords[self.__elt_to_vertex]
else:
return self.__vertex_to_coords[self.__elt_to_vertex[n,:]]
def elt_to_ccoords(self, n=None):
""" return element number to center coords or center coord of element n """
if n is None:
return np.sum(self.elt_to_vcoords(),axis=1)/3
else:
return np.sum(self.elt_to_vcoords(n),axis=0)/3
def set_dof_data(self, **dof_data):
""" set DOF data given by keyword arguments """
for k in dof_data.keys():
self.__dof_data[k] = dof_data[k]
def dof_data(self):
""" print dof data and return list of keys"""
if self.__dof_data:
print("DOF data:")
template = "\t{0:15}{1:20}"
print(template.format("[name]","[shape]"))
for k in self.__dof_data.keys():
print(template.format(k, str(self.__dof_data[k].shape)))
return self.__dof_data.keys()
else:
print("No additional DOF data specified.")
def n_dofs(self):
""" get total number of DOFs in mesh """
if self.__dof_data:
return self.__dof_data["dof_to_coords"].shape[0]
else:
return self.n_vertices()
def dof_to_coords(self, n=None):
"""Get DOF number to coordinates (global or of DOF n) """
if self.__dof_data:
if n is None:
return self.__dof_data["dof_to_coords"]
else:
return self.__dof_data["dof_to_coords"][n,:]
else:
return self.vertex_to_coords(n)
def elt_to_dofs(self, n=None):
""" get elt number to DOF numbers (global or of elt n) """
if self.__dof_data:
if n is None:
return self.__dof_data["elt_to_dofs"]
else:
return self.__dof_data["elt_to_dofs"][n,:]
else:
return self.elt_to_vertex(n)
def elt_to_dofcoords(self, n=None):
"""return element number to DOF coords, or DOF coords of element n
i.e., n_eltsxn_dofs_eltx2 or n_elt_dofsx2 array """
if n is None:
return self.dof_to_coords()[self.elt_to_dofs()]
else:
return self.dof_to_coords()[self.elt_to_dofs(n)]
def set_boundary_data(self, **boundary_data):
""" Set boundary data given by keyword arguments """
for k in boundary_data.keys():
self.__boundary_data[k] = boundary_data[k]
def boundary_groups(self):
""" print boundary groups """
if self.__boundary_data:
print("Boundary edge-to-dofnumber groups:")
template = "\t{0:10}{1:20}"
print(template.format("[name]","[shape]"))
for k in self.__boundary_data.keys():
print(template.format(k, str(self.__boundary_data[k].shape)))
return self.__boundary_data.keys()
else:
print("No boundary data specified.")
def bedge_to_dofs(self, *group):
""" Get all boundary edges to DOF numbers or only for group(s) specified by names """
if len(group) == 0:
return np.concatenate(tuple(self.__boundary_data.values()))
else:
inv_keys = [k for k in group if k not in self.__boundary_data.keys()]
group = list(set(group) - set(inv_keys))
if len(inv_keys) > 0:
print("\nInvalid boundary group(s) given:")
for k in inv_keys:
print("\t-", k)
if len(group) > 0:
return np.concatenate(tuple([self.__boundary_data[g] for g in group]))
else:
return None
def plot(self, **kwargs):
"""Plots trianglular mesh with or without DOFs indicated
Input (as keyword arguments):
dof_to_coords - DOF number to coordinate (Bool or as coordinates)
title - title of figure (default is generic title)
figsize - size of figure (default is (10,10))
grid - True if grid lines are shown (default: False)
savefig - file name in case of saved figure
boundary - True if boundary DOFs indicated, can also be one or
more names of boundary groups (names in list if more than one)
"""
dof_to_coords = kwargs.pop("dof_to_coords",None)
title = kwargs.pop("title",None)
figsize = kwargs.pop("figsize",(10,10))
grid = kwargs.pop("grid",False)
savefig = kwargs.pop("savefig",None)
boundary = kwargs.pop("boundary",None)
"""
if dof_to_coords in {1, True}:
dof_to_coords = self.dof_to_coords()
elif dof_to_coords in {0, False}:
dof_to_coords = None
"""
if boundary is not None:
if isinstance(boundary, list):
bedge_to_dofs = self.bedge_to_dofs(*boundary)
elif boundary in {1, True}:
bedge_to_dofs = self.bedge_to_dofs()
else:
bedge_to_dofs = self.bedge_to_dofs(boundary)
boundary = np.unique(np.ravel(bedge_to_dofs)) if bedge_to_dofs is not None else None
plot_mesh(self.vertex_to_coords(), self.elt_to_vertex(),
dof_to_coords, boundary,
title, figsize, grid, savefig)
#--------------------------------------------------------------------------------------#
class RectangleMesh(Mesh):
"""Rectangle shaped triangular mesh (first order unit square is default)
Input:
x,y - intervals defining rectangle box
nx,ny - subdivisions in x and y directions
deg - degree of lagrange DOFs
diag - left or right
"""
def __init__(self, x=[0,1], y=[0,1], nx=4, ny=4, deg=1, diag='right'):
vertex_to_coords, elt_to_vertex, boundary = regular_mesh_data((x, y), (nx, ny), 1, diag)
super(RectangleMesh, self).__init__(vertex_to_coords, elt_to_vertex)
if 1 < deg <= 10:
dof_to_coords, elt_to_dofs, boundary = regular_mesh_data((x, y), (nx, ny), deg, diag)
self.set_dof_data(dof_to_coords=dof_to_coords,
elt_to_dofs=elt_to_dofs)
elif deg > 10:
raise ValueError("Illegal value for degree (must be in range [1,10]).")
self.set_boundary_data(top=boundary["top"],
bottom=boundary["bottom"],
left=boundary["left"],
right=boundary["right"])
self.__box = (x, y)
self.__res = (nx, ny)
self.__deg = deg
self.__diag = diag
def deg(self):
""" returns regree of lagrange DOFs """
return self.__deg
def mesh_size(self):
""" return h - size of elements in mesh """
return max((self.__box[0][1] - self.__box[0][0])/float(self.__res[0]),\
(self.__box[1][1] - self.__box[1][0])/float(self.__res[1]))
#--------------------------------------------------------------------------------------#
class TriangleMesh(Mesh):
"""Regular mesh of reference triangle for plotting shape functions """
def __init__(self, nx=4, ny=4):
vertex_to_coords, elt_to_vertex = triangle_mesh_data(nx, ny)
super(TriangleMesh, self).__init__(np.array(vertex_to_coords), np.array(elt_to_vertex))
#-------------------------------------------------------------------------------------#
if __name__ == '__main__':
""" Here we do some tests """
def rectangle_mesh_test(nx=3, ny=3, diag="r", deg=2):
print("Test methods for Rectangle mesh (unit square) with params:\
\n\tres: {}, diag: {}, deg: {}\n".format((nx,ny), diag, deg))
print("\nBasic stuff -------------------------")
mesh = RectangleMesh(nx=nx,ny=ny,deg=deg,diag=diag)
print("- n elts: ", mesh.n_elts())
print("- n vertices: ", mesh.n_vertices())
print("- n edges: ", mesh.n_edges())
print("- vertex_to_coords:", mesh.vertex_to_coords().shape,
"\n vertex 0:", mesh.vertex_to_coords(0))
print("- elt_to_vertex:", mesh.elt_to_vertex().shape,
"\n elt 0:", mesh.elt_to_vertex(0))
print("- elt_to_vcoords:", mesh.elt_to_vcoords().shape,
"\n elt 0:", np.array2string(mesh.elt_to_vcoords(0), prefix=" elt 0: "))
print("- elt_to_ccoords:", mesh.elt_to_ccoords().shape,
"\n elt 0:", mesh.elt_to_ccoords(0))
print("\nDOF stuff --------------------------")
print("- dof data:", mesh.dof_data())
print("- n dofs:", mesh.n_dofs())
print("- dof_to_coords:", mesh.dof_to_coords().shape,
"\n elt 0:", mesh.dof_to_coords(0))
print("- elt_to_dofs:", mesh.elt_to_dofs().shape,
"\n elt 0:", mesh.elt_to_dofs(0))
print("- elt_to_dofcoords:", mesh.elt_to_dofcoords().shape,
"\n elt 0:", np.array2string(mesh.elt_to_dofcoords(0), prefix=" elt 0: "))
print("\nBoundary stuff --------------------")
print("- boundary groups:", mesh.boundary_groups())
print("- bedge_to_dofs: (all)", mesh.bedge_to_dofs().shape)
print("- bedge_to_dofs: (some)", mesh.bedge_to_dofs("top","left").shape)
mesh.plot(dof_to_coords=True,boundary=["left", "right"])
#print(mesh.vertex_to_coords().shape)
#print(mesh.elt_to_vertex())
#mesh.plot()
#dof_to_coords, elt_to_dofs = regular_mesh_dofs(([1,0],[1,0]), (2,2), 2, "right")
def dof_test(n=1, diag="r", deg=1):
""" plot element wise DOFs """
mesh = RectangleMesh(nx=n,ny=n,deg=deg,diag=diag)
for j in range(mesh.n_elts()):
dfs = mesh.elt_to_dofcoords(j)
for d in dfs:
mesh.plot(dof_to_coords=np.array([d]))
if j > 10:
break
def mesh_test(n=16, deg=1, diag="r"):
""" mesh class test """
rect_mesh = RectangleMesh(nx=n,ny=n,deg=deg,diag=diag)
elt_to_vertex = rect_mesh.elt_to_vertex()
vertex_to_coords = rect_mesh.vertex_to_coords()
mesh = Mesh(vertex_to_coords, elt_to_vertex)
mesh.deg()
n = 10
#rectangle_mesh_test(nx=n, ny=n, diag="r", deg=2)
#dof_test(n=4, diag="l", deg=1)
mesh_test()<file_sep>import numpy as np
from gaussquad import gaussPts
from shapefuncs import ShapeFunctions
class Element:
""" Finite Element class
Input:
deg - degree of piecewise polynomial (int)
gauss - degree of Gaussian quadrature (int)
"""
def __init__(self, deg, gauss):
self.__deg = deg
self.__sfns = ShapeFunctions(self.__deg)
self.__initialized = False
self.__vertices = None
self.__dofs = None
self.__jacobi_dets = None
# get Gaussian quadrature points and weights ([x,y,w]), of reference triangle
xw = np.array(gaussPts(gauss, dim=2))
self.__n_quad = xw.shape[0] # number of quad points
self.__quad_weights = xw[:,2]/2 # quad weights
self.__quad_points = xw[:,:2] # quad points
def deg(self):
"""Return polynomial degree of element"""
return self.__deg
def n_dofs(self):
"""Return number of DOFs"""
return self.__sfns.n_dofs()
def initialized(self):
"""True if element vertices and DOFs are initialized"""
return self.__initialized
def n_quad(self):
"""Return number of quadrature points"""
return self.__n_quad
def quad_weights(self, n=None):
"""Return quadrature weights or weight of quad point n"""
if n is None:
return self.__quad_weights
else:
return self.__quad_weights[n]
def quad_points(self, n=None):
"""Return quadrature points or quad point n"""
if n is None:
return self.__quad_points
else:
return self.__quad_points[n,:]
def set_data(self, vertices, dofs=None):
"""Set data for element
Input:
vertices - vertex coords of element
dofs - DOF coords of elememt, must correspond to degree
(optional if degree equals 1) in which case DOFs are vertices"""
if dofs is None:
dofs = vertices
assert dofs.shape == (self.n_dofs(),2), "DOFs incompatible with shape functions."
assert vertices.shape == (3,2), "Invalid vertex data."
self.__vertices = vertices
self.__dofs = dofs
# set Jacobi determinant of transformation xi -> x, i.e. dx/dxi at quad points
jacobis = np.zeros((self.n_quad(),2,2))
for j in range(self.n_dofs()):
dphi_x, dphi_y = self.eval(j, self.quad_points(), derivative=True).T
x, y = dofs[j,:]
jacobis[:,0,0] += dphi_x*x
jacobis[:,0,1] += dphi_y*x
jacobis[:,1,0] += dphi_x*y
jacobis[:,1,1] += dphi_y*y
self.__jacobi_dets = np.linalg.det(jacobis)
self.__ijacobis = np.linalg.inv(jacobis)
self.__initialized = True
def clear_data(self):
"""Clear element data i.e., vertices and DOFs and Jacobis"""
self.__vertices = None
self.__dofs = None
self.__jacobi_dets = None
self.__ijacobis = None
self.__initialized = False
def vertices(self, n=None):
"""Return vertex coords of element or coord of vertex n """
if n is None or not self.initialized():
return self.__vertices
else:
return self.__vertices[n,:]
def dofs(self, n=None):
"""Return DOF coords of element or coord of DOF n """
if n is None or not self.initialized():
return self.__dofs
else:
return self.__dofs[n,:]
def jacobi_dets(self):
"""Return Jacobi determinants of transformation xi -> x at quad points
(with P1 basis: det = 2*measure) """
return self.__jacobi_dets
def measure(self):
"""Measure (area) of element"""
if self.initialized():
return np.linalg.det(np.concatenate((self.vertices(),np.ones((3,1))),axis=1))/2
else:
return 0
def eval(self, n, xi, derivative=False):
"""Evaluate shape function n (or derivative) at ref coord xi
Input:
n - n'th shape function to be evaluated
xi - local coord
Output:
phi_n(xi) or dphi_n(xi)"""
return self.__sfns.eval(n, xi, derivative=derivative)
def map_to_elt(self, xi):
""" maps ref coord xi to global coord x using shape functions i.e.,
x = sum_j phi_j(xi) * dofcoord_j
Input:
xi - coord in reference triangle
Output:
x - coord in current (physical) triangle"""
return np.sum([np.array([self.eval(j,xi)]).T*self.dofs(j)
for j in range(self.n_dofs())], axis=0)
def integrate(self, f):
"""Integrate (global) scalar function f over element
Input:
f - function to be integrated (callable or constant)
Output:
integral over element"""
if callable(f):
integrand = f(self.map_to_elt(self.quad_points()))
return np.sum(integrand*self.jacobi_dets()*self.quad_weights())
else:
return f*self.measure()
def assemble_P1_stiffness(self):
"""Shortcut method for assembling stiffness matrix for P1 elemenets"""
E = self.__vertices[[1, 2, 0],:] - self.__vertices[[2, 0, 1],:]
return np.matmul(E,E.T)/(4*self.measure())
def assemble(self, c=None, derivative=True):
"""Assembles local stiffness (default) or mass matrix
Input:
c - coefficient (callable or constant), can be tensor valued if derivative
derivative - True if stiffness, false if mass
Output:
A - matrix of (c dphi_i, dphi_j) or (c phi_i, phi_j)"""
if c is None and derivative and self.deg() == 1:
return self.assemble_P1_stiffness()
else:
n = self.n_dofs()
A = np.zeros((n,n))
for i in range(n):
for j in range(n):
if derivative:
A[i,j] = self.integrate_dphi_dphi(i, j, c=c)
else:
A[i,j] = self.integrate_phi_phi(i, j, c=c)
return A
def assemble_rhs(self, f):
"""Assembles local right hand side
Input:
f - function (callable or constant)
Output:
rhs - vector of (phi_i, f)"""
n = self.n_dofs()
rhs = np.zeros(n)
for i in range(n):
rhs[i] = self.integrate_phi_f(i, f)
return rhs
def integrate_phi_phi(self, i, j, c=None):
"""Integrate product of shape functions over element
Input:
i, j - indexes of shape functions
c - coeff (scalar valued or constant)
Outpu:
integral of c*phi_i*phi_j over element"""
# broadcast coeff to (n_quad,) regardless of input
if c is None:
c_eval = 1
elif callable(c):
c_eval = c(self.quad_points())
else:
c_eval = c*np.ones(self.n_quad())
phi_i = self.eval(i, self.quad_points(), False)
phi_j = self.eval(j, self.quad_points(), False)
return np.sum(c_eval*phi_i*phi_j*self.jacobi_dets()*self.quad_weights())
def integrate_dphi_dphi(self, i, j, c=None):
"""Integrate product of shape function gradients over element
Input:
i, j - indexes of shape functions
c - coeff (scalar/tensor valued or constant)
Output:
integral of c*dphi_i*dphi_j over element"""
# broadcast coeff to (n_quad, 2, 2) regardless of input
if c is None:
c_eval = np.broadcast_to(np.eye(2),(self.n_quad(),2,2))
elif callable(c):
c_eval = np.array([k*np.eye(2) for k in c(self.quad_points())])
else:
c_eval = np.array([c*np.eye(2) for k in range(self.n_quad())])
# eval shapefunctions at quad points and get jacobis of transform x -> xi (map to reference), dxi/dx
gradi = self.eval(i, self.quad_points(), True)
gradj = self.eval(j, self.quad_points(), True)
inv_jaco = self.__ijacobis
# chain rule, i.e., dx_phi = dxi_phi_ref * dxi/dx
gradi = np.array([np.sum(gradi*inv_jaco[:,0,:],1), np.sum(gradi*inv_jaco[:,1,:],1)]).T
gradj = np.array([np.sum(gradj*inv_jaco[:,0,:],1), np.sum(gradj*inv_jaco[:,1,:],1)]).T
# multiply with coeff
gradi = np.array([np.sum(gradi*c_eval[:,0,:],1), np.sum(gradi*c_eval[:,1,:],1)]).T
# return integral
return np.sum(np.sum(gradi*gradj,1)*self.jacobi_dets()*self.quad_weights())
def integrate_phi_f(self, i, f):
"""Integrate product of shape function and function f
Input:
f - (scalar) function or constant
Output:
integral of f*phi_i over element"""
# evaluate f at quad points
if callable(f):
f_eval = f(self.map_to_elt(self.quad_points()))
else:
f_eval = f
# return integral
integrand = self.eval(i, self.quad_points(), derivative=False)*f_eval
return np.sum(integrand*self.jacobi_dets()*self.quad_weights())
def norm(self, u, f=None, p=2):
if callable(f):
f_eval = f(self.map_to_elt(self.quad_points()))
else:
f_eval = f if bool(f) else 1
integrand = np.power(np.sum([self.eval(j, self.quad_points(), False)*u[j]
for j in range(self.n_dofs())],axis=0)-f_eval,p)
return sum(np.abs(integrand*self.jacobi_dets())*self.quad_weights())
#--------------------------------------------------------------------------------------#
#--------------------------------------------------------------------------------------#
if __name__ == "__main__":
""" Here we do some tests """
def test1():
from meshing import RectangleMesh
mesh = RectangleMesh(nx=1,ny=1)
fe = Element(1,4)
for j in range(mesh.n_elts()):
vs = mesh.elt_to_vcoords(j)
fe.set_data(vs)
print("\n--------- element {} ------------".format(j))
print("measure: \t\t", fe.measure())
print("det: \t\t\t", fe.jacobi_dets())
print("assemble stiffness:\n{}".format(fe.assemble()))
print("assemble mass:\n{}".format(fe.assemble(derivative=False)))
print("assemble rhs: {}".format(fe.assemble_rhs(1)))
#print("map to elt:\n{}".format(fe.map_to_elt(np.ones((4,2)))))
#print("map to elt:\n{}".format(fe.map_to_elt(np.array([0,0]))))
#--------------------------------------------------------------------------------------#
def map_test(n=4,deg=1,diag="r",gauss=4):
print("Map to element test:\n===============================================")
from meshing import RectangleMesh
mesh = RectangleMesh(nx=n,ny=n,deg=deg,diag=diag)
ref_vertices = np.array([[0,1],[0,0],[1,0]])
fe = Element(deg,gauss)
vertices = mesh.elt_to_vcoords(); dofs = mesh.elt_to_dofcoords()
j = 0
for v,d in zip(vertices, dofs):
fe.set_data(v, d)
mp = fe.map_to_elt(ref_vertices)
print("============================\n")
print("Vertex mapping:", np.allclose(fe.vertices(), mp))
print("Center mapping:", np.allclose(fe.map_to_elt(np.array([1/3,1/3])), mesh.elt_to_ccoords(j)))
j += 1
def integral_test(deg=1,gauss=1):
print("Integrate test:\n===============================================")
from meshing import RectangleMesh
mesh = RectangleMesh(nx=4,ny=4,deg=deg,diag="l")
funcs = [lambda x: 1,\
lambda x: np.sum(x,1),\
lambda x: np.prod(x,1),
lambda x: np.sin(np.prod(x,1)),
lambda x: np.log(np.prod(x,1)+1)]
answers = [1,\
1,\
0.25,\
0.239812,\
0.208761]
fe = Element(deg,gauss)
vertices = mesh.elt_to_vcoords()
dofs = mesh.elt_to_dofcoords()
template = "{:<10} - {:<10} = {:<10}"
print(template.format("True ","Calc ","Diff"))
print("------------------------------------------")
template = "{:<10.10f} - {:<10.10f} = {:<10.10f}"
for f, ans in zip(funcs, answers):
integral = 0
for v,d in zip(vertices, dofs):
fe.set_data(v,d)
integral += fe.integrate(f)
print(template.format(ans, integral, np.abs(ans-integral)))
def assemble_test(n=4,gauss=2):
print("Assemble test:\n===============================================")
from meshing import RectangleMesh
mesh = RectangleMesh(nx=n,ny=n,diag="r")
fe = Element(1,gauss)
vertices = mesh.elt_to_vcoords()
result = True
for v in vertices:
fe.set_data(v)
a1 = fe.assemble()
a2 = fe.assemble_P1_stiffness()
a3 = fe.assemble(derivative=False)
#print(a1)
#print(a2)
#print(np.isclose(a1, a2))
#print("===================\n")
result = result and np.allclose(a1, a2)
if not result:
print("Test failed.")
break
print("Success")
def rhs_test(n=4,gauss=2):
print("RHS test:\n===============================================")
from meshing import RectangleMesh
mesh = RectangleMesh(nx=n,ny=n,diag="l")
fe = Element(1,gauss)
vertices = mesh.elt_to_vcoords()
#template = "{:<10} - {:<10} = {:<10}"
#print(template.format("True ","Calc ","Diff"))
#print("------------------------------------------")
#template = "{:<10.10f} - {:<10.10f} = {:<10.10f}"
for v in vertices:
fe.set_data(v)
rhs = fe.assemble_rhs(1)
print(rhs)
print(fe.measure()/3)
print(np.allclose(rhs,fe.measure()/3))
print("===================\n")
#test1()
#map_test(n=4, deg=5,diag="r", gauss=1)
#integral_test(deg=1,gauss=2)
#assemble_test(n=7,gauss=1)
#rhs_test(gauss=1)
from meshing import RectangleMesh
n = 2; gauss = 4
mesh = RectangleMesh(nx=n,ny=n,diag="l")
fe = Element(1,gauss)
fe.set_data(mesh.elt_to_vcoords(1))
<file_sep>def =triquad(N,v)
#returns [X,Y,Wx,Wy]
"""
% triquad.m - Gaussian Quadrature for a triangular domain
%
% This scripts computes the N^2 nodes and weights for a triangle with
% vertices given by the 3x2 vector v. The nodes are produced by collapsing
% the square to a triangle.
%
% Sample Usage:
%
% >>[X,Y,Wx,Wy]=triquad(8,[0 0; 0 2; 2 1])
% >>f=@(x,y) exp(x+y);
% >>Q=Wx'*feval(f,X,Y)*Wy;
%
% Reference: <NAME>, <NAME>, A Survey of Numerical Cubature
% over Triangles (1994)
% http://citeseer.ist.psu.edu/lyness94survey.html
%
% Written by: <NAME>
% Contact: gregvw(at)math(dot)unm(dot)edu
% http://math.unm.edu/~gregvw
"""
n=1:N; nnk=2*n+1; A=[1/3 repmat(1,1,N)./(nnk.*(nnk+2))];
n=2:N; nnk=nnk(n); B1=2/9; nk=n+1; nnk2=nnk.*nnk;
B=4*(n.*nk).^2./(nnk2.*nnk2-nnk2); ab=[A.T [2; B1; B.T]]; s=sqrt(ab(2:N,2));
[V,X]=eig(diag(ab(1:N,1),0)+diag(s,-1)+diag(s,1));
[X,I]=sort(diag(X)); x=(X+1)/2; wx=ab(1,2)*V(1,I).T.^2/4;
N=N-1; N1=N+1; N2=N+2; y=cos((2*(N:-1:0).T+1)*pi/(2*N+2));
L=zeros(N1,N2); y0=2; iter=0;
while max(abs(y-y0))>eps
L(:,1)=1; L(:,2)=y;
for k in range(2,N1): #k=2:N1
L(:,k+1)=( (2*k-1)*y.*L(:,k)-(k-1)*L(:,k-1) )/k;
end
Lp=(N2)*( L(:,N1)-y.*L(:,N2) )./(1-y.^2);
y0=y; y=y0-L(:,N2)./Lp; iter=iter+1;
end
cd=[ 1, 0, 0; -1, 0, 1; 0, 1,-1]*v;
t=(1+y)/2; Wx=abs(det(cd(2:3,:)))*wx; Wy=1./((1-y.^2).*Lp.^2)*(N2/N1)^2;
[tt,xx]=meshgrid(t,x); yy=tt.*xx;
X=cd(1,1)+cd(2,1)*xx+cd(3,1)*yy; Y=cd(1,2)+cd(2,2)*xx+cd(3,2)*yy;
<file_sep>import numpy as np
from numpy.linalg import inv
def get_psi(m):
"""Get monomial basis component
Input:
m = [k,l]
Output:
psi(x,y) = x^k * y^l
"""
def psi(xi):
""" xi - 2D local coord or nx2 array of coords """
try:
return (xi[:,0]**m[0])*(xi[:,1]**m[1])
except IndexError:
return (xi[0]**m[0])*(xi[1]**m[1])
return psi
#--------------------------------------------------------------------------------------#
def get_dpsi(m):
"""Get gradient of monomial basis component
Input:
m = [k,l]
Output:
nabla psi(x,y) = [kx^{k-1} * y^l, x^k * ly^{l-1}]
"""
def dpsi(xi):
""" xi - 2D local coord or nx2 array of coords """
try:
if m[0] == 0:
comp1 = 0*xi[:,0]
else:
comp1 = m[0]*(xi[:,0]**(m[0]-1))*(xi[:,1]**m[1])
if m[1] == 0:
comp2 = 0*xi[:,1]
else:
comp2 = m[1]*(xi[:,1]**(m[1]-1))*(xi[:,0]**m[0])
except IndexError:
if m[0] == 0:
comp1 = 0
else:
comp1 = m[0]*(xi[0]**(m[0]-1))*(xi[1]**m[1])
if m[1] == 0:
comp2 = 0*xi[1]
else:
comp2 = m[1]*(xi[1]**(m[1]-1))*(xi[0]**m[0])
return np.array([comp1, comp2]).T
return dpsi
#--------------------------------------------------------------------------------------#
def monomial_basis(deg):
"""Get complete monomial basis and derivative
Input:
deg - degree monomial
Output:
[psi_1,...,psi_n], [dpsi_1,...,dpsi_n]
"""
psi = [get_psi([m,n]) for m in range(deg+1) for n in range(deg+1) if m+n<=deg]
dpsi = [get_dpsi([m,n]) for m in range(deg+1) for n in range(deg+1) if m+n<=deg]
return psi, dpsi
#--------------------------------------------------------------------------------------#
def get_lagrange_nodes(deg):
"""Get nodal points in ref elt for Lagrange basis
Input:
deg - degree of polynomial space (number of nodes)
Output:
[x,y] coordinates of nodes
"""
pts = np.linspace(0,1,deg+1)
return np.array([[xi,yi] for yi in np.flip(pts) for xi in pts if xi+yi<=1])
#--------------------------------------------------------------------------------------#
def get_phi(i, coeffs, psi, n_nodes):
"""Get i'th Lagrange basis function or derivative
Input:
coeffs - coefficient matrix for expansion in monomial basis
psi - complete monomial basis
n_nodes - number of nodes
"""
def phi(xi):
""" xi - 2D local coord or nx2 array of coords """
return np.sum([coeffs[i,j]*psi[j](xi) for j in range(n_nodes)], axis=0)
return phi
#--------------------------------------------------------------------------------------#
def get_dphi(i, coeffs, dpsi, n_nodes):
"""Get i'th Lagrange basis function derivative
Input:
coeffs - coefficient matrix for expansion in monomial basis
dpsi - complete monomial basis derivative
n_nodes - number of nodes
"""
def dphi(xi):
""" xi - 2D local coord or nx2 array of coords """
try:
comp1 = np.sum([coeffs[i,j]*dpsi[j](xi)[:,0] for j in range(n_nodes)], axis=0)
comp2 = np.sum([coeffs[i,j]*dpsi[j](xi)[:,1] for j in range(n_nodes)], axis=0)
except IndexError:
comp1 = np.sum([coeffs[i,j]*dpsi[j](xi)[0] for j in range(n_nodes)], axis=0)
comp2 = np.sum([coeffs[i,j]*dpsi[j](xi)[1] for j in range(n_nodes)], axis=0)
return np.array([comp1, comp2]).T
return dphi
#--------------------------------------------------------------------------------------#
def get_lagrange_basis(deg):
"""Get complete Lagrange basis and derivative,
where monomial coefficients are found using Vandermonde matrix, i.e.,
[psi_j(x_i)]_ij * [a_ij]_ij = Id, thus, [a_ij]_ij = inv([psi_j(x_i)]_ij)
Input:
deg - degree of polynomial space
Output:
[phi_1,...,phi_n], [dphi_1,...,dphi_n]
"""
nodes = get_lagrange_nodes(deg)
n_nodes = nodes.shape[0]
psi, dpsi = monomial_basis(deg)
# assmeble Vandermonde matrix
V = np.zeros((n_nodes, n_nodes))
for i in range(n_nodes):
for j in range(n_nodes):
V[i,j] = psi[j](nodes[i,:])
monomial_coeffs = inv(V).T
phi = [get_phi(i, monomial_coeffs, psi, n_nodes) for i in range(n_nodes)]
dphi = [get_dphi(i, monomial_coeffs, dpsi, n_nodes) for i in range(n_nodes)]
return phi, dphi
#--------------------------------------------------------------------------------------#
class ShapeFunctions:
""" Lagrange shape functions defined on reference element """
def __init__(self, deg):
"""
deg - degree of shape functions (1,2 or 3)
"""
# check valid dimentions and degree
assert isinstance(deg, int) and (1 <= deg <= 10), 'Invalid degree for Lagrange shape functions.'
# get shape functions
phi, dphi = get_lagrange_basis(deg)
self.__phi = phi
self.__dphi = dphi
def eval(self, n, xi, derivative=False):
""" eval n'th shape function, either phi or dphi, at xi """
if derivative:
return self.__dphi[n](xi)
else:
return self.__phi[n](xi)
def n_dofs(self):
""" return number of DOFs """
return len(self.__phi)
#--------------------------------------------------------------------------------------#
#--------------------------------------------------------------------------------------#
if __name__ == "__main__":
""" Here we do some tests """
def eval_test(x):
""" print output of the functions """
print("Input: ", np.array2string(x, prefix="Input: "))
print("\npsi eval test")
psi = get_psi([1,1])
print(psi(x))
print("\ndpsi eval test")
dpsi = get_dpsi([1,1])
print(dpsi(x))
deg = 1; n_nodes = 3
psi, dpsi = monomial_basis(deg)
print("\nphi test")
coeffs = np.ones((3,3))
phi = get_phi(0, coeffs, psi, n_nodes)
print(phi(x))
print("\ndphi test")
dphi = get_dphi(2, coeffs, dpsi, n_nodes)
print(dphi(x))
print("\nlagrange nodes, deg ", deg)
lnodes = get_lagrange_nodes(deg)
print(lnodes)
#--------------------------------------------------------------------------------------#
def plot_sfns(deg):
""" plot the lagrange basis functions """
import matplotlib.pyplot as plt
from matplotlib.tri import Triangulation
from meshing import TriangleMesh
# get shape functions
sf = ShapeFunctions(deg)
n_dofs = sf.n_dofs()
# get mesh of ref triangle and make triangulation
mesh = TriangleMesh(10,10)
vertex_to_coords = mesh.vertex_to_coords()
elt_to_vertex = mesh.elt_to_vertex()
X = vertex_to_coords[:,0]; Y = vertex_to_coords[:,1]
tri = Triangulation(X, Y, elt_to_vertex)
# plot the basis functions
for j in range(n_dofs):
#fig, ax = plt.subplots(subplot_kw={"projection": "3d"},figsize=(10,10))
#surf = ax.plot_trisurf(tri, sf.eval(j, vertex_to_coords), shade=1)
fig, ax = plt.subplots(figsize=(10,10),num=j+1)
cont = ax.tricontourf(tri, sf.eval(j, vertex_to_coords), 100)
plt.colorbar(cont)
ax.set_title("Degree {} Lagrange basis function {}/{}.".format(deg, j+1, n_dofs))
# plot the DOFs
#mesh.plot(dof_to_coords=get_lagrange_nodes(deg),
# title="Reference triangle with Lagrange nodes")
mesh = TriangleMesh(1,1)
mesh.plot(dof_to_coords=get_lagrange_nodes(deg),
title="Reference triangle with Lagrange nodes", grid=True)
#--------------------------------------------------------------------------------------#
def sf_test(deg, x):
""" print output of the functions """
print("Input: ", np.array2string(x, prefix="Input: "))
sf = ShapeFunctions(deg)
print("Evals: ===========================")
for j in range(sf.n_dofs()):
print("SF ", j)
print(sf.eval(j, x))
print("Grad evals: ======================")
for j in range(sf.n_dofs()):
print("SF ", j)
print(sf.eval(j, x, derivative=True))
#--------------------------------------------------------------------------------------#
linsp = np.linspace(0,1,10)
x = np.array([linsp, linsp]).T
# x = np.array([1,2])
#eval_test(x)
deg = 1
#plot_sfns(deg)
#x = np.array([0,1])
#sf_test(2, x)
print(get_lagrange_nodes(2))
| ef9aa4983ec9f09da82c1dd718ce62fc209ad60f | [
"Markdown",
"Python"
] | 10 | Python | mattskb/FEMpy | d08e94f5de868f596d58689353ef68b4597c7806 | e323906eac66758bb98158ffdfdb73bc1e8774d9 |
refs/heads/master | <file_sep>exports.customError = (err, status) => {
const error = new Error(err)
error.statusCode = status
return error
} | a8e0249ecad301153d1e01b5b6e156f5b3142573 | [
"JavaScript"
] | 1 | JavaScript | GuptaAman08/GrraphQL-NODE-EXPRESS | 13123d6bb280a1cf5bdb8fdcb567be02913c78a3 | fd9472d9eb8e0dea84bf04311f370e5c535e8152 |
refs/heads/master | <repo_name>phpdude/django-skeleton<file_sep>/etc/uwsgi.ini
[uwsgi]
gid = {{ project_name }}
uid = {{ project_name }}
chdir = /home/{{ project_name }}/{{ project_name }}/
pidfile = /home/{{ project_name }}/{{ project_name }}/tmp/uwsgi.pid
socket = /home/{{ project_name }}/{{ project_name }}/tmp/uwsgi.sock
chmod-socket = 777
virtualenv = env
pythonpath = .
;pythonpath=project
module = project.wsgi:application
master = true
processes = 5
harakiri = 30
buffer-size = 32768
vacuum = true
plugins = python<file_sep>/project/settings/debug_toobar.py
import sys
settings = sys.modules['project.settings']
DEBUG_TOOLBAR_CONFIG = {
'SHOW_TEMPLATE_CONTEXT': True,
'ENABLE_STACKTRACES': True,
}
if settings.DEBUG:
settings.INSTALLED_APPS += (
'debug_toolbar',
)
settings.MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
<file_sep>/README.md
# django-skeleton v0.2.0
Django skeleton project by @dude
You can bootstrap your django project with command
> django-admin.py startproject --template=https://github.com/phpdude/django-skeleton/archive/master.zip -e "ini,yml,conf,json" yoursite
After installation you must create virtualenv and install all required packages by default.
> cd yoursite
> sh upgrade.sh
<file_sep>/project/settings/emails.py
import sys
settings = sys.modules['project.settings']
# SERVER_EMAIL = ''
# DEFAULT_FROM_EMAIL = ''
# ADMINS = (('<NAME>', '<EMAIL>'),)
# EMAIL_HOST = 'your.host.ip'
# EMAIL_HOST_USER = '<EMAIL>'
# EMAIL_HOST_PASSWORD = '<PASSWORD>'
# EMAIL_PORT = 587
# EMAIL_USE_TLS = True<file_sep>/upgrade.sh
#!/bin/sh
cd `dirname $0`
ENV_DIR='env'
if [ ! -d $ENV_DIR ]; then
echo "Not found environment. Trying to create new one..."
virtualenv env
fi
if [ ! -d $ENV_DIR ]; then
echo "Not found virtualenv directory. Tried to create it, but looks without success. Upgrade aborted."
exit -1
fi
source $ENV_DIR/bin/activate
pip install -U pip
pip install -r requirements.txt -U
python manage.py migrate<file_sep>/fabfile.py
# coding=utf-8
import os
from fabric.api import env
from fabric.context_managers import cd
from fabric.decorators import roles
from fabric.operations import run
env.roledefs['production'] = ['<EMAIL>:port']
def production_env():
"""Production environment"""
# Speedup connection setup to server.
env.disable_known_hosts = True
env.key_filename = [os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')]
env.user = 'django'
env.project_root = '/home/{{ project_name }}/{{ project_name }}/'
env.shell = '/bin/bash -c'
# I usually place virtualenv into BASE_DIR/env folder. You can do same or use your paths.
env.virtenv = '%s/env' % env.project_root
env.python = '%s/bin/python' % env.virtenv
env.pip = '%s/bin/pip' % env.virtenv
@roles('production')
def deploy():
git_pull()
pip_install()
collectstatic()
# static_compress()
@roles('production')
def git_pull():
production_env()
with cd(env.project_root):
run('git pull origin master')
@roles('production')
def collectstatic():
production_env()
with cd(env.project_root):
run('docker-compose run assets-prod')
run('{0} manage.py collectstatic --noinput'.format(env.python))
@roles('production')
def static_compress():
production_env()
with cd(env.project_root):
run('{0} manage.py compress'.format(env.python))
@roles('production')
def pip_upgrade():
production_env()
run('{pip} install -U -r {filepath}'.format(pip=env.pip,
filepath=os.path.join(env.project_root, 'requirements.txt')))
@roles('production')
def pip_install():
production_env()
run('{pip} install -q -r {filepath}'.format(pip=env.pip,
filepath=os.path.join(env.project_root, 'requirements.txt')))
@roles('production')
def migrate():
production_env()
with cd(env.project_root):
run('{0} manage.py migrate'.format(env.python))
@roles('production')
def syncdb():
production_env()
with cd(env.project_root):
run('{0} manage.py syncdb'.format(env.python))
@roles('production')
def update():
deploy()
migrate()
reload_all()
@roles('production')
def clear_cache():
production_env()
with cd(env.project_root):
run('{0} manage.py clear_cache'.format(env.python))
@roles('production')
def reload_all():
production_env()
run('supervisorctl restart {{ project_name }}:')
<file_sep>/assets/frontend/js/main.js
import Style from '../sass/site'<file_sep>/Dockerfile
FROM python:2.7
ENV PYTHONUNBUFFERED 1
RUN pip install -U pip 3to2
RUN mkdir -p /code/
WORKDIR /code
ADD requirements.txt requirements.txt
RUN pip install -r requirements.txt --no-cache-dir
ENV DOCKER 1
EXPOSE 8000<file_sep>/project/settings/paths.py
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import sys
PROJECT_DIR = os.path.realpath(os.path.dirname(os.path.dirname(__file__)))
BASE_DIR = os.path.realpath(os.path.dirname(PROJECT_DIR))
sys.stderr.write('settings.BASE_DIR is "%s", settings.PROJECT_DIR is "%s"\n' % (BASE_DIR, PROJECT_DIR))
<file_sep>/project/settings/cache.py
import sys
settings = sys.modules['project.settings']
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': 'cache:11211'
}
}
if settings.PRODUCTION:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211'
}
}
<file_sep>/assets/webpack.config.js
'use strict';
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var Clean = require('clean-webpack-plugin');
var PRODUCTION = !!process.env.PRODUCTION;
module.exports = {
context: __dirname + '/frontend',
entry: {
main: './js/main'
},
output: {
path: __dirname + '/dist/app',
publicPath: '/static/app/',
filename: 'js/[name].js'
},
resolve: {
extensions: ['', '.js', '.scss'],
root: __dirname + '/frontend'
},
watch: !PRODUCTION,
watchOptions: {
aggregateTimeout: 100,
poll: 50
},
module: {
loaders: [
{
test: /\.js$/,
include: __dirname + '/frontend',
loader: "babel",
query: {
presets: ['es2015'],
plugins: ['transform-runtime']
}
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css?sourceMap!autoprefixer-loader?browsers=last 2 version!resolve-url!sass')
}, {
test: /\.(png|jpg|svg|ttf|eot|woff|woff2)$/,
loader: 'url?limit=8192&name=[path][name].[ext]'
}
],
noParse: [
/jquery\.js$/
]
},
sassLoader: {
sourceMap: true,
outputStyle: 'expanded',
sourceComments: true
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
}),
new webpack.NoErrorsPlugin(),
new webpack.optimize.CommonsChunkPlugin({name: 'common', minChunks: 2}),
new ExtractTextPlugin("styles.css", {allChunks: true}),
new Clean(__dirname + '/dist/app')
],
devtool: PRODUCTION ? null : 'inline-source-map'
};
if (PRODUCTION) {
module.exports.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: {
// don't show unreachable variables etc
warnings: false,
drop_console: true,
unsafe: true
}
})
);
}<file_sep>/project/settings/security.py
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '{{ secret_key }}'
ALLOWED_HOSTS = ['127.0.0.1']
AUTH_PASSWORD_VALIDATORS = [{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
}, {
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
}, {
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
}, {
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
}]
<file_sep>/project/settings/env.py
# Best place to change this env variables is project/settings/local_env.py file. It loads after this one specially to
# allow you manage env without touching project code.
PRODUCTION = False
DEBUG = True
print 'Application modes: DEBUG is %s, PRODUCTION is %s' % (DEBUG, PRODUCTION)
<file_sep>/project/settings/i18n.py
# Internationalization
# https://docs.djangoproject.com/en/{{ docs_version }}/topics/i18n/
import os
import sys
settings = sys.modules['project.settings']
LANGUAGE_CODE = 'en'
USE_I18N = True
USE_L10N = True
LOCALE_PATHS = (os.path.join(settings.PROJECT_DIR, 'conf/locale'),)
<file_sep>/docker-compose.yml
db:
image: postgres
environment:
- POSTGRES_USER={{ project_name }}
- POSTGRES_PASSWORD={{ project_<PASSWORD> }}
cache:
image: memcached
assets:
image: phpdude/node-bower-webpack
volumes:
- ./project/assets:/data
command: /bin/bash -c 'npm i --no-bin-links && webpack --display-modules --profile'
web:
build: ./
privileged: true
command: /bin/bash -c 'python manage.py migrate && python manage.py runserver 0.0.0.0:8000'
volumes:
- ./:/code/
ports:
- "8000:8000"
links:
- db
- cache
- assets
assets-prod:
extends:
service: assets
command: /bin/bash -c 'npm i --no-bin-links && PRODUCTION=1 webpack --display-modules --profile'<file_sep>/requirements.txt
# Latest django
django
django_extensions
# deploy toolkit
Fabric
# Debug toolbar
django-debug-toolbar
# @phpdude libs
django-macros-url
django-template-names
# cache
python-memcached
django-clear-cache
# Database drivers. Uncomment anyone is used.
#MySQL-python
#mysqlclient
psycopg2
# Project custom apps
<file_sep>/project/settings/__init__.py
import inspect
import os
import pkgutil
import sys
from pprint import pformat
ordering = ('env', 'local_env', 'paths', 'middleware', 'debug_toolbar')
modules = [x[1] for x in pkgutil.walk_packages(__path__)]
modules.sort(key=lambda x: x in ordering and ordering.index(x) + 1 or sys.maxint)
sys.stderr.write('Loading project.settings submodules: %s\n' % (", ".join(modules)))
for module_name in modules:
module = __import__(module_name, globals(), locals(), [])
for var_name, val in inspect.getmembers(module):
if var_name.isupper():
locals().update({var_name: val})
try:
# noinspection PyUnresolvedReferences
from ..settings_local import *
except ImportError:
pass
settingsraw = []
REWRITE_DOCKER_BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
for s in locals().copy():
if s.isupper():
try:
value = pformat(locals()[s], indent=0, width=100000).replace(REWRITE_DOCKER_BASE_DIR, '.')
settingsraw.append("%s = %s\n" % (s, value))
except:
pass
settingsfile = os.path.dirname(__file__) + '/../settings_compiled.py'
if not os.path.isfile(settingsfile) or open(settingsfile).readlines() != settingsraw:
sys.stderr.write('Updating compiled settings file ...\n')
file(settingsfile, 'wb').writelines(settingsraw)
sys.stderr.write("\n")
| 4e53a67e4c9f0f26bb56831ba13620c9c87eb6e9 | [
"YAML",
"Markdown",
"JavaScript",
"INI",
"Python",
"Text",
"Dockerfile",
"Shell"
] | 17 | INI | phpdude/django-skeleton | b03ee34c9cb72e014885e3d01814d3074bb2f9ed | 6c9a6c11b8c9920b6726b96650b0d6db7383605e |
refs/heads/master | <repo_name>kboy-silvergym/Tinder-With-FacePlusPlus<file_sep>/TinderSwipeWithAI/SoundUseCase.swift
//
// SoundUseCase.swift
// TinderSwipeWithAI
//
// Created by <NAME> on 2019/07/15.
// Copyright © 2019 Kboy. All rights reserved.
//
import Foundation
import Foundation
import AVFoundation
import UIKit
enum Sound: String {
case correct1
case incorrect1
case heart1
}
class SoundUseCase {
static var sePlayer: AVAudioPlayer?
static func playSound(type: Sound) {
guard let sound = NSDataAsset(name: type.rawValue) else { return }
sePlayer = try? AVAudioPlayer(data: sound.data)
if type == .heart1 {
sePlayer?.numberOfLoops = 5
} else {
sePlayer?.numberOfLoops = 0
}
sePlayer?.play()
}
static func stopMusic() {
sePlayer?.stop()
}
}
<file_sep>/TinderSwipeWithAI/FacePlusAPI.swift
//
// FacePlusAPI.swift
// TinderSwipeWithAI
//
// Created by <NAME> on 2019/07/15.
// Copyright © 2019 Kboy. All rights reserved.
//
import Alamofire
class FacePlusAPI {
let apiKey = ""
let apiSec = ""
enum URL: String {
case detect = "https://api-us.faceplusplus.com/facepp/v3/detect"
}
func processFace(image: UIImage, handler: @escaping (FaceInfo?) -> ()) {
guard let imageData = image.jpegData(compressionQuality: 1.0) else {
handler(nil)
return
}
let base64Data = imageData.base64EncodedString(options: .lineLength64Characters)
let parameters: Parameters = [
"api_key": apiKey,
"api_secret": apiSec,
"image_base64": base64Data,
"return_attributes": "gender,age,smiling,glass,emotion,beauty,ethnicity,skinstatus"
]
AF.request(URL.detect.rawValue, method: .post, parameters: parameters)
.responseJSON { response in
switch response.result {
case .success(let json):
print(json)
guard let json = json as? [String: Any] else {
handler(nil)
return
}
print(json)
guard let faces = json["faces"] as? [[String: Any]],
!faces.isEmpty else {
handler(nil)
return
}
let face = faces.first!
let attributes = face["attributes"] as! [String: Any]
let gender = attributes["gender"] as! [String: String]
let age = attributes["age"] as! [String: Int]
let beauty = (attributes["beauty"] as! [String: Any])["male_score"] as! NSNumber
let info = FaceInfo(
gender: Gender(rawValue: gender["value"]!)!,
age: age["value"]!,
beauty: beauty.intValue
)
handler(info)
case .failure(let error):
print(error.localizedDescription)
handler(nil)
}
}
}
}
<file_sep>/TinderSwipeWithAI/ViewController.swift
//
// ViewController.swift
// TinderSwipeWithAI
//
// Created by <NAME> on 2019/07/15.
// Copyright © 2019 Kboy. All rights reserved.
//
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
@IBOutlet weak var webViewContainer: UIView!
@IBOutlet weak var genderLabel: UILabel!
@IBOutlet weak var ageLabel: UILabel!
@IBOutlet weak var faceScoreLabel: UILabel!
@IBOutlet weak var indicator: UIActivityIndicatorView!
private let api = FacePlusAPI()
private var webView: WKWebView!
private let javascriptCode = """
function like() {
const elem = document.getElementsByClassName("recsGamepad__button");
elem[3].click();
};
function unLike() {
const elem = document.getElementsByClassName("recsGamepad__button");
elem[1].click();
};
"""
override func viewDidLoad() {
super.viewDidLoad()
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: webViewContainer.bounds, configuration: webConfiguration)
webViewContainer.addSubview(webView)
let myURL = URL(string:"https://tinder.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
webView.evaluateJavaScript(
self.javascriptCode,
completionHandler: { result, error in
})
}
private func processFace(completionHandler: (() -> Void)?){
SoundUseCase.playSound(type: .heart1)
self.genderLabel.text = ""
self.ageLabel.text = "判定中....."
self.faceScoreLabel.text = ""
indicator.isHidden = false
indicator.startAnimating()
let image: UIImage = self.webViewContainer.screenShot()
self.api.processFace(image: image, handler: { faceInfo in
SoundUseCase.stopMusic()
guard let faceInfo = faceInfo else {
self.indicator.stopAnimating()
self.ageLabel.text = "測定不能"
self.unLike()
return
}
self.genderLabel.text = "性別: " + faceInfo.gender.rawValue
self.ageLabel.text = "年齢: " + faceInfo.age.description
self.faceScoreLabel.text = "顔面スコア: " + faceInfo.beauty.description
let isFemale: Bool = faceInfo.gender == .female
let isUnder30: Bool = faceInfo.age < 30
let isKawaii: Bool = faceInfo.beauty > 50
if isFemale, isUnder30, isKawaii {
self.faceScoreLabel.textColor = .red
self.indicator.stopAnimating()
self.like()
} else {
self.faceScoreLabel.textColor = .blue
self.indicator.stopAnimating()
self.unLike()
}
})
}
private func like(){
SoundUseCase.playSound(type: .correct1)
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
self.webView.evaluateJavaScript(
"like();",
completionHandler: { result, error in
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.processFace(){ }
}
})
}
}
private func unLike(){
SoundUseCase.playSound(type: .incorrect1)
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
self.webView.evaluateJavaScript(
"unLike();",
completionHandler: { result, error in
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.processFace(){ }
}
})
}
}
@IBAction func buttonTapped(_ sender: Any) {
processFace() {
}
}
}
extension UIView {
func screenShot() -> UIImage {
let rect = self.bounds
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
let context: CGContext = UIGraphicsGetCurrentContext()!
self.layer.render(in: context)
let capturedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return capturedImage
}
}
<file_sep>/README.md
# Tinder-With-FacePlusPlus
<file_sep>/TinderSwipeWithAI/FaceInfo.swift
//
// FaceInfo.swift
// TinderSwipeWithAI
//
// Created by <NAME> on 2019/07/15.
// Copyright © 2019 Kboy. All rights reserved.
//
import Foundation
enum Gender: String {
case male = "Male"
case female = "Female"
}
struct FaceInfo {
let gender: Gender
let age: Int
let beauty: Int
}
| 501875c137c6644f495d8dd3f03952b59e682acc | [
"Swift",
"Markdown"
] | 5 | Swift | kboy-silvergym/Tinder-With-FacePlusPlus | 25e248cca8a9d6698e93ca7307ac5e46ce704fa6 | ce6cb3e182e94a74cd76e4bf8ff4c7a9047bb0f1 |
refs/heads/main | <repo_name>foreignbyproxy/hardhat-fake-erc20-network<file_sep>/README.md
# hardhat-deploy-fake-erc20
### Work In Progress
A [Hardhat](https://hardhat.org) plugin to deploy a configurable number of ERC-20 tokens to the local Hardhat network. This is inteded to be used to help developers quickly deploy ERC20 tokens and mint a beginning balance for each account on the network. This is useful for dApps that interact with multiple ERC20 tokens. The plugin uses [OpenZeppelin's](https://openzeppelin.com/) ERC-20 contract to create the tokens.
## Installation
Run the following command to install hardhat-deploy-fake-erc20 in your hardhat project. The pluging requires the [@nomiclabs/hardhat-ethers](https://github.com/nomiclabs/hardhat/tree/master/packages/hardhat-ethers) plugin and the Ethereum library `ethers.js`.
```bash
npm install hardhat-deploy-fake-erc20 @nomiclabs/hardhat-ethers ethers@^5.0.0
```
Import the plugin in your `hardhat.config.js`:
```js
require("hardhat-deploy-fake-erc20");
```
Or if you are using TypeScript, in your `hardhat.config.ts`:
```ts
import "hardhat-deploy-fake-erc20";
```
## Required plugins
- [@nomiclabs/hardhat-ethers](https://github.com/nomiclabs/hardhat/tree/master/packages/hardhat-ethers)
## Configuration
The plugin adds the `fakeERC20Network` property to `hardhat.config.js`.
This is an example:
```js
module.exports = {
fakeERC20Network: {
tokens: [
{
name: "Gold",
symbol: "GLD",
defaultMintAmount: "80000000000000000000",
},
...
],
defaultMintAmount: "80000000000000000000",
},
};
```
**tokens** - An array of objects that describe the tokens to be deployed to the local network.
| Property | Required | Description |
| ----------------- | -------- | ---------------------------------------------------------------------- |
| name | Yes | The name of the ERC20 token |
| symbol | Yes | The Symbol of the token |
| defaultMintAmount | No | The amount to mint for each user. Overrides global `defaultMintAmount` |
**defaultMintAmount** - The amount to of each token to minto for each user. This is a fallback if no `defaultMintAmount` is added to the tokens
## Tasks
The plugin adds the `deploy-fake-erc20` task to Hardhat. The task will deploy the tokens described in the `fakeERC20Network.tokens` array and mint the `defaultMintAmount` for each user on the network. The task returns the contract address for each token deployed.
```
npx hardhat deploy-fake-erc20
```
<file_sep>/test/configs.test.ts
// tslint:disable-next-line no-implicit-dependencies
import { expect } from "chai";
import { useEnvironment } from "./helpers";
import { defaultSettings } from "../src/utils";
/*
Sets up an environment where no configuration is passed to fakeERC20Network. This should
then set the defaultSettings as the configuration for fakeERC20Network.
This makes sure that even if the user didnt provide a token or defaultMintAmount at least
something gets deployed. It would be pointless to deploy nothing
*/
describe("Configs - No config", function () {
useEnvironment("no-config");
it("Config should have 1 token and defaultMintAmount", function () {
expect(this.hre.config.fakeERC20Network).to.eql(defaultSettings);
});
});
/*
Sets up an environment where only a defaultMintAmount is set and no tokens configuration are passed. This makes
sure that the task is deploying at least one token.
This makes sure that even if the user didnt provide a token at least
something gets deployed. Again, it would be pointless to deploy nothing
*/
describe("Config - Partial config - No Token", function () {
useEnvironment("partial-config-no-token");
it("Config should have 1 token and defaultMintAmount", function () {
expect(this.hre.config.fakeERC20Network.tokens).to.eql(
defaultSettings.tokens
);
expect(this.hre.config.fakeERC20Network.defaultMintAmount).to.equal(
"70000000000000000000"
);
});
});
/*
Sets up an environment where no defaultMintAmount is set. This makes sure that the task
has a defaultMintAmount set whether they put one or not.
*/
describe("Config - Partial config - No defaultMintAmount", function () {
useEnvironment("partial-config-no-defaultMintAmount");
it("Config should have 2 tokens and defaultMintAmount", function () {
expect(this.hre.config.fakeERC20Network.tokens.length).to.equal(2);
expect(this.hre.config.fakeERC20Network.tokens[0].symbol).to.equal(
"GOLD"
);
expect(this.hre.config.fakeERC20Network.tokens[1].symbol).to.equal(
"SILVER"
);
expect(this.hre.config.fakeERC20Network.defaultMintAmount).to.equal(
defaultSettings.defaultMintAmount
);
});
});
/*
Makes sure that the HardHatUserConfig is being merged into the HRE correctly
*/
describe("Config - Full config", function () {
useEnvironment("full-config");
it("Config should have 3 tokens and defaultMintAmount", function () {
expect(this.hre.config.fakeERC20Network.tokens.length).to.equal(3);
expect(this.hre.config.fakeERC20Network.defaultMintAmount).to.equal(
"80000000000000000000"
);
});
});
<file_sep>/src/types/mute.d.ts
declare module "mute" {
var mute: () => () => {};
export default mute;
}
<file_sep>/src/tasks.ts
import ora from "ora";
import {
checkLocalhostNetwork,
getInitialUserData,
getTaskResultsDisplay,
} from "./utils";
import ERC20FakeFactory from '../artifacts/contracts/ERC20FakeFactory.sol/ERC20FakeFactory.json';
import type { TaskResults } from "./types/types";
import type { HardhatRuntimeEnvironment } from "hardhat/types";
export async function deployTokens(_: any, hre: HardhatRuntimeEnvironment) {
const { config, ethers } = hre;
//Check to make sure a network is running on localhost
await checkLocalhostNetwork(config);
const { fakeERC20Network } = config;
//Get all the users on the network
const accounts = await ethers.getSigners();
//Get the ERC20 Factory ABI
const contractFactory = new ethers.ContractFactory(
ERC20FakeFactory.abi,
ERC20FakeFactory.bytecode,
accounts[0]
);
const spinner = ora();
//Iterate over each token to deploy the ERC20FakeFactory contract on the local network and
//mint the token for each signer
const taskResults: TaskResults = {};
for (let token of fakeERC20Network.tokens) {
spinner.start(`Deploying: ${token.name} (${token.symbol})`);
//Get an array for each user and their initial token balance
const initialMintAmount =
token.defaultMintAmount ?? fakeERC20Network.defaultMintAmount;
let initialUsers = getInitialUserData(accounts, initialMintAmount);
//Deploy the token and wait until it is mined on the local network
try {
let contract = await contractFactory.deploy(
token.name,
token.symbol,
initialUsers
);
await contract.deployTransaction.wait();
spinner.succeed(
`Token Deployed: ${token.name} - (${contract.address})`
);
taskResults[token.symbol] = contract.address;
} catch (error) {
taskResults[token.symbol] = "Failed";
spinner.fail(`Token Deployment Failed: ${token.name}`);
}
}
// Display task results
spinner.info(`Tokens Deployed`);
const results = getTaskResultsDisplay(taskResults);
console.log(results);
}
<file_sep>/src/types/types.ts
export interface FakeERC20Network {
tokens: Token[];
defaultMintAmount: string;
}
export interface Token {
name: string;
symbol: string;
defaultMintAmount?: string;
}
export interface InitialUserData {
userAddress: string;
initialBalance: string;
}
export interface TaskResults {
[k: string]: string;
}
<file_sep>/src/utils.ts
import "isomorphic-fetch";
import type { HardhatConfig } from "hardhat/types";
import type { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers";
import type { InitialUserData, TaskResults } from "./types/types";
export const TASK_NAME = "deploy-fake-erc20";
export const defaultSettings = {
tokens: [
{
name: "Fake ERC20 Token",
symbol: "FAKE",
},
],
defaultMintAmount: "1000000000000000000000",
};
/*
Checks to make sure that a local instance of HardHat node is running
*/
export async function checkLocalhostNetwork(config: HardhatConfig) {
//Make sure the "localhost" url is set so we can ping it
if (!config?.networks?.localhost?.url) {
throw new Error("No localhost URL");
}
// The JSON-RPC server run by the `hardhat node` task returns status=200 with an
// empty body when the server is sent a request with the method set to "OPTIONS"
// and refuses the connection if the server is not running
const response = await fetch(config.networks.localhost.url, {
method: "OPTIONS",
}).catch((err) => {
throw new Error(
"Can't find the HardHat local server. You must start the server using the `npx hardhat node` command."
);
});
if (response.status !== 200) {
throw new Error(
"Did not get the expected status from the local server"
);
}
return true;
}
/*
Format ETH accounts and initial mint balance object for the fake ERC20 contract
*/
export function getInitialUserData(
accounts: SignerWithAddress[],
initialMintAmount: string
): InitialUserData[] {
return accounts.map((account) => {
return {
userAddress: account.address,
initialBalance: initialMintAmount,
};
});
}
export function getTaskResultsDisplay(taskResults: TaskResults) {
let results = [
'Task Results\n',
'=========================\n',
];
Object.keys(taskResults).forEach((symbol) => {
results.push(`${symbol} - ${taskResults[symbol]}\n`);
});
return results.join('');
}
<file_sep>/test/task.test.ts
import chai, { expect } from "chai";
import chaiAsPromised from "chai-as-promised";
import { jestSnapshotPlugin } from "mocha-chai-jest-snapshot";
import sinon from "sinon";
import mute from "mute";
chai.use(chaiAsPromised);
chai.use(jestSnapshotPlugin());
import { useEnvironment } from "./helpers";
import * as utils from "../src/utils";
describe("Task", function () {
useEnvironment("full-config");
let getInitialUserDataSPY = sinon.spy(utils, "getInitialUserData");
let getTaskResultsDisplaySPY = sinon.spy(utils, "getTaskResultsDisplay");
afterEach(function () {
sinon.reset();
});
after(function () {
sinon.restore();
});
it("Task - Throws if local network not detected and exits", async function () {
let ethersGetSignersSPY = sinon.spy(this.hre.ethers, "getSigners");
let ethersContractFactorySPY = sinon.spy(
this.hre.ethers,
"ContractFactory"
);
await expect(this.hre.run(utils.TASK_NAME)).to.be.rejectedWith(Error);
// Expect the task to end so the following functions are not called
expect(ethersGetSignersSPY.called).to.equal(false);
expect(ethersContractFactorySPY.called).to.equal(false);
expect(getInitialUserDataSPY.called).to.equal(false);
});
it("Task - Task completes successfully", async function () {
const tokenNumber = this.hre.config.fakeERC20Network.tokens.length;
let ethersContractFactorySPY = sinon.spy(
this.hre.ethers,
"ContractFactory"
);
//Setup stubs and spies5
sinon.stub(console, "log");
const checkLocalhostNetworkSTUB = sinon
.stub(utils, "checkLocalhostNetwork")
.returns(Promise.resolve(true));
/*
Run task
Note: Using mute package to suppress the output from Ora.
Ora uses process.stderr.write instead of console.log.
*/
let unmute = mute();
await this.hre.run(utils.TASK_NAME).finally(unmute);
//Tests
expect(checkLocalhostNetworkSTUB.called).to.equal(true);
expect(ethersContractFactorySPY.called).to.equal(true);
expect(getInitialUserDataSPY.callCount).to.equal(tokenNumber);
expect(getTaskResultsDisplaySPY.calledOnce).to.equal(true);
expect(getTaskResultsDisplaySPY.firstCall.args[0]).toMatchSnapshot();
checkLocalhostNetworkSTUB.restore();
});
});
<file_sep>/test/test-projects/full-config/hardhat.config.ts
// We load the plugin here.
import { HardhatUserConfig } from "hardhat/types";
import "../../../src/index";
const config: HardhatUserConfig = {
solidity: "0.7.3",
fakeERC20Network: {
tokens: [
{
name: "Gold",
symbol: "GLD",
defaultMintAmount: "80000000000000000000",
},
{
name: "Silver",
symbol: "SLV",
defaultMintAmount: "600000000000000000000",
},
{
name: "Bronze",
symbol: "BRZ",
},
],
defaultMintAmount: "80000000000000000000",
},
};
export default config;
<file_sep>/src/index.ts
import { extendConfig, task } from "hardhat/config";
import "@nomiclabs/hardhat-ethers";
import { deployTokens } from "./tasks";
import { defaultSettings, TASK_NAME } from "./utils";
import "./types/type-extensions";
import type { HardhatConfig, HardhatUserConfig } from "hardhat/types";
extendConfig(
(config: HardhatConfig, userConfig: Readonly<HardhatUserConfig>) => {
//Merge default settings and userConfig for fakeERC20Network
config.fakeERC20Network = {
...defaultSettings,
...userConfig.fakeERC20Network
}
}
);
task(
TASK_NAME,
"Deploys fake ERC20 tokens to your localhost network"
).setAction(deployTokens);
<file_sep>/test/test-projects/partial-config-no-defaultMintAmount/hardhat.config.ts
// We load the plugin here.
import { HardhatUserConfig } from "hardhat/types";
import "../../../src/index";
const config: HardhatUserConfig = {
solidity: "0.7.3",
fakeERC20Network: {
tokens: [
{
name: "<NAME>",
symbol: "GOLD",
},
{
name: "<NAME>",
symbol: "SILVER",
},
],
},
};
export default config;
<file_sep>/hardhat.config.ts
/**
* @type import('hardhat/config').HardhatUserConfig
*/
import "./src/index";
import { HardhatUserConfig } from "hardhat/types";
const config: HardhatUserConfig = {
solidity: "0.8.0",
};
export default config;
<file_sep>/src/types/type-extensions.ts
import "hardhat/types/config";
import "hardhat/types/runtime";
import type { FakeERC20Network } from './types';
/*
Extends the HardhatConfig and HardhatUserConfig with the fakeERC20Network types
*/
declare module "hardhat/types/config" {
export interface HardhatConfig {
fakeERC20Network: FakeERC20Network
}
export interface HardhatUserConfig {
fakeERC20Network?: Partial<FakeERC20Network>
}
}
<file_sep>/test/helpers.ts
import path from "path";
import { resetHardhatContext } from "hardhat/plugins-testing";
import type{ HardhatRuntimeEnvironment } from "hardhat/types";
declare module "mocha" {
interface Context {
hre: HardhatRuntimeEnvironment;
}
}
export function useEnvironment(fixtureProjectName: string) {
beforeEach("Loading hardhat environment", function () {
process.chdir(
path.join(__dirname, "test-projects", fixtureProjectName)
);
this.hre = require("hardhat");
});
afterEach("Resetting hardhat", function () {
resetHardhatContext();
});
}
<file_sep>/test/utils.test.ts
// tslint:disable-next-line no-implicit-dependencies
import chai, { expect } from "chai";
import fetchMock from "fetch-mock";
import chaiAsPromised from "chai-as-promised";
import { jestSnapshotPlugin } from "mocha-chai-jest-snapshot";
chai.use(chaiAsPromised);
chai.use(jestSnapshotPlugin());
import { ethers } from "hardhat";
import { useEnvironment } from "./helpers";
import {
checkLocalhostNetwork,
getInitialUserData,
getTaskResultsDisplay,
} from "../src/utils";
describe("Utils - checkLocalhostNetwork", function () {
useEnvironment("no-config");
afterEach(() => {
fetchMock.reset();
});
it("Throws when localhost URL is falsey", async function () {
let config = { ...this.hre.config };
config.networks.localhost.url = "";
await expect(checkLocalhostNetwork(config)).to.be.rejectedWith(Error);
});
it("Throws when localhost URL is does not respond", async function () {
let config = { ...this.hre.config };
await expect(checkLocalhostNetwork(config)).to.be.rejectedWith(Error);
});
it("Throws when response from local server is not status 200", async function () {
let config = { ...this.hre.config };
fetchMock.mock(config.networks.localhost.url, 500);
await expect(checkLocalhostNetwork(config)).to.be.rejectedWith(Error);
});
it("Returns true if response from local server is status 200", async function () {
let config = { ...this.hre.config };
fetchMock.mock(config.networks.localhost.url, 200);
await expect(checkLocalhostNetwork(config)).to.eventually.equal(true);
});
});
describe("Utils - getInitialUserData", function () {
useEnvironment("no-config");
it("Returns an array of addresses and initialBalances", async function () {
let accounts = await ethers.getSigners();
const initialMint = "1000000";
const initialUsers = getInitialUserData(accounts, initialMint);
expect(initialUsers.length).to.equal(accounts.length);
expect(initialUsers[0].hasOwnProperty("userAddress")).to.equal(true);
expect(initialUsers[0].userAddress).to.equal(accounts[0].address);
expect(initialUsers[0].hasOwnProperty("initialBalance")).to.equal(true);
expect(initialUsers[0].initialBalance).to.equal(initialMint);
});
});
describe("Utils - displayTaskResults", function () {
useEnvironment("no-config");
it("The function should return string output", function () {
const taskResults = {
test1: "Success",
test2: "Failed",
};
const results = getTaskResultsDisplay(taskResults);
expect(results).toMatchSnapshot();
});
});
| bf2bfea54b27e600d2f1e2d115eb8d5df581d792 | [
"Markdown",
"TypeScript"
] | 14 | Markdown | foreignbyproxy/hardhat-fake-erc20-network | 7f659da1f6be74e1f11134e18b88e66fc9186903 | fe2e79c4cb866c2358d25dc09fc41b2d136941df |
refs/heads/master | <file_sep>int readEMF=A4;
String fiveSecData ="";
int data[1000]={};
void setup() {
pinMode(D7,OUTPUT);
pinMode(readEMF,INPUT);
Particle.function("funcKey", funcName);
Particle.variable("fiveSecData", fiveSecData);
}
void loop() {
}
int takeReading(){
int startTimer = 0;
int currentTime = 0;
startTimer = Time.second();
currentTime = Time.second();
if(startTimer>53){
delay(6000);
startTimer = Time.second();
}
digitalWrite(D7,HIGH);
for(int i=0;currentTime<=startTimer+6;i++) {
data[i]=analogRead(readEMF);
currentTime = Time.second();
}
arrayToString();
digitalWrite(D7,LOW);
return currentTime;
}
int funcName(String switch1) {
if(switch1=="HIGH"){
return takeReading();
}
return 777;
}
void arrayToString(){
String fiveSecData1="";
String fiveSecData2="";
String fiveSecData3="";
for(int c=0;c<100;c++){
fiveSecData1=fiveSecData1+","+String(data[c]);
}
for(int c=100;c<200;c++){
fiveSecData2=fiveSecData2+","+String(data[c]);
}
for(int c=200;c<300;c++){
fiveSecData3=fiveSecData3+","+String(data[c]);
}
fiveSecData=fiveSecData1;
Particle.publish("data1",fiveSecData , 1, PUBLIC);
fiveSecData=fiveSecData2;
Particle.publish("data2",fiveSecData , 1, PUBLIC);
fiveSecData=fiveSecData3;
Particle.publish("data3",fiveSecData , 1, PUBLIC);
}
<file_sep># HCIN720 Contributors
* <NAME>
* <NAME>
* <NAME>
* <NAME>
# Final Project Electromagnetic Sensing
# This Branch Contain following files
# Laser Cutting
lasercutting_belt.svg
# 3D Printing
shapr3d_export_2019-12-04_18h51m 2.stl
bodyWatch.stl
# Particle code
EMFReading.ino
# MATLAB code
trainClassifier[1].m
HCIN720[1].m
# Curcuit
cuircuitProoject.PNG
# instructable
https://www.instructables.com/id/Real-Time-Device-Recognition-Using-EM-Footprints/
| 49a41e74fae57d6d3c62b79f3ff1d2843dfdc861 | [
"Markdown",
"C++"
] | 2 | C++ | rahuljaiswalisIN/HCIN720 | 9e405a1eebe0d9e3fa3564926c25a075c3d61779 | d043966c7008660e4eda3417fabbc576844eac42 |
refs/heads/master | <repo_name>Olehkozyk/my-app<file_sep>/src/App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Navbar from "./components/Navbar/Navbar";
import Header from "./components/Header/Header";
import Profile from "./components/Profile/Profile";
import {BrowserRouter, Route} from "react-router-dom";
import DialogsContainer from "./components/Dialogs/DialogsContainer";
import Users from "./components/Users/Users";
function App() {
return (
<BrowserRouter>
<div className='app-wrapper'>
<Header />
<div className="app-wrapper__content">
<Navbar />
<div className='app-wrapper-content'>
<Route path='/dialogs' render={() => <DialogsContainer />} />
<Route path='/profile' render={() => <Profile />} />
<Route path='/users' render={() => <Users />} />
</div>
</div>
</div>
</BrowserRouter>
);
}
export default App;
<file_sep>/src/redux/store.js
import dialogsReducer from "./dialogs-reducer";
import profileReducer from "./profile-reducer";
import sidebarReducer from "./sidebar-reducer";
const UPDATE_NEW_MESS_BODY = 'UPDATE-MESSAGE';
const SEND_MESSAGE = 'SEND-MESSAGE';
let store = {
_state: {
dialogsPage: {
dialogs: [
{id: 1, name: 'Sasha'},
{id: 2, name: 'Mila'},
{id: 3, name: 'Oleh'},
{id: 4, name: 'Poc'},
{id: 5, name: 'ARa'},
],
messages: [
{id: 1, message: 'test1'},
{id: 2, message: 'test2'},
{id: 3, message: 'test3'},
{id: 4, message: 'test4'},
{id: 5, message: 'test5'},
],
newMessageTextBody: "",
},
},
getState() {
return this._state;
},
dispatch(action) {
this._state.profilePage = profileReducer(this._state.profilePage, action)
this._state.dialogsPage = dialogsReducer(this._state.dialogsPage, action)
this._state.sidebar = sidebarReducer(this._state.sidebar, action)
this._callSubscriber(this._state);
},
_callSubscriber() {
console.log('state-achnge');
},
subscribe(observer) {
this._callSubscriber = observer; //Patern watcher observer
}
}
export default store;
window.store = store;
//store - OOP<file_sep>/src/redux/profile-reducer.js
const UPDATE_POST = 'UPDATE-POST';
const ADD_POST = 'ADD-POST';
let initialState = {
posts: [
{id: 1, message: 'dfsadf'},
{id: 2, message: 'sds'},
{id: 3, message: '2'},
{id: 4, message: 'dfs3313adf'},
{id: 5, message: 'adada'},
],
newPostText: 'it-kam'
}
const profileReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_POST: {
let newPost = {
id: 5,
message: state.newPostText,
likeCount: 0,
}
return {
...state,
posts: [...state.posts, newPost],
newPostText: '',
}
}
case UPDATE_POST: {
return {
...state,
newPostText: action.newText,
};
}
default: {
return state;
}
}
}
export const addPostAction = () => ({type: 'ADD-POST'});
export const updatePost = (text) => ({type: 'UPDATE-POST', newText: text});
export default profileReducer;<file_sep>/src/components/Navbar/Navbar.jsx
import React, { Component } from 'react';
import {NavLink} from "react-router-dom";
import s from './Navbar.module.css';
const Navbar = () => {
return (
<nav className={s.nav}>
<NavLink to="/profile" activeClassName={s.active}>
Profile
</NavLink>
<NavLink to="/dialogs" activeClassName={s.active}>
Dialogs
</NavLink>
</nav>
)
}
export default Navbar;<file_sep>/src/redux/dialogs-reducer.js
const UPDATE_NEW_MESS_BODY = 'UPDATE-MESSAGE';
const SEND_MESSAGE = 'SEND-MESSAGE';
let initialState = {
dialogs: [
{id: 1, name: 'Sasha'},
{id: 2, name: 'Mila'},
{id: 3, name: 'Oleh'},
{id: 4, name: 'Poc'},
{id: 5, name: 'ARa'},
],
messages: [
{id: 1, message: 'test1'},
{id: 2, message: 'test2'},
{id: 3, message: 'test3'},
{id: 4, message: 'test4'},
{id: 5, message: 'test5'},
],
newMessageTextBody: "",
}
const dialogsReducer = (state = initialState, action) => {
switch (action.type) {
case UPDATE_NEW_MESS_BODY:
return {
...state,
newMessageTextBody: action.body
};
case SEND_MESSAGE :
let body = state.newMessageTextBody;
return {
...state,
newMessageTextBody: '',
messages: [...state.messages, {id: 6, message: body}],
};
default:
return state;
}
}
export const updateNewMessageBodyCreator = (body) => ({type: UPDATE_NEW_MESS_BODY, body: body});
export const sendMessageCreator = () => ({type: SEND_MESSAGE});
export default dialogsReducer;<file_sep>/src/components/Profile/ProfileInfo/ProfileInfo.jsx
import React from 'react';
import s from './ProfileInfo.module.css';
const ProfileInfo = () => {
return (
<div className={s.profileInfo}>
<h2>ProfileInfo</h2>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT3gOfZwbfKc6rdP8DNdHnS9GwFBRMO72vJaQ&usqp=CAU" alt=""/>
<div className={s.description}>
Info Profile
</div>
</div>
)
}
export default ProfileInfo;<file_sep>/src/components/Users/Users.jsx
import React from 'react';
let Users = (props) => {
return <div>dfsd</div>
}
export default Users;<file_sep>/src/components/Profile/MyPosts/Myposts.jsx
import React, { Component } from 'react';
import Post from '../Post';
const Myposts = (props) => {
let postsElements =
props.posts.map( p => <Post message={p.message} likeCount={p.likeCount}/>);
let newPostElement = React.createRef();
let onAddPost = () => {
props.addPost();
}
let onPostChange = () => {
let text = newPostElement.current.value;
props.updateNewPostText(text)
}
return (
<div>
My posts
<div>
<textarea ref={newPostElement} onChange={onPostChange} value={props.newPostText} />
<button onClick={onAddPost}>Add Post</button>
</div>
<div>
{postsElements}
</div>
</div>
)
}
export default Myposts;<file_sep>/src/components/Profile/Post.jsx
import React, { Component } from 'react';
const Post = (props) => {
return (
<div>
Post Message : {props.message}
Like: {props.likeCount}
</div>
)
}
export default Post; | 2e39aa7b346b849e5277278ea70b433b9ead9464 | [
"JavaScript"
] | 9 | JavaScript | Olehkozyk/my-app | 2f97cc27aa550db29c0aa6b8f86507dda023cb59 | 62004c0a4bac786556a48b4a56d3a0100e1f3fac |
refs/heads/master | <repo_name>firestrand/Automator<file_sep>/Automator/TaskRunner.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Automator
{
public class TaskRunner : ITaskRunner
{
public List<ITask> GetTaskList(ITaskContext taskContext)
{
throw new NotImplementedException();
}
public ITaskContext GetTaskContext()
{
throw new NotImplementedException();
}
public void ExecuteTasks()
{
throw new NotImplementedException();
}
}
}
<file_sep>/Automator/ITaskContext.cs
namespace Automator
{
public interface ITaskContext
{
}
}<file_sep>/Automator/ITaskRunner.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Automator
{
public interface ITaskRunner
{
List<ITask> GetTaskList(ITaskContext taskContext);
ITaskContext GetTaskContext();
void ExecuteTasks();
}
}
| 74ffbdad426f09153a4cf776c56d37427e7483bf | [
"C#"
] | 3 | C# | firestrand/Automator | b14173e4df82e1e4664bbd41351cb74e093c2ca9 | a3bfc429882ac86e4fc524cdcb8a160ce8637f5d |
refs/heads/master | <file_sep>/**
* COMP 410
*See inline comment descriptions for methods not described in interface.
*
*/
package LinkedList_A1;
public class LinkedListImpl implements LIST_Interface {
Node root;//this will be the entry point to your linked list (the head)
private int lstSize = 0;
public LinkedListImpl(){//this constructor is needed for testing purposes. Please don't modify!
root=new Node(0); //Note that the root's data is not a true part of your data set!
}
//implement all methods in interface, and include the getRoot method we made for testing purposes. Feel free to implement private helper methods!
public boolean insert(Node n, int index) {
Node p;
//insert the node from index = 0
if (index > size() || index < 0) {
return false;
}
//get the node p at 'index-1'
if (index == 0) {
p = getRoot();
} else {
p = get(index - 1);
}
if (index == size()) { //add a node at the end of the linked list
n.prev = p;
p.next = n;
}else { //insert a node in the middle of the linked list
n.prev = p;
n.next = p.next;
p.next.prev = n;
p.next = n;
}
lstSize ++;
return true;
}
public boolean remove(int index) {
//do not allow to remove the root
if (index >= size() || index < 0) {
return false;
}
//get the node p at 'index'
Node p = get(index);
if (index == size()-1) { //remove a node at the end
p.prev.next = null;
} else { //remove a node in the middle
p.prev.next = p.next;
p.next.prev = p.prev;
}
lstSize --;
return true;
}
public Node get(int index) {
Node p = root;
//do not allow to get index = -1, it is hided
if (index > size() || index < 0) {
return null;
}
for (int i = 0; i < index + 1; i++) {
p = p.next;
}
return p;
}
public int size() {
return lstSize;
}
public boolean isEmpty() {
return (size() == 0);
}
public void clear() {
root.next = null;
lstSize = 0;
}
public Node getRoot(){ //leave this method as is, used by the grader to grab your linkedList easily.
return root;
}
}
<file_sep># ADT-Implementation-in-JAVA
The package includes the implementation of some basic ADTs in Java. Check here for the detailed requirements: http://www.cs.unc.edu/~stotts/COMP410-s17/assn.html
1. Double linked list
2. Binary search tree
3. Minimum binary heap
4. Splay tree
5. Basic Directed graph with topological sort
6. Dijkstra's Single Source Shortest Path Algorithm
<file_sep>package SPLT_A4;
public class SPLT implements SPLT_Interface{
private BST_Node root;
private int size;
public SPLT() {
this.size = 0;
}
public void insert(String s) {
if (size == 0) {
root = new BST_Node(s);
size ++;
return;
}
root = root.insertNode(s);
if (root.justMade) {
size ++;
}
}
public void remove(String s) {
if (size == 0) {
return;
}
if (!contains(s)) {
return;
}
if (size == 1) {
root = null;
size --;
return;
}
BST_Node rChild = root.right;
if (root.left != null && rChild != null) {
root = root.left.findMax();
root.right = rChild;
rChild.par = root;
} else if (root.left == null && rChild != null) {
root = root.right;
root.par = null;
} else if (root.left != null && rChild == null) {
root = root.left;
root.par = null;
}
size --;
}
public String findMin() {
if (size == 0) {
return null;
} else {
root = root.findMin();
return root.data;
}
}
public String findMax() {
if (size == 0) {
return null;
} else {
root = root.findMax();
return root.data;
}
}
public boolean empty() {
return (size == 0)? true:false;
}
public boolean contains(String s) {
if (size == 0) return false;
root = root.containsNode(s);
if (root.data.compareTo(s) == 0) {
return true;
} else return false;
}
public int size() {
return size;
}
public int height(){
return (size == 0)? -1:root.getHeight();
}
public BST_Node getRoot() { //please keep this in here! I need your root node to test your tree!
return root;
}
}
<file_sep>package SPLT_A4;
public class BST_Node {
String data;
BST_Node left;
BST_Node right;
BST_Node par; //parent...not necessarily required, but can be useful in splay tree
boolean justMade; //could be helpful if you change some of the return types on your BST_Node insert.
//I personally use it to indicate to my SPLT insert whether or not we increment size.
BST_Node(String data){
this.data=data;
this.justMade=true;
}
BST_Node(String data, BST_Node left,BST_Node right,BST_Node par){ //feel free to modify this constructor to suit your needs
this.data=data;
this.left=left;
this.right=right;
this.par=par;
this.justMade=true;
}
// --- used for testing ----------------------------------------------
//
// leave these 3 methods in, as is (meaning also make sure they do in fact return data,left,right respectively)
public String getData(){ return data; }
public BST_Node getLeft(){ return left; }
public BST_Node getRight(){ return right; }
// --- end used for testing -------------------------------------------
// --- Some example methods that could be helpful ------------------------------------------
//
// add the meat of correct implementation logic to them if you wish
// you MAY change the signatures if you wish...names too (we will not grade on delegation for this assignment)
// make them take more or different parameters
// have them return different types
//
// you may use recursive or iterative implementations
public BST_Node containsNode(String s) {
BST_Node tree = this;
BST_Node pTree = null;
while (tree != null) {
pTree = tree;
if (tree.data.compareTo(s) > 0) {
tree = tree.left;
} else if (tree.data.compareTo(s) < 0) {
tree = tree.right;
} else {
splay(tree);
return tree;
}
}
splay(pTree);
return pTree;
}
public BST_Node insertNode(String s) {
BST_Node tree = this;
BST_Node pTree = null;
while (tree != null) {
pTree = tree;
if (tree.data.compareTo(s) > 0) {
tree = tree.left;
} else if (tree.data.compareTo(s) < 0) {
tree = tree.right;
} else { //if the tree contains s
splay(tree);
tree.justMade = false;
return tree;
}
}
tree = new BST_Node(s);
tree.par = pTree;
if (pTree.data.compareTo(s) < 0) {
pTree.right = tree;
} else pTree.left = tree;
splay(tree);
tree.justMade = true;
return tree;
}
/*public boolean removeNode(String s) {
return false;
}*/
public BST_Node findMin() {
BST_Node tree = this;
if (tree != null) {
while (tree.left != null)
tree = tree.left;
}
splay(tree);
return tree;
}
public BST_Node findMax() {
BST_Node tree = this;
if (tree != null) {
while (tree.right != null)
tree = tree.right;
}
splay(tree);
return tree;
}
public int getHeight() {
return 1 + Math.max((left != null)? left.getHeight():-1, (right != null)? right.getHeight():-1);
}
private void splay(BST_Node toSplay) {
while (toSplay.par != null) {
if (toSplay.par.right == toSplay) {
rotateRight(toSplay);
} else if (toSplay.par.left == toSplay) {
rotateLeft(toSplay);
}
}
} //you could have this return or take in whatever you want..so long as it will do the job internally. As a caller of SPLT functions, I should really have no idea if you are "splaying or not"
//I of course, will be checking with tests and by eye to make sure you are indeed splaying
//Pro tip: Making individual methods for rotateLeft and rotateRight might be a good idea!
// --- end example methods --------------------------------------
private void rotateLeft(BST_Node splayLeft) {
if (splayLeft.par != null && splayLeft.par.par == null) {
splayLeft.par.left = splayLeft.right;
splayLeft.par.par = splayLeft;
if (splayLeft.right != null) {
splayLeft.right.par = splayLeft.par;
}
splayLeft.right = splayLeft.par;
splayLeft.par = null;
} else if (splayLeft.par != null && splayLeft.par.par.left == splayLeft.par) {
BST_Node tree = splayLeft;
while (tree.par != null && tree == tree.par.left) {
tree.par.left = tree.right;
if (tree.right != null) {
tree.right.par = tree.par;
}
tree.right = tree.par;
tree = tree.par;
}
if (tree.par != null) {
splayLeft.par = tree.par;
tree.par.right = splayLeft;
} else {
splayLeft.par = null;
}
for (BST_Node ptree = splayLeft; ptree != tree; ptree = ptree.right) {
ptree.right.par = ptree;
}
} else if (splayLeft.par != null && splayLeft.par.par.right == splayLeft.par) {
splayLeft.par.left = splayLeft.right;
if (splayLeft.right != null) {
splayLeft.right.par = splayLeft.par;
}
splayLeft.right = splayLeft.par;
splayLeft.par.par.right = splayLeft.left;
if (splayLeft.left != null) {
splayLeft.left.par = splayLeft.par.par;
}
splayLeft.left = splayLeft.par.par;
if (splayLeft.par.par.par != null) {
if (splayLeft.par.par.par.right == splayLeft.par.par) {
splayLeft.par.par.par.right = splayLeft;
} else {
splayLeft.par.par.par.left = splayLeft;
}
}
splayLeft.par = splayLeft.par.par.par;
splayLeft.right.par = splayLeft;
splayLeft.left.par = splayLeft;
}
}
private void rotateRight(BST_Node splayRight) {
if (splayRight.par != null && splayRight.par.par == null) {
splayRight.par.right = splayRight.left;
splayRight.par.par = splayRight;
if (splayRight.left != null) {
splayRight.left.par = splayRight.par;
}
splayRight.left = splayRight.par;
splayRight.par = null;
} else if (splayRight.par != null && splayRight.par.par.right == splayRight.par) {
BST_Node tree = splayRight;
while (tree.par != null && tree == tree.par.right) {
tree.par.right = tree.left;
if (tree.left != null) {
tree.left.par = tree.par;
}
tree.left = tree.par;
tree = tree.par;
}
if (tree.par != null) {
splayRight.par = tree.par;
tree.par.left = splayRight;
} else {
splayRight.par = null;
}
for (BST_Node ptree = splayRight; ptree != tree; ptree = ptree.left) {
ptree.left.par = ptree;
}
} else if (splayRight.par != null && splayRight.par.par.left == splayRight.par) {
splayRight.par.right = splayRight.left;
if (splayRight.left != null) {
splayRight.left.par = splayRight.par;
}
splayRight.left = splayRight.par;
splayRight.par.par.left = splayRight.right;
if (splayRight.right != null) {
splayRight.right.par = splayRight.par.par;
}
splayRight.right = splayRight.par.par;
if (splayRight.par.par.par != null) {
if (splayRight.par.par.par.left == splayRight.par.par) {
splayRight.par.par.par.left = splayRight;
} else {
splayRight.par.par.par.right = splayRight;
}
}
splayRight.par = splayRight.par.par.par;
splayRight.left.par = splayRight;
splayRight.right.par = splayRight;
}
}
}
| 9ddf7b402f7c45e7b5dcf8a377168b0b6c233126 | [
"Markdown",
"Java"
] | 4 | Java | wanchen6/ADT-Implementation-in-JAVA | 42051e07ebd44f3e555ccc6ec5c7d3b7078a5fee | a299fd8c0be92a184699f9ff8b1b8adc315df1a9 |
refs/heads/master | <file_sep>#!/bin/bash
## Author: <NAME>
## Monitoring: Grob4Interface
## Date: 17/08/2018
## Description: This script is used to extract Datas from Runtimeinfo Service
## AIM: Felexibility of the Json Check
## HowTo: curl and JQ and grep are now my friends
## Timeout of curl: 25 sec --> doit etre dans nagios en tant que unknown
## NOTES - The syntaxe: In this bash script
### --> The comparison of Decimals must be done with > < and NOT -gt -le
### --> The conditions if must be between [[]] and not (())
### --> The syntaxe of JQ is tricky: Be so attentive to every small detail
# START
UNKNOWN_STATE=3
CRITICAL_STATE=2
WARNING_STATE=1
OK_STATE=0
categoryName="DiskInfo"
while getopts H:N:W:C: option
do
case "${option}"
in
H) Host=${OPTARG};;
#I) instanceName=${OPTARG};;
N) counterName=${OPTARG};;
W) warning=${OPTARG};;
C) critical=${OPTARG};;
esac
done
mainJson=`(curl --silent $Host:12084/runtimeinformation.json --connect-timeout 25 | jq -r ".[] | .performanceCounterValues[] | select ((.categoryName==\"$categoryName\") and (.counterName==\"$counterName\")) ")`
Json=`(curl --silent $Host:12084/runtimeinformation.json --connect-timeout 25 | jq -r ".[] | .performanceCounterValues[] | select (.categoryName==\"$categoryName\")")`
#Partitionvalue=$(echo "$(echo "$mainJson" | jq -r '. | [.instanceName, .value] ')")
#echo "The value of different partitions: $Partitionvalue"
#echo " MORE DETAILS ABOUT DISKINFO: $mainJson"
result=$(
Drives=$(echo "$(echo $Json | jq -c '. | select (.counterName | contains("% Free Space")) | .instanceName')")
echo "The available disk partitions on this Interface-VM are: \n $Drives \n"
#Convert the output to an array
Partition=(${Drives})
len=${#Partition[@]}
for (( i=0; i < $len; i++ ));
do
value=$(echo "$mainJson" | jq -r " select (.instanceName==${Partition[i]}) | .value")
if [[ "$counterName" == "% Free Space" ]]
then
if (( $(echo "$value <= $critical" | bc -l) ))
then echo "Status CRITICAL - The Free space value of ${Partition[i]} Drive is: $value% \n Note: The Thersholds are [Warning=$warning% : Critical=$critical%] \n"
elif (( $(echo "$value <= $warning" | bc -l) )) && (( $(echo "$value > $critical" | bc -l) ))
then echo "Status WARNING - The Free space value of ${Partition[i]} Drive is: $value% \n Note: The Thersholds are [Warning=$warning% : Critical=$critical%] \n"
elif (( $(echo "$value > $warning" | bc -l) ))
then
echo "Status OK - The Free space value of ${Partition[i]} Drive is: $value% \n Note: The Thersholds are [Warning=$warning% : Critical=$critical%] \n"
else echo "Status UNKNOWN - Unable to determine the value of $counterName \n"
fi
elif [[ "$counterName" == "TotalSize" ]] || [[ "$counterName" == "TotalFreeSpace" ]]
then
echo "Status OK - The value of ${Partition[i]} Drive is: $value \n Note: There is NO Thersholds \n"
else
echo "Status UNKNOWN - Unable to determine the value of $counterName"
fi
done
# To extract the performance Data from the output message
for (( i=0; i < $len; i++ ));
do
value=$(echo "$mainJson" | jq -r " select (.instanceName==${Partition[i]}) | .value")
perf="|${Partition[i]}=${value};${warning};${critical};"
perf2="|${Partition[i]}=${value};${value};${value};"
if [[ "$counterName" == "% Free Space" ]]
then
echo $perf
else
echo $perf2
fi
done
)
echo "RuntimeInfo Part: \n $mainJson \n "
#Clever
if echo $result | grep CRITICAL; then
exit ${CRITICAL_STATE}
fi
if echo $result | grep WARNING; then
exit ${WARNING_STATE}
fi
if echo $result | grep UNKNOWN; then
exit ${UNKNOWN_STATE}
fi
if echo $result | grep OK; then
exit ${OK_STATE}
fi
## Info: for Performance data in Icinga: echo "blabla| $i=${res};${WARNSERVICE};${CRITSERVICE};"
<file_sep>#!/bin/bash
###
## Author: <NAME>
## Monitoring: Grob4Interface
## Date: 17/08/2018
## Description: This script is used to extract Datas from Runtimeinfo Service
## AIM: Felexibility of the Json Check
## HowTo: curl and JQ and grep are now my friends
## Timeout of curl: 25 sec --> doit etre dans nagios en tant que unknown
## NOTES - The syntaxe: In this bash script
### --> The syntaxe of JQ is tricky: Be so attentive to every small detail
# START
UNKNOWN_STATE=3
CRITICAL_STATE=2
WARNING_STATE=1
OK_STATE=0
categoryName="DiskInfo"
while getopts H:N:W:C: option
do
case "${option}"
in
H) Host=${OPTARG};;
#I) instanceName=${OPTARG};;
N) counterName=${OPTARG};;
W) warning=${OPTARG};;
C) critical=${OPTARG};;
esac
done
mainJson=`(curl --silent $Host:12084/runtimeinformation.json --connect-timeout 25 | jq -r ".[] | .performanceCounterValues[] | select ((.categoryName==\"$categoryName\") and (.counterName==\"$counterName\")) ")`
Json=`(curl --silent $Host:12084/runtimeinformation.json --connect-timeout 25 | jq -r ".[] | .performanceCounterValues[] | select (.categoryName==\"$categoryName\")")`
#Partitionvalue=$(echo "$(echo "$mainJson" | jq -r '. | [.instanceName, .value] ')")
#echo "The value of different partitions: $Partitionvalue"
#echo " MORE DETAILS ABOUT DISKINFO: $mainJson"
result=$(
Drives=$(echo "$(echo $Json | jq -c '. | select (.counterName | contains("% Free Space")) | .instanceName')")
echo "The available disk partitions on this Interface-VM are: \n $Drives \n"
#Convert the output to an array
Partition=(${Drives})
len=${#Partition[@]}
for (( i=0; i < $len; i++ ));
do
value=$(echo "$mainJson" | jq -r " select (.instanceName==${Partition[i]}) | .value")
if [[ "$counterName" == "% Free Space" ]]
then
if (( $(echo "$value <= $critical" | bc -l) ))
then echo "Status CRITICAL - The Free space value of ${Partition[i]} Drive is: $value% \n Note: The Thersholds are [Warning=$warning% : Critical=$critical%] \n"
elif (( $(echo "$value <= $warning" | bc -l) )) && (( $(echo "$value > $critical" | bc -l) ))
then echo "Status WARNING - The Free space value of ${Partition[i]} Drive is: $value% \n Note: The Thersholds are [Warning=$warning% : Critical=$critical%] \n"
elif (( $(echo "$value > $warning" | bc -l) ))
then echo "Status OK - The Free space value of ${Partition[i]} Drive is: $value% \n Note: The Thersholds are [Warning=$warning% : Critical=$critical%] \n"
else echo "Status UNKNOWN - Unable to determine the value of $counterName \n"
fi
elif [[ "$counterName" == "TotalSize" ]] || [[ "$counterName" == "TotalFreeSpace" ]]
then echo "Status OK - The value of ${Partition[i]} Drive is: $value \n Note: There is NO Thersholds \n"
else echo "Status UNKNOWN - Unable to determine the value of $counterName"
fi
done
# To extract the performance Data from the output message
for (( i=0; i < $len; i++ ));
do
value=$(echo "$mainJson" | jq -r " select (.instanceName==${Partition[i]}) | .value")
perf="|${Partition[i]}=${value};${warning};${critical};"
perf2="|${Partition[i]}=${value};${value};${value};"
if [[ "$counterName" == "% Free Space" ]]
then
echo $perf
else
echo $perf2
fi
done
)
# The main Runtimeinfo Part: in this script the main info is Disk info. Another script can contain another category name.
echo ´"RuntimeInfo Part: \n $mainJson \n "
#Clever
if echo $result | grep CRITICAL; then
exit ${CRITICAL_STATE}
fi
if echo $result | grep WARNING; then
exit ${WARNING_STATE}
fi
if echo $result | grep UNKNOWN; then
exit ${UNKNOWN_STATE}
fi
if echo $result | grep OK; then
exit ${OK_STATE}
fi
## Done!
| 449c4d00ef9c3e0bdb5df824bc7bc1ff846398d7 | [
"Shell"
] | 2 | Shell | HmZ111/Di-a-monds | d4882de228b8096eba9f443a7cbafdddd689db6b | bb6e4e9701492b9c4125df021a39d95fb89bf61c |
refs/heads/master | <file_sep>*Italic star.*<file_sep>List 1
1. Item 1
1. Item 2
1. Item 3
1. Item 4
List 2
1. Item 1
1. Item 1a
1. Item 1a1
1. Item 1a1a
List 3
1. Item 1
1. Item 1a
1. Item 1b
1. Item 1b1
1. Item 1b2
1. Item 1b2a
1. Item 1b2b
List 4
1. Item 1
1. Item 2
1. Item 3<file_sep>~~Strike though.~~<file_sep># Markplus
> Partial GFM Markdown renderer with built-in syntax highlighting
## Installation
```shell
npm install markplus
```
## Render
Renders a string of Markdown content.
```javascript
const markplus = require('markplus')
const html = markplus.render('# Heading 1')
// html = '<h1>Heading 1</h1>'
```
## Settings
Settings is the second argument passed to the Markdown renderer.
Settings is a JavaScript object.
```javascript
const content = '## Heading 1'
const settings = {
// Your settings here
}
const html = markplus(content, settings)
```
## Render From
Start the rendering from a specific from-point.
The from-point is defined by markdown syntax, eg: `## Heading 2`.
The start-point is located via a regex string search. Thefore only part of Markdown content is processed internally. This is to increase performance.
```javascript
const html = markplus.render(content, {
from: '## Heading 2'
})
```
Example:
```javascript
const markplus = require('markplus')
const content = '
# Heading 1
> Block quote
## Heading 2
This is a paragraph.
'
const html = markplus.render('## Heading 2', {
from: '## Heading 2'
})
```
Output:
```html
<h2>Heading 2</h1>
<p>This is a paragraph.</p>
```
## Render To
End the rendering before a specific to-point.
The to-point is defined by markdown syntax, eg: `## Heading 2`.
Important: The renderer outputs content **before** the to-point, but does not include the to-point itself.
The to-point is located via a regex string search. Thefore only part of Markdown content is processed internally. This is to increase performance.
```javascript
const html = markplus.render(content, {
to: '## Heading 2'
})
```
Example:
```javascript
const markplus = require('markplus')
const content = '
# Heading 1
> Block quote
## Heading 2
This is a paragraph.
'
const html = markplus.render('## Heading 2', {
to: '## Heading 2'
})
```
Output:
```html
<h1>Heading 2</h1>
<p>This is a paragraph.</p>
```
<file_sep>import path from 'path'
import test from 'ava'
import parser from './parser'
test('loadFile: throws non-existent file', async t => {
await t.throws(parser.loadFile('non-existent.md'))
})
test('loadFile: loads file contents', async t => {
const filepath = path.join(__dirname, 'mock', 'heading-1.md')
const contents = await parser.loadFile(filepath)
t.is(contents, '# Heading 1')
})
test('parse: trims leading whitespace', t => {
const html = parser.parse(' # heading 1\n ## heading 2')
t.is(html, '<h1>heading 1</h1>\n<h2>heading 2</h2>')
})
test('parse: should render mixed markdown and html', t => {
const html = parser.parse('# Heading 1\n<div>This is not markdown.</div>\n## Heading 2')
t.is(html, '<h1>Heading 1</h1>\n<div>This is not markdown.</div>\n<h2>Heading 2</h2>')
})
test('parse: lines w/o leading html or md chars are <p>\'s', t => {
const html = parser.parse('# Heading 1\nThis is a paragraph.\n## Heading 2')
t.is(html, '<h1>Heading 1</h1>\n<p>This is a paragraph.</p>\n<h2>Heading 2</h2>')
})
// Headings
test('syntax.h1: "# h1" to <h1>h1<h1>', t => {
const html = parser.syntaxRenderers.h1('# h1')
t.is(html, '<h1>h1</h1>')
})
test('syntax.h1: "# h1" to <h1>h1<h1>', t => {
const html = parser.syntaxRenderers.h1('# h1')
t.is(html, '<h1>h1</h1>')
})
test('syntax.h2: "## h2" to <h2>H2<h2>', t => {
const html = parser.syntaxRenderers.h2('## H2')
t.is(html, '<h2>H2</h2>')
})
test('syntax.h2: "## h2" to <h2>h2<h2>', t => {
const html = parser.syntaxRenderers.h2('## h2')
t.is(html, '<h2>h2</h2>')
})
test('syntax.h3: "### h3" to <h3>h3<h3>', t => {
const html = parser.syntaxRenderers.h3('### h3')
t.is(html, '<h3>h3</h3>')
})
test('syntax.h3: "### h3" to <h3>h3<h3>', t => {
const html = parser.syntaxRenderers.h3('### h3')
t.is(html, '<h3>h3</h3>')
})
test('syntax.h4: "#### h4" to <h4>h4<h4>', t => {
const html = parser.syntaxRenderers.h4('#### h4')
t.is(html, '<h4>h4</h4>')
})
test('syntax.h4: "#### h4" to <h4>h4<h4>', t => {
const html = parser.syntaxRenderers.h4('#### h4')
t.is(html, '<h4>h4</h4>')
})
test('syntax.h5: "##### h5" to <h5>h5<h5>', t => {
const html = parser.syntaxRenderers.h5('##### h5')
t.is(html, '<h5>h5</h5>')
})
test('syntax.h5: "##### h5" to <h5>h5<h5>', t => {
const html = parser.syntaxRenderers.h5('##### h5')
t.is(html, '<h5>h5</h5>')
})
test('syntax.h6: "###### h6" to <h6>h6<h6>', t => {
const html = parser.syntaxRenderers.h6('###### h6')
t.is(html, '<h6>h6</h6>')
})
test('syntax.h6: "###### h6" to <h6>h6<h6>', t => {
const html = parser.syntaxRenderers.h6('###### h6')
t.is(html, '<h6>h6</h6>')
})
test('syntax.h1-6 renderes all correct html headings', t => {
const html = parser.parse('# h1\n## h2\n### h3\n#### h4\n##### h5\n###### h6')
t.is(html, '<h1>h1</h1>\n<h2>h2</h2>\n<h3>h3</h3>\n<h4>h4</h4>\n<h5>h5</h5>\n<h6>h6</h6>')
})
<file_sep># Spec
## Headers
```markdown
# Heading 1
```
```html
<h1>Heading 1</h1>
```
`## Heading 2`
`### Heading 3`
`#### Heading 4`
`##### Heading 5`
`###### Heading 6`
- Unordered Lists
+ [ ] `- Item 1`
+ [ ] `+ Item 1`
+ [ ] `* Item 1`
+ [ ] ` - Item 1a` (any depth)
- Ordered Lists
+ [ ] `1. Item 1`
+ [ ] `1. Item 1\n * Item 1a`
+ [ ] `1. Item 1\n * Item 1a` (any depth)
1. Item 1
1. Item 1a
1. Item 1b
1. Item 1c
- Item 1d
- Item 1d
- Item 1d<file_sep>__Bold _italic_ underscores.__
**Bold *italic* stars.**
**Bold stars _italic underscore_.**
__Bold underscores *italic star*.__<file_sep>**Bold double star.**<file_sep>const fs = require('fs')
const Promise = require('bluebird')
const parser = {}
parser.syntaxRenderers = {
h1: line => {
const content = line.substr(1).trim()
return `<h1>${content}</h1>`
},
h2: line => {
const content = line.substr(2).trim()
return `<h2>${content}</h2>`
},
h3: line => {
const content = line.substr(3).trim()
return `<h3>${content}</h3>`
},
h4: line => {
const content = line.substr(4).trim()
return `<h4>${content}</h4>`
},
h5: line => {
const content = line.substr(5).trim()
return `<h5>${content}</h5>`
},
h6: line => {
const content = line.substr(6).trim()
return `<h6>${content}</h6>`
},
html: line => line,
p: line => `<p>${line}</p>`
}
parser.syntaxChecks = {
h1: line => {
return line.substr(0, 2) === '# '
},
h2: line => {
return line.substr(0, 3) === '## '
},
h3: line => {
return line.substr(0, 4) === '### '
},
h4: line => {
return line.substr(0, 5) === '#### '
},
h5: line => {
return line.substr(0, 6) === '##### '
},
h6: line => {
return line.substr(0, 7) === '###### '
},
html: line => {
return (line.substr(0, 1) === '<') &&
(line[1] !== ' ')
},
p: line => {
return (line.substr(0, 1) !== '<')
}
}
parser.checkSyntax = line => {
let type = null
Reflect.ownKeys(parser.syntaxChecks).some(name => {
const checker = parser.syntaxChecks[name]
const foundType = checker(line)
if (foundType) {
type = name
// Exit some-loop
return true
}
// Continue some-loop
return null
})
return type
}
parser.loadFile = uri => new Promise((resolve, reject) => {
fs.readFile(uri, 'utf8', (err, data) => {
if (err) {
return reject(err)
}
resolve(data)
})
})
parser.parse = content => {
const lines = content.split('\n').map(line => {
line = line.trim()
const type = parser.checkSyntax(line)
const renderer = parser.syntaxRenderers[type]
const rendered = renderer(line)
return rendered
})
const html = lines.join('\n')
return html
}
module.exports = parser
<file_sep>- Item 1
- Item 2
- Item 3
- Item 1
- Item 1a
- Item 1b
- Item 2
- Item 2a
- Item 2b
- Item 3
- Item 4
- Item 1
- Item 1a
- Item 1a1
- Item 1a1a
- Item 1a1a1
- Item 1a1a1a
- Item 1
+ Item 1a
* Item 1b<file_sep>const fs = require('fs')
const path = require('path')
const markdown = require('markdown').markdown
const files = fs.readdirSync('./input')
files.forEach(file => {
const ext = path.parse(file).ext
if (ext === '.md') {
fileContents = String(fs.readFileSync('./input/' + file))
const html = markdown.toHTML(fileContents)
const name = path.parse(file).name
fs.writeFileSync('./output/' + name + '.html', html)
}
})<file_sep>List 1
1. Item 1
1. Item 2
- Item 2a
- Item 2b
List 2
1. Item 1
- Item 1a
1. Item 1a1
- Item 1a1a
1. Item 1a1
- Item 1a1
List 3
- Item 1
1. Item 1a
- Item 1a1
1. Item 1a1a
- Item 1a1
<file_sep>> This is a blockquote.
> This is a multi-line
> blockquote.
> This is not a multi-line
> Blockquote | 38a6fbdadae018eb1427e42d231be7492e4958f7 | [
"Markdown",
"JavaScript"
] | 13 | Markdown | minkjs/markdown-renderer | 0713da156e12be71acd905e537b2abb7086411af | 8b2be6e4c5a5fe281ad1bfb3af71b5854ccc2f3f |
refs/heads/master | <repo_name>katat/backbone-test<file_sep>/apps/test/templates/condition.html
<h1 style="text-align:center">{{name}}</h1>
<h3>Treatments :</h3>
<div class="panel-group" id="accordion">
{{#each treatments}}
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#{{@key}}">
{{display_name}}
</a>
</h4>
</div>
<div id="{{@key}}" class="panel-collapse collapse">
<div class="panel-body">
{{description}}
</div>
</div>
</div>
{{/each}}
</div><file_sep>/apps/test/views/condition.js
define([
'backbone',
'apps/test/models',
'handlebars',
'text!apps/test/templates/condition.html',
'bootstrap'
], function (Backbone, Models, Handlebars, tpl) {
var ConditionView = Backbone.View.extend({
template: Handlebars.compile(tpl),
render: function () {
this.$el.html(this.template(this.model.toJSON()));
this.$el.find('#accordion').collapse();
return this;
}
});
return ConditionView;
});<file_sep>/apps/test/views/main.js
define([
'backbone',
'handlebars',
'text!apps/test/templates/main.html'
], function (Backbone, Handlebars, tpl) {
var MainView = Backbone.View.extend({
template: Handlebars.compile(tpl),
render: function () {
this.$el.html(this.template({}));
return this;
}
});
return MainView;
});<file_sep>/require.main.js
require.config({
waitSeconds: 200,
shim: {
underscore: { exports: '_' },
jquery: { exports: '$' },
backbone: {
deps: [
'underscore',
'jquery'
],
exports: 'Backbone'
},
handlebars: { exports: 'Handlebars' },
bootstrap: { deps: ['jquery'] }
},
paths: {
jquery: 'lib/jquery',
bootstrap: 'lib/bootstrap/dist/js/bootstrap',
underscore: 'lib/underscore',
backbone: 'lib/backbone',
text: 'lib/text',
handlebars: 'lib/handlebars'
}
});
require([
'backbone',
'jquery',
'handlebars',
'apps/test/models',
'apps/test/views/main',
'apps/test/views/condition'
], function (Backbone, $, Handlebars, Models, MainView, ConditionView) {
var AppRouter = Backbone.Router.extend({
routes: {
'': 'showMainView',
'/slug/': 'showConditionView'
},
initialize: function () {
this.bind('all', this.changeRoute);
},
changeRoute: function () {
},
showMainView: function () {
var mainView = new MainView();
$('body').html(mainView.render().el);
},
showConditionView: function () {
var models = new Models();
models.fetch({
success: function () {
console.log(models.toJSON());
var conditionView = new ConditionView({ model: models });
$('body').html(conditionView.render().el);
}
});
}
});
var app = new AppRouter();
Backbone.history.start();
Backbone.app = app;
}); | 283fa535e625c9605be8c0e94c13acc47821bc26 | [
"JavaScript",
"HTML"
] | 4 | HTML | katat/backbone-test | f359132297b6d9909bd22cc754a267defe16fd3e | 10bf23f653dd59b2cf7a34de79ef1c2f7bbb101e |
refs/heads/master | <repo_name>GBOLUTS/Minesweeper<file_sep>/src/com/company/Buttons.java
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import static java.awt.event.MouseEvent.BUTTON1;
/**
* Created by Гена on 22.04.17.
*/
public class Buttons extends JButton {
ArrayList<JButton> listOfButtons = new ArrayList<JButton>();
//Метод открытия соседних клеток
public void pressAdjButtons (String command, ArrayList<JButton> list){
int pos = Integer.parseInt(command) + 1;
ArrayList <Integer> numberOfAdjFields = GameField.findNumbersOfAdjFields(pos,GameField.NUMBER_X,GameField.NUMBER_Y);
for (int i = 0; i < numberOfAdjFields.size(); i++) {//Уменьшил все позиции на 1, чтобы получить комманды
int posit = numberOfAdjFields.get(i);
numberOfAdjFields.set(i, posit - 1);
}
for (int i = 0; i < list.size(); i++) {
String commandOfButton = list.get(i).getActionCommand();
if (!commandOfButton.equals("X")){
int numberOfCommand = Integer.parseInt(commandOfButton);
if (numberOfAdjFields.contains(numberOfCommand)){
list.get(i);
}
}
}
}
public void openAllFields (){
for (int i = 0; i < listOfButtons.size(); i++) {
String commandOfText = listOfButtons.get(i).getActionCommand();
String text = GameField.field.get(Integer.parseInt(commandOfText));
listOfButtons.get(i).setText(text);
listOfButtons.get(i).setForeground(Color.BLACK);
}
}
public void whenYouLose(){
openAllFields();
JOptionPane.showMessageDialog(null, "Вы проиграли!", "Сожалеем, Вы проиграли!", JOptionPane.WARNING_MESSAGE);
}
public void checkWin(){//Условие победы (либо открыты все без мин, либо правильно расставлены мины (и нет лишних))
int numberOfAllNotMined = GameField.NUMBER_X*GameField.NUMBER_Y - GameField.NUMBER_OF_MINES;
if ((GameField.NUMBER_OF_OPEN_FIELDS>=numberOfAllNotMined)||((GameField.NUMBER_OF_WRONG_MINES == 0)&&(GameField.NUMBER_OF_RIGHT_MINES==GameField.NUMBER_OF_MINES))){
openAllFields();
JOptionPane.showMessageDialog(null, "Вы Выиграли!", "Поздравляем, Вы выиграли!", JOptionPane.WARNING_MESSAGE);
}
}
public JButton addButton(int answer) {
JButton button = new JButton("");
listOfButtons.add(button);
button.setBackground(Color.white);
String decodedAnswer =(String) GameField.field.get(answer);
button.setActionCommand(String.valueOf(answer));
if (decodedAnswer.equals("X"))
{button.addMouseListener(new MineClicked());}
else
{button.addMouseListener(new NotMineClicked());}
return button;
}
public class MineClicked implements MouseListener {
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
JButton button = (JButton) e.getSource();
if (e.getButton() == BUTTON1) {//Левый клик мыши
if(button.getForeground().equals(Color.red)){//Если ранее решили что тут мина
button.setForeground(Color.BLACK);
button.setText("?");
GameField.NUMBER_OF_RIGHT_MINES--;
}else {
whenYouLose();
}
}
if (e.getButton() == MouseEvent.BUTTON3) {//Правый клик мыши
if (button.getForeground().equals(Color.black)||button.getText().equals("")) {
button.setText("1");
button.setForeground(Color.red);
button.setBackground(Color.black);
GameField.NUMBER_OF_RIGHT_MINES++;
checkWin();
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
public class NotMineClicked implements MouseListener{
@Override
public void mouseClicked(MouseEvent e) {
JButton button = (JButton) e.getSource();
String command = button.getActionCommand();//Узнаём номер кнопки
String decodedCommand = GameField.field.get(Integer.parseInt(command));
if (decodedCommand.equals("0")){decodedCommand = "";}
if (e.getButton() == BUTTON1) {//Левый клик мыши
if (button.getForeground().equals(Color.RED)) {//Если раньше решили, что здесь мина
button.setText("?");
button.setForeground(Color.black);
GameField.NUMBER_OF_WRONG_MINES--;
} else {
if (button.getText().equals("") || button.getText().equals("?")) {
button.setText(decodedCommand);
button.setForeground(Color.BLACK);
button.setBackground(Color.cyan);
if (decodedCommand.equals("")) {
pressAdjButtons(command, listOfButtons);
}
GameField.NUMBER_OF_OPEN_FIELDS++;
checkWin();
}
}
}
if (e.getButton() == MouseEvent.BUTTON3) {
if (button.getText().equals("")||button.getText().equals("?")) {//Правый клик если заполнено и не ?, не изменяет
button.setText("1");
button.setForeground(Color.red);
GameField.NUMBER_OF_WRONG_MINES++;//Правый клик мыши
}
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
}
<file_sep>/src/com/company/Main.java
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
GameField gameField = new GameField(15,15,30);
gameField.setVisible(true);
}
}
| 214477aca7c990e59a307f4401b2297cd894ac4c | [
"Java"
] | 2 | Java | GBOLUTS/Minesweeper | 70a027bd900cb50f82825ccc932b5096347b25ab | 311e8ae179088ddc4a06683ff1a0d9558694f87a |
refs/heads/master | <file_sep><?php
class ProcessaDelFile extends Process {
function processa(){
}
/**
* Faz a exclusão do arquivo ZIP informado, gerado após processamento.
* O arquivo, por padrão, é armazenado na pasta _out/print/zip.
* Essa chamada ocorre, geralmente, após um processamento de questões
* e o servidor de produção copiar com sucesso o arquivo ZIP gerado.
*
* @param string $delZipFile Nome do arquivo a ser excluído. Ex.: user_19012015_183357.zip
* @return boolean
* @throws Exception Caso o parâmetro $delZipFile não tenha sido informado.
*/
function delZipFileOutPrint($delZipFileOutPrint='') {
if (strlen($delZipFileOutPrint) > 0) {
//Faz a exclusão do arquivo
//if (Zip::delZipFileOutPrint($delZipFileOutPrint)) {
if (1==1) {
$objResponse = new Response();
//Envia o resultado para o json de saída:
$objTimeCounter = TimeCounter::fim();
$arrOut = array(
'timeExec' => $objTimeCounter->tempoEmSegundos,
'memoryExec' => $objTimeCounter->memoria,
'arquivoZipExcluido' => $delZipFileOutPrint
);
$out = $objResponse->setMessageOk($arrOut)->getJson();
$this->setOut($out);
}
} else {
throw new Exception("O parâmetro 'delZipFileOutPrint' não foi informado ou está vazio.");
}
}
}<file_sep><?php
class TimeCounter {
private static $elapsed_time;
private static $script_start;
public static function inicio(){
list($usec, $sec) = explode(' ', microtime());
self::$script_start = (float) $sec + (float) $usec;
}
public static function fim($out=false){
list($usec, $sec) = explode(' ', microtime());
$script_end = (float) $sec + (float) $usec;
self::$elapsed_time = round($script_end - self::$script_start, 5);
if ($out) {
self::out();
} else {
$objOut = new stdClass();
$objOut->tempoEmSegundos = self::$elapsed_time.' secs';
$objOut->memoria = self::getMemory().' Mb';
return $objOut;
}
}
public static function out(){
$memory = self::getMemory();
$out = "<br/><br/><font color='#F00'>";
$out .= "Tempo transcorrido: ".self::$elapsed_time." secs.<br />";
$out .= "Uso de memória: {$memory} Mb.";
$out .= "</font>";
echo $out;
}
/**
* Retorna o total de memória consumida em Mb.
* @return float
*/
private static function getMemory(){
$memory = round(((memory_get_peak_usage(true) / 1024) / 1024), 2);
return $memory;
}
}<file_sep><?php
class Questao {
private $arrArquivoRtf = array();//Guarda objetos do tipo ArquivoRtf
private $idQuestao = 0;
private $idTexto = 0;
private $indiceQuestao = 0; //Quando usado, serve para indicar a ordem sequencial da questão em um doc
/*
* Valores possíveis para $tipQ e o número mínimo de arquivos obrigatórios esperados,
* além do enun_ e reso_, que são obrigatórios para todos):
*
* 2 = Múltipla escolha - mínimo de 3 arquivos
* 4 = Somatória - mínimo de 3 arquivos
* 3 = Verdadeiro/False - mínimo de 3 arquivos
* 6 = Múltipla escolha especial - 0 arquivo
* 11 = Verdadeiro/False especial - 0 arquivo
* 1 = Analítica - 0 arquivo
* 5 = Relacionamento de coluna - 0 arquivo
*/
private $arrTipoQ = array(
'2' => 'Múltipla escolha',
'6' => 'Múltipla escolha especial',
'3' => 'Verdadeiro/falso',
'11' => 'Verdadeiro/Falso especial',
'4 ' => 'Somatória',
'1' => 'Analítica',
'5 ' => 'Relacionamento de coluna'
);
private $arrGrauDif = array('ELEVADA', 'MEDIA', 'BAIXA');
private $arrAvaliacao = array('RUIM', 'REGULAR', 'BOA', 'OTIMA', 'EXCELENTE');
/**
* Guarda o número mínimo de arquivos obrigatórios adicionais para o tipo informado,
* além do enun_ e reso_, que são obrigatórios para todos os tipos.
* @var int
*/
private $minArqsAdicObrig = 0;
private $tipoQuestao = 0;
private $tipoQPorExtenso = '';
private $fonteVestib = '';
private $grauDif = '';
private $avaliacao = '';
private $classif = '';
/**
* Atribui o ID da questão ao objeto atual e gera um array com os prefixos
* possíveis para cada arquivo que compõe uma questão.
*
* @param int $idQuestao
*/
function __construct($idQuestao, $idTexto, $tipoQ) {
try {
if ((int)$idQuestao == 0) {
throw new Exception("ID da questão inválido. Informe um ID maior que zero.");
}
$this->setIdQuestao($idQuestao);
$this->setIdTexto($idTexto);
$this->setTipoQuestao($tipoQ);
} catch (Exception $e) {
throw $e;
}
}
function setIndice($indice){
$this->indiceQuestao = (int)$indice;
}
function getIndice(){
return (int)$this->indiceQuestao;
}
function setFonteVestib($fonteVestib=''){
$this->fonteVestib = $fonteVestib;
}
function getFonteVestib(){
return $this->fonteVestib;
}
function setGrauDif($grauDif=''){
$this->grauDif = $grauDif;
}
function getGrauDif(){
return $this->grauDif;
}
function setAvaliacao($avaliacao=''){
$this->avaliacao = $avaliacao;
}
function getAvaliacao(){
return $this->avaliacao;
}
function setClassif($classif=''){
$this->classif = $classif;
}
function getClassif(){
return $this->classif;
}
function setIdQuestao($idQuestao){
if ((int)$idQuestao > 0) {
$this->idQuestao = (int)$idQuestao;
} else {
throw new \Exception("O parâmetro idQuestao não foi informado.");
}
}
function getIdQuestao(){
return (int)$this->idQuestao;
}
function setIdTexto($idTexto){
$this->idTexto = (int)$idTexto;
}
function getIdTexto(){
return $this->idTexto;
}
/**
* Verifica se o tipo de questão informado é um tipo válido.
* Identifica a quantidade mínima de arquivos adicionais (além do enun e reso)
* que o tipo de questão informado deve ter.
*
* @param string $tipoQ
* @return void
* @throws Exception Se o tipo de questão informado não for válido.
*/
function setTipoQuestao($tipoQ) {
$tipoQ = (int)$tipoQ;
if ($tipoQ == 0) {
throw new Exception("Tipo do ID/Questão:{$this->getIdQuestao()} vazio ou inválido.");
}
$arrTipoQ = $this->arrTipoQ;
$key = FALSE;
try {
foreach($arrTipoQ as $key => $value) {
if ((int)$key == $tipoQ) {
$this->tipoQPorExtenso = $value;
$key = TRUE;
break;
}
}
// $key = array_search($tipoQ, $this->arrTipoQ);
if (FALSE === $key) {
throw new Exception("O tipo de questão informado '$tipoQ' não é válido.");
} else {
//Formato identificado.
//Localiza o número de arquivos obrigatórios, além do enun_ e reso_
$this->tipoQuestao = $tipoQ;
$minimoArqsAdicObrig = 0;
switch ($tipoQ) {
case 2: //Múltipla escolha
case 4://Somatória
case 3://V/F
$minimoArqsAdicObrig = 3;
break;
}
$this->minArqsAdicObrig = (int)$minimoArqsAdicObrig;
}
} catch (Exception $e) {
throw $e;
}
}
/**
* Retorna o total de arquivos obrigatórios ADICIONAIS (não conta enun)
* para a questão atual,de acordo com o tipo da questão
* (somatória, múltipla escolha, V/F etc)
* @return int
*/
function getMinArqsAdicObrig(){
return (int)$this->minArqsAdicObrig;
}
function getTipoQPorExtenso(){
return $this->tipoQPorExtenso;
}
function getTipoQuestao(){
return (int)$this->tipoQuestao;
}
/**
* Cria o arquivo view a partir de um template RTF
*
* @return string | false Path do arquivo view RTF ou false se falhar.
* @throws Exception Se o arquivo template tpl_view.rtf não existir.
*/
function createViewFile(){
$pathView = $this->getPathView();
$rootTplView = Config::getRootTemplate();
$pathTpl = $rootTplView.'/tpl_view.rtf';
if (file_exists($pathTpl)) {
//Exclui o arquivo view da questão atual, se houver.
@unlink($pathView);
if (copy($pathTpl, $pathView)) {
//Cópia efetuada com sucesso!
return $pathView;
}
} else {
$msgErr = "O arquivo template {$pathTpl} não foi localizado.";
throw new Exception($msgErr);
}
return FALSE;
}
/**
* Método que utiliza um arquivo docx como modelo para gerar
* um arquivo docx de cada questão a ser incluída no documento final.
*
* IMPORTANTE:
* Como o arquivo docx é um arquivo compactado, para editar seu conteúdo
* basta renomeá-lo para zip, descompactá-lo e editar o arquivo word/document.xml.
*
* Passos executados neste método:
* - Criar uma cópia do template 'tpl_questao_doc_colab.docx' para a pasta
* onde o processamento deve ocorrer. IMPORTANTE: A cópia deve ter a extensão .zip;
* - Descompactar o novo arquivo .zip;
* - Substituir no arquivo '.../word/document.xml', os marcadores pelos respectivos atributos da questão;
* - Compactar novamente esses arquivos, agora usando a extensão .docx, porém usando um identificador
* sequencial no nome (formato: 'q_[i].docx', onde [i] refere-se a uma numeração sequencial (1, 2, 3,...)).
*
* @param int $indice Índice sequencial a ser usado no nome do arquivo docx alterado.
* @return boolean|string Se método executado com sucesso retorna o path do arquivo docx alterado ($pathZipChange).
* @throws Exception Caso o arquivo document.xml esperado não seja localizado.
*/
function createQuestaoColab($indice){
$idQuestao = $this->getIdQuestao();
$rootRtf = Config::getPathRtf();
$rootTplView = Config::getRootTemplate();
$pathTpl = $rootTplView.'/tpl_questao_doc_colab.docx';
$pathZip = $rootRtf.'/tpl_colab_'.$idQuestao.'.zip';
$pathZipChange = $rootRtf.'/q_'.$indice.'.docx';
$arrGrauDif = $this->arrGrauDif;
$arrAvaliacao = $this->arrAvaliacao;
if (file_exists($pathTpl)) {
try {
if (copy($pathTpl, $pathZip)) {
//Cópia efetuada com sucesso!
$folderUnzipDocx = $rootRtf.'/'.$idQuestao;
$pathWordDocument = $folderUnzipDocx.'/word/document.xml';//Arquivo a ser editado
$objZip = new Zip();
$objZip->extractTo($pathZip, $folderUnzipDocx);
if (file_exists($pathWordDocument)) {
$strXml = file_get_contents($pathWordDocument);
$fonteVestib = $this->getFonteVestib();
$grauDif = $this->getGrauDif();
$avaliacao = $this->getAvaliacao();
$classif = $this->getClassif();
//Substitui as variáveis no XML
$strXml = str_replace('{ID_QUESTAO}', $idQuestao, $strXml);
$strXml = str_replace('{FONTE}', $fonteVestib, $strXml);
$strXml = $this->changeVarXml($arrGrauDif, $strXml, $grauDif);
$strXml = $this->changeVarXml($arrAvaliacao, $strXml, $avaliacao);
$strXml = str_replace('{CLASSIF}', str_replace('//',' > ',$classif), $strXml);
//Substitui o conteúdo do arquivo pelo XML alterado:
file_put_contents($pathWordDocument, $strXml);
Zip::contractTo($folderUnzipDocx, $pathZipChange);
} else {
$msgErr = "O arquivo do MS-Word '{$pathWordDocument}' não foi localizado.";
throw new Exception($msgErr);
}
} else {
$msgErr = "Tentativa de criar uma cópia de '{$pathTpl}' para '{$pathZip}' falhou.";
throw new Exception($msgErr);
}
if (file_exists($pathZipChange)) {
return $pathZipChange;
}
return null;
} catch (Exception $e) {
throw $e;
}
} else {
$msgErr = "O arquivo template {$pathTpl} não foi localizado.";
throw new Exception($msgErr);
}
return FALSE;
}
private function changeVarXml($arrOptions, $strXml, $selectedValue){
if (strlen($strXml) > 0 && is_array($arrOptions)) {
foreach($arrOptions as $item) {
$change = "";
if ($item === $selectedValue) $change = 'X';
$strXml = str_replace("{{$item}}", $change, $strXml);
}
}
return $strXml;
}
function getPathTc(){
return $this->getPath('texto', true);
}
function getPathEnun(){
return $this->getPath('enun');
}
function getPathReso(){
return $this->getPath('reso');
}
function getPathView(){
return $this->getPath('view');
}
private function getPath($prefixo, $textoComum=false){
$path = '';
$rootFolderRtf = Config::getPathRtf();
$idSufixo = $this->getIdQuestao();
if ($textoComum) {
$idSufixo = $this->getIdTexto();
}
if ($idSufixo > 0) {
$path = "{$rootFolderRtf}/{$prefixo}_{$idSufixo}.rtf";
}
return $path;
}
/**
* Retorna um array associativo contendo a string RTF de cada alternativa, se houver.
* O índice do array é o prefixo (altA, altB...) ao qual a string se refere.
*
* @return string[]
*/
function getArrStrAlternativas(){
$arrStringAlt = array();
$arrArquivoRtf = $this->getArrArquivoRtf();
if (is_array($arrArquivoRtf)) {
foreach($arrArquivoRtf as $objArquivoRtf) {
$prefixo = $objArquivoRtf->getPrefixo();
$posAlt = strpos($prefixo, 'alt');
if ($posAlt !== false) {
//O item atual refere-se a um arquivo alt:
$arrStringAlt[$prefixo] = $objArquivoRtf->getString();
}
}
}
return $arrStringAlt;
}
/**
* Verifica se o total de arquivos RTF lidos e com prefixo válido é igual ou
* maior ao mínimo de arquivos esperados de acordo com o tipo da questão.
*
* @param int $minArqsAdicObrig
* @return boolean
*/
function vldNumArquivos(){
$minArqsAdicObrig = $this->getMinArqsAdicObrig();
$minArqsObrig = $minArqsAdicObrig + 2;//Acrescenta o enun e reso ao valor.
$arrObjArquivoRtf = $this->getArrArquivoRtf();
$totalRtfFiles = count($arrObjArquivoRtf);
$msgErr = '';
//Valida ENUN e RESO, que são obrigatórios:
//====================================================================
if (!isset($arrObjArquivoRtf['enun'])) {
$msgErr .= "Arquivo com prefixo 'enun' não foi localizado.";
}
if (!isset($arrObjArquivoRtf['reso'])) {
$msgErr .= "Arquivo com prefixo 'reso' não foi localizado.";
}
//====================================================================
if (strlen($msgErr) > 0) {
//Questão inválida. A questão deve ter pelo menos ENUN e RESO.
throw new Exception("A questão atual é inválida. {$msgErr}");
} else {
/*
* Valida os arquivos adicionais de acordo com o mínimo obrigatório
* para o tipo da questão atual.
*/
if ($totalRtfFiles < $minArqsObrig) {
return FALSE;
}
}
return TRUE;
}
function getArrArquivoRtf(){
return $this->arrArquivoRtf;
}
function delFiles(){
$arrFiles = Util::searchFiles('questao', $this->idQuestao);
foreach ($files as $file) {
unlink($file);
}
}
/**
* Localiza todos os arquivos da questão atual, incluindo texto comum, se houver.
* Após carregar os paths dos arquivos verifica se os arquivos obrigatórios existem,
* de acordo com o tipo da questão.
*
* @return void
* @throws Exception Se estiver faltando um ou mais arquivos obrigatórios.
*/
function checkArquivosRtf(){
$rootFolderRtf = Config::getPathRtf("\\");
try {
//Valida os arquivos obrigatórios adicionais ao enun_ e reso_.
$idTexto = $this->getIdTexto();
$arrFiles = Util::searchFiles('questao', $this->idQuestao);
$idTipoQuestao = $this->getTipoQuestao();
if (is_array($arrFiles)) {
$tamArr = count($arrFiles);
for ($i = 0; $i < $tamArr; $i++) {
$pathFile = $arrFiles[$i];//Ex.: rtf_files/altA_xxx.rtf
$prefixoArqTmpWord = strpos($pathFile,'~');//Verifica se é arquivo temporário criado pelo MS-Word.
$prefixoAlternativa = strpos($pathFile,'alt');//Verifica se é arquivo temporário criado pelo MS-Word.
if ($idTipoQuestao == 1 && $prefixoAlternativa !== false) {
//A questão atual é analítica. Descarta arquivos de alternativa.
@unlik($pathFile);
continue;
}
if ($prefixoArqTmpWord !== false) {
/*
* O arquivo atual é um arquivo temporário criado pelo MS-Word.
* Exclui o arquivo.
*/
$pathFileTmpMsWord = str_replace('/','\\',$pathFile);
MsWord::delTempFile($pathFileTmpMsWord);
continue;
}
$this->addFile($pathFile);
}
if ($idTexto > 0) {
//Verifica se há arquivo de Texto Comum (TC):
$pathFileTc = $this->getPathTc();
$this->addFile($pathFileTc);
}
}
/*
* Verifica se o total de arquivos lidos está dentro do mínimo esperado
* para o tipo de questão atual
*/
if (!$this->vldNumArquivos()) {
$msgErr = "A questão {$this->idQuestao} não possui a quantidade mínima de arquivos esperada. "
. "O tipo identificado é '{$objTipoQuestao->getTipoQPorExtenso()}', obrigatório pelo menos "
. "{$minArqsAdicObrig} arquivo(s) adicionais além do ENUN e RESO.";
throw new Exception($msgErr);
}
} catch (Exception $e) {
throw $e;
}
}
/**
* Guarda um objeto contendo uma parte do arquivo atual a partir do seu prefixo.
* Exemplo de prefixo: enun, reso, altA, altB...
*
* @param $pathFile objeto contendo os dados de um arquivo extraídos a partir de seu path.
* @return void
*/
function addFile($pathFile){
if (strlen($pathFile) > 0) {
$objArquivoRtf = new ArquivoRtf();
$objArquivoRtf->setPathFile($pathFile);
$prefixo = $objArquivoRtf->getPrefixo();
$this->arrArquivoRtf[$prefixo] = $objArquivoRtf;
} else {
$msgErr = "Uma URL de arquivo RTF não foi informada.";
throw new Exception($msgErr);
}
}
}<file_sep><?php
class RequestViewRtf extends Process {
protected $objQuestaoZip = null;
function __construct(QuestaoZip $objQuestaoZip){
$this->objQuestaoZip = $objQuestaoZip;
}
function setParams($idQuestao, $urlZipOrig, $tipoQ) {
try {
$this->setIdQuestao($idQuestao);
if (strlen($urlZipOrig) > 0) {
$folderLocalDest = $this->idQuestao;
$this->objQuestaoZip->copy($urlZipOrig, $folderLocalDest);
} else {
throw new \Exception("Parâmetro 'urlZipOrig' não informado.");
}
if (strlen($tipoQ) > 0) {
$this->objTipoQuestao->setTipoQuestao($tipoQ);
} else {
throw new \Exception("Parâmetro 'tipoQ' não informado.");
}
} catch (Exception $e) {
throw $e;
}
}
function getObjQuestaoZip(){
try {
return $this->vldInstanceObj('objQuestaoZip', 'QuestaoZip');
} catch (Exception $e) {
throw $e;
}
}
function getObjTipoQuestao(){
try {
return $this->vldInstanceObj('objTipoQuestao', 'TipoQuestao');
} catch (Exception $e) {
throw $e;
}
}
}
<file_sep><?php
class ProcessaQuestao extends Process {
function processa(){
$objResponse = new Response();
$arrObjQuestao = $this->arrObjQuestao;
$out = null;
if (is_array($arrObjQuestao)) {
foreach($arrObjQuestao as $objQuestao) {
//Uma ou mais questões foram informadas
MsWord::encerraMsWord();
$objQuestao->checkArquivosRtf();
/*
* Processa os arquivos enun, reso e alternativas, se houver.
* Executa macros
* Verifica a existência de figuras
* Extrai texto contido do arquivo
*/
$objMsWord = new MsWord();
$objMsWord->processaRtfsDaQuestao($objQuestao);
//Gera o arquivo view_...rtf:
$objMsWord->geraArquivoView($objQuestao);
$arrParams = $objMsWord->getParams();
//Gera imagens GIF a partir dos PDFs gerados:
$objImageMagick = new ImageMagick();
$arrPdfsGerados = $objMsWord->getPdfsGerados();
if ($arrPdfsGerados !== false) {
foreach($arrPdfsGerados as $pathViewPdf) {
//Gera as imagens
$objImageMagick->geraImgGif($pathViewPdf);
}
}
/*
* Gera um arquivo zip contendo os arquivos que devem retornar
* à origem da solicitação.
*/
$arrArquivoRtf = $objQuestao->getArrArquivoRtf();
$objTimeCounter = TimeCounter::fim();
$arrOut = array(
'timeExec' => $objTimeCounter->tempoEmSegundos,
'memoryExec' => $objTimeCounter->memoria,
'idQuestao' => $objQuestao->getIdQuestao(),
'dados' => $arrParams
);
}
$pathZip = Zip::createZip($arrObjQuestao);
$urlResponseZip = Config::getLocalhost().$pathZip;
$arrOut['urlZip'] = $urlResponseZip;//Arquivos finais zipados (RTF + PDF + GIF)
$out = $objResponse->setMessageOk($arrOut)->getJson();
}
$this->setOut($out);
}
}<file_sep>factory_editor
==============
ANTES DE INICIAR ===============================================================
É necessário ter instalado os seguintes softwares:
- MS-Word
- Sonic PDF Creator 3x ou superior (licença adquirida pela Interbits)
- Ghostscript 9x ou superior (http://pages.cs.wisc.edu/~ghost/gsview/)
- ImageMagick 6.x.x ou superior (http://www.imagemagick.org/script/binary-releases.php#windows)
Pré-requisitos:
Para que o PHP possa interagir e usar os recursos do MS-Word é necessário
que o Apache esteja rodando como serviço.
RODANDO O APACHE COMO SERVIÇO ==================================================
- Caso esteja usando Wamp ou Xampp, pare o Apache.
- Localize o arquivo httpd.exe (por exemplo, C:\wamp\bin\apache\apache2.4.2\bin\httpd.exe)
e execute-o com duplo clique.
CONFIGURANDO CORRETAMENTE O SONIC PDF ==================================================
O Sonic PDF mostrou-se a melhor opção para a geração de PDF, mantendo fiel aos diversos
símbolos e caracteres usados nas questões do SuperPro Web.
Para que o PHP possa imprimir o PDF a partir de um arquivo view, resolução e/ou Texto Comum,
é necessário configurar o Sonic corretamente.
1 - Execute o programa Driver Options a partir do menu Iniciar/Todos os Programas/Sonic Pdf Creator...
2 - Na aba GERAL, preencha os campos citados abaixo com os seguintes valores:
- Title = 'Questões'
- Author = 'Interbits'
- Subject = 'SuperPro Web'
3 - Na aba SECURITY, preencha os campos citados abaixo com os seguintes valores:
- Habilitar a opção Secure PDF
- Habilitar a opção 128 bit (Acrobat 5.0 or later)
- Incluir uma senha em 'Change permissions and passwords'
- Desabilitar todas as opções contidas no grupo 'Permissions'
4 - Na aba VIEW, preencha os campos citados abaixo com os seguintes valores:
- Habilitar Hide toolbar
- Habilitar Hide menubar
- Habilitar Center window
- Habilitar resize window to first...
- Habilitar show document title
4 - Na aba OUTPUT, preencha os campos citados abaixo com os seguintes valores:
- Desabilitar 'Show PDF Creation...', 'Open result in PDF...', 'Always secure PDF' e 'Prompt output PDF...'
- Habilitar 'Use default file name...' e preencher o campo Folder com o endereço
da pasta onde o PDF deve ser gerado (ex.: C:\wamp\www\phpmsword\_out\print)
- Na opção 'Existing PDF File', habilitar "Replace"
IMPORTANTE: o Sonic deve estar configurado como impressora padrão do Windows.
<file_sep><?php
class Util {
/**
* Variável que determina se o PDF deve ser impresso no processamento das questões.
*
* @param boolean $value
*/
public static function setPrintPdf($value){
$_SESSION['PRINT_PDF'] = $value;
}
public static function getPrintPdf(){
$value = $_SESSION['PRINT_PDF'];
if (!is_bool($value)) $value = true;
return $value;
}
public static function searchFiles($tipo, $idQuestao=0, $idTexto=0, $arrPaths=null){
if (!is_array($arrPaths)) {
$arrPaths = array();
}
if ($idQuestao >= 0) {
$root = Config::getPathRtf("\\");
if ($tipo == 'questao') {
//Localiza todos os arquivos da questão:
$pattern = "{$root}\*{$idQuestao}.rtf";
} elseif ($tipo == 'alternativas') {
//Localiza as alternativas (arquivos RTF) da questão:
$pattern = "{$root}\alt*{$idQuestao}.rtf";
} elseif ($tipo == 'pdfEgif') {
//Localiza os arquivos PDF e GIF gerados para view, reso e texto:
$root = Config::getRootPrint();
$pattern = "$root\*{$idQuestao}.*";
if ($idTexto > 0) $pattern = "$root\*{{$idQuestao},{$idTexto}}.*";
} elseif ($tipo == 'docxAlterados') {
$pattern = "{$root}\q_*.docx";
}
$files = glob($pattern, GLOB_BRACE);
if (is_array($files)) {
$tamArr = count($files);
for ($i = 0; $i < $tamArr; $i++) {
$arrPaths[] = $files[$i];
}
}
}
return $arrPaths;
}
}
<file_sep><?php
interface IProcessa {
function processa();
}
?><file_sep> <?php
class Zip {
private $username = '';
private $urlArqZipLocal = '';
static $tentativas = 0;
function __construct($urlZipOrig = ''){
if (strlen($urlZipOrig) > 0) {
$this->download($urlZipOrig);
}
}
/**
* Copia o arquivo zip da origem informada para a pasta local.
* Se a pasta de destino não existir tenta criá-la.
*
* @param string $urlZipOrig Uma URL absoluta. Ex.: http://www.sprweb.com.br/...
* @param string $folderLocalDest Uma endereço relativo. Pode ser o ID da questão.
* @return void
*
* @throws Exception Se um ou mais parâmetros obrigatórios não forem informados.
* @throws Exception Se a tentativa de criar o diretório de destino falhar.
* @throws Exception Se não for possível identificar o nome do arquivo de origem.
* @throws Exception Se a tentativa de copiar o arquivo zip da origem para o destino falhar.
*/
function download($urlZipOrig = '') {
if (strlen($urlZipOrig) > 0) {
//Tentar copiar o arquivo zip para a pasta local
$folderDownloadZip = Config::getrootRtf();
$arrPath = pathinfo($urlZipOrig);
if (strlen($arrPath['basename']) > 0) {
$urlArqZipLocal = $folderDownloadZip.'/'.$arrPath['basename'];
} else {
$msgErr = "Não foi possível extrair o parâmetro 'basename' da variável urlZipOrig informada. "
. "Impossível criar a URL de destino para o arquivo zip.";
throw new Exception($msgErr);
}
$urlArqZipLocal = str_replace('//','/',$urlArqZipLocal);
//Exclui o arquivo caso já exista na pasta de destino:
if (file_exists($urlArqZipLocal)) {
unlink($urlArqZipLocal);
}
$rootIn = Config::getRootRtf();
if (!is_dir($rootIn)) {
mkdir($rootIn);
}
if (copy($urlZipOrig,$urlArqZipLocal)) {
//Cópia efetuada com sucesso!
$this->setUrlArqZipLocal($urlArqZipLocal);
} else {
$msg = "A tentativa de copiar o arquivo zip de '{$urlZipOrig}' para '{$urlArqZipLocal}' falhou. "
. "Verifique se o arquivo realmente existe no local de origem.";
throw new Exception($msg);
}
} else {
throw new Exception("O parâmetro 'urlZipOrig' não foi informado ou é inválido.");
}
return $this;
}
function extractTo($pathFileOrig, $folderDest, $delZipFile=false) {
$this->setUrlArqZipLocal($pathFileOrig);
$this->extract($folderDest, $delZipFile);
}
/**
* Extrai o conteúdo do arquivo zip recebido e grava os arquivos extraídos em uma pasta default.
*
* @param $folderDest Path de destino após extração.
* @param boolean $delZipFile Se true, após extração exclui o arquivo ZIP.
* @return void
*/
public function extract($folderDest, $delZipFile=false){
$urlArqZipLocal = $this->getUrlArqZipLocal();
if (file_exists($urlArqZipLocal)) {
try {
$zip = new ZipArchive;
$zip->open($urlArqZipLocal);
if (strlen($zip->filename) > 0) {
$zip->extractTo($folderDest);//Cria a pasta de destino se não existir
$zip->close();
} else {
$msgErr = "Não foi possível extrair o arquivo '{$urlArqZipLocal}'. "
. "Verifique se o arquivo realmente existe na origem ou se está corrompido.";
throw new Exception($msgErr);
}
} catch (Exception $e) {
$msgErr = $e->getMessage();
$pos = strpos($msgErr, 'Permission denied');
if ($pos !== false && self::$tentativas < 3) {
//Há um arquivo 'preso no MS-Word'
MsWord::encerraMsWord();
MsWord::delTempFilesFromFolder($folderDest);
self::$tentativas++;
$this->extract($delZipFile);
} else {
echo self::$tentativas;
self::$tentativas = 0;
throw $e;
}
}
if ($delZipFile) {
try {
//Exclui o arquivo zip:
$this->delZipFile();
} catch (Exception $e) {
return;
}
}
} else {
throw new Exception("O arquivo zip '{$urlArqZipLocal}' não foi localizado. Impossível continuar.");
}
}
function setUrlArqZipLocal($urlArqZipLocal){
$this->urlArqZipLocal = str_replace('//','/',$urlArqZipLocal);
}
function getUrlArqZipLocal(){
return $this->urlArqZipLocal;
}
/**
* Exclui o arquivo zip da questão atual.
*
*/
function delZipFile(){
$urlZipLocalFile = $this->urlArqZipLocal;
unlink($urlZipLocalFile);
}
/**
* Recebe o nome de um arquivo zip gerado em _out/print (configuração padrão de saída)
* e exclui esse arquivo, caso exista.
*
* @param string $pathDelZipFile Path do arquivo ZIP a ser excluído.
* @return boolean
*/
public static function delZipFileOutPrint($pathDelZipFile){
try {
$arrPath = pathinfo($pathDelZipFile);
$basename = $arrPath['basename'];
$folderZip = Config::getRootPrint().'zip';
$pathZipOutPrint = "$folderZip/{$basename}";
if (file_exists($pathZipOutPrint)) {
$return = unlink($pathZipOutPrint);
if (!$return) {
$msgErr = "O arquivo '{$pathZipOutPrint}' foi localizado, porém não foi possível excluí-lo. "
. "Verifique se o arquivo está em uso ou bloqueado para edição.";
throw new Exception($msgErr);
}
return $return;
} else {
$msgErr = "O arquivo '$pathZipOutPrint' não foi localizado. Impossivel fazer a exclusão.";
throw new Exception($msgErr);
}
} catch(Exception $e) {
throw $e;
}
}
/**
* Gera um zip contendo os seguintes arquivos:
* - Arquivos RTF processados
* - Arquivos PDF gerados
* - Arquivos GIF gerados
*
* @param Questao[] $arrObjQuestao
* @return string URL de download do arquivo zip gerado
* @throws Exception Caso não seja possível gerar o arquivo zip
*/
public static function createZip($arrObjQuestao){
$subfolder = Config::getSubfolder();
$folderZip = Config::getRootPrint().'zip';
if (!is_dir($folderZip)) {
mkdir($folderZip);
}
$pathFileZip = $folderZip."/{$subfolder}.zip";
if (is_array($arrObjQuestao)) {
foreach($arrObjQuestao as $objQuestao) {
$idQuestao = $objQuestao->getIdQuestao();
$idTexto = $objQuestao->getIdTexto();
$arrArquivoRtf = $objQuestao->getArrArquivoRtf();
foreach($arrArquivoRtf as $objArquivoRtf) {
$arrZip[] = $objArquivoRtf->getPathFile();
}
//Localiza os arquivos PDF e GIF da questão e texto comum, se houver:
$arrZip = Util::searchFiles('pdfEgif', $idQuestao, $idTexto, $arrZip);
}
} else {
$msgErr = "O array \$arrObjQuestao contendo as referências dos arquivos a compactar"
. "está vazio ou não foi informado. Impossível gerar o zip de resposta.";
throw new Exception($msgErr);
}
try {
//Adiciona os arquivos processados no zip:
Zip::contract($pathFileZip, $arrZip);
//Verifica se o arquivo zip foi criado:
if (!file_exists($pathFileZip)) {
$msgErr = "Não foi possível gerar o arquivo zip '{$pathFileZip}'.";
throw new Exception($msgErr);
}
//Exclui os arquivos RTF gerados:
Process::delTree(Config::getPathRtf());
//Exclui os demais arquivos:
foreach($arrZip as $path) {
@unlink($path);
}
return $pathFileZip;
} catch (Exception $e) {
throw $e;
}
}
public static function contract($pathFileZip, $arrZip){
$zip = new ZipArchive();
if( $zip->open( $pathFileZip , ZipArchive::CREATE ) === true){
$c = 0;
foreach($arrZip as $pathfile) {
$arrpath = pathinfo($pathfile);
$file = $arrpath['basename'];
/*
* IMPORTANTE: verificar se o arquivo realmente existe.
* Se tentar incluir um arquivo que não existe o zip não será
* criado e nenhum erro será capturado.
*/
if (!file_exists($pathfile)) continue;
if (!$zip->addFile($pathfile , $file)) {
$msgErr = "Não foi possível adicionar o arquivo {$pathfile} "
. "ao zip {$pathFileZip}.";
throw new Exception($msgErr);
} else {
$c++;
//echo $pathfile.' - '.$file.'<br>';
}
}
$zip->close();
} else {
$msgErr = "Não foi possível criar o arquivo {$pathFileZip}.";
throw new Exception($msgErr);
}
}
/**
* Recebe o path de uma pasta local e gera um zip dos arquivos dessa pasta.
*
* @param string $folderOrig Path da pasta a ser compactada (pode conter subpastas).
* @param string $pathFileZipDest Path do nome do arquivo zip a ser gerado.
* @return boolean
* @throws Exception Caso não seja possivel fechar o objeto ZipArquive.
*/
public static function contractTo($folderOrig, $pathFileZipDest) {
$zip = new ZipArchive();
if ($zip->open($pathFileZipDest, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) === true){
$files = new RecursiveIteratorIterator (new RecursiveDirectoryIterator($folderOrig), RecursiveIteratorIterator::LEAVES_ONLY);
// Iteração:
foreach ($files as $name => $file) {
//Elimina \. e \.. (caso contrário dará erro ao fechar o zip):
$posRels = strpos($file,'.rels');
$posDot = strpos($file,'\.');
if ($posDot !== false && $posRels === false) {
continue;
}
// Retira a parte do $folderOrig do path do arquivo:
$new_filename = str_replace($folderOrig, '', $name);
$file = str_replace('\\','/',$file);
// Retira a '/' no início do path, caso exista:
$new_filename = substr($new_filename,strrpos($new_filename,'/') + 1);
$new_filename = str_replace('\\','/',$new_filename);
//echo "$file - $new_filename <br>";
if (!is_readable($file) || !file_exists($file)){
echo "Arquivo {$file} não pode ser lido.";
} else {
//echo $new_filename.'<br>';
$zip->addFile($file, $new_filename);
}
}
// close the zip file
if (!$zip->close()) {
$msgErr = "Não foi possível encerrar o objeto ZipArquive. Tentativa de compactação do path '{$folderOrig}' para '{$pathFileZipDest}' falhou.";
throw new Exception($msgErr);
}
return TRUE;
}
}
}
<file_sep><?php
/**
* Classe usada para imprimir uma imagem a partir de um arquivo PDF.
*
* Instalação Windows:
* http://www.imagemagick.org/script/binary-releases.php#windows
*
*/
Class ImageMagick {
private $pathFilePdf = '';
function __construct($pathFilePdf=''){
try {
if (strlen($pathFilePdf) > 0) {
$this->setPathPdf($pathFilePdf);
}
} catch (Exception $e) {
throw $e;
}
}
private function setPathPdf($pathFilePdf){
if (file_exists($pathFilePdf)) {
$this->pathFilePdf = $pathFilePdf;
} else {
$msgErr = "O arquivo PDF informado '{$pathFilePdf}' não foi encontrado. "
. "Impossível gerar a imagem a partir do arquivo.";
throw new Exception($msgErr);
}
}
private function getPathPdf(){
$pathFilePdf = $this->pathFilePdf;
if (strlen($pathFilePdf) == 0) {
$msgErr = "Nenhum pathPdf foi informado. Impossível gerar imagem GIF.";
throw new Exception($msgErr);
}
return $pathFilePdf;
}
/**
* Gera um arquivo GIF a partir do arquivo PDF informado.
* O arquivo GIF deve ser gerado sempre na pasta root de impressão ($rootPrint)
* definida em Config.php.
*
* @param $pathFilePdf Path relativo do arquivo PDF a partir do qual a imagem GIF deve ser gerada.
* @return string Retorna o path da imagem gerada
* @throws Exception Caso a impressão do arquivo GIF tenha falhado.
*/
function geraImgGif($pathFilePdf = ''){
try {
if (strlen($pathFilePdf) == 0) {
$pathFilePdf = $this->getPathPdf();
}
$pathFilePdf = realpath($pathFilePdf);
/*
* O arquivo de imagem deve ficar na mesma pasta do arquivo PDF:
*/
$pathFileImg = str_replace('.pdf','.gif',$pathFilePdf);
//Exclui o arquivo de image, caso já exista
@unlink($pathFileImg);
$pathImageMagick = Config::getPathImageMagick();
//Script compatível com a versão antiga do Ghost e ImageMagick:
$exec="{$pathImageMagick}convert -density 94 $pathFilePdf -trim +antialias +repage -append $pathFileImg";
//Versão mais recente do ImageMagick (12/01/2015) - não funciona no servidor da sala de reunião:
//$exec="{$pathImageMagick}convert -density 94 $pathFilePdf -trim -antialias -alpha remove +repage -append $pathFileImg";
exec($exec,$output,$return);
if (file_exists($pathFileImg)){
chmod($pathFileImg,1777);//Muda a permissão do arquivo
return $pathFileImg;
} else {
$msgErr = "Ocorreu um erro ao tentar gerar o arquivo de imagem {$pathFileImg}"
. " a partir do PDF {$pathFilePdf}. Verifique se o Ghostscript está instalado em sua máquina.";
throw new Exception($msgErr);
}
} catch(Exception $e) {
throw $e;
}
}
}
<file_sep><?php
include('class/Config.php');
include('class/Action.php');
include('class/Util.php');
include('class/Process.php');
include('class/Request.php');
include('class/Response.php');
include('class/Zip.php');
include('class/Questao.php');
include('class/MsWord.php');
include('class/ImageMagick.php');
include('class/ArquivoRtf.php');
include('class/ProcessaQuestao.php');
include('class/ProcessaDocColab.php');
include('class/ProcessaDelFile.php');
include('class/TimeCounter.php');
set_time_limit(0);
ini_set('memory_limit', '1024M'); //1G - Não remover esta linha!!
set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
// error was suppressed with the @-operator
if (0 === error_reporting()) {
return false;
}
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
/**
* Recebe uma requisição do servidor de aplicação para manipular arquivos RTF.
*
* Parâmetros esperados:
* action = DEL_FILE_OUT_PRINT | PROCESSA_DOC_COLAB | PROCESSA_QUESTAO
*
* Para action != de 'DEL_FILE':
* params = username=<username>&urlZipOrig=<urlDoArquivoZip> (parâmetros codificados com base64)
* Ou então, para action = 'DEL_FILE':
* params = delZipFileOutPrint=<delZipFile> (parâmetro codificado com base64)
*
* URL de teste:
* http://localhost/phpmsword/?action=<NOMEDAACTION>¶ms=YWN0aW9uPVBST0NFU1NBX1FVRVNUQU8mdXNlcm5hbWU9dGFuaWEmdXJsWmlwT3JpZz1odHRwOi8vc3Byd2ViLmNvbS5ici9kb2NzLzEwMDgwMC56aXAmbGlzdGFRPTEwMDgwMDowOk1F
*
* Exemplo do parâmetro params:
* $params = "username=tania&urlZipOrig=http://sprweb.com.br/docs/125278_e_100800_e_125272.zip";
* $params = "username=tania&urlZipOrig=http://sprweb.com.br/docs/100800.zip";
*/
//$params = "delZipFileOutPrint=tania_21012015_112320.zip";
//$params = "username=tania&urlZipOrig=http://sprweb.com.br/docs/124626.zip";
//$paramsEncode = base64_encode($params);
//echo "?params=".$paramsEncode.'<br><br>';
//die();
$out = 'ERR';
$objResponse = new Response();
//Medidor de tempo do script:
TimeCounter::inicio();
if (isset($_REQUEST['params'])) {
try {
if (!file_exists('config.xml')) {
throw new Exception("O arquivo obrigatório 'config.xml' não foi localizado.");
}
/**
* Recebe/valida os parâmetros contidos na variável $params (base64).
* Se houver erro na validação, retorna uma exceção.
*/
$idQuestao = 0;
$objRequest = new Request();
$action = $objRequest->getParamAction();
$urlZipOrig = $objRequest->urlZipOrig;
$username = $objRequest->username;
$delZipFileOutPrint = $objRequest->delZipFileOutPrint;//Apenas para action 'DEL_FILE'
$objProcessa = new Process();
if ($action == Action::DEL_FILE_OUT_PRINT) {
//Usuário soliciou a exclusão do arquivo ZIP informado.
$objProcessa = new ProcessaDelFile();
$objProcessa->delZipFileOutPrint($delZipFileOutPrint);
$out = $objProcessa->getOut();
} else {
$subfolder = $username."_".date('dmY_His');
//$subfolder = $username;
Config::setPathRtf($subfolder);
$pathRtf = Config::getPathRtf();
if (strlen($username) == 0) {
throw new Exception("O parâmetro 'username' não foi informado.");
}
//Faz o download do arquivo zip contendo os RTFs
$objZip = new Zip($urlZipOrig);
$objZip->extract($pathRtf, true);//Extrai o conteúdo do zip e exclui o ZIP após extração(parâmetro true)
//Array de objetos do tipo Questão após extração de cada idQuestao recebido:
$arrObjQuestao = $objRequest->getListaObjQuestao();
$arrOut = array();
if ($action == Action::PROCESSA_DOC_COLAB) {
// Gera um arquivo doc no formato específico para Colaborador contendo as questões informadas.
$objProcessa = new ProcessaDocColab($arrObjQuestao);
$objProcessa->geraDocxColab();
} elseif ($action == Action::PROCESSA_QUESTAO) {
// Valida arquivos obrigatórios, roda macros, gera PDF + IMG:
$objProcessa = new ProcessaQuestao($arrObjQuestao);
}
}
$out = $objProcessa->getOut();
} catch (Exception $e) {
//Um erro foi capturado. Retorna um json com os dados do erro.
//Process::delTree(Config::getPathRtf());//Exclui a pasta de arquivos RTF
$msgErr = $e->getMessage();
$posMacro = strpos($msgErr, "executar a macro especificada");
if ($posMacro !== false) {
$msgErr .= " IMPORTANTE: Verifique se o Apache está rodando como serviço.";
}
$out = $objResponse->setMessageErr($msgErr, $e->getLine(), $e->getFile())->getJson();
}
} else {
$out = $objResponse->setMessageErr("Variável 'params' não informada.",'ERR')->getJson();
}
echo $out;
<file_sep><?php
/**
* Manipula recursos do MS-Word por meio do PHP.
* É necessário que o apache esteja rodando como CONSOLE ao invés de rodar como serviço.
* Para isso, deve-se executar o arquivo httpd.exe diretamente, sem iniciar por exemplo o wamp ou xampp.
*/
class MsWord {
private static $objMsWordCom = null;
private static $arrMacros = array();
protected $objQuestaoRtf = null;
private $arrProcessamento = array();//Guarda o resultado do processamento da questão (TC, RESO e VIEW)
private $arrPdfsGerados = array();
/**
* Guarda os paths de TC já utilizados no doc atual.
* Necessário para evitar colocar o mesmo TC duas vezes no documento.
* A ordem correta (agrupamento de questões com o mesmo TC)
* deve vir no parâmetro listaQ no momento da requisição.
*/
private $arrPathTcEmUso = array();
function __construct() {
$this->setMsWord();
$this->arrPathTcEmUso = array();
//Macros que devem ser executadas apenas na 'view'.
$arrMacros['view'] = array(
'removeCabRodape',
'remove_espaco' //Remove espaço vazio após o conteúdo
);
//Macros que devem rodar para todos os outros arquivos, menos 'view':
$arrMacros['all'] = array(
'ortog_marg',
'altera_margens2pdf'
);
//Macros exclusivos de 'enun' e 'reso':
$arrMacros['enun_reso_tc'] = array(
'enter_antes_fig' //Adiciona ENTER em figuras que iniciam o texto
);
$arrMacros['altera_font_arial'] = array('altera_font_arial');
$arrMacros['corrige_espaco_entre_linhas'] = array('corrige_espaco_entre_linhas');
self::$arrMacros = $arrMacros;
}
function getArrMacros($indice){
$arrMacros = null;
if (array_key_exists($indice,self::$arrMacros)) {
$arrMacros = self::$arrMacros[$indice];
} else {
$msgErr = "O indice '{$indice}' solicitado não existe no array {$arrMacros}.";
throw new Exception($msgErr);
}
return $arrMacros;
}
function getEmpty(){
$empty = new VARIANT();
return $empty;
}
function openFile($pathFile){
if (strlen($pathFile) > 0 && file_exists($pathFile)) {
$word = self::$objMsWordCom;
$word->Documents->Open(realpath($pathFile));
return $word;
}
return null;
}
/**
* Concantena as partes da questão (enun + alternativas, se houver).
* Salva o resultado como view_xxxx.rtf.
*
* Após criar o arquivo RTF com sucesso, processa as etapas de validação para
* rodar as macros, extrair o conteúdo e checar a existência de imagem.
*
* @param Questao $objQuestao
* @return string Path do arquivo VIEW gerado.
*
* @throws Exception Se algum erro for capturado no processo.
*/
function geraArquivoView(Questao $objQuestao){
try {
$word = self::$objMsWordCom;
$idQuestao = $objQuestao->getIdQuestao();
$indiceQuestao = $objQuestao->getIndice();
$tipoQuestao = $objQuestao->getTipoQuestao();
$arrAlternativas = null;
if ($tipoQuestao !== 1) {
/*
* A questão não é analítica.
* Localiza os arquivos RTF das alternativas da questão atual, se houver:
*/
$arrAlternativas = Util::searchFiles('alternativas',$idQuestao);
}
$pathView = $objQuestao->createViewFile();
//$pathTc = $objQuestao->getPathTc();//Texto Comum
$pathEnun = $objQuestao->getPathEnun();
//Abre o arquivo view para concatenar as outras partes
$word->Documents->Open(realpath($pathView));
//Adiciona texto antes do início da questão:
$textoContido = $word->ActiveDocument->Content;
//Adiciona o Enunciado:
$addParagraphAfter = false;
if ($indiceQuestao > 0) $word->Selection->TypeText("{$indiceQuestao}. ");//Se existir, inclui a numeração sequencial
$word = $this->addFile($word, $pathEnun, $addParagraphAfter);
//Adiciona parágrafo após o Enunciado:
$word->Selection->TypeText(chr(13));
//Adiciona as alternativas, se houver:
if (is_array($arrAlternativas)) {
foreach ($arrAlternativas as $file) {
/*
* Cria uma cópia do arquivo atual para preservar seu conteúdo:
*/
$fileBkp = $file.'.copy';
if (!copy($file, $fileBkp)) {
$msgErr = "Não foi possível criar cópia do arquivo {$file} ao gerar arquivo View.";
throw new Exception($msgErr);
}
$leftRecuoIndent = 0.4;
$firstLineIndent = -0.4;
$objArquivoRtf = new ArquivoRtf($fileBkp);
$bodyRtf = $objArquivoRtf->getBody();
$itemAlternativa = ''; //a), b), c),... ou 08), 16), 32)...
$tplAlternativa = 'tpl_alternativa.rtf';
if ($tipoQuestao == 3) {
//V/F
$leftRecuoIndent = 0.91;
$firstLineIndent = -0.91;
$tplAlternativa = 'tpl_alternativa_VF.rtf';
} else {
//a)..., b)..., c).... ou 08), 16), 32)...
if ($tipoQuestao == 4) {
//Somatória
$leftRecuoIndent = 0.69;
$firstLineIndent = -0.61;
}
$prefixo = $objArquivoRtf->getPrefixo();
$alt = str_replace('altS','',$prefixo);
$alt = str_replace('alt','',$alt);
$alt = str_replace('-','',$alt);
$alt = strtolower($alt);
$itemAlternativa = $alt;
}
//Monta o item da alternativa atual usando templates:
$pathTplAlternativa = Config::getRootTemplate().$tplAlternativa;
if (file_exists($pathTplAlternativa)) {
$alternativaString = file_get_contents($pathTplAlternativa);
$alternativaString = str_replace('ALTERNATIVA',$itemAlternativa,$alternativaString);
$alternativaString = str_replace('ITEM',$bodyRtf,$alternativaString);
$fp = fopen($fileBkp, "w+");
if (fwrite($fp, $alternativaString)) {
fclose($fp);
} else {
$msgErr = "Erro ao gravar arquivo {$fileBkp}.";
throw new Exception($msgErr);
}
} else {
$msgErr = "O arquivo {$pathTplAlternativa} não foi localizado.";
throw new Exception($msgErr);
}
//Insere o arquivo da alternativa atual e roda macro nesse conteúdo:
$word->Run('modif_recuo_alternativas', realpath($fileBkp), $leftRecuoIndent, $firstLineIndent);
//$word = $this->addFile($word, $fileBkp, false);
//$arrMacrosIndex = $this->getArrMacros('recuo_alt_'.$macroRecuo);
//$word = $this->macroRun($word, $arrMacrosIndex);
//Apaga o arquivo de backup:
unlink($fileBkp);
}
}
$arrMacrosIndex = $this->getArrMacros('corrige_espaco_entre_linhas');
$word = $this->macroRun($word, $arrMacrosIndex);
$word->Documents[1]->Close(true);
//Processa o arquivo View recém criado:
$objArquivoRtf = new ArquivoRtf($pathView);
$this->processRtfFile($objArquivoRtf);
return $pathView;
} catch(Exception $e) {
throw $e;
}
}
/**
* Concatena o conteúdo do $pathFile informado no arquivo atualmente aberto.
*
* @param COM $word
* @param string $pathFile Path relativo do arquivo a ser concatenado ao atual.
* @param string $indicador Refere-se a um indicador criado no arquivo atual, onde o $pathFile deve ser inserido.
* @param boolean $addParagraphAfter Se true, adiciona um parágrafo após a inserção do arquivo.
* @return object COM
*/
function addFile($word, $pathFile, $indicador='', $addParagraphAfter=true){
if (strlen($indicador) > 0) {
$empty = $this->getEmpty();
$wdGoToBookmark = -1;
$word->Selection->GoTo($wdGoToBookmark,$empty,$empty,$indicador);
}
if (strlen($pathFile) > 0) {
if (!file_exists($pathFile)) {
//O arquivo informado não existe. Faz a inclusão de um arquivo vazio.
$pathFile = Config::getRootTemplate().'tpl_view.rtf';
}
if (file_exists($pathFile)) {
$word->Selection->InsertFile(realpath($pathFile), '', false);
if ($addParagraphAfter) $word->Selection->InsertParagraphAfter();
} else {
//Arquivo não existe. Ignora inclusão.
}
} else {
$word->Selection->TypeText(" ");
}
return $word;
}
/**
* Imprime o arquivo PDF a partir do arquivo view.rtf usando a impressora Sonic PDF.
* IMPORTANTE: o Sonic deve estar previamente instalado e configurado para
* imprimir na pasta de destino especificada em Config.php.
*
* @param COM object $word
* @return string Retorna o path do arquivo PDF gerado
*
* @throws Exception Se o objeto gerado a partir do processamento do arquivo view.rtf não for válido.
* @throws Exception Se a impressão do arquivo PDF falhou.
*/
private function printPdf($word){
try {
$docNameRtf = '';
$pathFilePdf = '';
//$objProcessado = $this->getObjProcessamento($prefixo);
Config::checkRootPrint();
if (is_object($word)) {
//$objArquivoRtf = $objProcessado->objArquivoRtf;
//$pathFileRtf = $objArquivoRtf->getPathFile();
//$pathFilePdf = $this->getPathPdfApartirDoPathRtf($pathFileRtf);
$docs = $word->Documents->Count;
if ($docs > 0) {
$docNameRtf = $word->Documents($docs)->Name;
$pathFilePdf = $this->getPathPdfApartirDoPathRtf($docNameRtf);
@unlink($pathFilePdf);//Exclui o arquivo PDF se já existir.
$word->Documents[$docs]->PrintOut();
while($word->BackgroundPrintingStatus > 0){
/*
* Ainda há documento na fila de impressão. Aguarda 1 segundo:
*/
sleep(1);
}
}
$sec = 0;
while(!file_exists($pathFilePdf) && $sec <= 10){
/*
* Ainda há documento na fila de impressão. Aguarda 1 segundo:
*/
sleep(1);
$sec++;
}
if ($sec >= 10) {
self::encerraMsWord();
$msgErr = "O arquivo {$pathFilePdf} não foi localizado."
. "A tentativa de impressão do PDF falhou para o RTF {$docNameRtf} após aguardar 10 segundos."
. "Verifique se o endereço configurado no Sonic PDF aponta corretamente para a pasta _out/print do projeto atual,"
. " ou então, se o Sonic PDF é a impressora padrão da máquina.";
throw new Exception($msgErr);
}
} else {
$msgErr = "O objeto MS-Word informado parece ser nulo ou é um objeto inválido."
. "Impossível imprimir o arquivo PDF.";
throw new Exception($msgErr);
}
} catch (Exception $e) {
throw $e;
}
return $pathFilePdf;
}
private function getPathPdfApartirDoPathRtf($docNameRtf){
$pathFilePdf = '';
if (strlen($docNameRtf) > 0) {
$filePdf = str_replace('.rtf', '.pdf', $docNameRtf);
$pathFilePdf = Config::getRootPrint().$filePdf;
} else {
$msgErr = "Não foi possível criar o path do arquivo PDF. Um path RTF não foi informado.";
throw new Exception ($msgErr);
}
return $pathFilePdf;
}
private function setMsWord($visible=0,$newInstance=false){
try {
//Tenta recuperar uma instância ativa do Word, se existir:
if ($newInstance) throw new Exception();
$objMsWordCom = com_get_active_object("Word.Application");
} catch (Exception $e){
$objMsWordCom = new COM("word.application");
}
if (is_object($objMsWordCom)) {
$objMsWordCom->Visible = $visible;//1=Mostra interface, 0 = oculta interface
self::$objMsWordCom = $objMsWordCom;
} else {
$message = "Não foi possível criar/recuperar uma instância do MS-Word.";
throw new Exception($message);
}
}
/**
* Encerra explicitamente a instância do MS-Word que estiver ativa.
* @return void
*/
public static function encerraMsWord(){
$cmd = 'TASKKILL /f /fi "imagename eq winword.exe"';
$Result = shell_exec($cmd);
}
/**
* Exclui arquivos temporário do MS-Word a partir da pasta informada.
*
* @param string $folder
* @return void
*/
public static function delTempFilesFromFolder($folder){
$files = glob("$folder\~$*.rtf", GLOB_BRACE);
if (is_array($files)) {
foreach($files as $file) {
$pathTempFile = $folder.'\\'.$file;
self::delTempFile($pathTempFile);
}
}
}
/**
* Exclui o arquivo temporário informado.
*
* @param $pathFileTmpMsWord Path relativo do arquivo a ser excluído.
* @return void
*/
public static function delTempFile($pathFileTmpMsWord){
//Exclui o arquivo temporário
$cmd = 'DEL /f /a '.$pathFileTmpMsWord;
shell_exec($cmd);
}
/**
* Executa, para cada arquivo de $objQuestao (não inclui view_):
* - Macros.
* - Verifica a existência de figuras.
* - Extrai o conteúdo do arquivo para permitir consulta por texto contido.
*
* @param QuestaoRtf $objQuestao
* @return string Path do arquivo processado
* @throws \Exception Se objQuestaoRtf for inválido
*/
function processaRtfsDaQuestao($objQuestao){
$arrPaths = array();
$counterArqAlternativas = 0; //Contador de arquivos da Questão atual, validados corretamente (possuem conteúdo)
if ($objQuestao instanceof Questao) {
$arrObjArquivoRtf = $objQuestao->getArrArquivoRtf();//Prefixos que possuem arquivo
$minArqsAdicOrig = $objQuestao->getMinArqsAdicObrig();//Número mínimo de arquivos adicionais esperados
foreach($arrObjArquivoRtf as $prefixo => $objArquivoRtf) {
if ($prefixo === 'view') {
continue;
}
$pathFile = $this->processRtfFile($objArquivoRtf);
if ($pathFile !== false) {
//Arquivo possui conteúdo.
if ($prefixo != 'enun') $counterArqAlternativas++;
$arrPaths[] = $pathFile;
}
}
if ($counterArqAlternativas < $minArqsAdicOrig) {
//A questão atual não possui a quantidade mínima de arquivos obrigatórios.
$idQuestao = $objQuestao->getIdQuestao();
$msgErr = "A questão atual (ID: {$idQuestao}) parece estar incompleta. "
. "Num/alternativas preenchidas: {$counterArqAlternativas}, mínimo esperado: {$minArqsAdicOrig}. "
. "Um ou mais arquivos obrigatórios estão vazios.";
throw new \Exception($msgErr);
}
return $arrPaths;
} else {
throw new \Exception("O objeto 'objQuestaoRtf' parece não ser derivado da classe 'QuestaoRtf'.");
}
}
function processaRtfTC(){
$arrArquivosRtf = TextoComum::getArquivosRtf();
if (is_array($arrArquivosRtf)) {
//Um ou mais TC foram localizados
foreach($arrArquivosRtf as $objArquivoRtf) {
$objReturn = $this->processRtfFile($objArquivoRtf);
if (is_object($objReturn)) {
$this->arrProcessamentoTC[$objArquivoRtf->getIdArquivo()] = $objReturn;//Guarda o objeto retornado
}
}
}
}
/**
* Ações realizadas no processamento:
* - executa macros do MS-Word
* - verifica arquivos obrigatórios e que não podem estar vazios
* - extrai o conteúdo do arquivo informado
* - imprime PDF para view, reso e texto
*
* Serve de suporte para o método processRtfFiles(), mas pode ser usado separadamente
* para um único arquivo (por exemplo, após gerar o view RTF).
*
* @param ArquivoRtf $objArquivoRtf
* @param boolean $printPdf
* @return string | false Path do arquivo processado ou false caso o arquivo esteja vazio.
*/
function processRtfFile(ArquivoRtf $objArquivoRtf){
try {
$objReturn = new \stdClass();
$word = self::$objMsWordCom;
$arrMacros = self::$arrMacros;
$pathFile = $objArquivoRtf->getPathFile();
$prefixo = $objArquivoRtf->getPrefixo();
$existeImg = false;
$gerarPdf = false;
//Prefixos que não podem estar vazios:
$arrPrefixoObrig = array('enun','altA','altB','altC','altD','altS01','altS02','altS04','altS08');
//Abre o arquivo informado no MS-Word:
$realPathFile = realpath($pathFile);
$word->Documents->Open($realPathFile);
//Executa macros do MS-Word de acordo com o prefixo do arquivo.
//==============================================================
if (Util::getPrintPdf()) {
//A requisição atual deve gerar PDF.
$indexMacro = 'all';//Macros que devem rodar em todos os arquivos, menos 'view'.
if ($prefixo == 'view') $indexMacro = $prefixo;
$arrMacrosIndex = $arrMacros[$indexMacro];
$word = $this->macroRun($word, $arrMacrosIndex);
if ($prefixo == 'enun' || $prefixo == 'reso') {
$word = $this->macroRun($word, $arrMacros['enun_reso_tc']);
}
}
//==============================================================
$textoContido = $this->getContentRtf($word);
if ($textoContido === false) {
$word->Documents[1]->Close(true);
if (in_array($prefixo, $arrPrefixoObrig)) {
//Arquivo obrigatório. Nâo pode estar vazio
$msgErr = "O arquivo '{$pathFile}' está vazio. Não é possível prosseguir com a ação solicitada."
. "Por favor, edite/preencha o conteúdo desse arquivo e tente novamente.";
throw new Exception($msgErr);
} else {
//Arquivo não obrigatório
unlink($pathFile);
return false;
}
}
//Se view ou reso: verifica se há figura no arquivo:
if ($prefixo == 'texto' || $prefixo == 'view' || $prefixo == 'reso') {
$existeImg = $this->checkInlineImage($word);
$objReturn->objArquivoRtf = $objArquivoRtf;
$objReturn->textoContido = utf8_encode($textoContido);
$objReturn->existeImg = ($existeImg) ? 1: 0;
if ($prefixo == 'reso') {
/*
* Para questões de múltipla escolha, extrai o gabarito, se houver.
* Deve estar no formato [letra]):
*/
$gabaritoOk = '';
$abreChaves = substr($textoContido,0,1);
$gabarito = substr($textoContido,1,1);
$gabarito = strtoupper($gabarito);
$fechaChaves = substr($textoContido,2,1);
if (
$gabarito == 'A'
|| $gabarito == 'B'
|| $gabarito == 'C'
|| $gabarito == 'D'
|| $gabarito == 'E') {
//O gabarito é válido.
$gabaritoOk = $gabarito;
}
$objReturn->gabarito = $gabaritoOk;
}
$this->arrProcessamento[$prefixo] = $objReturn;
$gerarPdf = true;
}
$word->Application->ActiveDocument->Saved = true;
$word->ActiveDocument->SaveAs($realPathFile,6);//Salva como RTF
$word->Documents[1]->Close(true);
if ($gerarPdf === true && Util::getPrintPdf() === true) {
/*
* Após salvar as alterações realizadas a partir das macros, abre novamente
* o arquivo e imprime para PDF.
*/
$word->Documents->Open($realPathFile);
//Imprime para PDF e guarda o path do arquivo gerado.
$pathPdf = $this->printPdf($word);
$this->arrPdfsGerados[] = $pathPdf;
$word->Documents[1]->Close(true);
}
$this->arrProcessamento[$prefixo] = $objReturn;
return $pathFile;
} catch (Exception $e) {
$msgErr = "Erro ao abrir o arquivo {$pathFile} no MS-Word. ".$e->getMessage();
throw new Exception($msgErr);
die();
}
}
/**
* Após processar arquivos RTF (view, reso e texto), guarda o path dos PDFs gerados
* com sucesso.
*
* @return string[] | false
*/
function getPdfsGerados(){
$out = false;
$arrPdfsGerados = $this->arrPdfsGerados;
if (count($arrPdfsGerados) > 0) {
$out = $arrPdfsGerados;
}
return $out;
}
/**
* Recebe um array com uma ou mais macros que devem rodar no arquivo atualmente
* aberto no MS-Word.
*
* @param object $word MS-WORD COM
* @param string[] $arrMacrosIndex Macros que devem rodar no arquivo atual
* @return COM object
*/
function macroRun($word, $arrMacrosIndex){
foreach($arrMacrosIndex as $macro) {
try {
$word->Run($macro);
} catch(Exception $e) {
$msgErr = "Impossível rodar a macro '{$macro}'. "
. "Verifique se o nome da macro está correto e se ela existe no MS-Word local.";
throw new Exception($msgErr);
}
}
return $word;
}
/**
* Verifica se o arquivo aberto no MS-Word possui figura.
* Esta ação deve ser executada apenas em arquivos com prefixo 'view' e 'reso'.
*
* @param object $word Objeto COM MS-Word.
* @return boolean
*/
function checkInlineImage($word){
$existeFig = FALSE;
$numFig = $word->ActiveDocument->InlineShapes->Count;
//echo $file . ' - ' .$numFig.'ssdfs<br>';
for($x=1;$x<=$numFig;$x++){
$objImg = $word->ActiveDocument->InlineShapes[$x];
if (is_object($objImg)) {
$classe = @$objImg->OLEFormat->ClassType;
if (count($classe) == 0){
//Encontrou uma figura no arquivo
$existeFig = TRUE;
break;
} else {
/*
* Econtrou um objeto do Equation (Mathtype).
* O valor, geralmente, é Equation.DSMT4
*/
}
}
}
return $existeFig;
}
/**
* Faz a extração do conteúdo do arquivo RTF contido no objeto MS-Word informado.
* Esse conteúdo é obrigatório e deve ser extraído para permitir busca
* por palavra-chave no SuperPro Web.
*
* @param COM object $word
* @return string Conteúdo extraído do arquivo.
* @throws \Exception Se não houver arquivo aberto no MS-Word.
* @throws \Exception Se o arquivo RTF aberto estiver vazio.
*/
private function getContentRtf($word){
if (!is_object($word)){
$msgErr="O objeto informado é nulo ou não é um objeto do MS-Word.";
throw new Exception($msgErr);
}
$textoContido = '';
$docs = $word->Documents->Count;
$docName = '';
if ($docs > 0) {
$word->Documents($docs)->Activate;
$docName = $word->Documents($docs)->Name;
$textoContido = $word->Documents($docs)->Content;
$textoContido .= '';
$textoContido = trim($textoContido);
} else {
throw new Exception("Parece que não há arquivo aberto no Word.");
}
//echo $docName . '<br>';
//var_dump($textoContido);
if (strlen($textoContido) > 0){
return $textoContido;
} else {
return false;
//throw new Exception("O arquivo {$docName} parece estar vazio.");
}
}
function getObjProcessamento($prefixo) {
$prefixo = strtolower($prefixo);
$arrProcessamento = $this->arrProcessamento;
if (isset($arrProcessamento[$prefixo])) {
return $arrProcessamento[$prefixo];
} else {
if ($prefixo != 'texto') {
$msgErr = "O resultado do processamento gerado para o prefixo '{$prefixo}' parece não ser válido. "
. "Provavelmente esse arquivo não foi preenchido, porém é obrigatório para concluir a etapa solicitada.";
throw new Exception($msgErr);
} else {
return null;
}
}
}
function getParams(){
$arrParams = array();
$arrPrefixo = array('view','reso','texto');
foreach($arrPrefixo as $prefixo) {
$objParam = $this->getObjProcessamento($prefixo);
if ($objParam !== null) {
$arrParams[$prefixo] = array('existeImg'=> $objParam->existeImg,'textoContido'=> $objParam->textoContido);
if ($prefixo == 'reso') {
$arrParams[$prefixo]['gabarito'] = $objParam->gabarito;
}
}
}
return $arrParams;
}
function getDadosProcessamento(){
return $this->arrProcessamento;
}
}
<file_sep><?php
/**
* Classe responsável por trata a saída no formato json.
*
*/
class Response {
private $lineErr = 0;
private $fileErr = '';
function __construct() {
}
function setMessageErr($message, $lineErr = 0, $fileErr = ''){
$this->lineErr = $lineErr;
$this->fileErr = $fileErr;
return $this->setMessage($message, FALSE);
}
function setMessageOk($arr){
return $this->setMessage('Processamento realizado com sucesso!', TRUE, $arr);
}
/**
* Define uma mensagem de resposta e seu tipo.
*
* @param string $message
* @param string $success Pode ser TRUE ou FALSE
* @return \Response
*/
function setMessage($message,$success, $return = null) {
$this->arrMessage = array('message' => utf8_encode($message), 'success'=>$success, 'lineErr' => $this->lineErr, 'file' => $this->fileErr, 'return' => $return);
return $this;
}
function getJson(){
$json = json_encode($this->arrMessage);
return $json;
}
}
?>
<file_sep><?php
class ArquivoRtf {
private $prefixo;
private $pathFile = '';
private $idArquivo = 0;//Pode ser o ID de Questão ou de Texto Comum
private $arrPrefixo = array('view','texto','enun','reso');
function __construct($pathFile = '') {
//Carrega os prefixos de alternativas (altA, altB, altC...):
$letra = 65;
for($i=1;$i<=7;$i++) {
$this->arrPrefixo[] = 'alt'.chr($letra);
$letra++;
}
//Carrega os prefixos de somatória (altS01, altS02, altS04...):
$somatoria = 1;
for($i=1;$i<=7;$i++) {
$var = $somatoria;
if ($somatoria < 10) $var = '0'.$var;
$this->arrPrefixo[] = 'altS'.$var;
$somatoria *= 2;
}
try {
if (strlen($pathFile) > 0) {
$this->setPathFile($pathFile);
}
} catch (Exception $e) {
throw $e;
}
}
function setPathFile($pathFile){
if (file_exists($pathFile)) {
//Arquivo localizado. Verifica se possui um prefixo válido.
$arrPath = pathinfo($pathFile);
$filename = $arrPath['filename'];
$arrName = explode('_',$filename);//Separa o prefixo do nome. Ex.: enun_9999.rtf
$prefixo = $arrName[0];
$msgErrOrig = "da Questão";
if (!$this->vldPrefixo($prefixo)) {
throw new Exception("Não foi possível localizar o prefixo '{$prefixo}' a partir do path informado: '{$pathFile}'.");
}
$arrId = explode('.',$arrName[1]);
$id = (int)$arrId[0];
$this->pathFile = $pathFile;
if ($prefixo == 'texto') {
$msgErrOrig = "do Texto Comum";
}
if ($id == 0) {
throw new Exception("Não foi possível localizar o ID {$msgErrOrig} a partir do path informado: '{$pathFile}'.");
}
$this->idArquivo = $id;
$this->prefixo = $prefixo;
} else {
throw new Exception("O arquivo '{$pathFile}' não existe.");
}
}
function getPathFile(){
$pathFile = $this->pathFile;
if (strlen($pathFile) > 0) {
return $pathFile;
} else {
throw new Exception("O arquivo atual não possui um path válido ou não foi corretamente informado.");
}
}
/**
* Método de suporte ao método addFile().
* Verifica o prefixo informado e retorna TRUE caso ele exista na lista de prefixos válidos.
*
* @param string $prefixo
* @return boolean
*/
private function vldPrefixo($prefixo){
$key = array_search($prefixo, $this->arrPrefixo);
if ($key !== false) return TRUE;
return FALSE;
}
function getPrefixo(){
return $this->prefixo;
}
function getIdArquivo(){
return (int)$this->idArquivo;
}
function getString(){
try {
$pathFile = $this->getPathFile();
$strRtf = file_get_contents($pathFile);
return $strRtf;
} catch (Exception $e) {
throw $e;
}
}
function getBody(){
//Pega apenas o corpo do RTF atual, sem cabeçalho e rodapé
$stringRtf = trim($this->getString());
$pos = false;
$pos2 = false;
$pos = strrpos($stringRtf,"ltrpar \sectd");
if ($pos !== false){
$matriz = explode("sectd",$stringRtf);
$cab = $matriz[0]."sectd";
$inicio = strlen($cab);
$final = strrpos($stringRtf,"}");
$bodyIni = substr($stringRtf,$inicio,$final);
$final = strrpos($bodyIni,"}");
$bodyFim = substr($bodyIni,0,$final);
} elseif ($pos2 !== false){
$final = strrpos($stringRtf,"}");
$bodyFim = substr($stringRtf,1,$final-1);
} else {
$bodyFim = $stringRtf;
}
//Retira o lixo encontrado no rodapé, se houver
$pos = strripos(trim($bodyFim),"{\\*\\themedata");
if ($pos !== false){
$bodyPos = substr($bodyFim,0,$pos+1);
$bodyFim = $bodyPos;
}
//if ($tipoRtf == 'ALT' || $tipoRtf = 'RESO' || $tipoRtf == 'ENU'){
if (1==1) {
//EXTRAI A TABELA DE FONTES DO RTF ATUAL
//$this->setContentRtf($stringRtf);
//$this->arrFontTbl = $this->getFontTbl();
$c=0;
$posFechaChaves = strripos(trim($bodyFim),"}");//Verifica se fecha chaves no final
//echo $bodyFim.'<br><br><br><br><br><br><br><br>';
for ($i=0;$i<=5;$i++){
//Retira até 5 parágrafos no final (\par)
$pos = strripos(trim($bodyFim),"\\par");//Busca a última ocorrência
$tam = strlen($bodyFim);
$dif = $tam-$pos;
if ($pos !== false){
if ($dif <= 10){
//O \par está no final da string. Pode ser retirado
$c++;
$bodyFim = substr($bodyFim,0,$pos);
} else {
//O \par está no meio da string. Sai do loop.
break;
}
}
}//Fim do loop for
if ($posFechaChaves !== false && $c > 0) $bodyFim .= " }";
}
return $bodyFim;
}
}
?>
<file_sep><?php
class Process {
protected $arrObjQuestao = array();
protected $out = '';
function __construct($arrObjQuestao=null) {
if (is_array($arrObjQuestao)) {
$this->arrObjQuestao = $arrObjQuestao;
$this->processa();
}
}
function setOut($out) {
$this->out = $out;
}
function getOut(){
$out = $this->out;
if (strlen($out) == 0) {
$msgErr = "Nenhum processamento foi executado. Impossível identificar a ação desejada (o valor do parâmetro 'action' não é válido).";
$objResponse = new Response();
$out = $objResponse->setMessageErr($msgErr)->getJson();
}
return $out;
}
/**
* Verifica se o objeto solicitado percente à classe informada.
*
* @param $varName Nome da variável que guarda o objeto a ser retornado
* @param $class Nome da classe que deu origem ao objeto solicitado
*
* @return boolean
*/
protected function vldInstanceObj($varName, $class){
$obj = (isset($this->$varName)) ? $this->$varName : null;
if (is_object($obj)) {
if ($obj instanceof $class) {
return $obj;
} else {
throw new \Exception("O objeto {$varName} não é uma instância da classe {$class}.");
}
} else {
throw new \Exception("O parâmetro solicitado {$varName} parece não ser uma variável da classe atual.");
}
}
/**
* Elimina a pasta de arquivos RTF e todo seu conteúdo.
*
* @return boolean True caso tenha removido a pasta e todo o seu conteúdo com sucesso.
*/
public static function delTree($dir='') {
if (strlen($dir) == 0) {
//throw new Exception("Informe a pasta cujo conteúdo deseja excluir");
return false;
}
//Não permite excluir a pasta root _in:
if ($dir == Config::getRootRtf()) return;
$files = @array_diff(scandir($dir), array('.','..'));
if ($files !== null) {
foreach ($files as $file) {
(is_dir("$dir/$file")) ? self::delTree("$dir/$file") : unlink("$dir/$file");
}
return @rmdir($dir);
}
return;
}
}<file_sep><?php
/*
* Classe usada para gerar um arquivo doc para o colaborador.
*/
class ProcessaDocColab extends Process {
/**
* Guarda o total de questões processadas.
* @var int
*/
private $totalQuestoes = 0;
function getTotalQuestoes(){
return (int)$this->totalQuestoes;
}
/**
* Processa todas as questões recebidas no construtor da classe.
* Para cada questão, um novo docx é gerado a partir de um template docx específico.
* As macros são rodadas nos arquivos RTF, um arquivo VIEW é gerado e, por fim, esse
* arquivo é incluído no docx da questão.
*
* @return void
*/
function processa(){
$indiceQuestao = 1;
$arrObjQuestao = $this->arrObjQuestao;
$pathTcAnterior = '';
if (is_array($arrObjQuestao)) {
foreach($arrObjQuestao as $objQuestao) {
$idQuestao = $objQuestao->getIdQuestao();
$objQuestao->checkArquivosRtf();
$objQuestao->setIndice($indiceQuestao);
/*
* Processa os arquivos enun, reso e alternativas, se houver.
* Executa macros
* Verifica a existência de figuras
* Extrai texto contido do arquivo
*/
MsWord::encerraMsWord();
$objMsWord = new MsWord();
$objMsWord->processaRtfsDaQuestao($objQuestao);
//Gera o arquivo view_...rtf:
$pathView = $objMsWord->geraArquivoView($objQuestao);
$pathTc = $objQuestao->getPathTc();
$pathReso = $objQuestao->getPathReso();
if (file_exists($pathView)) {
// Cria o arquivo docx do colaborador:
$pathDocxColab = $objQuestao->createQuestaoColab($indiceQuestao);
if ($pathDocxColab !== null) {
//Inclui o arquivo VIEW no docx do colaborador:
$word = $objMsWord->openFile($pathDocxColab);
if ($pathTc == $pathTcAnterior) {
/*
* O texto comum já foi incluído na questão anterior.
* Impede de incluí-lo novamente.
*/
$pathTc = '';
}
//Inclui o Texto Comum, questão e resolução (se houver):
$word = $objMsWord->addFile($word, $pathTc, 'TEXTO_COMUM', false);
$word = $objMsWord->addFile($word, $pathView, 'QUESTAO', false);
$word = $objMsWord->addFile($word, $pathReso, 'RESOLUCAO', false);
$word->Documents[1]->Close(true);
$pathTcAnterior = $pathTc;
} else {
$msgErr = "Erro ao criar o arquivo .docx alterado para a questão atual (ID {$idQuestao}).";
throw new Exception($msgErr);
}
} else {
$msgErr = "Falha ao criar o arquivo VIEW da questão {$idQuestao}."
. "Impossível processar a questão atual para o doc do colaborador.";
throw new Exception($msgErr);
}
$indiceQuestao++;
}
}
$this->totalQuestoes = --$indiceQuestao;
}
function geraDocxColab(){
$totalQuestoes = $this->getTotalQuestoes();
$arrObjQuestao = $this->arrObjQuestao;
if ($totalQuestoes == 0) {
$msgErr = "Nenhuma questão foi processada corretamente, ou então "
. "o método processa() não foi chamado antes do método atual.";
throw new Exception($msgErr);
}
$objResponse = new Response();
$arrDocxChanged = Util::searchFiles('docxAlterados');
$rootRtf = Config::getPathRtf();
$rootTplView = Config::getRootTemplate();
$pathTplDocColab = $rootTplView.'/tpl_doc_colab.docx';
$pathTplDocColabFinalizado = $rootRtf.'/doc_colab_finalizado.docx';
$subfolder = Config::getSubfolder();
$folderZip = Config::getRootPrint().'zip';
$pathFileFinalDocx = $folderZip."/{$subfolder}.docx";
$pathFileZip = $folderZip."/{$subfolder}.zip";
try {
if (!file_exists($pathTplDocColab)) {
$msgErr = "O arquivo template '{$pathTplDocColab}' não foi localizado."
. "Impossível gerar o arquivo docx do colaborador.";
throw new Exception($msgErr);
}
if (copy($pathTplDocColab, $pathTplDocColabFinalizado)) {
MsWord::encerraMsWord();
$objMsWord = new MsWord();
$word = $objMsWord->openFile($pathTplDocColabFinalizado);
$rootDocx = Config::getPathRtf("\\");//local onde os arquivos docx foram processados e salvos.
for($i=1; $i <= $totalQuestoes; $i++) {
$pathFileDocx = "{$rootDocx}\q_{$i}.docx";
if (file_exists($pathFileDocx)) {
$word = $objMsWord->addFile($word, $pathFileDocx);
} else {
$msgErr = "O arquivo {$pathFileDocx} consta como processado, mas não foi localizado.";
throw new Exception($msgErr);
}
}
$arrMacrosIndex = $objMsWord->getArrMacros('altera_font_arial');
$word = $objMsWord->macroRun($word, $arrMacrosIndex);
$word->Documents[1]->Close(true);
$arrZip = array();
foreach($arrObjQuestao as $objQuestao) {
$idQuestao = $objQuestao->getIdQuestao();
$idTexto = $objQuestao->getIdTexto();
//Localiza os arquivos PDF e GIF da questão e texto comum, se houver:
$arrZip = Util::searchFiles('pdfEgif', $idQuestao, $idTexto, $arrZip);
}
//Zipa o arquivo docx finalizado:
$arrZip = array();//@todo Tira essa linha após finalizar a área do Colaborador
$arrZip[] = $pathTplDocColabFinalizado;
Zip::contract($pathFileZip, $arrZip);
//Exclui os arquivos gif, pdf e docx gerados:
foreach($arrZip as $path) {
@unlink($path);
}
//...e exclui também os arquivos RTF gerados:
Process::delTree(Config::getPathRtf());
//Envia o resultado para o json de saída:
$objTimeCounter = TimeCounter::fim();
$arrOut = array(
'timeExec' => $objTimeCounter->tempoEmSegundos,
'memoryExec' => $objTimeCounter->memoria,
'urlZip' => Config::getLocalhost().$pathFileZip
);
$out = $objResponse->setMessageOk($arrOut)->getJson();
$this->setOut($out);
} else {
$msgErr = "Não foi possível criar uma cópia do arquivo '{$pathTplDocColab}' para o path '{$pathTplDocColabFinalizado}'."
. "Verifique se o arquivo template 'doc_colab_finalizado.docx' existe ou se você possui permissão na pasta de destino.";
throw new Exception($msgErr);
}
} catch (Exception $e) {
throw $e;
}
}
}
<file_sep>ANTES DE INICIAR ===============================================================
É necessário ter instalado os seguintes softwares:
- MS-Word
- Sonic PDF Creator 3x ou superior (licença adquirida pela Interbits)
- Ghostscript 9x ou superior (http://pages.cs.wisc.edu/~ghost/gsview/)
- ImageMagick 6.x.x ou superior (http://www.imagemagick.org/script/binary-releases.php#windows)
Pré-requisitos:
Para que o PHP possa interagir e usar os recursos do MS-Word é necessário
que o Apache esteja rodando como serviço.
RODANDO O APACHE COMO SERVIÇO ==================================================
- Caso esteja usando Wamp ou Xampp, pare o Apache.
- Localize o arquivo httpd.exe (por exemplo, C:\wamp\bin\apache\apache2.4.2\bin\httpd.exe)
e execute-o com duplo clique.
PHP - HABILITAR EXTENSIONS =====================================================
- php_curl.dll
- php_openssl.dll
- php_com_dotnet.dll
CONFIGURANDO CORRETAMENTE O SONIC PDF ==========================================
O Sonic PDF mostrou-se a melhor opção para a geração de PDF, mantendo fiel aos diversos
símbolos e caracteres usados nas questões do SuperPro Web.
Para que o PHP possa imprimir o PDF a partir de um arquivo view, resolução e/ou Texto Comum,
é necessário configurar o Sonic corretamente.
1 - Execute o programa Driver Options a partir do menu Iniciar/Todos os Programas/Sonic Pdf Creator...
2 - Na aba GERAL, preencha os campos citados abaixo com os seguintes valores:
- Title = 'Questões'
- Author = 'Interbits'
- Subject = 'SuperPro Web'
3 - Na aba SECURITY, preencha os campos citados abaixo com os seguintes valores:
- Habilitar a opção Secure PDF
- Habilitar a opção 128 bit (Acrobat 5.0 or later)
- Incluir uma senha em 'Change permissions and passwords'
- Desabilitar todas as opções contidas no grupo 'Permissions'
4 - Na aba VIEW, preencha os campos citados abaixo com os seguintes valores:
- Habilitar Hide toolbar
- Habilitar Hide menubar
- Habilitar Center window
- Habilitar resize window to first...
- Habilitar show document title
4 - Na aba OUTPUT, preencha os campos citados abaixo com os seguintes valores:
- Desabilitar 'Show PDF Creation...', 'Open result in PDF...', 'Always secure PDF' e 'Prompt output PDF...'
- Habilitar 'Use default file name...' e preencher o campo Folder com o endereço
da pasta onde o PDF deve ser gerado (ex.: C:\wamp\www\phpmsword\_out\print)
- Na opção 'Existing PDF File', habilitar "Replace"
IMPORTANTE: o Sonic deve estar configurado como impressora padrão do Windows.<file_sep><?php
class Config {
private static $configXml = 'config.xml';
private static $subfolder = '';//Guarda a subpasta usada para gravar os RTFs da requisição atual
private static $pathRtf = ''; //Guarda o path de rootRtf + subfolder
/**
* Carrega o parâmetro solicitado a partir do arquivo config.xml
* @param string $param Nome do parâmetro (nó XML ) solicitado.
* @return string
*/
private static function getParamXml($param){
$xml = simplexml_load_file(self::$configXml);
return $xml->params->$param;
}
public static function getLocalhost(){
return self::getParamXml('localhost');
}
public static function getPathImageMagick(){
$pathImageMagick = self::getParamXml('pathImageMagick');
if (strlen($pathImageMagick) > 0) {
//Substitui barra invertida por barra normal, se houver
$pathImageMagick = str_replace('\\','/',$pathImageMagick);
$pathImageMagick .= "/";
$pathImageMagick = str_replace('//','/',$pathImageMagick);
}
return $pathImageMagick;
}
/*
* Retorna o path da pasta template onde arquivos modelo são armazenados.
* Por exemplo, o arquivo tpl_view.rtf usado para concatenar as partes de uma questão.
*
* @return string Retorna a pasta root solicidada com uma barra normal (/) no final.
*/
public static function getRootTemplate(){
$rootTemplate = self::getParamXml('rootTemplate');
return self::getRoot($rootTemplate, 'getRootTemplate');
}
/*
* Retorna a pasta root onde os arquivos PDF e img são gerados.
*
* @return string Retorna a pasta root solicidada com uma barra (/) no final.
*/
public static function getRootPrint(){
$rootPrintOut = self::getParamXml('rootPrintOut');
return self::getRoot($rootPrintOut, 'getRootPrint');
}
/**
* Verifica se a pasta root de impressão existe.
* Se não existir, tenta criá-la.
*
* @return boolean
*/
public static function checkRootPrint(){
$rootPrint = self::getRootPrint();
if (!is_dir($rootPrint)) {
mkdir($rootPrint);
}
if (!is_dir($rootPrint)) {
$msgErr = "Impossível criar a pasta root de impressão: '{$rootPrint}'.";
throw new Exception($msgErr);
}
}
/**
* Retorna a pasta root para a descompactação dos arquivos RTF.
* Caso ela não exista, será automaticamente criada no processo de unzip.
*
* @return string Retorna a pasta root solicidada com uma barra (/) no final.
*/
public static function getRootRtf(){
$rootRtf = self::getParamXml('rootRtf');
return self::getRoot($rootRtf, 'getRootRtf');
}
public static function setPathRtf($subfolder) {
self::$subfolder = $subfolder;
self::$pathRtf = Config::getRootRtf().$subfolder;
}
public static function getSubfolder(){
return self::$subfolder;
}
/**
* Retorna o path do local onde os arquivos RTF estão armazenados.
*
* @param string $barra Pode ser '/' ou "\\", define se a barra do path é normal ou invertida.
* @return type
*/
public static function getPathRtf($barra = "/"){
$path = self::$pathRtf;
if ($barra == "\\") {
$path = str_replace("/", $barra, $path);
}
return $path;
}
/**
* Retorna o path Root solicitado com uma barra normal (/) no final.
*
* @param string $root Path a ser retornado com a "/"
* @param string $op Tipo de operação para identifcar o erro, caso ocorra uma exceção.
* @return string
* @throws Exception Caso um path $root não seja informado.
*/
private static function getRoot($root, $op){
if (strlen($root) > 0) {
$root .= "/";
$root = str_replace("//",'/',$root);
} else {
$msgErr = "Uma pasta root não foi informada para a operação '{$op}'.";
throw new Exception($msgErr);
}
return $root;
}
}<file_sep><?php
class Action {
const PROCESSA_DOC_COLAB = 'PROCESSA_DOC_COLAB';
const DEL_FILE_OUT_PRINT = 'DEL_FILE_OUT_PRINT';
const PROCESSA_QUESTAO = 'PROCESSA_QUESTAO';
}
<file_sep><?php
class MatrizRtf {
private $arrMatrizRtf = array();
public static $folderRoot = 'matriz_rtf';
function __construct(){
//$arrMatrizRtf['TC_SINGULAR'] ='introTCsingular.rtf';
//$arrMatrizRtf['TC_PLURAL'] ='introTCplural.rtf';
$arrMatrizRtf['CAB_RTF'] = 'cabRTF.txt';//Matriz usada para iniciaro arquivo RTF.
$arrMatrizRtf['CAB_RTF_FONTTBL'] ='cabRTF_fontTbl.txt';//Matriz usada para iniciar o arquivo RTF.
$arrMatrizRtf['RODAPE_RTF'] ='rodape.txt';//Matriz usada para finalizar o arquivo RTF.
$arrMatrizRtf['CAB_RTF_V2'] ='cabRTF_v2.txt';//Cabeçalho RTF que antecede o corpo do arquivo (alternativo).
$arrMatrizRtf['MULTIPLA_ESCOLHA'] ='numAlternativa.rtf';//Matriz usada para alternativa de múltipla escolha.
$arrMatrizRtf['ALT_V_F'] ='numAlternativaVF.rtf';//Matriz usada para alternativa V/F
$arrMatrizRtf['SOMATORIA'] ='numAlternativaSoma.rtf';//Matriz usada para alternativa de somatória
$arrMatrizRtf['INDICE_QUESTAO'] ='indiceQuestao.rtf';//Matriz usada para montar questão com índice sequencial (1, 2, 3...)
$arrMatrizRtf['TITULO'] ='titulo.rtf';
$arrMatrizRtf['PAGINA_VAZIA'] ='paginaVazia.rtf';
$this->arrMatrizRtf = $arrMatrizRtf;
}
function getArrMatrizRtf(){
return $this->arrMatrizRtf;
}
function getFontTblMatrizRtf(){
//CARREGA O ARRAY DE FONTTBL DOS ARQUIVOS RTF USADOS COMO MATRIZ
$arrMatrizRtf = $this->arrMatrizRtf;
foreach($arrMatrizRtf as $file){
$pos = strpos($file,'.txt');
if ($pos > 0) continue;
$url = self::$folderRoot.'/'.$file;
$rtf = file_get_contents($url);
$this->bodyRtf($rtf,1);
}
$arrFontTbl = $this->arrFontTbl;
if (is_array($arrFontTbl)){
foreach($arrFontTbl as $fontTbl){
$arr[] = str_replace('Times New Roman','Arial',$fontTbl);
}
$this->arrFontTbl = $arr;
}
$this->body='';
}
/**
* Retorna a string RTF do arquivo matriz solicitado.
* Por exemplo, matriz para gerar enunciado, ou então alternativas, título etc.
*
* @param type $nomeMatriz
* @return string
*/
function getString($nomeMatriz){
$stringRtf = '';
$arrMatrizRtf = $this->arrMatrizRtf;
if (isset($arrMatrizRtf[$nomeMatriz])) {
$nomeArquivoRtf = $arrMatrizRtf[$nomeMatriz];
$pathMatrizRtf = self::getPath($nomeArquivoRtf);
if (file_exists($pathMatrizRtf)){
$stringRtf = file_get_contents($pathMatrizRtf);
} else {
throw new Exception("O arquivo '{$pathMatrizRtf}' não foi localizado.");
}
} else {
throw new Exception("O nome da matriz RTF solicitada parece estar incorreto.");
}
return $stringRtf;
}
public static function getPath($file){
$path = self::$folderRoot.'/'.$file;
return $path;
}
/**
* Mescla uma string RTF referente à alternativa com seu respectivo arquivo matriz.
* A partir do prefixo do arquivo (altA, altB, altS01 etc) identifica
* a matriz RTF que deve ser utilizada e mescla $stringRtfItem a essa matriz.
*
* @param string $prefixo enun, reso, altA, altB, altC, altS01, altS02...
* @return string
*/
function parseAlternativa($stringRtfItem, $prefixo){
$stringRtf = '';
$rtfAlternativa = '';
if ($prefixo == 'enun') {
$stringRtf = $stringRtfItem.'\par';
} elseif ($prefixo != 'reso') {
//Arquivo referente à alternativa
$indice = str_replace('altS','',$prefixo);
$indice = str_replace('alt','',$indice);
$indice = str_replace('_','',$indice);
$indice = strtolower($indice);
$rtfAlternativa = $this->getString('MULTIPLA_ESCOLHA');
if (abs($indice) > 0) $rtfAlternativa = $this->getString('SOMATORIA');//Somatória
$rtfAlternativa = str_replace('ALTERNATIVA',$indice,$rtfAlternativa);
$stringRtf = str_replace('ITEM',$stringRtfItem,$rtfAlternativa).'\par';
}
return $stringRtf;
}
}
?><file_sep><?php
class Request {
private $params64Decode = '';//String no formato var1=value1&var2=value2...
function __construct() {
$params64Decode = base64_decode($_REQUEST['params']);
$this->params64Decode = $params64Decode;
}
function getParamAction(){
if (isset($_REQUEST['action'])) {
$action = $_REQUEST['action'];
Util::setPrintPdf(true);//Faz impressão de PDF + geração de imagem
if ($action == Action::PROCESSA_DOC_COLAB) {
//Util::setPrintPdf(false);//Desabilita a impressão de PDF
}
return $action;
} else {
throw new Exception("O parâmetro 'action' não foi informado.");
}
}
/**
* Identifica cada questão a partir do arquivo lista_questoes.xml informado.
* Se o arquivo não existir, verifica se uma variável listaQ foi informada (método antigo).
*
* @return Questao[] Retorna um array de objetos
* @throws Exception Caso exista alguma questão com dados inconsistentes.
*/
function getListaObjQuestao(){
$arrObjQuestao = null;
try {
$listaQ = $this->listaQ;
$pathRtf = Config::getPathRtf();
$pathListaQxml = $pathRtf.'/lista_questoes.xml';
if (file_exists(realpath($pathListaQxml))) {
//Os dados de cada questão foram informados via arquivo XML:
$xml = simplexml_load_file($pathListaQxml);
$arrQuestao = $xml->questoes->questao;
foreach($arrQuestao as $questao) {
$objQ = new Questao((int)$questao->idQuestao, (int)$questao->idTexto, (int)$questao->tipoQuestao);
$objQ->setFonteVestib((string)$questao->fonteVestib);
$objQ->setGrauDif((string)$questao->grauDif);
$objQ->setAvaliacao((string)$questao->avaliacao);
$arrClassif = $questao->classificacoes->classificacao;
$strClassificacao = '';
foreach($arrClassif as $classificacao){
$classificacao = (string)$classificacao;
$strClassificacao .= "{$classificacao}<w:br/>";
}
$objQ->setClassif($strClassificacao);
$arrObjQuestao[] = $objQ;
}
if (!is_array($arrObjQuestao)) {
$msgErr = "Parece que o arquivo '{$pathListaQxml}' não está no formato correto ou está vazio.";
throw new Exception($msgErr);
}
}elseif (strlen($listaQ) > 0) {
/*
* Ao invés de um XML, um parâmetro listaQ foi informado na requisição (formato antigo).
* Esse parâmetro contém os dados de cada questão, caso exista mais de uma.
*/
$arrQuestao = explode(',',$listaQ);
if (is_array($arrQuestao)) {
foreach($arrQuestao as $questao) {
/*
*Formato da string $questao:
* idQuestao:idTexto,tipoQuestao:fonteVestib:grauDificuldade:avaliacao:classif
*/
@list($idQuestao, $idTexto, $tipoQ, $fonteVestib, $grauDif, $avaliacao, $classif) = explode(':',$questao);
$objQ = new Questao($idQuestao, $idTexto, $tipoQ);
$objQ->setFonteVestib($fonteVestib);
$objQ->setGrauDif($grauDif);
$objQ->setAvaliacao($avaliacao);
$objQ->setClassif($classif);
$arrObjQuestao[] = $objQ;
}
} else {
$msgErr = "Parece que o parâmetro 'listaQ' não está usando vírgula como separador das questões.";
throw new Exception($msgErr);
}
} else {
$msgErr = "O parâmetro 'listaQ' não foi informado na URL de chamada.";
throw new Exception($msgErr);
}
} catch (Exception $e) {
throw $e;
}
return $arrObjQuestao;
}
function __get($nameVar) {
$value = null;
parse_str($this->params64Decode);
if (isset($nameVar)) {
$value = @$$nameVar;
}
return $value;
}
} | 02cdaaa8af90ad5757e00461febd26892061bc7f | [
"Markdown",
"Text",
"PHP"
] | 21 | PHP | marclebon/factory_editor | 7813cfc4f3ca56bfb7ef117e4babf18b81968bb8 | b8afa049df1e65cbfca496c93111c565462c6e23 |
refs/heads/master | <file_sep># Goodman Target Simulator
This is a very simple script that simulates Goodman data. At this moment, it simply generates an image with one or more gaussian
profiles that mimic observations.
## Use me
The best way to use the Goodman Target Simulator is by installing it and running the `goodsim` script. The installation can be done as follows:
mkdir $path_to_gts
cd $path_to_gts
git clone https://github.com/b1quint/goodman_target_simulator.git .
pip install .
Since any Python installation can update your current packages, I strongly recommend you to use [Virtual Environments](http://python-guide-pt-br.readthedocs.io/en/latest/dev/virtualenvs/) or [Anaconda Environments](https://conda.io/docs/using/envs.html).
Once installed, the `goodsim` script will be installed in your system and you can run it from any terminal (as long as you are within the virtual environment where it was installed). If you want to know more of how it can be run, just type:
goodsim --help
## To Do
- [ ] Add distortions.
- [ ] Poisson noise?
- [ ] New Blue Camera and Red Camera templates.
- [ ] Real spectral response?
<file_sep>#!/usr/bin/env python
# -*- coding: utf8 -*-
"""
"""
from __future__ import absolute_import, division, print_function
import matplotlib as mpl
mpl.use('TkAgg')
import astropy.io.fits as pyfits
import numpy as np
import matplotlib.pyplot as plt
import pkg_resources
from astropy.modeling import models
__author__ = '<NAME>'
class GoodmanTargetSimulator:
pixel_scale = 0.15 # arcsec / pix
def __init__(self,
filename=None,
targets_pos=[1000],
targets_int=[1.],
seeing=1.,
snr=1.,
show=False):
"""
Parameters
----------
filename (str) :
targets_pos (indexable) :
targets_int (indexable) :
seeing (float) :
snr (float) :
"""
self.filename = filename
self.targets_pos = targets_pos
self.targets_int = targets_int
self.seeing = seeing
self.snr = snr
self.show = show
def run(self):
# Convert the seeing measured in full-width at half maximum to stddev
# and, then, from arcseconds to unbinned pixels.
seeing = self.arcsec2px(self.seeing / 2.335)
# Create the models
my_models = models.Const1D(0)
for (i, p) in enumerate(self.targets_pos):
peak_index = p
peak_value = self.targets_int[i]
my_models += models.Gaussian1D(mean=peak_index,
amplitude=peak_value, stddev=seeing)
# Get header
h = self.goodman_header()
# Create 1D data
height = h['NAXIS2']
x = np.arange(height)
y = my_models(x)
# From 1D to 2D
width = h['NAXIS1']
y = np.reshape(y, (1, height, 1))
y = np.repeat(y, width, axis=2)
# Create noise
noise = np.random.randn(1, height, width) \
* max(self.targets_int) / self.snr
y += noise
if self.show:
self.display_results(y)
# Write output file
pyfits.writeto(self.filename, y, h, overwrite=True)
def arcsec2px(self, x):
"""
Return x in pixels.
Parameters
----------
x (float) : a value in arcseconds.
Returns
------
y (float) : the same value in number of pixels
"""
return x / self.pixel_scale
def display_results(self, data):
"""
Simply display the resulting image.
Parameters
----------
data (ndarray) : 2D Array containinng the results.
"""
fig, axs = plt.subplots(1, 1)
axs.imshow(
data[0], origin='lower', interpolation='nearest', cmap='Blues')
axs.set_title(
"Simulated Gaussians with SNR = {:.1f}".format(self.snr))
axs.set_xlim(0, data.shape[2])
axs.set_ylim(0, data.shape[1])
axs.set_ylabel('Spatial direction [px]')
axs.set_xlabel('Spectral direction [px]')
plt.show()
@staticmethod
def goodman_header(camera=0):
"""
Get a sample of the Goodman Header.
Parameters
----------
camera (int) : an index representing which camera to be taken as
example - 0: Old blue camera, 1: New blue camera, 2: Red camera.
Returns
-------
h (astropy.io.fits.Header) : a sample instance of the header.
"""
# Select what is the source of the data
if camera == 0:
filename = 'sample_data/sample_blue_camera.fits'
elif camera == 1:
raise NotImplemented(
"I don't have a sample for the new blue camera yet.")
elif camera == 2:
raise NotImplemented("I don't have a sample for the red camera yet.")
# Read and deliver header
filename = pkg_resources.resource_filename(
'goodman_target_simulator', filename)
h = pyfits.getheader(filename)
for key in h.keys():
if 'PARAM' in key:
del h[key]
return h
if __name__ == '__main__':
gts = GoodmanTargetSimulator(
filename="dummy.fits",
targets_pos=[1000, 1500],
targets_int=[10., 5],
seeing=1.,
snr=100,
show=True
)
gts.run()<file_sep>"""
0.1.0 - First version of the software with no much implemented.
"""
api = 0
feature = 1
bug = 0
month = 5
year = 2017<file_sep>#!python
from goodman_target_simulator.core import GoodmanTargetSimulator
import argparse
if __name__ == "__main__":
_about = "Simulates Goodman Data"
parser = argparse.ArgumentParser(description=_about)
parser.add_argument('filename', type=str,
help="Output filename")
parser.add_argument('-i', '--targets_intensity', type=float, nargs='+',
help="Targets positions in pixels.")
parser.add_argument('-n', '--noise_ratio', type=float,
help="Signal-to-noise ratio.")
parser.add_argument('-p', '--targets_positions', type=float, nargs='+',
help="Targets positions in pixels.")
parser.add_argument('-s', '--show', action='store_true',
help="Show plots used in the process. true/[FALSE]")
parser.add_argument('-w', '--width', type=float,
help="Seeing width in arcseconds.")
args = parser.parse_args()
gts = GoodmanTargetSimulator(
filename=args.filename,
targets_pos=args.targets_positions,
targets_int=args.targets_intensity,
seeing=args.width,
snr=args.noise_ratio,
show=args.show
)
gts.run() | cddb486b5e3bff868c35badd535d1db1eb90fb43 | [
"Markdown",
"Python"
] | 4 | Markdown | b1quint/goodman_target_simulator | 8694226ac999a0ab2157e666f0846cdf3022faec | 0f24465a754f8810fdad4057f94f2541606f82cb |
refs/heads/master | <file_sep>#ifndef MODTESTPRIVATE_P_H
#define MODTESTPRIVATE_P_H
#include <Mod/modglobal.h>
class Q_MOD_EXPORT ModTestPrivate
{
public:
ModTestPrivate();
};
#endif // MODTESTPRIVATE_P_H
<file_sep>#ifndef MODTEST_H
#define MODTEST_H
#include <Mod/modglobal.h>
class Q_MOD_EXPORT ModTest
{
public:
ModTest();
};
#endif // MODTEST_H
<file_sep>#include <Mod>
int main(int argc, char *argv[])
{
ModTest port;
}
<file_sep>#ifndef MODGLOBAL_H
#define MODGLOBAL_H
#if defined(QT_BUILD_MOD_LIB)
# define Q_MOD_EXPORT __attribute__((visibility("default")))
#else
# define Q_MOD_EXPORT __attribute__((visibility("default")))
#endif
#endif // MODGLOBAL_H
| 3a35ca546a01ac187539d9dd8f137312c536ee09 | [
"C",
"C++"
] | 4 | C++ | wicaksono/qt-module-example | 28c44115b8d7fe0fd06fe0ff8c0f01b3dc14f452 | 3a8fbe99ffb42438cf3bda63beb566da56074e92 |
refs/heads/master | <repo_name>kai2008/btcmarkets<file_sep>/btcmarkets/compat.py
import sys
import json
if sys.version_info > (3, 0):
from urllib.request import urlopen, Request
from urllib.error import HTTPError
def urllib_request(method, url, headers, data):
if isinstance(data, str):
data = data.encode("utf-8")
resp = urlopen(Request(method=method, url=url, headers=headers, data=data))
return json.loads(resp.read().decode())
else:
from urllib2 import urlopen, Request, HTTPError
def urllib_request(method, url, headers, data):
if isinstance(data, str):
data = data.encode("utf-8")
resp = urlopen(Request(url=url, headers=headers, data=data))
return json.loads(resp.read().decode())
<file_sep>/tests/conftest.py
import pytest
from btcmarkets import BTCMarkets
@pytest.fixture(scope='module')
def api():
return BTCMarkets()
<file_sep>/btcmarkets/api.py
import json
from collections import OrderedDict
from btcmarkets.enums import Multipliers
from btcmarkets.compat import urllib_request
from btcmarkets.util import build_headers, BTCMException, maybe_list
class BTCMarkets:
base_url = 'https://api.btcmarkets.net'
def __init__(self, request_func=urllib_request, return_kwargs=False):
self.request = request_func
self.return_kwargs = return_kwargs
def get_accounts(self):
return self.process(method='GET', end_point='/account/balance', parse_output=True)
def get_order_book(self, instrument, currency):
return self.process(method='GET', end_point='/market/%s/%s/orderbook' % (instrument, currency))
def get_market_trades(self, instrument, currency, since=0):
return self.process(method='GET', end_point='/market/%s/%s/trades?since=%s' % (instrument, currency, since))
def get_open_orders(self, instrument, currency, limit=100, since=0):
data = OrderedDict([
('currency', currency), ('instrument', instrument), ('limit', limit), ('since', since),
])
return self.process(method='POST', end_point='/order/open', data=data, result_key='orders', parse_output=True)
def get_order_history(self, instrument, currency, limit=100, since=0):
data = OrderedDict([
('currency', currency), ('instrument', instrument), ('limit', limit), ('since', since)
])
return self.process(method='POST', end_point='/order/history', data=data, result_key='orders', parse_output=True)
def get_trade_history(self, instrument, currency, limit=100, since=0):
data = OrderedDict([
('currency', currency), ('instrument', instrument), ('limit', limit), ('since', since)
])
end_point = '/order/trade/history'
return self.process(method='POST', end_point=end_point, data=data, result_key='trades', parse_output=True)
def get_order_detail(self, order_ids):
data = OrderedDict([('orderIds', maybe_list(order_ids))])
return self.process(method='POST', end_point='/order/detail', data=data, result_key='orders', parse_output=True)
def insert_order(self, instrument, currency, order_side, price, volume, order_type):
"""
:param instrument: {'BTC', 'ETH', 'LTC'}
:param currency: {'BTC', 'AUD'}
:param order_side: ('Bid', 'Ask')
:param price: price for order.
:param volume: volume for order.
:param order_type: {'Limit', 'Market')
:return:
"""
price_precision = {'AUD': 2, 'BTC': 8}[currency]
data = OrderedDict([
('currency', currency),
('instrument', instrument),
('price', round(price, price_precision)),
('volume', volume),
('orderSide', order_side),
('ordertype', order_type),
('clientRequestId', '1'),
])
return self.process(method='POST', end_point='/order/create', data=data, parse_output=True)
def delete_order(self, order_ids):
"""
:param order_ids: list of order_ids
:return:
"""
data = OrderedDict([('orderIds', maybe_list(order_ids))])
return self.process(method='POST', end_point='/order/cancel', data=data, parse_output=True)
def parse_input_data(self, data):
for upper in ('currency', 'instrument'):
if upper in data:
data[upper] = data[upper].upper()
if 'price' in data:
data['price'] = int(data['price'] * Multipliers.PRICE)
if 'volume' in data:
data['volume'] = int(data['volume'] * Multipliers.VOLUME)
return data
@staticmethod
def parse_output_data(data):
for x in maybe_list(data):
if isinstance(x, dict):
if 'price' in x:
x['price'] = x['price'] / Multipliers.PRICE
if 'volume' in x:
x['volume'] = x['volume'] / Multipliers.VOLUME
if 'balance' in x:
x['balance'] = x['balance'] / Multipliers.VOLUME
return data
def build_request(self, method, end_point, data=None):
url = '%s/%s' % (self.base_url, end_point)
if data is not None:
data = self.parse_input_data(data)
data = json.dumps(data, separators=(',', ':'))
headers = build_headers(end_point, data)
return dict(method=method, url=url, headers=headers, data=data)
def process(self, method, end_point, data=None, result_key=None, parse_output=True):
kwargs = self.build_request(method, end_point, data)
if self.return_kwargs:
return kwargs
resp = self.request(**kwargs)
if isinstance(resp, dict) and resp.get('errorMessage') is not None:
raise BTCMException('[%s] %s' % (resp['errorCode'], resp['errorMessage']))
if result_key:
resp = resp[result_key]
if parse_output:
resp = self.parse_output_data(resp)
return resp
<file_sep>/btcmarkets/enums.py
class Instrument:
BTC = 'BTC'
ETH = 'ETH'
LTC = 'LTC'
ETC = 'ETC'
class Currency:
AUD = 'AUD'
BTC = 'BTC'
class OrderSide:
Buy = 'Bid'
Sell = 'Ask'
class OrderType:
LIMIT = 'Limit'
MARKET = 'Market'
class Multipliers:
PRICE = 100000000
VOLUME = 100000000
<file_sep>/btcmarkets/__init__.py
from .api import BTCMarkets
__version__ = "0.0.7"
<file_sep>/btcmarkets/util.py
import os
import time
import hmac
import base64
import hashlib
import collections
class BTCMException(Exception):
pass
def build_headers(end_point, post_data=None):
api_key = os.environ['BTCMARKETS_API_KEY'].encode("utf-8")
secret = os.environ['BTCMARKETS_SECRET'].encode("utf-8")
timestamp = str(int(time.time() * 1000))
string_body = end_point + "\n" + timestamp + "\n"
if post_data is not None:
string_body += post_data
b64_secret = base64.standard_b64decode(secret)
rsig = hmac.new(b64_secret, string_body.encode("utf-8"), hashlib.sha512)
bsig = base64.standard_b64encode(rsig.digest()).decode("utf-8")
return collections.OrderedDict([
("Accept", "application/json"),
("Accept-Charset", "UTF-8"),
("Content-Type", "application/json"),
("apikey", api_key.decode("utf-8")),
("timestamp", timestamp),
("signature", bsig),
])
def maybe_list(x):
if isinstance(x, (int, float, str, dict)):
return [x]
return x
<file_sep>/HISTORY.md
CIRRUS_HISTORY_SENTINEL
CIRRUS_HISTORY_SENTINEL
<file_sep>/README.md
# btcmarkets
![build_status]
`btcmarkets` is a python wrapper for the BTCMarkets API. It has no dependencies and works with Python 2/3.
### Quick start:
#### Install
```bash
$ pip install btcmarkets
```
#### Examples
`btcmarkets.BTCMarkets` class contains the definitions and parameters for each of the API endpoints
```pydocstring
>>> from btcmarkets import BTCMarkets
>>> btcm_api = BTCMarkets()
>>> btcm_api.get_accounts()
[{'currency': 'AUD', 'balance': 100, 'pendingFunds': 0}, ...]
>>> btcm_api.get_trade_history(instrument='BTC', currency='AUD')
{'errorCode': None,
'errorMessage': None,
'success': True,
'trades': [{'creationTime': 1498623229184,
'description': None,
'fee': 69963502,
'id': 123456789,
'orderId': 123456789,
'price': 350000000000,
'side': 'Bid',
'volume': 1000000},
...
]
}
```
Further documentation and examples can (somewhat) be found on the BTCMarkets API page - https://github.com/BTCMarkets/API
#### Auth endpoints (Accounts & Trading)
In order to be able to access POST endpoints (trading and accounts), the following environment variables need to be set
- `BTCMARKETS_API_KEY`
- `BTCMARKETS_SECRET`
API keys can be generated from https://btcmarkets.net/account/apikey
#### Advanced Usage
##### Using a different HTTP request library
By default `BTCMarkets` has no dependencies and will use python3s `urllib.request`.
You can replace this with any http library by passing the request function to the constructor eg.
```pydocstring
>>> import requests
>>> btcm_api = BTCMarkets(request_func=requests.request)
```
##### Even more control
Each of the `BTCMarkets` methods simply generate a dict to pass to a http request library.
For even finer grain control over your execution, setting `return_kwargs=True` will return the underlying request dict.
```pydocstring
>>> from btcmarkets import BTCMarkets
>>> btcm_api = BTCMarkets(return_kwargs=True)
>>> btcm_api.get_accounts()
{'method': 'GET',
'url': 'https://api.btcmarkets.net/account/balance',
'headers': OrderedDict([
('Accept', 'application/json'),
('Accept-Charset', 'UTF-8'),
('Content-Type', 'application/json'),
('apikey', 'MY_API_KEY'),
('timestamp', '1498699921678'),
('signature', '123456789123456789')
]),
}
```
This could be handy if you want to use the new `async/await` features of Python with a library like `aiohttp`
```
>>> from aiohttp import ClientSession
>>> session = ClientSession()
>>> resp = await session.request(**api.get_accounts())
>>> data = await resp.json()
>>> data
[{'currency': 'AUD', 'balance': 100, 'pendingFunds': 0}, ...]
```
[build_status]: https://travis-ci.org/limx0/btcmarkets.svg?branch=master<file_sep>/tests/test_api.py
import time
import pytest
from btcmarkets.api import BTCMarkets
from btcmarkets.compat import HTTPError
from btcmarkets.enums import OrderSide, OrderType
from btcmarkets.util import BTCMException
def test_pair_specific_funcs(api):
instrument, currency = 'BTC', 'AUD'
pair_funcs = [
api.get_open_orders,
api.get_order_history,
api.get_trade_history,
api.get_market_trades,
]
for func in pair_funcs:
result = func(instrument=instrument, currency=currency)
assert isinstance(result, list)
def test_order_book(api):
result = api.get_order_book('BTC', 'AUD')
assert all(x in result for x in ('bids', 'asks',))
def test_get_accounts(api):
accounts = api.get_accounts()
assert isinstance(accounts, list)
print(accounts)
def test_order_insert_delete(api):
instrument, currency = 'BTC', 'AUD'
price = 1
volume = 0.001
# Insert a super low bid
resp_insert = api.insert_order(
instrument=instrument, currency=currency, order_side=OrderSide.Buy, price=price,
volume=volume, order_type=OrderType.LIMIT
)
assert (resp_insert['id'])
# Check order exists and is correct
time.sleep(0.5)
resp_info = api.get_order_detail(order_ids=[resp_insert['id']])
assert resp_info[0]['status'] in ('New', 'Placed')
assert resp_info[0]['volume'] == volume
assert resp_info[0]['price'] == price
# Check delete
resp_delete = api.delete_order(order_ids=[resp_insert['id']])
assert resp_delete['responses'][0]['id']
assert resp_delete['responses'][0]['success']
time.sleep(0.5)
assert not api.get_open_orders(instrument, currency)
def test_return_kwargs():
api = BTCMarkets(return_kwargs=True)
kwargs = api.get_accounts()
assert kwargs['url'] == 'https://api.btcmarkets.net//account/balance'
assert kwargs['method'] == 'GET'
assert kwargs['headers']
def test_process_exception(api):
with pytest.raises(HTTPError):
api.delete_order('a')
def test_btcmarkets_exception(api):
with pytest.raises(BTCMException):
api.get_trade_history('BTC', 'AUD', limit=99999)
def test_order_insert_currency_precision(api):
success_orders = [
{"instrument": "BTC", "currency": "AUD", "price": 0.1, "volume": 1,
"order_side": "Bid", "order_type": "Limit"},
{"instrument": "ETH", "currency": "BTC", "price": 0.00000001, "volume": 1,
"order_side": "Bid", "order_type": "Limit"},
{"instrument": "BTC", "currency": "AUD", "price": 0.011, "volume": 1,
"order_side": "Bid", "order_type": "Limit"},
]
for order in success_orders:
resp = api.insert_order(**order)
assert resp['success']
api.delete_order([resp['id']])
| a9669e853aae6a14e1f3d22c2cc640bb5ef7511b | [
"Markdown",
"Python"
] | 9 | Python | kai2008/btcmarkets | efbb6b0352732545ab2c0f857e44184b83dfba25 | e74289b0e0252d2d1ede769cc696d7fc80afbec6 |
refs/heads/main | <repo_name>alftirta/dice-game<file_sep>/go.mod
module github.com/alftirta/dice-game
go 1.17
<file_sep>/dg/dg.go
package dg
import (
"errors"
"fmt"
"math/rand"
"strconv"
"time"
)
type Player struct {
ID, Score int
IsEliminated bool
Dice []int
}
type Setting struct {
TotalPlayers, TotalDice int
TimeDelay time.Duration
}
type Game struct {
Setting
TotalRemainingPlayers int
Players, Winners []Player
}
func init() {
rand.Seed(time.Now().UnixNano())
}
// rollDice lets the player to roll its dice.
func (p *Player) rollDice() {
for i := 0; i < len(p.Dice); i++ {
p.Dice[i] = rand.Intn(6) + 1
}
}
// removeDie removes one of the player's dice. *Note: "die" is the singular form of "dice".
func (p *Player) removeDie(i int) {
copy(p.Dice[i:], p.Dice[i+1:])
p.Dice = p.Dice[:len(p.Dice)-1]
}
// evaluate evaluates the rolled dice according to the dice-game rules.
func (g *Game) evaluate() {
oneCounter := make(map[int]int) // key: Player.ID; value: count
// If it's 1, then increment the oneCounter and delete the die.
// If it's 6, then delete the die.
for i := range g.Players {
oneCounter[g.Players[i].ID] = 0
for j := 0; j < len(g.Players[i].Dice); j++ {
if g.Players[i].Dice[j] == 1 {
oneCounter[g.Players[i].ID]++
g.Players[i].removeDie(j)
j--
} else if g.Players[i].Dice[j] == 6 {
g.Players[i].Score += 6
g.Players[i].removeDie(j)
j--
}
}
}
// Give the numbered 1 dice to the next player.
for i, v := range oneCounter {
if v > 0 {
if i < len(oneCounter) {
for j := 0; j < v; j++ {
if g.Players[i].IsEliminated == false {
g.Players[i].Dice = append(g.Players[i].Dice, 1)
}
}
} else {
for j := 0; j < v; j++ {
if g.Players[0].IsEliminated == false {
g.Players[0].Dice = append(g.Players[0].Dice, 1)
}
}
}
}
}
// Eliminate players who don't have any die left.
for i, p := range g.Players {
if len(p.Dice) == 0 && p.IsEliminated == false {
g.Players[i].IsEliminated = true
g.TotalRemainingPlayers--
}
}
}
// convertDiceToString convert a dice slice into string.
func (g *Game) convertDiceToString(i int) (result string) {
for j := 0; j < len(g.Players[i].Dice); j++ {
if j == len(g.Players[i].Dice)-1 {
result += strconv.Itoa(g.Players[i].Dice[j])
break
}
result += strconv.Itoa(g.Players[i].Dice[j]) + ", "
}
if result == "" {
result = "_"
}
return
}
// getWinners get game winners based on players' score.
func (g *Game) getWinners() {
for _, p := range g.Players {
if p.Score > g.Winners[0].Score {
g.Winners = []Player{p}
} else if p.Score == g.Winners[0].Score && p.ID != g.Players[0].ID {
g.Winners = append(g.Winners, p)
}
}
}
// announceTheWinners announce the winners on the terminal.
func (g *Game) announceTheWinners() {
if len(g.Winners) == len(g.Players) && len(g.Winners) > 1 {
fmt.Printf("Seri! Setiap pemain mendapatkan %d poin.\n", g.Winners[0].Score)
} else if len(g.Winners) == 1 {
fmt.Printf("Selamat! Pemenangnya adalah Pemain #%d dengan %d poin.\n", g.Winners[0].ID, g.Winners[0].Score)
} else if len(g.Winners) == 2 {
fmt.Printf(
"Seri! Pemain #%d dan Pemain #%d masing-masing mendapatkan %d poin.\n",
g.Winners[0].ID,
g.Winners[1].ID,
g.Winners[1].Score,
)
} else if len(g.Winners) > 2 {
str := "Seri! "
for i, w := range g.Winners {
if i < len(g.Winners)-1 {
str += fmt.Sprintf("Pemain #%d, ", w.ID)
} else {
str += fmt.Sprintf("and Pemain #%d masing-masing mendapatkan %d poin.\n", w.ID, w.Score)
}
}
fmt.Println(str)
}
}
// Play starts the game.
func (g *Game) Play() {
fmt.Println("====================")
fmt.Printf("Pemain = %d, Dadu = %d\n", g.Setting.TotalPlayers, g.Setting.TotalDice)
fmt.Println("====================")
time.Sleep(g.Setting.TimeDelay)
turn := 1
for {
// All players roll their dice.
fmt.Printf("Giliran %d lempar dadu:\n", turn)
for i := 0; i < len(g.Players); i++ {
// Check if each player still has dice.
if len(g.Players[i].Dice) > 0 && g.Players[i].IsEliminated == false {
g.Players[i].rollDice()
}
fmt.Printf(" Pemain #%d (%d): %s\n", g.Players[i].ID, g.Players[i].Score, g.convertDiceToString(i))
}
// Evaluate according to the game rules.
g.evaluate()
fmt.Println("Setelah evaluasi:")
for i := 0; i < len(g.Players); i++ {
fmt.Printf(" Pemain #%d (%d): %s\n", g.Players[i].ID, g.Players[i].Score, g.convertDiceToString(i))
}
fmt.Println("====================")
time.Sleep(g.Setting.TimeDelay)
// Check if the game is over.
if g.TotalRemainingPlayers <= 1 {
g.getWinners()
g.announceTheWinners()
fmt.Printf("Permainan telah berakhir dalam %d giliran.\n", turn)
break
}
turn++
}
}
// CreatePlayers creates players.
func CreatePlayers(totalPlayers, totalDice int) ([]Player, error) {
if totalPlayers < 0 {
msg := "totalPlayers cannot be negative"
return nil, errors.New(msg)
}
players := make([]Player, totalPlayers)
for i := 0; i < totalPlayers; i++ {
players[i] = Player{
ID: i+1,
Dice: make([]int, totalDice),
}
}
return players, nil
}
// CreateGame creates a dice game.
func CreateGame(ps []Player, td time.Duration) (Game, error) {
if ps == nil {
msg := "players cannot be nil"
return Game{}, errors.New(msg)
}
game := Game{
Setting: Setting{
TotalPlayers: len(ps),
TotalDice: len(ps[0].Dice),
TimeDelay: td * time.Millisecond,
},
TotalRemainingPlayers: len(ps),
Players: ps,
Winners: []Player{ps[0]},
}
return game, nil
}
| eb0669e0b141d0f5557dff2bf81324e3f346bafb | [
"Go",
"Go Module"
] | 2 | Go Module | alftirta/dice-game | 3dbdf16fe95e4597a09d7a2a919b0056e2f3df00 | 7402ed0c961015e2db2d281af404636bbaa439fd |
refs/heads/master | <repo_name>aHDPik/NegativeEffect<file_sep>/Matrix/FileManipulations/StaticMatrix.h
#pragma once
namespace staticmat {
constexpr int MAX_NAME_SIZE = 255 ;
constexpr int MAX_MATR_SIZE = 100;
struct Matrix {
char name[MAX_NAME_SIZE];
int vertSize;
double vertMatr[MAX_MATR_SIZE];
int horSize;
double horMatr[MAX_MATR_SIZE];
};
}<file_sep>/Matrix/Matrix/Editor.h
#include <opencv2/opencv.hpp>
struct Matrix {
std::string name;
std::vector<double> arr1;
std::vector<double> arr2;
int width;
int height;
};
int index(int x, int y, int width);
unsigned char clamp(double val);
Matrix* modifyImage(const std::uint8_t const* inputImage, std::uint8_t* outputImage, std::uint32_t width, std::uint32_t height, std::vector<Matrix>&);
Matrix* CreatMatrix(std::vector<Matrix>& ARR);
Matrix* ChooseMatrix(std::vector<Matrix>& ARR);
Matrix* Exit(std::vector<Matrix>& ARR);
Matrix* (*functions[])(std::vector<Matrix>& ARR);
Matrix* dialogChoose(std::vector<Matrix>& ARR);
void copyEdges(const std::uint8_t const* inputImage, std::uint8_t* outputImage, std::uint32_t width, std::uint32_t height, Matrix* M);
int dialog(const char* msgs[], int N);
int getNaturalInt(int* a);
void save(std::vector<Matrix>& ARR);
std::vector<Matrix> load(std::vector<Matrix>&);
std::vector<Matrix> addMatrix(std::vector<Matrix>& ARR, Matrix* M);<file_sep>/ConsoleTest/main.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char** argv) {
if (argc != 2)
return -1;
ifstream textFile(argv[1]);
string text;
textFile >> text;
cout << text << endl;
string a;
cin >> a;
}<file_sep>/Matrix/Matrix/Editor.cpp
#include "Editor.h"
#include <opencv2/opencv.hpp>
#include <iostream>
#include <fstream>
const char* msgs[] = { "\n [0] Create filter",
" [1] Choose filter",
" [2] Exit\n"
};
const int NMsgs = sizeof(msgs) / sizeof(msgs[0]);
Matrix* (*functions[])(std::vector<Matrix>&) = { CreatMatrix, ChooseMatrix, Exit };
Matrix* dialogChoose(std::vector<Matrix>& ARR) {
int rc = dialog(msgs, NMsgs);
return functions[rc](ARR);
}
Matrix* ChooseMatrix(std::vector<Matrix>& ARR) {
Matrix M;
int a = 0;
if (ARR.size() == 0) {
std::cout << "No filters!";
return nullptr;
}
else {
for (int i = 0; i < ARR.size(); i++)
std::cout << "[" << i << "] - " << ARR[i].name << std::endl;
do {
std::cout << "Your choise:";
std::cin >> a;
} while (a < 0 || a >= ARR.size());
return &ARR[a];
}
}
Matrix* CreatMatrix(std::vector<Matrix>& ARR) {
int a;
Matrix* M = new Matrix;
do {
std::cout << "Enter the number of the first matrix:";
std::cin >> M->height;
} while (!(M->height % 2));
for (int y = 0; y < M->height; y++) {
std::cout << "Enter the [" << y + 1 << "] element of the matrix:";
std::cin >> a;
M->arr1.push_back(a);
}
do {
std::cout << "Enter the number of the second matrix:";
std::cin >> M->width;
} while (!(M->width % 2));
for (int x = 0; x < M->width; x++) {
std::cout << "Enter the [" << x + 1 << "] element of the matrix:";
std::cin >> a;
M->arr2.push_back(a);
}
return M;
}
Matrix* Exit(std::vector<Matrix>& ARR) {
return nullptr;
}
Matrix* modifyImage(const std::uint8_t const* inputImage, std::uint8_t* outputImage, std::uint32_t width, std::uint32_t height, std::vector<Matrix>& ARR) {
Matrix* M;
if (M = dialogChoose(ARR)) {
cv::Mat bigImage(height + 2 * (M->height / 2), width + 2 * (M->width / 2), CV_8UC3);
for (int y = (M->height / 2); y < height + (M->height / 2); y++)
for (int x = (M->width / 2); x < width + (M->width / 2); x++) {
int ind = index(x, y, width + 2 * (M->width / 2));
int ind1 = index((x - (M->width / 2)), (y - (M->height / 2)), width);
for (int i = 0; i < 3; i++) {
bigImage.data[ind + i] = inputImage[ind1 + i];
}
}
copyEdges(inputImage, bigImage.data, width, height, M);
for (int y = M->height/2; y < height + (M->height / 2); y++)
for (int x = M->width/2; x < width + (M->height / 2); x++) {
int ind = index(x - M->width/2, y - M->height/2, width);
for (int i = 0; i < 3; i++) {
int j = 0;
double r = 0;
outputImage[ind + i] = 0;
for (int n = x - (M->width / 2), j = 0; n <= x + (M->width / 2); n++, j++)
r += M->arr1[j] * bigImage.data[index(n, y, width+2* (M->width / 2)) + i];
for (int m = y - (M->height / 2), j = 0; m <= y + (M->height / 2); m++, j++)
r += M->arr2[j] * bigImage.data[index(x, m, width+2*(M->width / 2)) + i];
outputImage[ind + i] = clamp(r / 2);
}
}
return M;
}
else {
return nullptr;
}
}
std::vector<Matrix> addMatrix(std::vector<Matrix>& ARR, Matrix* M) {
int a = 0, i;
do {
std::cout << "Do you want to save this filter?\n [Yes]-1 [No]-0\n Your choise:";
std::cin >> a;
} while (a < 0 || a>1);
if (a) {
do {
std::cout << "Enter name of filter:";
std::cin >> M->name;
for (i = 0; i < ARR.size(); i++) {
if (ARR[i].name == M->name) {
std::cout << "ERROR! This filter already have created!\n";
i=-1;
}
}
} while (i==-1);
ARR.push_back(*M);
}
else {
delete M;
}
return ARR;
}
void copyEdges(const std::uint8_t const* inputImage, std::uint8_t* bigImage, std::uint32_t width, std::uint32_t height, Matrix* M) {
for (int x = M->width / 2; x < width + M->width / 2; x++) {
int ind1 = index(x - (M->width / 2), 0, width);
for (int y = 0; y < M->height / 2; y++) {
int ind = index(x, y, width + 2*(M->width/2));
for (int i = 0; i < 3; i++) {
bigImage[ind + i] = inputImage[ind1 + i];
}
}
}
for (int x = M->width / 2; x < width + M->width / 2; x++) {
int ind1 = index(x - (M->width / 2), height-1, width);
for (int y = height+M->height/2; y < height+2*(M->height/2); y++) {
int ind = index(x, y, width + 2*(M->width/2));
for (int i = 0; i < 3; i++) {
bigImage[ind + i] = inputImage[ind1 + i];
}
}
}
for (int y = 0; y < height+2*(M->height/2); y++) {
int ind1 = index(M->width/2, y, width + 2 * (M->width / 2));
for (int x = 0; x < M->width / 2; x++) {
int ind = index(x, y, width + 2 * (M->width / 2));
for (int i = 0; i < 3; i++) {
bigImage[ind + i] = bigImage[ind1 + i];
}
}
}
for (int y = 0; y < height + 2 * (M->height / 2); y++) {
int ind1 = index(width-1, y, width + 2 * (M->width / 2));
for (int x = width+ M->width / 2; x < width+2*( M->width / 2); x++) {
int ind = index(x, y, width + 2 * (M->width / 2));
for (int i = 0; i < 3; i++) {
bigImage[ind + i] = bigImage[ind1 + i];
}
}
}
}
int index(int x, int y, int width) {
return ((x + y * width) * 3);
}
int dialog(const char* msgs[], int N) {
std::string errmsg;
int rc;
do {
std::cout << errmsg;
errmsg = "You are wrong. Repeat, please\n";
for (int j = 0; j < N; ++j)
puts(msgs[j]);
std::cout << "Make your choice:";
if (getNaturalInt(&rc) == 0) { rc = 0; }
} while (rc < 0 || rc >= N);
return rc;
}
int getNaturalInt(int* a) {
do {
std::cin >> *a;
if (*a < 0)
return 0;
if (*a < 0) {
std::cout << "Error! Please, repeat your input: ";
std::cin.clear();
std::cin.ignore(INT_MAX, '\n');
}
} while (*a < 0);
return 1;
}
unsigned char clamp(double val) {
if (val < 0)
return 0;
if (val > 255)
return 255;
return (unsigned char)val;
}
std::vector<Matrix> load(std::vector<Matrix>& ARR) {
int i = 0, j;
std::ifstream data;
data.open("data.txt", std::ifstream::in);
if (data.is_open()) {
data.seekg(0, std::ios::beg);
while (!data.eof()) {
//Matrix M;
Matrix* M = new Matrix;
data >> M->name;
if ((M->name.size() == 0))
break;
data >> M->height >> M->width;
for (int i = 0; i < M->height; i++) {
data >> j;
M->arr1.push_back(j);
}
for (int i = 0; i < M->width; i++) {
data >> j;
M->arr2.push_back(j);
}
ARR.push_back(*M);
}
data.close();
}
return ARR;
}
void save(std::vector<Matrix>& ARR) {
std::ofstream data;
data.open("data.txt", std::ios_base::out | std::ios_base::trunc);
if (data.is_open()) {
for (int j = 0; j < ARR.size(); j++) {
data << ARR[j].name << " " << ARR[j].height << " " << ARR[j].width << " " << std::endl;
for (int i = 0; i < ARR[j].height; i++)
data << ARR[j].arr1[i] << " ";
data << std::endl;
for (int i = 0; i < ARR[j].width; i++)
data << ARR[j].arr2[i] << " ";
data << std::endl;
}
data.close();
}
}<file_sep>/NegativeEffect/main.cpp
#include <opencv2/opencv.hpp>
#include <iostream>
#include <cstdint>
#include <memory>
//rgb24, bgr24, rgb32, rgba32, arbg32, yuv, nv12
void modifyImage(const std::uint8_t const* inputImage, std::uint8_t* outputImage, std::uint32_t width, std::uint32_t height) {
//[b00 g00 r00 b10 g10 r10 b20 g20 r20 b01 g01 r01 b11 g11 r11 b21 g21 r21]
//[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ]
// x=0 b=0 g=1 r=2
// x=1 b=3 g=4 r=5
// x=2 b=6 g=7 r=8
//b(x)=x*3 g(x)=x*3+1 r(x)=x*3+2
//b(0,0)=0
//b(0,1)=9
//b(0,2)=18
//b(y)=y*width*3
//b(x,y)=x*3+y*width*3=[(x+y*width)*3];
int size = width * height * 3;
for (int i = 0; i < size; i ++) {
outputImage[i] = 255 - inputImage[i];
}
}
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "Specify file name" << std::endl;
return -1;
}
cv::Mat img = cv::imread(argv[1]);
cv::imshow("Original image", img);
cv::Mat negativeSample = cv::Scalar(255, 255, 255) - img;
cv::imshow("Negative", negativeSample);
cv::Mat modifiedImage(img.rows, img.cols, CV_8UC3);
modifyImage(img.data, modifiedImage.data, img.cols, img.rows);
cv::imshow("Modified", modifiedImage);
cv::waitKey(0);
return 0;
}<file_sep>/Matrix/FileManipulations/DynamicMatrix.h
#pragma once
namespace dynamicmat {
struct Matrix {
char* name;
int nameSize;
int vertSize;
double* vertMatr;
int horSize;
double* horMatr;
};
}<file_sep>/Matrix/Matrix/main.cpp
#include <opencv2/opencv.hpp>
#include <iostream>
#include "Editor.h"
#include <fstream>
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "Specify file name!" << std::endl;
return -1;
}
cv::Mat img = cv::imread(argv[1]);
cv::imshow("Original image", img);
cv::waitKey(1);
cv::Mat modifiedImage(img.rows, img.cols, CV_8UC3);
std::vector<Matrix> Arr;
Arr = load(Arr);
Matrix* M;
do {
if (!(M = modifyImage(img.data, modifiedImage.data, img.cols, img.rows, Arr)))
break;
cv::imshow("Modified", modifiedImage);
cv::waitKey(1);
if (M->name.size() == 0) {
Arr = addMatrix(Arr, M);
}
} while (1);
save(Arr);
//for (int i = 0; i < ARR.size(); i++) {
// delete[] ARR[i]->arr1;
// delete[] ARR[i]->arr2;
// delete ARR[i];
//}
return 0;
}<file_sep>/Matrix/FileManipulations/main.cpp
#include "StaticMatrix.h"
#include "DynamicMatrix.h"
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char** argv) {
staticmat::Matrix statMat;
std::cin >> statMat.name;
std::cin >> statMat.vertSize;
for(int i=0; i<statMat.vertSize; i++)
std::cin >> statMat.vertMatr[i];
std::cin >> statMat.horSize;
for (int i = 0; i < statMat.horSize; i++)
std::cin >> statMat.horMatr[i];
std::ofstream outFile("out.bin", std::ios::binary);
outFile.write((char*)&statMat, sizeof(statMat));
outFile.close();
staticmat::Matrix statMatNew;
std::ifstream inFile("out.bin", std::ios::binary);
inFile.read((char*)&statMatNew, sizeof(statMatNew));
inFile.close();
dynamicmat::Matrix dynMat;
std::string matrName;
std::cin >> matrName;
dynMat.nameSize = matrName.size() + 1;
dynMat.name = new char[dynMat.nameSize];
std::memcpy(dynMat.name, matrName.c_str(), dynMat.nameSize);
std::cin >> dynMat.vertSize;
dynMat.vertMatr = new double[dynMat.vertSize];
for (int i = 0; i < dynMat.vertSize; i++)
std::cin >> dynMat.vertMatr[i];
std::cin >> dynMat.horSize;
dynMat.horMatr = new double[dynMat.horSize];
for (int i = 0; i < dynMat.horSize; i++)
std::cin >> dynMat.horMatr[i];
std::ofstream outDynFile("outDyn.bin", std::ios::binary);
outDynFile.write((char*)&dynMat, sizeof(dynMat));
outDynFile.write((char*)dynMat.name, dynMat.nameSize * sizeof(char));
outDynFile.write((char*)dynMat.vertMatr, dynMat.vertSize * sizeof(double));
outDynFile.write((char*)dynMat.horMatr, dynMat.horSize * sizeof(double));
outDynFile.close();
delete[] dynMat.name;
delete[] dynMat.vertMatr;
delete[] dynMat.horMatr;
dynamicmat::Matrix dynMatNew;
std::ifstream inDynFile("outDyn.bin", std::ios::binary);
inDynFile.read((char*)&dynMatNew, sizeof(dynMatNew));
dynMatNew.name = new char[dynMatNew.nameSize];
dynMatNew.vertMatr = new double[dynMatNew.vertSize];
dynMatNew.horMatr = new double[dynMatNew.horSize];
inDynFile.read((char*)dynMatNew.name, dynMatNew.nameSize * sizeof(char));
inDynFile.read((char*)dynMatNew.vertMatr, dynMatNew.vertSize * sizeof(double));
inDynFile.read((char*)dynMatNew.horMatr, dynMatNew.horSize * sizeof(double));
inDynFile.close();
delete[] dynMatNew.name;
delete[] dynMatNew.vertMatr;
delete[] dynMatNew.horMatr;
}<file_sep>/README.MD
# Задание
Реализовать функцию modifyImage, не меняя её сигнатуры и не используя глобальных переменных. Результирующее изображение должно совпадать с тем, что было получено при помощи функции opencv. | 7f399ee0b8f5e732c15898c9ba7d2f994acf3dd8 | [
"Markdown",
"C++"
] | 9 | C++ | aHDPik/NegativeEffect | a970dc0c1e94265882c352ac0fddfb6b5af50fb9 | 30cb84d252c63ecd19a7a30f9b25a2e54a0e1828 |
refs/heads/main | <repo_name>iamshakibb/athena<file_sep>/src/Components/Achievements/Achievements.js
import React from "react";
import { Container, Row } from "react-bootstrap";
import "./Achievements.scss";
import HappySVG from "../SVG/HappySVG";
import MarketingSVG from "../SVG/MarketingSVG";
import SurfaceSVG from "../SVG/SurfaceSVG";
import TransportationSVG from "../SVG/TransportationSVG";
export default function Achievements() {
return (
<div className="Achievements d-flex justify-content-center align-items-center mt-5 mb-5 pt-5">
<Container>
<Row>
<div className="col-md-5 d-flex align-items-center justify-content-center">
<div className="pr-5">
<h1>Our Achievements</h1>
<p>
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that
it has a more-or-less normal distribution of letter.
</p>
</div>
</div>
<div className="col-md-7">
<Row className="text-center align-items-center justify-content-between">
<Row className="achievementBox align-items-center justify-content-center">
<div className="mr-3">
<HappySVG />
</div>
<div className="text-left">
<p>200+</p>
<p>Happy Clients</p>
</div>
</Row>
<Row className="achievementBox1 align-items-center justify-content-center">
<div className="mr-3">
<MarketingSVG />
</div>
<div className="text-left">
<p>200+</p>
<p>Happy Clients</p>
</div>
</Row>
<Row className="achievementBox1 align-items-center justify-content-center">
<div className="mr-3">
<SurfaceSVG />
</div>
<div className="text-left">
<p>200+</p>
<p>Happy Clients</p>
</div>
</Row>
<Row className="achievementBox align-items-center justify-content-center">
<div className="mr-3">
<TransportationSVG />
</div>
<div className="text-left">
<p>200+</p>
<p>Happy Clients</p>
</div>
</Row>
</Row>
</div>
</Row>
</Container>
</div>
);
}
<file_sep>/src/Components/Footer/Footer.js
import React from "react";
import { Container, Row } from "react-bootstrap";
import logo from "../../assets/images/Illustration/Group 86.png";
import { faBehance, faDribbble, faFacebook, faLinkedinIn, faTwitter } from "@fortawesome/free-brands-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import "./Footer.scss";
export default function Footer() {
return (
<Container className="mt-5 py-3 contact" id="contact">
<Row>
<div className="col-md-4">
<div className="logo">
<img src={logo} alt="LOGO" />
</div>
<div className="socialLinks mt-3">
<FontAwesomeIcon icon={faFacebook} />
<FontAwesomeIcon icon={faTwitter} />
<FontAwesomeIcon icon={faLinkedinIn} />
<FontAwesomeIcon icon={faDribbble} />
<FontAwesomeIcon icon={faBehance} />
</div>
</div>
<div className="col-md-2 d-flex text-left d-flex justify-content-center">
<ul>
<li>Features</li>
<li>Enterprise</li>
<li>Pricing</li>
</ul>
</div>
<div className="col-md-2 d-flex text-left d-flex justify-content-center">
<ul>
<li>Blog</li>
<li>Help Center</li>
<li>Contact Us</li>
<li>Status</li>
</ul>
</div>
<div className="col-md-2 d-flex text-left d-flex justify-content-center">
<ul>
<li>About Us</li>
<li>Terms of Service</li>
<li>Security</li>
<li>Login</li>
</ul>
</div>
</Row>
</Container>
);
}
<file_sep>/src/Components/Services/Services.js
import React from "react";
import { Button, Container, Row } from "react-bootstrap";
import servicesImg from "../../assets/images/Illustration/20 [Converted]@2x.png";
import "./Services.scss";
export default function Services() {
return (
<div className="d-flex align-items-center justify-content-center mt-3 mb-5 services" id="services">
<Container>
<Row>
<div className="col-md-6">
<img className="img-fluid" src={servicesImg} alt="services Img" />
</div>
<div className="col-md-6 d-flex align-items-center justify-content-right">
<div>
<h1>Stay Running & Project</h1>
<p>
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that
it has a more-or-less normal distribution of letter.
</p>
<Button className="px-4">Contact us</Button>
</div>
</div>
</Row>
</Container>
</div>
);
}
<file_sep>/src/Components/EmailForm/EmailForm.js
import React from "react";
import { Button, Container, Row } from "react-bootstrap";
import "./EmailForm.scss";
export default function EmailForm() {
return (
<Container className="email mt-5 py-5">
<div className="col-md-12 heading text-center">
<h1>Get your design right, right now</h1>
<p>Be the first know our latest offers and updates!</p>
</div>
<div className="col-12 mt-5 d-flex align-items-center justify-content-center">
<form className="emailForm d-flex align-items-center justify-content-center">
<input className="w-75" type="email" placeholder="Enter Email" />
<Button className="py-2 mr-4">Get Started</Button>
</form>
</div>
</Container>
);
}
<file_sep>/src/Components/Heading/Heading.js
import React from "react";
export default function Heading({ heading, message }) {
return (
<div className="text-center heading mb-5">
<h1>{heading}</h1>
<p className="paragraphColor">{message}</p>
</div>
);
}
<file_sep>/src/Components/HeroSection/HeroSection.js
import { Container, Row } from "react-bootstrap";
import "./HeroSection.scss";
import heroImg from "../../assets/images/Illustration/16 [Converted]@2x.png";
export default function HeroSection() {
return (
<Container>
<Row className="heroContainer">
<div className="col-md-6 d-flex align-items-center">
<div>
<h1>
Florence <br /> agency
</h1>
<p>
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
book.
</p>
</div>
</div>
<div className="col-md-6">
<img className="img-fluid" src={heroImg} alt="Hero Section Img" />
</div>
</Row>
</Container>
);
}
<file_sep>/src/App.js
import "./App.scss";
import About from "./Components/About/About";
import Achievements from "./Components/Achievements/Achievements";
import EmailForm from "./Components/EmailForm/EmailForm";
import Footer from "./Components/Footer/Footer";
import HeroSection from "./Components/HeroSection/HeroSection";
import NavBar from "./Components/NavBar/NavBar";
import PriceSection from "./Components/PriceSection/PriceSection";
import Services from "./Components/Services/Services";
function App() {
return (
<>
<div className="headerBg">
<NavBar />
<HeroSection />
</div>
<About />
<Services />
<div className="secondaryBg">
<Achievements />
<PriceSection />
<EmailForm />
<Footer />
</div>
</>
);
}
export default App;
<file_sep>/src/Components/PriceSection/PriceSection.js
import React from "react";
import { Button, Container, Row } from "react-bootstrap";
import "./PriceSection.scss";
export default function PriceSection() {
return (
<Container className="mt-5 p-5 mb-5 priceSection" id="price">
<Row className="align-item-center justify-content-center text-center">
<div className="col-md-12 mb-5 text-center heading">
<h1>Choose Your Dedicated Team</h1>
</div>
<div className="col-md-4">
<div className="priceOption">
<div className="price">
<h1>$199</h1>
<p>For Basic</p>
</div>
<ul>
<li>Homepage</li>
<li>No Inner Page</li>
<li>Asset file</li>
<li>Source file</li>
<li>Free Stock Photos</li>
<li>10 Days Free Support</li>
<li>24/7 Support</li>
<Button className="px-4 mt-5">Order Now</Button>
</ul>
</div>
</div>
<div className="col-md-4">
<div className="priceOption">
<div className="price">
<h1>$399</h1>
<p>For Preferred</p>
</div>
<ul>
<li>Homepage</li>
<li>4 Inner Pages</li>
<li>Asset file</li>
<li>Source file</li>
<li>Free Stock Photos</li>
<li>20 Days Free Support</li>
<li>24/7 Support</li>
<Button className="px-4 mt-5">Order Now</Button>
</ul>
</div>
</div>
<div className="col-md-4">
<div className="priceOption">
<div className="price">
<h1>$599</h1>
<p>For Elite</p>
</div>
<ul>
<li>Homepage</li>
<li>8 Inner Pages</li>
<li>Asset file</li>
<li>Source file</li>
<li>Free Stock Photos</li>
<li>30 Days Free Support</li>
<li>24/7 Support</li>
<Button className="px-4 mt-5">Order Now</Button>
</ul>
</div>
</div>
</Row>
</Container>
);
}
<file_sep>/src/Components/NavBar/NavBar.js
import { Button, Container, Nav, Navbar } from "react-bootstrap";
import "./NavBar.scss";
import logo from "../../assets/images/Illustration/Group 86.png";
export default function NavBar() {
return (
<Container>
<Navbar expand="md">
<Navbar.Brand href="#home" className="logo">
<img src={logo} alt="LOGO" />
</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="ml-auto nav NavMenu">
<Nav.Link href="#home">Home</Nav.Link>
<Nav.Link href="#about">About</Nav.Link>
<Nav.Link href="#services">Services</Nav.Link>
<Nav.Link href="#price">Pricing</Nav.Link>
<Nav.Link href="#team">Our Team</Nav.Link>
<Button className="px-4 py-2">Contact us</Button>
</Nav>
</Navbar.Collapse>
</Navbar>
</Container>
);
}
| 6238be9701c52342972bfd1a01268af18fd1d54d | [
"JavaScript"
] | 9 | JavaScript | iamshakibb/athena | 4f15aa6d55103c5b0c9ca42d7c55b012ebabfe97 | a6b713a29bbd62b0f6e5788d79939373e975738d |
refs/heads/master | <file_sep>package keywords;
import edu.jsu.mcis.*;
public class GamegogyGUIKeywords {
private String columnName;
private String courseId;
private String courseTerm;
private String courseEnrollment;
private String studentId;
private String studentName;
private String studentEmail;
private String studentScore;
public void getSelectedItemFromComboBox() {
GamegogyGUI g = new GamegogyGUI();
}
}<file_sep>/*
package edu.jsu.mcis;
import java.util.*;
import org.junit.*;
import static org.junit.Assert.*;
public class GamegogyGUITest {
private GamegogyGUI g;
private String cDefault;
@Before
public void setup() {
g = new GamegogyGUI();
}
@Test
public void testCourseComboBoxHasCorrectValues() {
assertTrue();
}
@Test
public void testGradeDataisLoaded() {
assertTrue(false);
}
@Test
public void testCourseDataIsLoaded() {
assertTrue(false);
}
@Test
public void testTopStudentIsLoaded() {
assertTrue(false);
}
}
*/<file_sep>package edu.jsu.mcis;
import org.junit.*;
import static org.junit.Assert.*;
public class CSVParserTest {
private CSVParser p;
@Before
public void setup() {
p = new CSVParser();
}
@Test
public void testThatCourseIdsAreLoaded() {
assertNotNull(p.getStudentIds());
//in new test
//get first
//get last
//get length
//repeat for students
}
@Test
public void testThatStudentIdsAreLoaded() {
assertNotNull(p.getCourseIds());
}
@Test
public void testParserReadsStudentInfo(){
Student s = new Student("111111", "Jerrod", "Shields", "jshields");
Student t = p.getStudent("111111");
assertEquals(s, t);
}
@Test
public void testThatStudentIsNotReturned(){
Student t = p.getStudent("1");
assertNull(t);
}
@Test
public void testThatCourseIsNotReturned(){
Course t = p.getCourse("1");
assertNull(t);
}
@Test
public void testParserReadsCourseInfo(){
Course c = new Course("99018", "Spring", "2014", "16");
Course t = p.getCourse("99018");
assertEquals(c, t);
}
/*@Test
public void testThatCoursesAreLoaded(){
assertNotNull(p.getCourses());
}*/
}
| 004336cb64f2788726aacf632019e5d12fc29013 | [
"Java"
] | 3 | Java | cdikoko/Leaderboard | 046f88aa2c345bf1ef103f32950b728c41ce8b24 | 90ea8f301e6401efa395a9ad030bc002a1da5b43 |
refs/heads/master | <file_sep><img src="Images/main_picture.png" width="500" height="200" >
## Finding a mechanic has never been easier
CarFix is an app that connects vehicle owners to automotive professionals. CarFix enables connection in 2 types of users: a private customer (car owner) and a business customer (car service provider) and allows a private customer to search by criteria, view the business profile and schedule treatment online, conveniently and quickly.
The user will be able to receive a reminder on the phone about an hour before the treatment hour and at the end he will be able to rate the business owner according to his level of satisfaction.
In addition, at the end of the treatment the business owner will be able to specify the treatment details and what is done in the queue in the app. The queue will be kept in the care history of the vehicle owner and the business owner and will be available for future viewing from each user's home page.
## Application development
The application developed in Android studio and FireBase database to save the object and the information of the application.
## App walkthrough
### Registration
* In the login page press button register in the right button.<br>
* Choose the kind of user you want to register with.<br>
* Fill the fields with your information.
<img src="Images/login.png"> <img title="Private user registration" src="Images/privateuserregister.png"> <img title="Business user registration" src="Images/businessuserregister.png">
### Private user
After login, the private user transfered to his profile screen.
Private user can perform several actions:
1. Editing a personal profile.
2. Viewing upcoming appointments.
3. Rating the business.
<img src="Images/privateuserprofilepage.png">
more functions:
1. press on business phone number and the application move you to the dialer.
<img src="Images/dialer.png" width="700" height="400">
2. press on set notification, the application set notifiaction one hour before the appointment.
<img src="Images/notification.png" width="500" height="400">
### Business user
After login, the business user transfered to his profile screen.
Business user can perform several actions:
1. View upcoming queues - work schedule.
2. Edit business profile.
3. Leave the description of the service provided in the same queue - the description will be stored in a queue in DB for both users and will be updated on the home screens.
<img src="Images/businessuserprofile.jpg">
## Main Functionality
### Search
The user will be able to perform a search of his choice.
The system will display the businesses that meet the search results with:
1. contact information.
2. an average rating determined by customers who used the services of that business.
3. button through which he can enter the business page and book an appointment.
<img src="Images/searchandresultsscreens.png" width="500" height="400" >
### Book a treatment
The user will be able to book an appointment on the available dates and hours displayed in the calendar and the time wheel.
Once scheduled, it will be saved in the DB of both users and displayed on the home pages of both.
<img src="Images/booktreatment.png">
## Databse
In the project we use FireBase database to store all the information of the application.
The databse is designed with 3 objects as shown in the picture below.
<img src="Images/databasepicture.png">
<file_sep>package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
public class RegisterUser extends AppCompatActivity implements View.OnClickListener {
private Button registerUser;
//for user register
private EditText editTextEmail,editTexPassword,carNumber,carYear;
private ProgressBar progressBar;
private FirebaseAuth mAuth;
private Spinner carCompanyList;
private TextView privateUser,businessUser;// choose which user to register
//for business user
private EditText editBusinessName,editBussinesPassword,editBusinessAddress,editBusinessEmail,editBusinesPhone;
private Spinner kindOfBusiness,businessCity;
private Button carsInBusinessButton;
private String [] listOfCars;
private boolean [] checkCars;
private ArrayList<Integer> carsBussines;
private boolean WhichUser = true;
private String finalListOfCarBusiness = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_user);
//set the private user button
privateUser = (TextView) findViewById(R.id.PrivateUser);
privateUser.setOnClickListener(this);
//set the business user button
businessUser = (TextView) findViewById(R.id.BusinessUser);
businessUser.setOnClickListener(this);
// initialize the Firebase variable
mAuth = FirebaseAuth.getInstance();
registerUser = (Button)findViewById(R.id.registerbutton);
registerUser.setOnClickListener(this);
// initialize private user register
editTextEmail = (EditText) findViewById(R.id.Email);
editTexPassword = (EditText) findViewById(R.id.password);
carNumber = (EditText) findViewById(R.id.carNumber);
carYear = (EditText) findViewById(R.id.CarYear);
carCompanyList = (Spinner) findViewById(R.id.carModelScrollDown);
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.CarTypes));
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
carCompanyList.setAdapter(myAdapter);
//initialize business register
editBusinessName = (EditText) findViewById(R.id.businessName);
editBusinessName.setVisibility(View.GONE);
editBusinessEmail = (EditText) findViewById(R.id.businessEmail);
editBusinessEmail.setVisibility(View.GONE);
editBussinesPassword = (EditText) findViewById(R.id.businessPassword);
editBussinesPassword.setVisibility(View.GONE);
kindOfBusiness = (Spinner) findViewById(R.id.kindOfBusiness);
ArrayAdapter<String> myAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.KindOfBusiness));
myAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
kindOfBusiness.setAdapter(myAdapter1);
kindOfBusiness.setVisibility(View.GONE);
//Cars to treat in BUsiness the final array is carsBusiness
carsInBusinessButton = (Button) findViewById(R.id.CarsInBusiness);
carsInBusinessButton.setVisibility(View.GONE);
carsInBusinessButton.setOnClickListener(this);
carsBussines = new ArrayList<Integer>();
//business address
editBusinessAddress = (EditText) findViewById(R.id.businessAddress);
editBusinessAddress.setVisibility(View.GONE);
businessCity = (Spinner) findViewById(R.id.CitySpinner);
ArrayAdapter<String> myAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.Cities));
myAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
businessCity.setAdapter(myAdapter2);
businessCity.setVisibility(View.GONE);
//business Phone number
editBusinesPhone = (EditText) findViewById(R.id.businessPhoneNumber);
editBusinesPhone.setVisibility(View.GONE);
progressBar = (ProgressBar) findViewById(R.id.progressBar2);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.registerbutton://There is 2 kinds of Users and 2 kinds of regiseters
if(WhichUser == true) {
registerPrivateUser();
break;
}else {
registerBusinessUser();
break;
}
case R.id.PrivateUser:
setPrivateUserVisible();
break;
case R.id.BusinessUser:
setBussinesVaribalesVisible();
break;
case R.id.CarsInBusiness:
listOfCarsForBusiness();
break;
}
}
/**
* register fot business users
* include Email,Business name,password for the user,garage,car that can be treated
* and address. all this information is stored in firebase in bussinessUser branch
*/
private void registerBusinessUser() {
String email = editBusinessEmail.getText().toString().trim();
String businessName = editBusinessName.getText().toString().trim();
String password = editBussinesPassword.getText().toString().trim();
String carToTreat = finalListOfCarBusiness;//
String KinfOfBusiness = kindOfBusiness.getSelectedItem().toString().trim();
String address = editBusinessAddress.getText().toString().trim();
String city = businessCity.getSelectedItem().toString().trim();
String phonenumber = editBusinesPhone.getText().toString().trim();
if(email.isEmpty()){
editBusinessEmail.setError("Please enter E-mail");
editBusinessEmail.requestFocus();
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
editBusinessEmail.setError("Please enter valid E-mail");
editBusinessEmail.requestFocus();
return;
}
if(password.isEmpty() || password.length()<6){
editTexPassword.setError("Enter 6 or more characters");
editTexPassword.requestFocus();
}
if(KinfOfBusiness.isEmpty()){
Toast.makeText(this, "Choose kind of business", Toast.LENGTH_SHORT).show();
}
if(finalListOfCarBusiness.isEmpty()){
Toast.makeText(this,"choose cars companies",Toast.LENGTH_LONG).show();
}
if(address.isEmpty()){
editBusinessAddress.setError("Please enter address");
editBusinessAddress.requestFocus();
}
if(businessName.isEmpty()){
editBusinessName.setError("Please enter address");
editBusinessName.requestFocus();
}
if(city.isEmpty()){
Toast.makeText(this, "Choose city of business", Toast.LENGTH_SHORT).show();
}
if(phonenumber.length() < 9 ){
editBusinesPhone.setError("Enter minimum 9 digit phone number");
editBusinesPhone.requestFocus();
}
//validation if email is empty or not valid for example
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
businessUser Buser = new businessUser(email,businessName,password,KinfOfBusiness,carToTreat,address,city,phonenumber,FirebaseAuth.getInstance().getCurrentUser().getUid());
FirebaseDatabase.getInstance().getReference("BusinessUsers").
child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(Buser).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
/* Buser.setID(FirebaseAuth.getInstance().getCurrentUser().getUid());
Toast.makeText(RegisterUser.this ,Buser.getID(),Toast.LENGTH_LONG).show();
*/
Toast.makeText(RegisterUser.this ,"User is registered successfully",Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
startActivity(new Intent(RegisterUser.this, LoginActivity.class));
}else{
Toast.makeText(RegisterUser.this ,"Failed to register User",Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}else{
Toast.makeText(RegisterUser.this ,"Failed to register User",Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
/**
* register fot private users
* include Email, password, car number, car year that can be treated.
* all this information is stored in firebase in privateUser branch
*/
private void registerPrivateUser() {
String email = editTextEmail.getText().toString().trim();
String password = editTexPassword.getText().toString().trim();
String carCompany = carCompanyList.getSelectedItem().toString().trim();
String car_number = carNumber.getText().toString().trim();
String car_year = carYear.getText().toString().trim();
//checks for the inputs validation
if(email.isEmpty()){
editTexPassword.setError("Please enter E-mail");
editTextEmail.requestFocus();
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
editTextEmail.setError("Please enter valid E-mail");
editTextEmail.requestFocus();
return;
}
if(carCompany.isEmpty()){
Toast.makeText(this,"You need to choose car company",Toast.LENGTH_LONG).show();
}
if(car_year.isEmpty()){
carYear.setError("Please enter car year");
carYear.requestFocus();
}
if(car_number.length()>8 || car_number.length()<6){
carNumber.setError("Please enter 7-8 digits");
carNumber.requestFocus();
}
//
//enter the information to the database
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
privateUser user = new privateUser(email,password,carCompany,car_number,car_year);
FirebaseDatabase.getInstance().getReference("PrivateUsers").
child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(RegisterUser.this ,"User is registered successfully",Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
startActivity(new Intent(RegisterUser.this, LoginActivity.class));
}else{
Toast.makeText(RegisterUser.this ,"Failed to register User",Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}else{
Toast.makeText(RegisterUser.this ,"Failed to register User",Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
private void listOfCarsForBusiness() {
listOfCars = getResources().getStringArray(R.array.CarTypesForBusiness);
checkCars = new boolean[listOfCars.length];
AlertDialog.Builder mBuilder = new AlertDialog.Builder(RegisterUser.this);
mBuilder.setTitle("Choose companies you treat");
mBuilder.setMultiChoiceItems(listOfCars, checkCars, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int position, boolean isChecked) {
if(isChecked) {
if (!carsBussines.contains(position)) {
carsBussines.add(position);
}
}else if (carsBussines.contains(position)) {
carsBussines.remove(position);
}
}
});
mBuilder.setCancelable(false);
mBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//String finalListCars = "";
for (int i = 0 ; i < carsBussines.size();i++){
finalListOfCarBusiness = finalListOfCarBusiness + listOfCars[carsBussines.get(i)];
if( i != carsBussines.size()-1){
finalListOfCarBusiness = finalListOfCarBusiness + ", ";
}
}
}
});
mBuilder.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
mBuilder.setNeutralButton("Clear all", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
for(int i = 0; i<checkCars.length;i++){
checkCars[i] = false;
carsBussines.clear();
}
}
});
AlertDialog mDialog = mBuilder.create();
mDialog.show();
}
private void setPrivateUserVisible() {
editTextEmail.setVisibility(View.VISIBLE);
editTexPassword.setVisibility(View.VISIBLE);
carCompanyList.setVisibility(View.VISIBLE);
carNumber.setVisibility(View.VISIBLE);
carYear.setVisibility(View.VISIBLE);
WhichUser = true;// to register the private user
editBusinessName.setVisibility(View.GONE);
editBussinesPassword.setVisibility(View.GONE);
kindOfBusiness.setVisibility(View.GONE);
carsInBusinessButton.setVisibility(View.GONE);
editBusinessAddress.setVisibility(View.GONE);
editBusinessEmail.setVisibility(View.GONE);
businessCity.setVisibility(View.GONE);
editBusinesPhone.setVisibility(View.GONE);
}
private void setBussinesVaribalesVisible() {
editBusinessEmail.setVisibility(View.VISIBLE);
editBusinessName.setVisibility(View.VISIBLE);
editBussinesPassword.setVisibility(View.VISIBLE);
kindOfBusiness.setVisibility(View.VISIBLE);
carsInBusinessButton.setVisibility(View.VISIBLE);
editBusinessAddress.setVisibility(View.VISIBLE);
businessCity.setVisibility(View.VISIBLE);
editBusinesPhone.setVisibility(View.VISIBLE);
WhichUser = false;// to register the Business user
editTextEmail.setVisibility(View.GONE);
editTexPassword.setVisibility(View.GONE);
carCompanyList.setVisibility(View.GONE);
carNumber.setVisibility(View.GONE);
carYear.setVisibility(View.GONE);
}
}<file_sep>package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView register,forgotPassword;
private EditText editTextEmail,EditTextPassword;
private Button signIn;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
register = (TextView)findViewById(R.id.register);
register.setOnClickListener(this);
forgotPassword =(TextView) findViewById(R.id.forgotPassword);
forgotPassword.setOnClickListener(this);
signIn = (Button) findViewById(R.id.loginButton);
signIn.setOnClickListener(this);
editTextEmail = (EditText) findViewById(R.id.loginEmail);
EditTextPassword = (EditText) findViewById(R.id.loginPassword);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.register:
startActivity(new Intent(this,RegisterUser.class));
break;
case R.id.loginButton:
userLogin();
break;
case R.id.forgotPassword:
startActivity(new Intent(this,resetPassword.class));
break;
}
}
private void userLogin() {
//convert Text lines to Strings
String userName = editTextEmail.getText().toString().trim();
String password = EditTextPassword.getText().toString().trim();
/**
* checks for the user login validation of the email and password
*/
if(userName.isEmpty()){
editTextEmail.setError("Please enter E-mail");
editTextEmail.requestFocus();
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(userName).matches()){
editTextEmail.setError("Please enter valid E-mail");
editTextEmail.requestFocus();
return;
}
if(password.isEmpty()){
EditTextPassword.setError("Please enter password");
EditTextPassword.requestFocus();
return;
}
// Progress bar visible
progressBar.setVisibility(View.VISIBLE);
mAuth.signInWithEmailAndPassword(userName,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
String RegisterdID = currentUser.getUid();
/**
* the function is separated to two parts because of the Firebase structure.
* this function is for the business user login.
*/
DatabaseReference jloginDatabaseBusiness = FirebaseDatabase.getInstance().getReference("/BusinessUsers/").child(RegisterdID);
jloginDatabaseBusiness.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String userType = snapshot.child("type").getValue().toString();
if (userType.equals("BusinessUser")) {
Intent intentBusiness = new Intent(MainActivity.this, ProfileScreenBusiness.class);
intentBusiness.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intentBusiness);
} else {
Toast.makeText(MainActivity.this, "Failed Login. Please Try Again", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
/**
* this Function is for private user login using reference and add value listener.
*/
DatabaseReference jloginDatabasePrivate = FirebaseDatabase.getInstance().getReference("/PrivateUsers/").child(RegisterdID);
jloginDatabasePrivate.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String userType = snapshot.child("type").getValue().toString();
if (userType.equals("PrivateUser")) {
Intent intentPrivate = new Intent(MainActivity.this, ProfileScreenPrivate.class);
intentPrivate.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intentPrivate);
} else {
Toast.makeText(MainActivity.this, "Failed Login. Please Try Again", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}else{
Toast.makeText(MainActivity.this,"Failed to login",Toast.LENGTH_LONG).show();;
progressBar.setVisibility(View.GONE);
}
}
});
}
}<file_sep>package com.example.myapplication;
import java.util.Date;
public class Appointment {
private String dateNtime;
private String PrivateID;
private String BusinessID;
private String description;
public Appointment(String datetime,String PID,String BID){
this.dateNtime = datetime;
this.PrivateID = PID;
this.BusinessID = BID;
this.description = "No description for now";
}
public Appointment(String datetime,String PID,String BID,String description){
this.dateNtime = datetime;
this.PrivateID = PID;
this.BusinessID = BID;
this.description = description;
}
public Appointment(){}
public String getDescription(){
return this.description;
}
public void setString(String des){
this.description = des;
}
public void setDate(String date) {
this.dateNtime = date;
}
public void setPrivateID(String privateID) {
this.PrivateID = privateID;
}
public void setBusinessID(String businessID) {
this.BusinessID = businessID;
}
public String getDate() {
return this.dateNtime;
}
public String getPrivateID() {
return this.PrivateID;
}
public String getBusinessID() {
return this.BusinessID;
}
}
<file_sep>package com.example.myapplication;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class appointmentAdapterBusiness extends BaseAdapter {
private Activity context;
ArrayList<Appointment> appointments;// gets list of appointments of the private user
private static LayoutInflater inflater = null;
private DatabaseReference dref = FirebaseDatabase.getInstance().getReference();
// build the adapter for the screen items
public appointmentAdapterBusiness(Activity context, ArrayList<Appointment> app) {
this.context = context;
this.appointments = app;
inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return this.appointments.size();
}
@Override
public Appointment getItem(int position) {
return this.appointments.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
//Enter to each item in the view the exact information from the database.
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
itemView = (itemView == null) ? inflater.inflate(R.layout.list_appointement_business, null) : itemView;
TextView textViewTime = (TextView) itemView.findViewById(R.id.app_Date);
TextView textViewPrivateName = (TextView) itemView.findViewById(R.id.privateAppName);
TextView textViewCar = (TextView) itemView.findViewById(R.id.privateCar);
TextView textViewCarNumber = (TextView) itemView.findViewById(R.id.privateCarNumber);
Appointment selected = appointments.get(position);
dref.child("PrivateUsers").child(selected.getPrivateID()).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
textViewTime.setText(selected.getDate().replace("e", ""));
textViewPrivateName.setText(snapshot.child("email").getValue().toString().trim());
textViewCar.setText(snapshot.child("carCompany").getValue().toString().trim());
textViewCarNumber.setText(snapshot.child("CarNumber").getValue().toString().trim());
}
@Override
public void onCancelled(@NonNull DatabaseError error) {}
});
Button leaveDescription = (Button) itemView.findViewById(R.id.setDescription);
leaveDescription.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openDescriptionDialog(selected.getBusinessID(), selected.getPrivateID(), textViewPrivateName.getText().toString(),selected.getDate());
}
});
return itemView;
}
public void openDescriptionDialog(String businessID,String userID,String businessName,String date) {
addDescriptionBsuinessDialog descDialog = new addDescriptionBsuinessDialog(businessID,userID,businessName,date);
descDialog.show(((AppCompatActivity) context).getSupportFragmentManager(),"H");
}
}
<file_sep>package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import java.util.Map;
public class EditPrivateUserProfile extends AppCompatActivity implements View.OnClickListener {
public EditText editEmail,editPassword,editCarNumber,editCarYear;
public Spinner CarType;
public Button Save;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_private_user_profile);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String currentuid = user.getUid();
editEmail = findViewById(R.id.EDITEMAILPRIVATE);
editPassword = findViewById(R.id.EDITPASSWORDPRIVATE);
editCarNumber = findViewById(R.id.EDITCARNUMBERPRIVATE);
editCarYear = findViewById(R.id.EDITCARYEARPRIVATE);
//ADD EDIT TO SPINNER CARTYPE
CarType = (Spinner) findViewById(R.id.EDITCARTYPEPRIVATE);
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.CarTypes));
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
CarType.setAdapter(myAdapter);
Save = (Button) findViewById(R.id.saveEditPrivateProfile);
Save.setOnClickListener(this);
DatabaseReference rootref = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootref.child("PrivateUsers");
userRef.child(currentuid).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()) {
String email = snapshot.child("email").getValue(String.class);
String Password = snapshot.child("Password").getValue(String.class);
String carYear = snapshot.child("CarYear").getValue(String.class);
String carNumber = snapshot.child("CarNumber").getValue(String.class);
String carType = snapshot.child("carCompany").getValue(String.class);
editEmail.setText(email);
editPassword.setText(Password);
editCarNumber.setText(carNumber);
editCarYear.setText(carYear);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.saveEditPrivateProfile:
changePrivateProfile();
break;
}
}
private void changePrivateProfile() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String currentuid = user.getUid();
DatabaseReference rootref = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootref.child("PrivateUsers");
userRef.child(currentuid).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
String identifier = currentuid;
Map<String, Object> values = new HashMap<>();
values.put("email", editEmail.getText().toString().trim());
values.put("Password", editPassword.getText().toString().trim());
values.put("CarNumber", editCarNumber.getText().toString().trim());
values.put("CarYear", editCarYear.getText().toString().trim());
values.put("carCompany", CarType.getSelectedItem().toString().trim());
if (!values.isEmpty()) {
user.updateEmail(editEmail.getText().toString().trim()).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()) {
Toast.makeText(EditPrivateUserProfile.this, editEmail.getText().toString().trim(), Toast.LENGTH_LONG).show();
}else {
Toast.makeText(EditPrivateUserProfile.this, "dont change email", Toast.LENGTH_LONG).show();
}
}
});
user.updatePassword(editPassword.getText().toString().trim()).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()) {
Toast.makeText(EditPrivateUserProfile.this, editPassword.getText().toString().trim(), Toast.LENGTH_LONG).show();
}else {
Toast.makeText(EditPrivateUserProfile.this, "dont change password", Toast.LENGTH_LONG).show();
}
}
}); userRef.child(identifier).updateChildren(values, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(@Nullable DatabaseError error, @NonNull DatabaseReference ref) {
Intent intent = new Intent(EditPrivateUserProfile.this, ProfileScreenPrivate.class);
Toast.makeText(EditPrivateUserProfile.this, "Profile updated", Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
} else {
Toast.makeText(EditPrivateUserProfile.this, "Cant Save new data", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}<file_sep>package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView;
import android.view.View;
import java.util.ArrayList;
public class searchResults extends AppCompatActivity implements View.OnClickListener {
private ListView listViewBusiness;
private businessAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
populateListView();
}
public void populateListView() {
listViewBusiness = (ListView) findViewById(R.id.listOfBusiness);
ArrayList<businessUser> list = getIntent().getParcelableArrayListExtra("businessList");
adapter = new businessAdapter(this, list);
listViewBusiness.setAdapter(adapter);
listViewBusiness.setOnItemClickListener((parent, view, position, id) -> {
Toast.makeText(this, "Click on item" + position, Toast.LENGTH_LONG).show();
});
}
@Override
public void onClick(View v) {
}
}
<file_sep>package com.example.myapplication;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RatingBar;
import androidx.appcompat.app.AppCompatDialogFragment;
public class addDescriptionBsuinessDialog extends AppCompatDialogFragment {
private EditText decription;
private addDescriptionInterface listener;
private String businessID,userID,businessName,date;
public addDescriptionBsuinessDialog(String businessID, String userID,String businessName,String date) {
this.businessID = businessID;
this.userID = userID;
this.businessName = businessName;
this.date = date;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.activity_add_description, null);
decription = view.findViewById(R.id.addDescription);
builder.setView(view)
.setTitle("Add description: " )
.setNegativeButton("cancel", (dialogInterface, i) -> {
})
.setPositiveButton("Save changes", (dialogInterface, i) -> {
String descriptionString = decription.getText().toString();
listener.saveDescription(descriptionString,this.businessID,this.userID,this.date);
});
return builder.create();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (addDescriptionInterface) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() +
"must implement ExampleDialogListener");
}
}
public interface addDescriptionInterface {
void saveDescription(String Description,String businessID,String userID,String date);
}
}
<file_sep>package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* The class BookTreatment is used to book treatments in business and private user database,
* get the previous information from both and check the time available.
*/
public class BookTreatment extends AppCompatActivity implements View.OnClickListener{
public CalendarView currentCalandar;
public String date,time;
public Button Book;
public Spinner BookTime;
public FirebaseDatabase database = FirebaseDatabase.getInstance();
public DatabaseReference dRefBusiness = database.getReference("BusinessUsers");
public DatabaseReference dRefPrivate = database.getReference("PrivateUsers");
public DatabaseReference dRefAppoint = database.getReference("Appointments");
public ImageButton backToBusinessProfile;
public String BusinessId,userId ;
public ArrayList<String> problematicHours = new ArrayList<String>();
public String Pshecuale = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_treatment);
backToBusinessProfile = (ImageButton) findViewById(R.id.ReturnTosearchList);
backToBusinessProfile.setOnClickListener(this);
Intent intent = getIntent();
BusinessId = intent.getStringExtra("BID");//get the Business id from the last screen
userId = FirebaseAuth.getInstance().getCurrentUser().getUid();// get the currenrt user id from the database
BookTime = (Spinner) findViewById(R.id.spinnerBookTime);
List<String> list = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.Appointment_time)));
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
BookTime.setAdapter(myAdapter);
currentCalandar = (CalendarView) findViewById(R.id.calendarView);
//listener for the calendar changes and check the time that available for the business in that day
currentCalandar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
list.clear(); // clear the hours list
list.addAll(Arrays.asList(getResources().getStringArray(R.array.Appointment_time))); // add the hours list again
myAdapter.notifyDataSetChanged();//notify thr adapter of the spinner
problematicHours.clear();// clear previous problematic hours
date = (dayOfMonth >= 10 ? dayOfMonth:"0"+dayOfMonth) + "/" + ((month+1) < 10 ? "0"+(month+1):(month+1)) + "/" + year;
dRefBusiness.child(BusinessId).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()&&snapshot.child("BookedTreatment").exists()) {
String s = "";
for (DataSnapshot child : snapshot.child("BookedTreatment").getChildren()) {
if (child.exists()) {
String key= child.getKey();
s+=child.child("date").getValue().toString();
}
}
if (s.length() != 0) {
String BookBusinessToAdapter[] = s.split("e");
for (int i = 0; i < BookBusinessToAdapter.length; i++) {
if (BookBusinessToAdapter[i].substring(0, 10).equals(date)) {
problematicHours.add(BookBusinessToAdapter[i].split(",")[1]);//add the problematic hours for each business
}
}
for (int i = 0; i < problematicHours.size(); i++) {
list.remove(problematicHours.get(i));// remove them from the strings list
}
myAdapter.notifyDataSetChanged();//notify the adapter on the changes
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
});
Book = (Button) findViewById(R.id.BookInCalander);
Book.setOnClickListener(this);
}
// on click wwaits for user click in the screen and get the id of the component clicked
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.BookInCalander:
saveDateAndTime();
break;
case R.id.ReturnTosearchList:
Intent BackToSearchintent = new Intent(this, searchScreen.class);
startActivity(BackToSearchintent);
break;
}
}
/**
* א.this function book the treatment in both users databases
*/
private void saveDateAndTime() {
String spinnerselection = BookTime.getSelectedItem().toString().trim();
String toPush = date + "," + spinnerselection + "e";
Boolean start = true;
String key = dRefBusiness.push().getKey();
Appointment newP = new Appointment(toPush,userId,BusinessId);
// we check if the private user has previous schedule if there is save it in P schedule
// add to all the places in the database
dRefBusiness.child(BusinessId).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
//save to business user database
dRefBusiness.child(BusinessId).child("BookedTreatment/"+key+"/").setValue(newP, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(@Nullable DatabaseError error, @NonNull DatabaseReference ref) {
}
});
//save to private user database
dRefPrivate.child(userId).child("BookedTreatment/"+key+"/").setValue(newP, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(@Nullable DatabaseError error, @NonNull DatabaseReference ref) {
Toast.makeText(BookTreatment.this, "Treatment saved in date "+toPush , Toast.LENGTH_LONG).show();
Intent intent = new Intent(BookTreatment.this, ProfileScreenPrivate.class);
startActivity(intent);
}
});
//save to appointment in the database
dRefAppoint.child(key).setValue(newP, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(@Nullable DatabaseError error, @NonNull DatabaseReference ref) {
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
| a71506716ee565f488a8413fe8c4c85cbe0ec9ac | [
"Markdown",
"Java"
] | 9 | Markdown | CarFix-SYD/CarFix | 33b470e73327a3b2df0942cea3ff28d2d83b957a | d19f54d4f6830e6063f0a85f1233268b25733338 |
refs/heads/master | <repo_name>noyan-alimov/travel-planner<file_sep>/src/client/js/fetchImage.js
export const fetchImage = (apiImage, city) => {
fetch(`https://pixabay.com/api/?key=${apiImage}&q=${city}&image_type=photo`)
.then(res => res.json())
.then(data => {
const output = document.querySelector('.image');
output.style.backgroundImage = `url(${data.hits[0].largeImageURL})`;
});
};
<file_sep>/src/client/index.js
import './styles/styles.scss';
import { fetchImage } from './js/fetchImage';
import { fetchTouristAttractions } from './js/fetchTouristAttractions';
import { putTitleAboveTable } from './js/putTitleAboveTable';
import { fetchLatLng } from './js/fetchLatLng';
const form = document.querySelector('.form');
form.addEventListener('submit', e => {
e.preventDefault();
const city = document.querySelector('#city').value;
const apiImage = '16743373-5f5da7530e215f793144c572a';
fetchLatLng(city);
fetchImage(apiImage, city);
fetchTouristAttractions(city);
putTitleAboveTable();
});
<file_sep>/src/client/js/putTitleAboveTable.js
export const putTitleAboveTable = () => {
const output = document.querySelector('.attractions');
const tableTitle = document.createElement('h2');
tableTitle.textContent = 'Top Tourist Attractions';
tableTitle.style.marginBottom = '1rem';
output.appendChild(tableTitle);
};
<file_sep>/src/server/server.js
const app = require('./index');
app.listen(8080, () => {
console.log('App listening on port 8080!');
});
<file_sep>/README.md
# Travel Planner App
This is a web app that helps users to plan their travel
## What it does
- Receives user input, the city where they want to travel and the date when they depart
- Outputs the weather for multiple days starting from departure, the photo of the city, and top tourist attractions of this city including their names and ratings
## How to use
Clone the project and then run to use the app
```bash
npm install
npm run build-prod
npm start
```
To test
```bash
npm test
```
To use in development mode run these 2 commands in 2 different terminals
```bash
npm run build-dev
npm start
```
## API(s) used
1. [GeoNames](http://www.geonames.org/) - To input the name of the city and output latitude and longitude
1. [WeatherBit](https://www.weatherbit.io/) - To input latitude and longitude and output weather information
1. [Pixabay](https://pixabay.com/) - To input the name of the city and output an image of it
1. [Google Maps](https://developers.google.com/places/web-service/search) - To input the name of the city and output top tourist attractions
## Built with
- **Sass** - preprocessor to be compiled into CSS
- **Webpack** - asset management
- **Babel** - JavaScript compiler
- **Node.js** - JavaScript runtime
- **Express.js** - Server framework for Node.js
- **Jest** - testing unit
- **Service Workers** - to enable offline capability
<file_sep>/src/client/js/__tests__/calculateDayDifference.test.js
import { calculateDayDifference } from '../calculateDayDifference';
test('Calculating the difference days between user input and today', () => {
expect(calculateDayDifference('2020-05-30', '2020-05-27')).toBe(3);
});
<file_sep>/src/server/index.test.js
const request = require('supertest');
const app = require('./index');
describe('POST /touristAttractions ', () => {
test('It should fetch tourist attractions and respond with an array of these attractions', async () => {
const response = await request(app)
.post('/touristAttractions')
.send({
results: [
{
name: 'London Eye',
rating: 4.5
},
{
name: '<NAME>',
rating: 4.4
}
]
});
expect(response.statusCode).toEqual(200);
});
});
| d0d1b00797fd9a5a360ff0105794f6424e95b587 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | noyan-alimov/travel-planner | e17f081131d3043abaa620e6bf080d8e067ff242 | fece2c188f2d6a4bb5362447397b1f85a8c9c467 |
refs/heads/master | <file_sep>#!/usr/bin/python
# sendmsg Get a summary of per pid inet conversations (data transmission not packets)
# via BPF Compiler Collection (BCC) https://github.com/iovisor/bcc
# and associate them with dns responses.
#
#
# ONLY FOR IPV4 need to add code for ipv6
# Messages via a kprobe on sock_sendmsg (user space)
# Dns names via uprobes on libc functions
# Organizations via maxminddb databases https://dev.maxmind.com/geoip/geoip2/geolite2/
#
# 15-Feb-2020 Zizzu created this.
from __future__ import print_function
from bcc import BPF
from socket import inet_ntop, AF_INET, AF_INET6
from struct import pack
from time import strftime
import maxminddb
# define BPF program
bpf_text = """
#include <uapi/linux/ptrace.h>
#include <linux/socket.h>
#include <net/sock.h>
struct ipv4_key_t {
u32 pid;
u32 daddr;
u16 dport;
char proto[5];
char comm[TASK_COMM_LEN];
};
BPF_PERF_OUTPUT(ipv4_events);
struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
};
struct addrinfo {
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
u32 ai_addrlen;
struct sockaddr *ai_addr;
char *ai_canonname;
struct addrinfo *ai_next;
};
struct val_t {
u32 pid;
char host[80];
struct addrinfo **res;
struct hostent **result;
};
struct dns_response_t {
u32 addr;
char host[80];
};
BPF_PERF_OUTPUT(dns_events);
BPF_HASH(start, u32, struct val_t);
int trace_sock_sendmsg
(struct pt_regs *ctx, struct socket *sock, struct msghdr *msg)
{
u32 pid = bpf_get_current_pid_tgid() >> 32;
struct sockaddr *msg_name = (struct sockaddr *)msg->msg_name;
if(msg_name) {
u16 dport = 0, family = msg_name->sa_family;
if (family == AF_INET) {
struct ipv4_key_t ipv4_key = {.pid = pid};
bpf_probe_read_str(
&ipv4_key.proto, sizeof(ipv4_key.proto), sock->sk->__sk_common.skc_prot->name);
bpf_get_current_comm(&ipv4_key.comm, sizeof(ipv4_key.comm));
ipv4_key.daddr = ((struct sockaddr_in *)msg_name)->sin_addr.s_addr;
dport = ((struct sockaddr_in *)msg_name)->sin_port;
ipv4_key.dport = ntohs(dport);
ipv4_events.perf_submit(ctx, &ipv4_key, sizeof(ipv4_key));
}
}
else {
u16 dport = 0, family = sock->sk->__sk_common.skc_family;
if (family == AF_INET) {
struct ipv4_key_t ipv4_key = {.pid = pid};
bpf_probe_read_str(
&ipv4_key.proto, sizeof(ipv4_key.proto), sock->sk->__sk_common.skc_prot->name);
ipv4_key.daddr = sock->sk->__sk_common.skc_daddr;
dport = sock->sk->__sk_common.skc_dport;
ipv4_key.dport = ntohs(dport);
bpf_get_current_comm(&ipv4_key.comm, sizeof(ipv4_key.comm));
ipv4_events.perf_submit(ctx, &ipv4_key, sizeof(ipv4_key));
}
}
return 0;
}
struct hostent *
trace_gethostbyname_entry(struct pt_regs *ctx, const char *name)
{
if (!PT_REGS_PARM1(ctx))
return 0;
struct val_t val = {};
u32 pid = bpf_get_current_pid_tgid();
bpf_probe_read(&val.host, sizeof(val.host),
(void *)PT_REGS_PARM1(ctx));
val.pid = bpf_get_current_pid_tgid();
start.update(&pid, &val);
return 0;
}
struct hostent *
trace_gethostbyname_return(struct pt_regs *ctx, const char *name)
{
struct val_t *valp;
u32 pid = bpf_get_current_pid_tgid();
struct dns_response_t result = {};
valp = start.lookup(&pid);
if (valp == 0)
return 0; // missed start
struct hostent *res = (struct hostent *)PT_REGS_RC(ctx);
if(res) {
bpf_probe_read(&result.host, sizeof(result.host), (void *)valp->host);
result.addr = (u32)res->h_addr_list[0];
dns_events.perf_submit(ctx, &result, sizeof(result));
}
start.delete(&pid);
return 0;
}
struct hostent *
trace_gethostbyname2_entry(struct pt_regs *ctx, const char *name, int af)
{
if (!PT_REGS_PARM1(ctx))
return 0;
if(af != AF_INET)
return 0;
struct val_t val = {};
u32 pid = bpf_get_current_pid_tgid();
bpf_probe_read(&val.host, sizeof(val.host),
(void *)PT_REGS_PARM1(ctx));
val.pid = bpf_get_current_pid_tgid();
start.update(&pid, &val);
return 0;
}
struct hostent *
trace_gethostbyname2_return(struct pt_regs *ctx, const char *name, int af)
{
struct val_t *valp;
u32 pid = bpf_get_current_pid_tgid();
struct dns_response_t result = {};
valp = start.lookup(&pid);
if (valp == 0)
return 0; // missed start
struct hostent *res = (struct hostent *)PT_REGS_RC(ctx);
if(res) {
bpf_probe_read(&result.host, sizeof(result.host), (void *)valp->host);
result.addr = (u32)res->h_addr_list[0];
dns_events.perf_submit(ctx, &result, sizeof(result));
}
start.delete(&pid);
return 0;
}
int trace_gethostbyname_r_entry
(struct pt_regs *ctx, const char *name, struct hostent *ret,
char *buf, size_t buflen, struct hostent **result, int *h_errnop)
{
if (!PT_REGS_PARM1(ctx))
return 0;
struct val_t val = {};
u32 pid = bpf_get_current_pid_tgid();
bpf_probe_read(&val.host, sizeof(val.host),
(void *)PT_REGS_PARM1(ctx));
val.result = result;
val.pid = bpf_get_current_pid_tgid();
start.update(&pid, &val);
return 0;
}
int trace_gethostbyname_r_return
(struct pt_regs *ctx)
{
struct val_t *valp;
u32 pid = bpf_get_current_pid_tgid();
struct dns_response_t result = {};
valp = start.lookup(&pid);
if (valp == 0)
return 0; // missed start
struct hostent *res = *valp->result;
int retval = PT_REGS_RC(ctx);
if(res && retval == 0) {
bpf_probe_read(&result.host, sizeof(result.host), (void *)valp->host);
result.addr = (u32)res->h_addr_list[0];
dns_events.perf_submit(ctx, &result, sizeof(result));
}
start.delete(&pid);
return 0;
}
int trace_gethostbyname2_r_entry
(struct pt_regs *ctx, const char *name, int af,
struct hostent *ret, char *buf, size_t buflen,
struct hostent **result) // int *h_errnop)
{
if (!PT_REGS_PARM1(ctx))
return 0;
if(af != AF_INET)
return 0;
struct val_t val = {};
u32 pid = bpf_get_current_pid_tgid();
bpf_probe_read(&val.host, sizeof(val.host),
(void *)PT_REGS_PARM1(ctx));
val.result = result;
val.pid = bpf_get_current_pid_tgid();
start.update(&pid, &val);
return 0;
}
int trace_gethostbyname2_r_return
(struct pt_regs *ctx)
{
struct val_t *valp;
u32 pid = bpf_get_current_pid_tgid();
struct dns_response_t result = {};
valp = start.lookup(&pid);
if (valp == 0)
return 0; // missed start
struct hostent *res = *valp->result;
int retval = PT_REGS_RC(ctx);
if(res && retval == 0) {
bpf_probe_read(&result.host, sizeof(result.host), (void *)valp->host);
result.addr = (u32)res->h_addr_list[0];
dns_events.perf_submit(ctx, &result, sizeof(result));
}
start.delete(&pid);
return 0;
}
int trace_getaddrinfo_entry
(struct pt_regs *ctx, const char *node, const char *service,
const struct addrinfo *hints, struct addrinfo **res)
{
if (!PT_REGS_PARM1(ctx))
return 0;
struct val_t val = {};
u32 pid = bpf_get_current_pid_tgid();
bpf_probe_read(&val.host, sizeof(val.host),
(void *)PT_REGS_PARM1(ctx));
val.res = res;
val.pid = bpf_get_current_pid_tgid();
start.update(&pid, &val);
return 0;
}
int trace_getaddrinfo_return (struct pt_regs *ctx)
{
struct val_t *valp;
u32 pid = bpf_get_current_pid_tgid();
struct dns_response_t result = {};
valp = start.lookup(&pid);
if (valp == 0)
return 0; // missed start
struct addrinfo *res = *valp->res;
int retval = PT_REGS_RC(ctx);
if(res->ai_family != AF_INET)
return 0;
if(res && retval == 0) {
bpf_probe_read(&result.host, sizeof(result.host), (void *)valp->host);
result.addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr.s_addr;
dns_events.perf_submit(ctx, &result, sizeof(result));
}
start.delete(&pid);
return 0;
}
"""
# load BPF program
b = BPF(text=bpf_text)
if BPF.get_kprobe_functions("sock_sendmsg"):
b.attach_kprobe(event="sock_sendmsg", fn_name="trace_sock_sendmsg")
#Libraries can be given in the name argument without the lib prefix es: libc -> c
b.attach_uprobe(name="c", sym="gethostbyname", fn_name="trace_gethostbyname_entry")
b.attach_uretprobe(name="c", sym="gethostbyname", fn_name="trace_gethostbyname_return")
b.attach_uprobe(name="c", sym="gethostbyname2", fn_name="trace_gethostbyname2_entry")
b.attach_uretprobe(name="c", sym="gethostbyname2", fn_name="trace_gethostbyname2_return")
b.attach_uprobe(name="c", sym="gethostbyname_r", fn_name="trace_gethostbyname_r_entry")
b.attach_uretprobe(name="c", sym="gethostbyname_r", fn_name="trace_gethostbyname_r_return")
b.attach_uprobe(name="c", sym="gethostbyname2_r", fn_name="trace_gethostbyname2_r_entry")
b.attach_uretprobe(name="c", sym="gethostbyname2_r", fn_name="trace_gethostbyname2_r_return")
b.attach_uprobe(name="c", sym="getaddrinfo", fn_name="trace_getaddrinfo_entry")
b.attach_uretprobe(name="c", sym="getaddrinfo", fn_name="trace_getaddrinfo_return")
dns = {}
conversations = []
def exepath(pid):
exe = ""
try:
with open('/proc/%s/maps' % (pid),'r') as f:
for line in f:
try:
exe = line[line.index('/'):-1].replace('\n','')
break
except ValueError:
continue
return exe
except Exception as e:
return ""
# process events
def print_ipv4_event(cpu, data, size):
event = b["ipv4_events"].event(data)
addr = inet_ntop(AF_INET, pack("I", event.daddr))
host = ""
if addr in dns:
host = dns[addr]
org = None
with maxminddb.Reader('GeoLite2-ASN.mmdb') as reader:
res = reader.get(addr)
if res: org = res['autonomous_system_organization']
exe = exepath(event.pid)
if (event.pid, event.proto, addr, event.dport) not in conversations:
conversations.append((event.pid, event.proto, addr, event.dport))
print(b"%-9s %-7d %-12.12s %-20.20s %-5s %-16s %-5d %-30s %s" % (
strftime("%H:%M:%S").encode('ascii'),
event.pid,
event.comm,
exe,
event.proto,
addr,
event.dport,
org,
host)
)
def dns_event(cpu, data, size):
event = b["dns_events"].event(data)
addr = inet_ntop(AF_INET, pack("I", event.addr))
host = event.host.decode('utf-8', 'replace')
if addr not in dns:
dns[addr] = host
print("%-9s %-7s %-12.12s %-20.20s %-5s %-16s %-5s %-30s %s" %
("SEEN", "PID", "THREAD", "EXE", "PROTO", "REMOTE", "PORT", "ORG", "HOST"))
# read events
b["ipv4_events"].open_perf_buffer(print_ipv4_event)
b["dns_events"].open_perf_buffer(dns_event)
while 1:
try:
b.perf_buffer_poll()
except KeyboardInterrupt:
exit()
<file_sep># Linux Tracing tools
### Conversations.py
Get a realtime summary of per pid inet data transmission via BPF Compiler Collection (BCC) https://github.com/iovisor/bcc and associate them with dns responses extracted from libc functions calls.

### Dnsdig.py
Uses sysdig to get dns responses from the recvfrom syscall buffer and python to parse and format the responses.
<file_sep>#!/usr/bin/python3
# dnsdig.py by zizzu 2020
# extract dns responses bytes from recvfrom syscall buffer via sysdig
# parse the output via python and translate bytes to human readable form via dnslib
# remove the inner if inside the for loop to show all the responses instead of a summary
import shlex
import dnslib
import base64
import subprocess
server="8.8.8.8" # your dns server use: and (fd.sip=... or fd.sip=...) for multiple dns addresses
command=f'sysdig -b -s 1000 -p"%evt.buffer" evt.type=recvfrom and fd.l4proto=udp and fd.sip={server} and fd.sport=53 and evt.dir=\<'
def run_command(cmd):
mem = []
process = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
b64_string = output.strip().decode('ascii')
b64_string += '=' * (-len(b64_string) % 4)
hex_string = base64.b64decode(b64_string)
try:
d = dnslib.DNSRecord.parse(hex_string)
for rr in d.rr:
if rr not in mem:
mem.append(rr)
print(rr)
except Exception as e:
print(str(e))
rc = process.poll()
return rc
run_command(command)
| 08db098e81c28f73c9531e9f8665a73aec66ca3a | [
"Markdown",
"Python"
] | 3 | Python | zizzu0/Linux-Tracing | d8e1209592c68da6ce2cc5fb7687a8b75623f9bf | c2106f88d21310c3dde86171c04461e35b55ea93 |
refs/heads/master | <repo_name>DongxuYI/ajax<file_sep>/README.md
# ajax
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/DongxuYI/ajax.git
git push -u origin master
<file_sep>/talking/talking.php
<?php
switch ($_POST["value"]) {
case '哈哈':
$arr = array("111","222","333");
$res = array_rand($arr,1);
print_r($arr[$res]);
break;
case '呵呵':
$arr = array("444","555","666");
$res = array_rand($arr,1);
print_r($arr[$res]);
break;
default:
$arr = array("777","888","999");
$res = array_rand($arr,1);
print_r($arr[$res]);
break;
}
?><file_sep>/LoginCheck/LoginCheck.php
<?php
$arr = array("一","二","三","四","五");
$name = $_POST["name"];
$inner = in_array($name,$arr);
//echo $inner;
if($inner){
echo "重名" ;
}else{
echo "可以";
}<file_sep>/waterFall/test.php
<?php
header("Content-Type:text/html;charset=utf-8");
$content = file_get_contents("./info/data.json");
echo $content;<file_sep>/ajax1/ajax.php
<?php
$piclist = array (
'baby'=>array('img/baby.jpg','Angelababy,中文名杨颖,1989年2月28日出生于上海,中国内地影视女演员、模特'),
'hxm'=>array('img/hxm.jpg','baby的老公,教主,著名男演员,最近演了一部烂片'),
'lh'=>array('img/lh.jpg','红魔,傻狍子,小鲜肉,萌萌哒,我家有一副1米的海报')
);
$res = $_POST['name'];
echo $piclist[$res][0]."|".$piclist[$res][1];
?><file_sep>/luowang/01.php
<?php
$content = file_get_contents("info.json");
//传输过去的是字符串,要翻译成数组
$res = json_decode($content);
$randIndex = array_rand($res , 3);//取出的是索引值
$randArr = array();
for ( $i = 0 ; $i < count($randIndex) ; $i++ ) {
array_push($randArr , $res[ $randIndex [ $i ]]);
}
//$last = array_unique($randArr)
echo json_encode($randArr);
<file_sep>/test.php
<?php
header ("Content-type:text/html;charset=utf8");
echo $_GET['callback']."()";
//接受到的函数直接执行
?>
| 450ceeaf5582807f73f6aa91e8d13fa81e1171b1 | [
"Markdown",
"PHP"
] | 7 | Markdown | DongxuYI/ajax | 8f573c97dd8b559effb10ff2fa4bee3cd11112d1 | cf3ba9fb05bd82165147f79f54a0323729cb99d6 |
refs/heads/main | <repo_name>i92esper/Proyecto5<file_sep>/Clase Ruta/sendero.cc
#include "sendero.h"
Sendero::Sendero(){
nombreSendero_="";
recorridoTotal_=-1;
}
bool Sendero::setRecorrido_total(int recorridoTotal){
if(recorridoTotal < 1)
return false;
recorridoTotal_=recorridoTotal;
return true;
}
<file_sep>/Clase Monitor 1.2/monitor.h
//Monitor.cc, por <NAME>
#ifndef MONITOR_H
#define MONITOR_H
#include <list>
#include <iostream>
#include "visita_guiada.h"
#include <string>
#include <ctime>
using namespace std;
class Monitor{
private:
//variable nombre y dni, identificadores
string nombre_completo_;
string DNI_;
//lista con las visitas del monitor
list <Visita_guiada> visitas_asignadas_;
//boolean que define si el monitor está correctamente creado
bool estado_;
//fecha de inicio de sesion (siempre igual o mayor a la fecha actual)
tm fecha_;
public:
//iniciador sencillo
Monitor();
//crea un monitor con estableciendo sus variables y comprobando que sean correctas
bool crearMonitor(string nombre,string dni,tm fecha);
//mete en la lista las visitas asignadas por dni al monitor
void getHorario(vector <Visita_guiada> vg);
//confirma que una visita x ha sido realizada
void confirmarAsistencia(Visita_guiada &a);
//el monitor se identifica con su nombre y su dni y si es correcto entra en el sistema
bool identificacion(vector <string> v);
//serie de sets y gets varios
inline string getDNI(){return DNI_;};
bool setDNI(string dni);
inline int getvisitas_asignadas_size(){return visitas_asignadas_.size();}
inline tm getFecha(){return fecha_;};
bool setFecha(tm fecha);
inline bool getEstado(){return estado_;};
};
#endif
<file_sep>/Clase Administrador/administrador.cc
#include <vector>
#include <iostream>
#include <string>
#include "administrador.h"
using namespace std;
bool Administrador::iniciarSesion(vector <Administrador> a){
for(vector <Administrador>::iterator i=a.begin();i!=a.end();i++){
if(usuario_.compare(i->getUsuario())==0 && codigo_.compare(i->getCodigo())==0){
return true;}
}
return false;
}
void Administrador::cerrarSesion(){exit(-1);}
int Administrador::verificarUsuario(vector <Administrador> a){
Administrador b(getUsuario(),getCodigo());
a.push_back(b);
return a.size();
}
<file_sep>/Clase Incidencia 1.1/incidencia_unittest.cc
#include "gtest/gtest.h"
#include <iostream>
#include "incidencia.h"
#include <vector>
#include <string>
using namespace std;
TEST(Incidencia,eliminarIncidencia){
Incidencia test,test2;
EXPECT_TRUE(test.setIncidencia(0,"El monitor no podia atender"));
EXPECT_EQ("El monitor no podia atender",test.getinforme());
vector <Incidencia> v;
v.push_back(test);
v=test.eliminarIncidencia(v);
EXPECT_EQ(0,v.size());
}
TEST(Incidencia,Informe){
Incidencia test,test2;
EXPECT_TRUE(test.setIncidencia(1,"El cliente no aparece"));
EXPECT_FALSE(test2.setIncidencia(2,""));
}
<file_sep>/Clase Sendero/sendero.cc
/*
Fichero: sendero.cc
Descripción: fichero con los cuerpos de procedimiento de los métodos de la clase Sendero
Autor: <NAME>
*/
#include "sendero.h"
Sendero::Sendero(){
nombreSendero_="";
recorridoTotal_=-1;
}
bool Sendero::setRecorrido_total(int recorridoTotal){
if(recorridoTotal < 1)
return false;
recorridoTotal_=recorridoTotal;
return true;
}
<file_sep>/Clase Sendero/sendero.h
/*
Fichero: sendero.h
Descripción: Fichero con los prototipos de las funciones de la clase Sendero
Autor: <NAME>
*/
#ifndef SENDERO_H
#define SENDERO_H
#include <string>
using namespace std;
class Sendero{
private:
//String que almacena el nombre del sendero
string nombreSendero_;
//Entero que almacena el recorrido total en la magnitud Km
int recorridoTotal_;
public:
//Constructor de la clase Sendero para incializar todas las variables de la clase
Sendero();
//Void que asigna el nombre del sendero de la instancia
inline void setNombre_sendero(string nombreSendero){nombreSendero_=nombreSendero;}
//String que retorna el nombre asignado a la instancia
inline string getNombre_sendero() const {return nombreSendero_;}
//Boolean que comprueba que el recorrido se ha asignado a una distancia estrictamente positiva
bool setRecorrido_total(int recorridoTotal);
//Entero que retornar el recorrido total asignado a la instancia
inline int getRecorrido_total() const {return recorridoTotal_;}
};
#endif
<file_sep>/Clase Ruta/sendero.h
#ifndef SENDERO_H
#define SENDERO_H
#include <string>
using namespace std;
class Sendero{
private:
string nombreSendero_;
int recorridoTotal_;
public:
Sendero();
inline void setNombre_sendero(string nombreSendero){nombreSendero_=nombreSendero;}
inline string getNombre_sendero() const {return nombreSendero_;}
bool setRecorrido_total(int recorridoTotal);
inline int getRecorrido_total() const {return recorridoTotal_;}
};
#endif
<file_sep>/Clase Monitor 1.2/visita_guiada.cc
/*
Fichero: visita_guiada.cc
Descripción: Fichero con los procedimientos de las operaciones de la clase Visita_guiada
Autor: <NAME>
*/
#include "visita_guiada.h"
//Arreglo con las letras del DNI para hacer las correspondientes comprobaciones
char arr1 [23] = {'T','R','W','A','G','M','Y','F','P','D','X','B','N','J','Z','S','Q','V','H','L','C','K','E'};
//Macro SYSDATE del sistema
tm * ltm;
Visita_guiada::Visita_guiada(){
time_t now=time(NULL);
ltm=localtime(&now);
estado_=CREATED;
ruta_=0;
monitor_="";
dni_="";
fecha_.tm_year=1970;
fecha_.tm_mon=1;
fecha_.tm_mday=1;
id_.resize(5);
id_="";
nvisitantes_=0;
}
bool Visita_guiada::crearVisita(tm fecha, string dni, int ruta, string monitor){
if(!setFecha(fecha))
return false;
if(!setDNI(dni))
return false;
if(!setRuta(ruta))
return false;
if(!setMonitor(monitor))
return false;
estado_=VERIFIED;
createID();
return true;
}
bool Visita_guiada::setFecha(tm &fecha){
if(fecha.tm_mon-ltm->tm_mon > 2)
return false;
if(fecha.tm_year < ltm->tm_year)
return false;
fecha_=fecha;
return true;
}
bool Visita_guiada::setDNI(string dni){
int numeros=stoi(dni);
if(arr1[numeros%23] != dni[dni.size()-1])
return false;
return true;
}
bool Visita_guiada::setRuta(int ruta){
if(ruta<1 || ruta>5)
return false;
ruta_=ruta;
return true;
}
bool Visita_guiada::setMonitor(string monitor){
monitor_=monitor;
return true;
}
bool borrarVisitas(vector<Visita_guiada> vg){
int flag=false;
for(unsigned int i=0; i<vg.size(); ++i){
if(vg[i].estado_==DONE || vg[i].estado_==DELETED){
vg.erase(vg.begin()+i);
flag=true;
}
}
return flag;
}
bool Visita_guiada::modificarVisita(int ruta){
if(!setRuta(ruta))
return false;
return true;
}
bool Visita_guiada::modificarVisita(tm &fecha){
if(!setFecha(fecha))
return false;
return true;
}
bool Visita_guiada::setNvisitantes(int nvisitantes){
if(nvisitantes < 1 || nvisitantes > 10)
return false;
nvisitantes_=nvisitantes;
return true;
}
void Visita_guiada::createID(){
for(int i=0; i<5; ++i){
id_=id_+arr1[rand()%23];
}
}
<file_sep>/Clase Ruta/ruta.h
/*
Fichero: ruta.h
Descripción: fichero con los prototipos de la clase Ruta
Autor: <NAME>
*/
#ifndef RUTA_H
#define RUTA_H
#include <cctype>
#include <vector>
#include "sendero.h"
#include <string>
using namespace std;
class Ruta{
private:
//ID asignado a la ruta particular
int id_;
//Entero que indica el tipo de ruta, 1 -> Andando, 2 -> Bici y 3 -> Barco
int tipoRuta_;
//Nombre asociado a la ruta
string nombreRuta_;
//Vector que almacena los senderos en orden de recorrido asignados a la ruta
vector<Sendero> senderos_;
//Char que almacena los tres tipos de dificultad que existen en los tipos de ruta, F -> Facil, M -> Medio y D -> Difícil
char dificultad_;
public:
//Constructor de la clase Ruta, para inicializar todas las variables privadas de la clase Ruta
Ruta();
//Boolean que retorna true en caso de que la ruta se haya creado correctamente
bool crearRuta(int tipoRuta, string nombreRuta, char dificultad, vector<Sendero> &senderos);
//Boolean que retorna true en caso de que se haya asignado uno de los tipos de rutas disponibles en el sistema
bool setTipo_ruta(int tipoRuta);
//Bolean que retorna true en caso de que se haya asignado uno de los tipos de dificultades disponibles en el sistema
bool setDificultad(char dificultad);
//Boolean que retorna true en caso de que se hayan asignado correctamente los senderos a la instancia de la ruta
bool setSenderos(vector<Sendero> senderos);
};
#endif
<file_sep>/Clase Incidencia 1.1/main.cc
#include "incidencia.h"
#include <vector>
#include <string>
int main(){
Incidencia test;
test.setIncidencia(0,"El monitor no podía atender");
vector <Incidencia> v;
v.push_back(test);
test.eliminarIncidencia(v);
}
<file_sep>/Clase Administrador/administrador.h
#ifndef ADMINISTRADOR_H
#define ADMINISTRADOR_H
#include <vector>
#include <iostream>
#include <string>
using namespace std;
class Administrador{
private:
string usuario_;
string codigo_;
public:
Administrador(string usuario,string codigo){
usuario_=usuario;
codigo_=codigo;
}
bool iniciarSesion(vector <Administrador> a);
void cerrarSesion();
int verificarUsuario(vector <Administrador> a);
inline string getUsuario(){return usuario_;};
inline string getCodigo(){return codigo_;};
inline void setCodigo(string codigo){codigo_=codigo;};
inline void setUsuario(string usuario){usuario_=usuario;};
};
#endif
<file_sep>/Clase Monitor 1.2/monitor_unittest.cc
#include "gtest/gtest.h"
#include "monitor.h"
#include "visita_guiada.h"
#include <ctime>
#include <vector>
#include <list>
#include <string>
using namespace std;
//prueba que se recojan las visitas asignadas a ese dni
TEST(Monitor,getHorario){
Monitor test;
Visita_guiada a;
tm fecha;
fecha.tm_year=2020;
fecha.tm_mon=12;
fecha.tm_mday=25;
test.crearMonitor("Pepito","31023573T",fecha);
a.crearVisita(fecha,"31478961B",1,"31023573T");
vector <Visita_guiada> v;
v.push_back(a);
test.getHorario(v);
EXPECT_EQ(1,test.getvisitas_asignadas_size());
}
//prueba que se cree correctamente el usuario
TEST(Monitor,estado){
Monitor test,test2;
tm fecha;
fecha.tm_year=2020;
fecha.tm_mon=11;
fecha.tm_mday=25;
test.crearMonitor("31023573T","Alfonso",fecha);
EXPECT_TRUE(test.getEstado());
EXPECT_FALSE(test2.getEstado());
}
//comprueba que se cambie el estado de una visita concreta a done
TEST(Monitor,confirmarAsistencia){
Visita_guiada a;
tm fecha;
fecha.tm_year=2020;
fecha.tm_mon=12;
fecha.tm_mday=17;
Monitor test;
test.crearMonitor("31023573T","Alfonso",fecha);
a.crearVisita(fecha,"31478961B",1,"31023573T");
test.confirmarAsistencia(a);
EXPECT_EQ(DONE,a.getRealizada());
}
//comprueba que funcione la identificacion comparando un dni con un vector de dnis
TEST(Monitor,identificacion){
tm fecha;
fecha.tm_year=2020;
fecha.tm_mon=12;
fecha.tm_mday=25;
Monitor test;
EXPECT_TRUE(test.crearMonitor("31023573T","Alfonso",fecha));
Monitor test2;
EXPECT_TRUE(test2.crearMonitor("31478961B","Jose",fecha));
vector <string> a;
Monitor test3;
a.push_back(test.getDNI());
a.push_back(test2.getDNI());
EXPECT_TRUE(test.identificacion(a)) ;
EXPECT_FALSE(test3.identificacion(a));
}
<file_sep>/Clase Monitor 1.2/monitor.cc
//Monitor.cc, por <NAME>
#include <list>
#include <vector>
#include "visita_guiada.h"
#include "monitor.h"
#include <string>
#include <iostream>
#include <ctime>
using namespace std;
//definimos el punter ode tm que teendrá la hora local
tm * lotm;
Monitor::Monitor(){
time_t now=time(NULL);
lotm=localtime(&now);
nombre_completo_="";
DNI_="";
estado_=false;
fecha_.tm_year=0;
fecha_.tm_mon=0;
fecha_.tm_mday=0;
visitas_asignadas_.clear();
}
bool Monitor::setDNI(string dni){
DNI_=dni;
return true;
}
bool Monitor::identificacion(vector <string> v){
for (vector<string>::iterator i=v.begin();i!=v.end();i++){
string a=getDNI(),b=*i;
if(b.compare(a)==0){
return true;}
}
return false;
}
void Monitor::getHorario(vector <Visita_guiada> vg){
for (vector<Visita_guiada>::iterator i=vg.begin();i!=vg.end();i++){
string a=getDNI(),b=i->getMonitor();
if(b.compare(a)==0 && setFecha(fecha_)){
visitas_asignadas_.push_back(*i);}
}
}
void Monitor::confirmarAsistencia(Visita_guiada &a){
a.setRealizada();
}
bool Monitor::setFecha(tm fecha){
if(fecha.tm_year < lotm->tm_year){return false;}
if (fecha.tm_mon < lotm->tm_mon && fecha.tm_year == lotm->tm_year){return false;}
if(fecha.tm_mon == lotm->tm_mon && fecha.tm_year == lotm->tm_year && fecha.tm_mday < lotm->tm_mday){return false;}
fecha_=fecha;
return true;
}
bool Monitor::crearMonitor(string nombre,string dni,tm fecha){
nombre_completo_=nombre;
if(!setDNI(dni)) {return false;}
DNI_=dni;
if(!setFecha(fecha)){return false;}
fecha_=fecha;
estado_=true;
return true;
};
<file_sep>/Clase Visita Guiada/visita_guiada_unittest.cc
/*
Fichero: visita_guiada_unittest.cc
Descripción: fichero con los test de la clase Visita Visita guiada.
Autor: <NAME>.
*/
#include "gtest/gtest.h"
#include "visita_guiada.h"
#include <ctime>
using namespace std;
TEST(Visita_guiada, crearVisita){ //Creación correcta de la visita guiada
Visita_guiada prueba;
tm fecha;
fecha.tm_year=2020;
fecha.tm_mon=11;
fecha.tm_mday=20;
string dni="31478961B";
int ruta=2;
string monitor="41087678C";
EXPECT_TRUE(prueba.crearVisita(fecha,dni,ruta,monitor));
EXPECT_FALSE(prueba.crearVisita(fecha,dni,10,monitor));
}
TEST(Visita_guiada, setRuta){ //Ruta valida para la visita
Visita_guiada prueba;
EXPECT_FALSE(prueba.setRuta(6));
EXPECT_FALSE(prueba.setRuta(0));
EXPECT_TRUE(prueba.setRuta(3));
}
TEST(Visita_guiada, setRealizada){ // Visita realizada o cancelada por el visitante correctamente
Visita_guiada prueba;
EXPECT_EQ(CREATED,prueba.getRealizada());
tm fecha;
fecha.tm_year=2020;
fecha.tm_mon=11;
fecha.tm_mday=20;
string dni="31478961B";
int ruta=2;
string monitor="41087678C";
prueba.crearVisita(fecha,dni,ruta,monitor);
EXPECT_EQ(VERIFIED,prueba.getRealizada());
prueba.setRealizada();
EXPECT_EQ(DONE,prueba.getRealizada());
prueba.eliminarVisita();
EXPECT_EQ(DELETED,prueba.getRealizada());
}
TEST(Visita_guiada, Fechavalida){ //Antelacion de dos meses, superior o igual a la actual
Visita_guiada prueba;
EXPECT_FALSE(prueba.modificarVisita(10));
EXPECT_TRUE(prueba.modificarVisita(3));
tm fecha;
fecha.tm_year=1900;
fecha.tm_mon=11;
fecha.tm_mday=20;
EXPECT_FALSE(prueba.modificarVisita(fecha)); //Error a la hora de meter una fecha invalida
fecha.tm_year=2020;
EXPECT_TRUE(prueba.modificarVisita(fecha));
}
TEST(Visita_guiada, visitantesMaximo){ //Numero de visitantes maximo permitido
Visita_guiada prueba;
EXPECT_FALSE(prueba.setNvisitantes(-5));
EXPECT_FALSE(prueba.setNvisitantes(12));
EXPECT_TRUE(prueba.setNvisitantes(5));
EXPECT_EQ(prueba.getNvisitantes(),5);
}
TEST(Visita_guiada, creacionID){ //Creacion de un ID asignado a cada visita
Visita_guiada prueba;
tm fecha;
fecha.tm_year=2020;
fecha.tm_mon=11;
fecha.tm_mday=20;
string dni="31478961B";
int ruta=2;
string monitor="41087678C";
prueba.crearVisita(fecha,dni,ruta,monitor);
string id;
id=prueba.getID();
EXPECT_EQ(5,id.size());
}
TEST(Visita_guiada, borrarVisitas){ //Borrar las instancias de visitas con la funcion friend de la clase
vector <Visita_guiada> v;
Visita_guiada v1, v2, v3;
tm fecha;
fecha.tm_year=2020;
fecha.tm_mon=11;
fecha.tm_mday=20;
string dni="31478961B";
int ruta=2;
string monitor="41087678C";
v1.crearVisita(fecha,dni,ruta,monitor);
v2.crearVisita(fecha,dni,ruta,monitor);
v3.crearVisita(fecha,dni,ruta,monitor);
v2.eliminarVisita();
v.push_back(v1);
v.push_back(v2);
v.push_back(v3);
borrarVisitas(v);
EXPECT_EQ(2,v.size());
}
<file_sep>/Clase Monitor 1.2/visita_guiada.h
/*
Fichero: visita_guiada.h
Descripción: fichero .h de los prototipos de la clase Visita guiada
Autor: <NAME>
*/
#ifndef VISITA_GUIADA_H
#define VISITA_GUIADA_H
#include <string>
#include <ctime>
#include <iostream>
#include <vector>
using namespace std;
/*Enum donde se enumeran los estados que pueden tener una visita:
DELETED->La visita ha sido eliminada para su posterior borrado logico
CREATED->Visita creada
VERIFIED->Visita verificada en el sistema lista para realizarse
DONE->Visita realizada lista para eliminarse del sistema para su posterior borrado lógico
*/
enum done{DELETED=-2, CREATED=-1, VERIFIED=0, DONE=1};
enum ret{FAILURE=-1, SUCCESS=0};
class Visita_guiada{
private:
//ID asignado a la instancia de la visita
string id_;
//Dato de tipo date asignado a la visita
tm fecha_;
//enumeracion done que indica si la instancia ha sido borrada, creada, verificada y realizada
done estado_;
//DNI del visitante que ha reservado la visita
string dni_;
//Crear clase ruta, debera comprobar si la ruta introducida corresponde a una ruta existente
int ruta_;
//Crear clase monitor, para asi comprobar si esta identificado en el sistema, y asi poder asignarlo a la visita
string monitor_;
//Numero de visitantes en la visita
int nvisitantes_;
public:
//Constructor de la clase, inicia la semilla para la generacion del ID de la instancia particular
Visita_guiada();
//Funcion booleana que retorna true en caso de que se haya creado la visita correctamente, false en caso contrario
bool crearVisita(tm fecha, string dni, int ruta, string monitor);
//Funcion booleana que retorna true en caso de que la ruta corresponda con las rutas dentro del sistema
bool setRuta(int ruta);
//Funcion booleana que comprueba que el dni es valido
bool setDNI(string dni);
//Funcion booelana que cmprueba que la fecha de reserva de la visita sea apta para el sistema
bool setFecha(tm &fecha);
//Funcion booleana que comprueba que el monitor introducido existe dentro del sistema
bool setMonitor(string monitor);
//Funcion void que crea un ID alfanumérico asignado a cada visita particular
void createID();
//Funcion string que retorna el ID asignado a la visita
inline string getID() const {return id_;}
//Funcion tm que retorna la fecha asignada a la visita
inline tm getFecha() const {return fecha_;}
//Funcion string que retornar el DNI del visitante que ha reservado la visita
inline string getDNI() const {return dni_;}
//Funcion int que retorna la ruta asignada a la visita guiada
inline int getRuta() const {return ruta_;}
//Funcion string que retorna el monitor asignado
inline string getMonitor() const {return monitor_;}
//Funcion done que devuelve el estado de la visita guiada
inline done getRealizada() const {return estado_;}
//Funcion void que asigna el estado de realizada para su posterior borrado lógico
inline void setRealizada() {estado_=DONE;}
//Funcion void que asigna el estado de eliminado para su posterior borrado lógico
inline void eliminarVisita() {estado_=DELETED;}
//Funcion boolean que retorna true si se ha eliminado una visita o mas, y false si no se ha borrado ninguna visita
friend bool borrarVisitas(vector<Visita_guiada> vg);
//Funcion boolean que asigna true si se ha podido asignar la nueva fecha deseada
bool modificarVisita(tm &fecha);
//Funcion boolean que asigna true si se ha podido asignar la nueva ruta deseada
bool modificarVisita(int ruta);
//Funcion boolean que retorna true en caso de que el numero de visitantes sea valido
bool setNvisitantes(int nvisitantes);
//Funcion int que retornar el numero de visitantes de la visita creada
inline int getNvisitantes() const {return nvisitantes_;}
};
#endif
<file_sep>/Clase Ruta/ruta.cc
/*
Fichero: ruta.cc
Descripción: fichero con los cuerpos de procedimiento de los métodos de la clase Ruta
Autor: <NAME>
*/
#include "ruta.h"
Ruta::Ruta(){
tipoRuta_=0;
nombreRuta_="";
dificultad_=' ';
senderos_.resize(0);
}
bool Ruta::crearRuta(int tipoRuta, string nombreRuta, char dificultad, vector<Sendero> &senderos){
if(!setTipo_ruta(tipoRuta))
return false;
nombreRuta_=nombreRuta;
if(!setDificultad(dificultad))
return false;
if(!setSenderos(senderos))
return false;
return true;
}
bool Ruta::setTipo_ruta(int tipoRuta){
if(tipoRuta < 1 || tipoRuta > 3)
return false;
tipoRuta_=tipoRuta;
return true;
}
bool Ruta::setDificultad(char dificultad){
if(toupper(dificultad) != 'F' && toupper(dificultad) != 'M' && toupper(dificultad) != 'D')
return false;
dificultad_=dificultad;
return true;
}
bool Ruta::setSenderos(vector<Sendero> senderos){
if(senderos.size() > 8){
return false;
}
for(int i=0; i<senderos.size(); ++i){
senderos_.push_back(senderos[i]);
}
return true;
}
<file_sep>/Clase Ruta/ruta_unittest.cc
/*
Fichero: ruta_unittest.cc
Descripción: fichero con los test de la clase Ruta
Autor: <NAME>
*/
#include "gtest/gtest.h"
#include "ruta.h"
#include "sendero.h"
#include <vector>
using namespace std;
TEST(Ruta, createRutaTrue){
Ruta prueba;
vector<Sendero> senderos(3);
senderos[0].setNombre_sendero("Sendero 1");
senderos[1].setNombre_sendero("Sendero 2");
senderos[2].setNombre_sendero("Sendero 3");
EXPECT_TRUE(prueba.crearRuta(2,"El colorado",'M',senderos));
}
TEST(Ruta, createRutaFalse){
Ruta prueba;
vector<Sendero> senderos(3);
senderos[0].setNombre_sendero("Sendero 1");
senderos[1].setNombre_sendero("Sendero 2");
senderos[2].setNombre_sendero("Sendero 3");
EXPECT_FALSE(prueba.crearRuta(2,"El colorado",'z',senderos));
}
TEST(Ruta, setRuta){
Ruta prueba;
EXPECT_TRUE(prueba.setTipo_ruta(2));
EXPECT_FALSE(prueba.setTipo_ruta(4));
}
TEST(Ruta, setDificultad){
Ruta prueba;
EXPECT_TRUE(prueba.setDificultad('m'));
EXPECT_FALSE(prueba.setDificultad('J'));
}
TEST(Ruta, setSenderos){
Ruta prueba;
vector<Sendero> senderos(9);
EXPECT_FALSE(prueba.setSenderos(senderos));
senderos.resize(5);
EXPECT_TRUE(prueba.setSenderos(senderos));
}
<file_sep>/Clase Incidencia 1.1/incidencia.cc
#include <iostream>
#include <vector>
#include "incidencia.h"
#include <string>
using namespace std;
bool Incidencia::setIncidencia(int tipo_incidencia, string informe){
if(!setInforme(informe)){return false;}
if(!settipo_incidencia(tipo_incidencia)){return false;}
return true;
}
void Incidencia::notificaIncidencia(){
cout<<"Hay una nueva incidencia";
}
vector <Incidencia> Incidencia::eliminarIncidencia(vector <Incidencia> v){
int n=v.size();
for(int i=0;i<v.size();i++){
if(v[i].getinforme()==informe_){
setResuelta();
v[i]=v[i+1];
v.resize(n-1);
}
}
return v;
}
bool Incidencia::setInforme(string informe){
if(informe==""){return false;}
informe_=informe;
return true;
}
bool Incidencia::settipo_incidencia(int tipo){
tipo_incidencia_=tipo;
return true;
}
<file_sep>/Clase Incidencia 1.1/incidencia.h
#ifndef INCIDENCIA_H
#define INCIDENCIA_H
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Incidencia{
private:
int tipo_incidencia_;
string informe_;
bool resuelta_;
public:
Incidencia(){
tipo_incidencia_=-1;
informe_="";
resuelta_=false;}
inline int gettipo_incidencia(){return tipo_incidencia_;};
inline string getinforme(){return informe_;};
Incidencia getIncidencia();
bool setIncidencia(int tipo_incidencia, string informe);
void notificaIncidencia();
vector <Incidencia> eliminarIncidencia(vector <Incidencia> v);
inline void setResuelta(){resuelta_=true;};
bool setInforme(string informe);
bool settipo_incidencia(int tipo);
inline bool getResuelta(){return resuelta_;};
};
#endif
<file_sep>/Clase Sendero/sendero_unittest.cc
/*
Fichero: sendero_unittest.cc
Descripción: fichero con los test de la clase Sendero
Autor: <NAME>
*/
#include "gtest/gtest.h"
#include "sendero.h"
using namespace std;
TEST(Sendero, setNombre){
Sendero prueba;
EXPECT_EQ("",prueba.getNombre_sendero());
prueba.setNombre_sendero("Nombre1");
EXPECT_EQ("Nombre1",prueba.getNombre_sendero());
}
TEST(Sendero, setRecorrido){
Sendero prueba;
prueba.setRecorrido_total(-34);
EXPECT_EQ(-1,prueba.getRecorrido_total());
prueba.setRecorrido_total(100);
EXPECT_EQ(100,prueba.getRecorrido_total());
}
<file_sep>/Clase Administrador/administrador_unittest.cc
#include "gtest/gtest.h"
#include <iostream>
#include <vector>
#include "administrador.h"
using namespace std;
TEST(Administrador,iniciarSesion){
Administrador test("<NAME>","37119"),test2("<NAME>","77777");
vector <Administrador> v;
v.push_back(test);
EXPECT_TRUE(test.iniciarSesion(v));
EXPECT_FALSE(test2.iniciarSesion(v));
}
TEST(Administrador,verificarUsuario){
Administrador test("<NAME>","111213");
vector <Administrador> v;
test.verificarUsuario(v);
EXPECT_EQ(1,test.verificarUsuario(v));
}
| 23fc17184a3cdd89331593255be4a2a2aed6b762 | [
"C++"
] | 21 | C++ | i92esper/Proyecto5 | 2497fe78d13da95e681e72954bdfa5a1267e72cc | 9327c40674f8ea96758a624f1f8e186fbe8d2449 |
refs/heads/master | <repo_name>gardym/switchback<file_sep>/src/reducers/interactions/__tests__/useInventoryItem.test.js
import useInventoryItem from '../useInventoryItem';
describe('if no first item is selected', () => {
it('selects this one', () => {
const action = { id: 'chickenWire' };
const state = { interaction: { firstItem: null } };
const items = { chickenWire: { text: 'Chicken wire' } };
const nextState = useInventoryItem(state, action, items);
const firstItem = nextState.interaction.firstItem;
expect(firstItem.text).toEqual('Chicken wire');
expect(firstItem.selected).toBeTruthy();
});
});
describe('if a first item is selected', () => {
const action = { id: 'chewingGum' };
const state = {
inventory: {
items: [
{ id: 'chewingGum' },
{ id: 'chickenWire' }
]
},
interaction: {
firstItem: {
id: 'chickenWire',
selected: true
}
}
};
describe('and it can be used with this item', () => {
it('combines the items into the produces and clears the selection', () => {
const items = {
chickenWire: {
useWith: 'chewingGum',
produces: 'wireLadder'
},
wireLadder: {
id: 'wireLadder'
}
};
const nextState = useInventoryItem(state, action, items);
expect(nextState.interaction.firstItem).toBeNull();
expect(nextState.inventory.items.length).toEqual(1);
expect(nextState.inventory.items[0].id).toEqual('wireLadder');
});
});
describe('and it cant be used with this item', () => {
it('clears the interaction selections but doesnt modify the items', () => {
const items = { chickenWire: { useWith: 'motorbike' } };
const nextState = useInventoryItem(state, action, items);
expect(nextState.interaction.firstItem).toBeNull();
expect(nextState.inventory.items.length).toEqual(2);
});
});
});
<file_sep>/src/actions/index.js
export const addPage = id => {
return {
type: "ADD_PAGE",
id
}
};
export const drawNextLine = (pageId, idx) => {
return {
type: "DRAW_NEXT_LINE",
pageId,
idx
}
};
export const pickUpItem = id => {
return {
type: "PICK_UP_ITEM",
id
}
};
export const useInventoryItem = id => {
return {
type: "USE_INVENTORY_ITEM",
id
}
};
export const hoverInventoryItem = id => {
return {
type: "HOVER_INVENTORY_ITEM",
id
}
};
export const unhoverInventoryItem = id => {
return {
type: "UNHOVER_INVENTORY_ITEM",
id
}
}
export const hoverHotspot = id => {
return {
type: "HOVER_HOTSPOT",
id
}
}
export const unhoverHotspot = id => {
return {
type: "UNHOVER_HOTSPOT",
id
}
}
export const hotspotClick = (id, pageIdx, lineIdx, partIdx) => {
return {
type: "USE_HOTSPOT",
id,
pageIdx,
lineIdx,
partIdx
}
}
<file_sep>/src/reducers/interactions/__tests__/hoverInventoryItem.test.js
import hoverInventoryItem from '../hoverInventoryItem';
const action = { id: 'balloon' };
const items = { balloon: { text: 'Balloon', hoverText: 'A balloon' },
pin: { text: 'Pin', hoverText: 'A pin' } };
const blankState = {
interaction: {
firstItem: null,
secondItem: null
},
inventory: {
description: null
}
};
describe('when a first item has not been selected in the previous state', () => {
it('hovers over the item in the next state', () => {
const nextState = hoverInventoryItem(blankState, action, items);
expect(nextState.inventory.description).toEqual('A balloon');
expect(nextState.interaction.firstItem).toBeDefined();
expect(nextState.interaction.firstItem.text).toEqual('Balloon');
expect(nextState.interaction.firstItem.selected).toBeFalsy();
});
});
describe('when a first item has been selected, but not a second item', () => {
const firstSelectedState = Object.assign({}, blankState, {
interaction: {
firstItem: {
id: 'balloon',
selected: true
}
}
});
describe('if the second item is the first item', () => {
it('does not hover over it again', () => {
const nextState = hoverInventoryItem(firstSelectedState, action, items);
expect(nextState.interaction.secondItem).toBeUndefined();
});
});
describe('if the second item is not the first item', () => {
it('hovers over the second item', () => {
const secondAction = { id: 'pin' };
const nextState = hoverInventoryItem(firstSelectedState, secondAction, items);
expect(nextState.inventory.description).toEqual('A pin');
expect(nextState.interaction.secondItem).toBeDefined();
expect(nextState.interaction.secondItem.text).toEqual('Pin');
expect(nextState.interaction.secondItem.selected).toBeFalsy();
});
});
});
<file_sep>/src/reducers/interactions/__tests__/unhoverInventoryItem.test.js
import unhoverInventoryItem from '../unhoverInventoryItem';
const action = { };
describe('when a first item is not selected', () => {
const state = { interaction: { firstItem: { selected: false } } };
it('unhovers the first item', () => {
const nextState = unhoverInventoryItem(state, action);
expect(nextState.interaction.firstItem).toBeNull();
expect(nextState.inventory.description).toBeNull();
});
});
describe('when a first item is selected', () => {
const state = { interaction: { firstItem: { selected: true }, secondItem: { } } };
it('unhovers the second item', () => {
const nextState = unhoverInventoryItem(state, action);
expect(nextState.interaction.firstItem).toBeDefined();
expect(nextState.interaction.secondItem).toBeNull();
});
});
<file_sep>/src/reducers/index.js
import Act5 from '../acts/act5.json';
import Act5Hotspots from '../acts/act5-hotspots';
import items from '../acts/items';
import inventory from './inventory';
import { pages, mapScriptPageToStatePage } from './pages';
import interaction from './interaction';
const currentAct = Object.assign({}, Act5, { hotspots: Act5Hotspots });
const initialInteractionState = {
firstItem: null,
secondItem: null
};
const initialInventoryState = {
items: [
items['rubberSportsHand'],
items['batteries']
]
};
const storeAppFactory = (initialPageId) => {
const initialPageState = [
mapScriptPageToStatePage(currentAct.pages[initialPageId], {
inventory: initialInventoryState
})
];
const initialCombinedState = {
pages: initialPageState,
interaction: initialInteractionState,
inventory: initialInventoryState
};
const storeApp = (state = initialCombinedState, action) => {
let nextState = Object.assign({}, interaction(state, action, currentAct, items));
nextState = Object.assign({}, inventory(nextState, action, items));
nextState = Object.assign({}, pages(nextState, action, currentAct));
return nextState;
};
return storeApp;
};
export default storeAppFactory;
<file_sep>/src/reducers/interactions/useInventoryItem.js
const useInventoryItem = ({interaction, ...state}, action, allItems) => {
let nextState = interaction;
if(!interaction.firstItem || !interaction.firstItem.selected) {
nextState = Object.assign({}, interaction, {
firstItem: {
id: action.id,
selected: true,
text: allItems[action.id].text
}
});
} else {
let inventoryItems = state.inventory.items;
if(allItems[interaction.firstItem.id].useWith === action.id) {
inventoryItems = inventoryItems.filter(i => {
return i.id !== interaction.firstItem.id && i.id !== action.id
});
inventoryItems.push(allItems[allItems[interaction.firstItem.id].produces]);
}
nextState = Object.assign({}, interaction, {
firstItem: null,
secondItem: null
});
return Object.assign({}, state, {
interaction: nextState,
inventory: {
...state.inventory,
items: inventoryItems
}
});
}
return Object.assign({}, state, { interaction: nextState });
}
export default useInventoryItem;
<file_sep>/src/InventoryItem.js
import React, { Component } from 'react';
import ReactHoverObserver from 'react-hover-observer';
class InventoryItem extends Component {
render() {
return (
<ReactHoverObserver
onHoverChanged={({isHovering}) => this.props.onHoverChanged(this.props.id, isHovering)}>
<div className='item'
onClick={() => this.props.onInventoryItemClicked(this.props.id)}><p>{this.props.text}</p></div>
</ReactHoverObserver>
);
}
}
export default InventoryItem;
<file_sep>/src/reducers/__tests__/inventory.test.js
import inventory from '../inventory';
const action = { type: 'PICK_UP_ITEM', id: 'banana' };
const items = { banana: { id: 'banana' } };
describe('when an item is picked up', () => {
describe('if it isnt in the inventory', () => {
const state = { inventory: { items: [ ] } };
it('its added to the inventory', () => {
const nextState = inventory(state, action, items);
expect(nextState.inventory.items.length).toEqual(1);
expect(nextState.inventory.items[0].id).toEqual('banana');
});
});
describe('if it is already in the inventory', () => {
const state = { inventory: { items: [ { id: 'banana' } ] } };
it('its not added to the inventory', () => {
const nextState = inventory(state, action, items);
expect(nextState.inventory.items.length).toEqual(1);
});
});
});
<file_sep>/src/reducers/interactions/unhoverInventoryItem.js
const unhoverInventoryItem = ({interaction, ...state}, action) => {
let nextState = interaction;
if(interaction.firstItem && !interaction.firstItem.selected) {
nextState = Object.assign({}, interaction, { firstItem: null });
} else {
nextState = Object.assign({}, interaction, { secondItem: null });
}
return Object.assign({}, state, {
interaction: nextState,
inventory: {
...state.inventory,
description: null
}
});
}
export default unhoverInventoryItem;
<file_sep>/src/Line.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import './Line.css';
import Typing from 'react-typing-animation';
import { addPage, pickUpItem, drawNextLine, hoverHotspot, unhoverHotspot, hotspotClick } from './actions';
import ReactHoverObserver from 'react-hover-observer';
class Line extends Component {
render() {
const parts = this.props.parts.map((p, idx) => {
if(typeof p === "string") {
return (<span key={idx}>{p}</span>);
} else {
if(p.type === "link-page") {
return (<span className={p.type} key={idx}
onClick={() => this.props.onLinkClick(p.target)}>{p.text}</span>);
} else if (p.type === "link-item") {
return( <span className={p.type} key={idx}
onClick={() => this.props.onItemClick(p.target)}>{p.text}</span>);
} else if (p.type === "link-hotspot") {
return (
<ReactHoverObserver className="hotspot-hover" key={idx}
onHoverChanged={({isHovering}) => this.props.onHotspotHoverChanged(p.id, isHovering)}>
<span className={p.type}
onClick={() => this.props.onHotspotClick(p.id, this.props.pageIdx, this.props.idx, idx)}>{p.text}</span>
</ReactHoverObserver>
);
} else {
return( <span className={p.type} key={idx}>{p.text}</span>);
}
}
});
let tip = "";
if(this.props.showTip) {
tip = (
<Typing cursor={false} speed={4}>
<p className="tip">{this.props.tip}</p>
</Typing>
);
}
if(this.props.drawing) {
return (
<div className="line">
<div>
<Typing cursor={false}
speed={4}
startDelay={40}
onFinishedTyping={() => this.props.onFinishedTyping(this.props.pageId, this.props.idx)}>{parts}</Typing>
</div>
</div>
);
} else if(this.props.drawn) {
return (
<div className="line">
<div>{parts}</div>
{tip}
</div>
);
}
return (null);
}
}
const mapDispatchToProps = dispatch => {
return {
onLinkClick: id => {
dispatch(addPage(id));
},
onItemClick: id => {
dispatch(pickUpItem(id));
},
onFinishedTyping: (pageId, idx) => {
dispatch(drawNextLine(pageId, idx));
},
onHotspotHoverChanged: (id, isHovering) => {
dispatch(isHovering ? hoverHotspot(id) : unhoverHotspot(id));
},
onHotspotClick: (id, pageIdx, lineIdx, partIdx) => {
dispatch(hotspotClick(id, pageIdx, lineIdx, partIdx));
}
}
};
const LineContainer = connect(
null,
mapDispatchToProps
)(Line);
export default LineContainer;
<file_sep>/src/reducers/interaction.js
import interactions from './interactions';
const interaction = (fullState, action, act, items) => {
switch (action.type) {
case "HOVER_INVENTORY_ITEM":
return interactions.hoverInventoryItem(fullState, action, items);
case "UNHOVER_INVENTORY_ITEM":
return interactions.unhoverInventoryItem(fullState, action);
case "USE_INVENTORY_ITEM":
return interactions.useInventoryItem(fullState, action, items);
case "HOVER_HOTSPOT":
return interactions.hoverHotspot(fullState, action, act);
case "UNHOVER_HOTSPOT":
return interactions.unhoverHotspot(fullState, action);
case "USE_HOTSPOT":
return interactions.useHotspot(fullState, action, act);
default:
return fullState;
}
};
export default interaction;
<file_sep>/src/reducers/__tests__/pages.test.js
import { pages } from '../pages';
const action = { type: 'ADD_PAGE', id: 'beach' };
describe('when a page is added', () => {
it('adds the page to the state', () => {
const action = { type: 'ADD_PAGE', id: 'beach' };
const act = { pages: { beach: { id: 'beach', lines: [ ] } } };
const state = { pages: [ ] };
const nextState = pages(state, action, act);
expect(nextState.pages.length).toEqual(1);
expect(nextState.pages[0].id).toEqual('beach');
});
});
describe('drawing a line with an inventory condition', () => {
describe('when the condition is doesNotContain', () => {
const act = {
pages: {
beach: {
id: 'beach',
lines: [
{
condition: {
type: 'inventory',
rule: 'doesNotContain',
value: ['towel']
},
parts: [ "You need a towel to come to the beach" ]
}
]
}
}
};
it('the line is drawn if it is not in the inventory', () => {
const state = { pages: [ ], inventory: { items: [ ] } };
const nextState = pages(state, action, act);
expect(nextState.pages[0].lines.length).toEqual(1);
});
it('the line is not drawn if it is in the inventory', () => {
const state = {
pages: [ ],
inventory: { items: [ { id: 'towel' } ] }
};
const nextState = pages(state, action, act);
expect(nextState.pages[0].lines.length).toEqual(0);
});
});
describe('and that condition is contains', () => {
const act = {
pages: {
beach: {
id: 'beach',
lines: [
{
condition: {
type: 'inventory',
rule: 'contains',
value: ['towel']
},
parts: [ "You've got a towel, great" ]
}
]
}
}
};
it('the line is drawn if it is in the inventory', () => {
const state = {
pages: [ ],
inventory: { items: [ { id: 'towel' } ] }
};
const nextState = pages(state, action, act);
expect(nextState.pages[0].lines.length).toEqual(1);
});
it('the line is not drawn if it is not in the inventory', () => {
const state = { pages: [ ], inventory: { items: [ ] } };
const nextState = pages(state, action, act);
expect(nextState.pages[0].lines.length).toEqual(0);
});
});
});
describe('when a line is drawn', () => {
});
<file_sep>/parser/build-acts.js
const util = require('util');
const fs = require('fs');
const parsedActDecorator = require('./parsedActDecorator');
const actsToParse = ['act5'];
actsToParse.forEach(act => {
const act5Text = fs.readFileSync(`${__dirname}/${act}.act`, 'utf8');
const results = parsedActDecorator.parse(act5Text);
fs.writeFileSync(`${__dirname}/../src/acts/${act}.json`, JSON.stringify(results));
});
<file_sep>/src/reducers/pages.js
export const mapScriptPageToStatePage = (page, fullState) => {
return {
id: page.id,
lines: page.lines.map((l, idx) => {
if(l.condition) {
if(l.condition.type === "inventory") {
let applicableValues = l.condition.value.filter(
c => fullState.inventory.items.find(i => i.id === c)
);
if(l.condition.rule === "doesNotContain" && applicableValues.length > 0) {
return null;
} else if(l.condition.rule === "contains" && applicableValues.length === 0) {
return null;
}
}
}
return Object.assign({}, l, {
hidden: idx !== 0,
drawing: idx === 0,
drawn: false
});
}).filter(l => l !== null)
}
};
const drawNextLine = (lines, idx) => {
return lines.map((l, i) => {
if(i === idx) {
return Object.assign({}, l, {
drawn: true,
drawing: false,
hidden: false
});
} else if(i === idx + 1) {
return Object.assign({}, l, {
drawn: false,
drawing: true,
hidden: false
});
} else {
return l
}
});
}
export const pages = (fullState, action, act) => {
let state = fullState.pages;
let nextState = state;
if(action.type === "ADD_PAGE") {
nextState = [
...state,
mapScriptPageToStatePage(act.pages[action.id], fullState)
];
} else if(action.type === "DRAW_NEXT_LINE") {
nextState = state.map(p => {
if(p.id === action.pageId) {
return {
id: p.id,
lines: drawNextLine(p.lines, action.idx)
}
}
return p;
});
}
return Object.assign({}, fullState, { pages: nextState } );
}
<file_sep>/src/Pages.js
import React, { Component } from 'react';
import Page from './Page';
import { connect } from 'react-redux';
class Pages extends Component {
render() {
let page = (
<Page page={this.props.pages[this.props.pages.length - 1]}
idx={this.props.pages.length - 1} />
);
return (
<div className="page-container">
{page}
</div>
);
}
}
const mapStateToProps = state => {
return {
pages: state.pages
}
};
const PagesContainer = connect(
mapStateToProps
)(Pages);
export default PagesContainer;
<file_sep>/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import storeAppFactory from './reducers';
let initialPageId = '_init';
if(document.location.hash !== "") {
initialPageId = document.location.hash.substring(1);
}
const store = createStore(storeAppFactory(initialPageId));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
<file_sep>/src/reducers/interactions/useHotspot.js
import { mapScriptPageToStatePage } from '../pages';
const useHotspot = ({interaction, ...state}, action, act) => {
if(interaction.firstItem && interaction.firstItem.selected) {
let pages = [ ...state.pages ];
if(act.hotspots[action.id].useWith[interaction.firstItem.id] !== undefined) {
let newPage = act.pages[act.hotspots[action.id].useWith[interaction.firstItem.id]];
pages.push(mapScriptPageToStatePage(newPage, state));
}
return Object.assign({}, state, {
interaction: Object.assign({}, interaction, {
firstItem: null,
secondItem: null
}),
pages: pages
});
} else {
const nextStatePages = state.pages.map((p, pidx) => {
if(pidx === action.pageIdx) {
return Object.assign({}, p, {
lines: p.lines.map((l, lidx) => {
if(lidx === action.lineIdx) {
return Object.assign({}, l, { showTip: true });
}
return l;
})
});
}
return p;
});
return Object.assign({}, state, {
interaction: interaction,
pages: nextStatePages
});
}
}
export default useHotspot;
<file_sep>/src/Inventory.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import InventoryItem from './InventoryItem';
import { useInventoryItem, hoverInventoryItem, unhoverInventoryItem } from './actions';
class Inventory extends Component {
render() {
const itemElements = this.props.inventory.items.map((i, idx) => {
return (
<InventoryItem text={i.text}
key={`${i.id}_${idx}`}
onInventoryItemClicked={this.props.onInventoryItemClicked}
onHoverChanged={this.props.onHoverChanged}
id={i.id} />
);
});
return (
<div className="inventory-container">
<div className="inventory-description">
<p>{this.props.inventory.description}</p>
</div>
<div className="inventory">
<div className="inventory-items">
{itemElements}
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => {
return {
inventory: state.inventory
}
};
const mapDispatchToProps = dispatch => {
return {
onInventoryItemClicked: (id) => {
dispatch(useInventoryItem(id));
},
onHoverChanged: (id, isHovering) => {
dispatch(isHovering ? hoverInventoryItem(id) : unhoverInventoryItem(id));
}
}
};
const InventoryContainer = connect(
mapStateToProps,
mapDispatchToProps
)(Inventory);
export default InventoryContainer;
<file_sep>/src/reducers/interactions/index.js
import hoverInventoryItem from './hoverInventoryItem';
import unhoverInventoryItem from './unhoverInventoryItem';
import useInventoryItem from './useInventoryItem';
import hoverHotspot from './hoverHotspot';
import unhoverHotspot from './unhoverHotspot';
import useHotspot from './useHotspot';
const interactions = {
hoverInventoryItem,
unhoverInventoryItem,
useInventoryItem,
hoverHotspot,
unhoverHotspot,
useHotspot
}
export default interactions;
<file_sep>/src/acts/items.js
const items = {
poweredCarLamp: {
id: "poweredCarLamp",
text: "Battery-powered car headlamp",
useWith: "rubberSportsHand",
produces: "safePoweredCarLamp",
hoverText: "Gives your hand a tingling sensation."
},
carlamp: {
id: "carlamp",
text: "Broken car headlamp",
useWith: "batteries",
produces: "poweredCarLamp",
hoverText: "The bulb's still intact. It's your lucky day."
},
batteries: {
id: "batteries",
text: "Batteries",
useWith: "carlamp",
produces: "poweredCarLamp",
hoverText: "You can put these in literally™ anything."
},
businessCard: {
id: "businessCard",
text: "Business Card",
hoverText: "<NAME>. Precinct 1A. Princedale."
},
rubberSportsHand: {
id: "rubberSportsHand",
text: "Novelty rubber 'foam' hand",
useWith: "poweredCarLamp",
produces: "safePoweredCarLamp",
hoverText: "Go Capybaras! Or so it says."
},
safePoweredCarLamp: {
id: "safePoweredCarLamp",
text: "Insulated, powered car headlamp",
hoverText: "Well insulated. Smells like burning rubber."
}
};
export default items;
<file_sep>/src/acts/act5-hotspots.js
const hotspots = {
ground: {
id: "ground",
text: "ground",
useWith: {
poweredCarLamp: "ground",
safePoweredCarLamp: "shineGround"
}
},
driver: {
id: "driver",
text: "driver",
useWith: {
poweredCarLamp: "flashDriver",
safePoweredCarLamp: "shineDriver"
}
}
};
export default hotspots;
<file_sep>/parser/parsedActDecorator.js
const actParser = require('./act-parser');
const util = require('util');
const flatten = function(arr) {
return arr.reduce((memo, val) => {
return memo.concat(val);
}, []);
};
const cleanParts = function(parts) {
return parts.reduce((memo, val) => {
if(typeof val === "string") {
if(typeof memo[memo.length - 1] === "string") {
memo[memo.length - 1] = memo[memo.length - 1 ] + val;
} else {
memo.push(val);
}
} else {
let changes = { };
if(val.type === "link-page" && Array.isArray(val.text)) {
changes.text = flatten(val.text[2]).join("");
} else if(val.type === "link-item" && Array.isArray(val.text)) {
changes.text = flatten(val.text).join("");
} else if(val.type === "link-hotspot" && Array.isArray(val.text)) {
changes.text = flatten(val.text).join("");
changes.tip = flatten(val.tip).join("");
}
memo.push(Object.assign({}, val, changes));
}
return memo;
}, [ ]);
};
const parsedActDecorator = function(actText) {
const parsedAct = actParser.parse(actText);
const cleanLines = parsedAct.map((l, idx) => {
if(!l || !l.line || l.line.length === 0) {
return null;
} else if(l.line[0].type && l.line[0].type === "page") {
return l.line[0];
} else {
return {
type: "line",
parts: flatten(l.line)
};
}
}).filter(l => {
return l !== null && l !== undefined;
});
let pages = { };
let currentPage = { };
for(let i = 0; i < cleanLines.length; i++) {
if(cleanLines[i].type === "page") {
currentPage = Object.assign({}, {
id: cleanLines[i].id,
lines: [ ]
});
pages[cleanLines[i].id] = currentPage;
} else if(cleanLines[i].type === "line" && !cleanLines[i].parts[0].rule) {
currentPage.lines.push({
parts: cleanParts(cleanLines[i].parts)
});
} else if(cleanLines[i].type === "line" && cleanLines[i].parts[0].rule) {
const predicatePart = cleanLines[i].parts[0];
const condition = {
type: predicatePart.type,
rule: predicatePart.rule,
value: flatten(predicatePart.value[0]).filter(v => {
return v && v !== ",";
})
};
currentPage.lines.push({
condition: condition,
parts: cleanParts(flatten(cleanLines[i].parts[2]))
});
}
}
return {
pages: pages
};
};
module.exports = {
parse: parsedActDecorator
};
<file_sep>/src/reducers/inventory.js
const inventory = (state, action, allItems) => {
if(action.type === "PICK_UP_ITEM") {
if(!state.inventory.items.find(i => i.id === action.id)) {
return {
...state,
inventory: {
...state.inventory,
items: [
...state.inventory.items,
allItems[action.id]
]
}
}
}
}
return state;
}
export default inventory;
<file_sep>/src/reducers/interactions/__tests__/unhoverHotspot.test.js
import unhoverHotspot from '../unhoverHotspot';
const action = { };
const state = {
interaction: {
firstItem: {
selected: true
}
}
};
describe('when a first item is selected', () => {
it('unhovers the second item', () => {
const nextState = unhoverHotspot(state, action);
expect(nextState.secondItem).toBeUndefined();
});
});
<file_sep>/parser/__tests__/act-parser.test.js
const util = require('util');
const parsedActDecorator = require('../parsedActDecorator');
describe('the shape of an act', () => {
it('should contain a pages object at its root', () => {
const parsedAct = parsedActDecorator.parse("^_init\n");
expect(parsedAct.pages).toBeDefined();
});
it('each page should have an id that is the same as its value', () => {
const parsedAct = parsedActDecorator.parse("^_init\n");
expect(parsedAct.pages._init.id).toEqual("_init");
});
it('each page should have an array of lines', () => {
const basicText = ["^_init", "Some plain text", "" ].join("\n");
const parsedAct = parsedActDecorator.parse(basicText);
expect(parsedAct.pages._init.lines.length).toBeGreaterThan(0);
});
it('each line should have parts', () => {
const basicText = ["^_init", "Some plain text", "" ].join("\n");
const parsedAct = parsedActDecorator.parse(basicText);
expect(parsedAct.pages._init.lines[0].parts).toBeDefined();
});
it('should map links', () => {
const basicText = [
"^_init",
"The #highway stretches out.",
""].join("\n");
const parsedAct = parsedActDecorator.parse(basicText);
let link = parsedAct.pages._init.lines[0].parts[1];
expect(link.type).toEqual("link-page");
expect(link.text).toEqual("highway");
expect(link.target).toEqual("highway");
});
it('should map links with text', () => {
const basicText = [
"^_init",
"The #highway:\"dark highway\"",
""].join("\n");
const parsedAct = parsedActDecorator.parse(basicText);
//console.log(util.inspect(parsedAct, { depth: null }));
let link = parsedAct.pages._init.lines[0].parts[1];
expect(link.text).toEqual("dark highway");
expect(link.target).toEqual("highway");
});
it('should map items', () => {
const basicText = [
"^_init",
"Pick up *card:\"small card\" from the ground.",
""].join("\n");
const parsedAct = parsedActDecorator.parse(basicText);
let item = parsedAct.pages._init.lines[0].parts[1];
expect(item.target).toEqual("card");
expect(item.text).toEqual("small card");
expect(item.type).toEqual("link-item");
});
it('should map hotspots', () => {
const basicText = [
"^_init",
"Inspect @ground:\"the ground\":\"it's too dark to see anything\".",
""].join("\n");
const parsedAct = parsedActDecorator.parse(basicText);
let hotspot = parsedAct.pages._init.lines[0].parts[1];
expect(hotspot.type).toEqual("link-hotspot");
expect(hotspot.text).toEqual("the ground");
expect(hotspot.id).toEqual("ground");
expect(hotspot.target).toEqual("ground");
expect(hotspot.tip).toEqual("it's too dark to see anything");
});
it('should map predicates', () => {
const basicText = [
"^_init",
"?inventory:contains:poweredCarLamp,safePoweredCarLamp",
" You hear an #engine approaching in the distance.",
""].join("\n");
const parsedAct = parsedActDecorator.parse(basicText);
let predicate = parsedAct.pages._init.lines[0].condition;
let parts = parsedAct.pages._init.lines[0].parts;
expect(predicate.type).toEqual("inventory");
expect(predicate.rule).toEqual("contains");
expect(predicate.value.length).toEqual(2);
expect(predicate.value[0]).toEqual("poweredCarLamp");
expect(predicate.value[1]).toEqual("safePoweredCarLamp");
expect(parts[0]).toEqual("You hear an ");
expect(parts[1].type).toEqual("link-page");
expect(parts.length).toEqual(3);
});
});
<file_sep>/README.md
## ???
Text adventures aren't dead
## Getting going
```
npm install
npm start
```
<file_sep>/src/Page.js
import React, { Component } from 'react';
import Line from './Line';
class Page extends Component {
componentDidUpdate() {
if(this.bottomScrollAnchor) {
this.bottomScrollAnchor.scrollIntoView({
block: 'end',
inline: 'end',
behavior: 'smooth'
});
}
}
render() {
const lineElements = this.props.page.lines.map((l, idx) => {
let hotspot = l.parts.find(p => p.type === "link-hotspot");
let tip = hotspot ? hotspot.tip : null;
return (
<Line pageId={this.props.page.id}
pageIdx={this.props.idx}
key={`${this.props.page.id}_${idx}`}
idx={idx}
parts={l.parts}
drawing={l.drawing}
hidden={l.hidden}
drawn={l.drawn}
tip={tip}
showTip={l.showTip} />
);
});
return (
<div className="page">
{lineElements}
<div ref={(el) => { this.bottomScrollAnchor = el; }} />
</div>
);
}
}
export default Page;
| ae1da67a06d406e45091f19b9d36867e44990905 | [
"JavaScript",
"Markdown"
] | 27 | JavaScript | gardym/switchback | ed56b28801a010166ac9e67c5482a97247f7511d | 1e2dffdbf44e5ceffdedcb922b861676f95af17d |
refs/heads/master | <file_sep>
(function () {
var intarvalo = randomIntFromInterval(10000, 60000);
console.log(intarvalo);
setInterval(function () {
try {
var inputs = document.getElementsByTagName("input"),
i,
len,
value = "Etiqueta",
achou = false;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'checkbox')
inputs[i].checked = true;
}
for (i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].value === value) {
inputs[i].click();
achou = true;
break;
}
}
if (!achou)
location.reload();
} catch (error) {
location.reload();
}
}, intarvalo);
function randomIntFromInterval(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
})();<file_sep>(function () {
const resourceRequest = new function () {
const _intervalInMinutes = 10;
const _modelToUse = "Proporção"; // Altere para o modelo desejado
const setModelToUse = function () {
var templates = document.getElementsByName("templates");
for (const template of templates) {
for (const option of template.options) {
if (option.text === _modelToUse) {
option.selected = 'selected';
}
}
}
};
const checkAll = function () {
const checks = document.getElementsByName("select-all");
for (const check of checks) {
check.click();
}
};
const request = function () {
var form = document.querySelectorAll("form[name='call-resources']");
if (form !== null && form !== undefined) {
form[0].submit();
}
};
const bind = function () {
setModelToUse();
setTimeout(function () {
checkAll();
request();
}, _intervalInMinutes * 60000);
};
this.init = function () {
bind();
}
};
resourceRequest.init();
})(window);<file_sep>
# Tribal Wars Scripts
Repositórios de scripts usados para TribalWars
## Contributors
[@victorgare](https://github.com/victorgare)
[@joaovperin](https://github.com/joaovperin)
[@IagoReis](https://github.com/IagoReis)
[@Dude29](https://github.com/Dude29)
## Sumario
* [Coletar Coordenadas - Barbaras](https://github.com/victorgare/tribalwars#coletar-coordenadas---barbaras)
* [Vender Recursos](https://github.com/victorgare/tribalwars#vender-recursos)
* [Auto Fake](https://github.com/victorgare/tribalwars#auto-fake)
* [Script de Intel](https://github.com/victorgare/tribalwars#script-de-intel)
* [Farm Mapa](https://github.com/victorgare/tribalwars#farm-mapa)
* [Identificador de Ataques](https://github.com/victorgare/tribalwars#identificador-de-ataques)
* [Planejador de Comandos](https://github.com/victorgare/tribalwars#planejador-de-comandos)
* [Farm Assistente de Saque](https://github.com/victorgare/tribalwars#farm-assistente-de-saque)
* [Coletar Coordenadas pelo Click](https://github.com/victorgare/tribalwars#coletar-coordenadas-pelo-click)
* [ContinuousRecruting](https://github.com/victorgare/tribalwars#continuous-recruting)
* [AccountCreator](https://github.com/victorgare/tribalwars#account-creator)
* [Resources Sender](https://github.com/victorgare/tribalwars#resources-sender)
* [Resources Request](https://github.com/victorgare/tribalwars#resources-request)
### Pre-requisitos
Instale a extensão Tampermonkey
### Installing
Para instalar os scripts no Tampermonkey, clique nos links que estarão disponiveis abaixo
## Built With
* Javascript
## Authors
* **<NAME>** - *Initial work* - [GitHub](https://github.com/victorgare)
## Coletar Coordenadas - Barbaras
* Deve ser executado no mapa!
* [Instalar Coletor de Coordenadas](https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/ColetarCoordenadas.user.js)
Este script cria um botão perto da informação da númeração do continente, quando o botão é clicado, uma caixa irá aparecer com as coordenadas das aldeias barbaras
## Vender Recursos
* Deve ser executado no mercado na parte de vender recursos por PPs!
* [Instalar Vender Recursos](https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/VenderRecursos.user.js)
Este script calcula a quantidade de recursos que você pode vender e cria uma oferta uma oferta abaixo para vender recursos por PPs.
**Exemplo**
O mercado oferece 1 pp por 300 de recursos e você tem 600 de recursos. O bot ira calcular que você poderia ganhar 2 pps, porem pela melhor oferta calculada pelo mercado, o pp valeria 330 de recursos, logo você não conseguiria vender os 600, sendo assim, o script identifica que você poderia vender 2 pps, porem reduz o número para um, pelo fato do calculo de melhor oferta do jogo.
**Ordem de venda dos recursos**
O script sempre vende os recursos nesta ordem:
```javascript
Ferro
Argila
Madeira
```
## Auto Fake
* Deve ser executado na praça de reuniões
* [Instalar Auto Fake](https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/AutoFakes.user.js)
Este script envia ataques fakes nas aldeias configuradas
**Configurações das quatidades a serem enviadas**
A quantidade de tropas pode ser configurada alterando os valores abaixos dentro do script (Não disponivel para arquivos e arqueiros a cavalo)
```javascript
var FakesPorAldeia = 30; //quantidade de fakes por aldiea
var sp = 0; // lanceiros
var sw = 0; // espadachins
var ax = 0; //barbaros
var scout = 0; //exploradores
var lc = 0; //calavaria leve
var hv = 0; // cavalaria pesada
var cat = 0; //catapulta
var ra = 1; // ariete
```
**Configuração das aldeias a serem atacadas**
As aldeias que receberam os ataques podem ser configuradas alterando o valor da variavel abaixo, separando as coordenadas por um espaço
```javascript
var coords = '111|111 222|222 333|333';
```
## Script de Intel
* Deve ser executado no mapa
* [Instalar Script de Intel](https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/Estatisticas.user.js)
Este script exibe informaçoes de evolução, ODA e ODD dos players no mapa, basta ativa-lo e abrir o mapa
## Farm Mapa
* Deve ser executado no mapa
* [Instalar Farm Mapa](https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/FarmMapa.user.js)
Script para farmar aldeias usando o assistente de saque (Configuração **A**) direto pelo mapa
**Configurações**
Apenas aumente o seu mapa o máximo possivel, ative o script e atualize a pagina, o script ira enviar ataques nas aldeias barbaras da mais próxima até a mais distante
## Identificador de ataques
* Deve ser executado nos comandos chegando, deve haver conta premiun!
* [Instalar Identificador de Ataques](https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/IdentificadorAtaques.user.js)
Script para identificar comandos vindos contra suas aldeias
**Configurações**
Na pagina de comandos chegando, aplicar um filtro no nome dos comandos para **Ataque**, assim, apenas comandos não identificados iram ser listados, o script seleciona todos e logo em seguida clica no botão identificar
## Planejador de Comandos
* Deve ser executado na pagina de confirmar o envio de um comando
* [Instalar Planejador de Comandos](https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/PlanejadorComandos.user.js)
O script permite que você configure um horário de chegada e assim o script envia para que chegue no horário
**Atenção**
Devido a delays de internet, o script não é muito preciso
## Farm Assistente de Saque
* Deve ser executado na pagina do assistente de saque
* [Instalar Farm Assistente de Saque](https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/FarmAssistenteSaque.user.js)
Envia comandos usando a configuração **A** do assistente de saque
## Coletar Coordenadas pelo Click
* Deve ser executado no mapa
* [Instalar Coletar Coordenadas pelo Click](https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/ColetarCoordsClick.user.js)
Adiciona um local onde as coordenadas das aldeias clicadas seram armazenadas. Basta clicar em qualquer aldeia e as coordenadas são adicionadas nesta area
## Continuous Recruting
* Deve ser executado na tela de recrutar da aldeia!
* [Instalar Continuous Recruting](https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/ContinuousRecruting.user.js)
O script verifica se há a unidade desejada na fila e caso não, adiciona 1 a fila de recrut (sim, apenas uma unidade), basta alterar o valor de alguma das variáveis abaixo para "true" e o script ira recrutar
```javascript
var lanca = false;
var espada = false;
var barbaro = false;
var explorador = false;
var cavalariaLeve = false;
var cavalariaPesada = false;
var catapulta = false;
var ariete = false;
```
**ATENÇÃO**
O script não tem limite de recrut!
## Account Creator
* Deve ser executado no link de criação de conta!
* [Instalar Account Creator](https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/AccountCreator.user.js)
Script ira criar contas fakes baseadas no link de convite fornecido e que iram ficar perto do usuário. Este script cria o tão famoso "Mar de BBs". Para usar configure as duas variaveis abaixo com o URL do link de convite e o mundo que deve ser colocada a conta
```javascript
var url = "seu link de convite"
var mundo = "numero do mundo que deve criar a acc ex: 87";
```
**ATENÇÃO**
O jogo limita a criação de 5 contas por dia por link de convite
## Resources Sender
* Deve ser executado no mercado na parte de enviar recursos!
* [Instalar Resources Sender](https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/ResourcesSender.user.js)
Script ira enviar recursos para cunhar moedas para uma aldeia especificada!
```javascript
const _destino = ""; // aldeia de destino
```
## Resources Request
* Deve ser executado no mercado na parte de pedir recursos!
* [Instalar Resources Request](https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/ResourcesRequest.user.js)
Script puxar recursos para a aldeia que estiver sendo executada!
```javascript
const _intervalInMinutes = 10; // intervalo de execução
const _modelToUse = "Proporção"; // Altere para o modelo desejado
```
Caso queira alterar o intervalo de executação, apenas alterar o valor da variavel, lembrando que deve ser em minutos
## Market Autofill
* Deve ser executado no mercado na parte de criar ofertas
* [Instalar Market Autofill](https://raw.githubusercontent.com/dude29/tribalwars/master/UserScript/MarketAutofill.user.js)
Automaticamente preenche as caixas de oferta no mercado com o valor predefinido
```javascript
value = 1000 // valor que o script usará para encher as caixas
```
<file_sep>var url = "";
var mundo = "";
const caracteres = "abcdefghijklmnopqrstuvxzwy";
var nameLength = Math.floor(Math.random() * 10) + 5;
const criarConta = "?ref=player_invite_linkrl";
const escolherMundo = "?welcome=1";
const logado = "?screen=overview&intro";
$(window).load(function () {
var urlAtual = window.location.href;
if (urlAtual.indexOf(criarConta) !== -1) {
console.log("criou a conta");
CriarConta();
}
if (urlAtual.indexOf(escolherMundo) !== -1) {
console.log("escolheu o mundo");
AcessarMundo();
}
if (urlAtual.indexOf(logado) !== -1) {
console.log("voltou pro inicio");
window.location.href = url;
}
});
//primeiro passo, preencher o form para criar a conta
function CriarConta() {
var name = "";
for (let i = 0; i < nameLength; i++) {
let randomNumber = Math.floor(Math.random() * 25);
name += caracteres[randomNumber];
}
$("#register_username").val(name);
$("#register_password").val(<PASSWORD> + "<PASSWORD>");
$("#register_email").val(name + "@" + name + ".com");
$("#terms").prop("checked", true);
$(".btn-register").on("click", function (e) {
e.preventDefault();
$(":submit").click();
});
$(".btn-register").trigger("click");
}
//acessa o mundo
function AcessarMundo() {
$("a").each(function () {
if (this.href.endsWith(mundo)) {
window.location.href = this.href;
}
});
}
<file_sep>// ==UserScript==
// @name Identificador de ATK
// @version 0.1
// @include https://*&screen=overview_villages&mode=incomings*
// @require https://code.jquery.com/jquery-2.2.4.min.js
// @downloadURL https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/IdentificadorAtaques.user.js
// @updateURL https://github.com/victorgare/tribalwars/raw/master/UserScript/IdentificadorAtaques.user.js
// ==/UserScript==
(function () {
var intarvalo = randomIntFromInterval(10000, 60000);
console.log(intarvalo);
setInterval(function () {
try {
var inputs = document.getElementsByTagName("input"),
i,
len,
value = "Etiqueta",
achou = false;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'checkbox')
inputs[i].checked = true;
}
for (i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].value === value) {
inputs[i].click();
achou = true;
break;
}
}
if (!achou)
location.reload();
} catch (error) {
location.reload();
}
}, intarvalo);
function randomIntFromInterval(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
})();<file_sep>"use strict";
$(document).ready(function () {
var villages = TWMap.villages;
var vk = TWMap.villageKey;
var key = {};
var keySorted = {};
var contador = 0;
var tempo = 350;
var x = 0;
var altAldTempo = aleatorio(180000, 300000);
//var altAldTempo = aleatorio(30000,60000);
var villagesToSkip = []; // add the villages id as string to the array
function aleatorio(superior, inferior) {
numPosibilidades = superior - inferior;
aleat = Math.random() * numPosibilidades;
return Math.round(parseInt(inferior) + aleat);
}
for (var j in vk) {
key[contador] = vk[j];
contador++;
}
var indice = 0;
for (var s = 0; s <= contador; s++) {
var coordsA = TWMap.CoordByXY(key[s]);
villageA = TWMap.context.FATooltip.distance(game_data.village.x, game_data.village.y, coordsA[0], coordsA[1]);
indice = 0;
for (var sb = 0; sb < contador; sb++) {
var coordsB = TWMap.CoordByXY(key[sb]);
villageB = TWMap.context.FATooltip.distance(game_data.village.x, game_data.village.y, coordsB[0], coordsB[1]);
if (villageA > villageB) {
indice++;
}
}
keySorted[indice] = key[s];
}
key = keySorted;
contador = 0;
for (var k in key) {
var village = villages[key[k]];
(function (villageA) {
var tempoAgora = (tempo * ++x) - aleatorio(150, 300);
setTimeout(function () {
if (villageA.owner == "0" && !(villagesToSkip.length > 0 && villagesToSkip.includes(villageA.id))) {
//var coordAtual = TWMap.CoordByXY(key[k]);
console.log(villageA);
var coordAtual = TWMap.CoordByXY(villageA);
TWMap.mapHandler.onClick(coordAtual[0], coordAtual[1], new Event('click'));
var url = TWMap.urls.ctx["mp_farm_a"].replace(/__village__/, villageA.id).replace(/__source__/, game_data.village.id);
TribalWars.get(url, null, function (a) { TWMap.context.ajaxDone(null, url); }, undefined, undefined);
contador++;
}
}, tempoAgora);
})(village);
}
function altAldeia() {
//$('.arrowRight').click();
//$('.groupRight').click();
location.reload();
}
setInterval(altAldeia, altAldTempo);
});<file_sep>// ==UserScript==
// @name 150 - Planejador XPTO
// @author <NAME>
// @version 0.2
// @include https://*screen=place&try=confirm*
// @require https://code.jquery.com/jquery-2.2.4.min.js
// @downloadURL https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/PlanejadorComandos.user.js
// @updateURL https://github.com/victorgare/tribalwars/raw/master/UserScript/PlanejadorComandos.user.js
// @run-at document-start
// ==/UserScript==
CommandSender = {
confirmButton: null,
duration: null,
dateNow: null,
offset: null,
init: function() {
$($('#command-data-form')['find']('tbody')[0])['append']('<tr><td>Chegada:</td><td> <input type="datetime-local" id="CStime" step=".001"> </td></tr><tr> <td>Offset:</td><td> <input type="number" id="CSoffset"> <button type="button" id="CSbutton" class="btn">Confirmar</button> </td></tr>');
this['confirmButton'] = $('#troop_confirm_submit');
this['duration'] = $('#command-data-form')['find']('td:contains("Dura\xE7\xE3o:")')['next']()['text']()['split'](':')['map'](Number);
this['offset'] = localStorage['getItem']('CS.offset') || -250;
this['dateNow'] = this['convertToInput'](new Date());
$('#CSoffset')['val'](this['offset']);
$('#CStime')['val'](this['dateNow']);
$('#CSbutton')['click'](function() {
var _0xbbd0x1 = Number($('#CSoffset')['val']());
var _0xbbd0x2 = CommandSender['getAttackTime']();
localStorage['setItem']('CS.offset', _0xbbd0x1);
CommandSender['confirmButton']['addClass']('btn-disabled');
setTimeout(function() {
CommandSender['confirmButton']['click']()
}, _0xbbd0x2 - Timing['getCurrentServerTime']() + _0xbbd0x1);
this['disabled'] = true
})
},
getAttackTime: function() {
var _0xbbd0x3 = new Date($('#CStime')['val']()['replace']('T', ' '));
_0xbbd0x3['setHours'](_0xbbd0x3['getHours']() - this['duration'][0]);
_0xbbd0x3['setMinutes'](_0xbbd0x3['getMinutes']() - this['duration'][1]);
_0xbbd0x3['setSeconds'](_0xbbd0x3['getSeconds']() - this['duration'][2]);
return _0xbbd0x3
},
convertToInput: function(_0xbbd0x4) {
_0xbbd0x4['setHours'](_0xbbd0x4['getHours']() + this['duration'][0]);
_0xbbd0x4['setMinutes'](_0xbbd0x4['getMinutes']() + this['duration'][1]);
_0xbbd0x4['setSeconds'](_0xbbd0x4['getSeconds']() + this['duration'][2]);
var a = {
y: _0xbbd0x4['getFullYear'](),
m: _0xbbd0x4['getMonth']() + 1,
d: _0xbbd0x4['getDate'](),
time: _0xbbd0x4['toTimeString']()['split'](' ')[0],
ms: _0xbbd0x4['getMilliseconds']()
};
if (a['m'] < 10) {
a['m'] = '0' + a['m']
};
if (a['d'] < 10) {
a['d'] = '0' + a['d']
};
if (a['ms'] < 100) {
a['ms'] = '0' + a['ms'];
if (a['ms'] < 10) {
a['ms'] = '0' + a['ms']
}
};
return a['y'] + '-' + a['m'] + '-' + a['d'] + 'T' + a['time'] + '.' + a['ms']
},
addGlobalStyle: function(_0xbbd0x6) {
var _0xbbd0x7, _0xbbd0x8;
_0xbbd0x7 = document['getElementsByTagName']('head')[0];
if (!_0xbbd0x7) {
return
};
_0xbbd0x8 = document['createElement']('style');
_0xbbd0x8['type'] = 'text/css';
_0xbbd0x8['innerHTML'] = _0xbbd0x6;
_0xbbd0x7['appendChild'](_0xbbd0x8)
}
};
CommandSender['addGlobalStyle']('#CStime, #CSoffset {font-size: 9pt;font-family: Verdana,Arial;}#CSbutton {float:right;}');
var a = setInterval(function() {
if (document['getElementById']('command-data-form') && jQuery) {
CommandSender['init']();
clearInterval(a)
}
}, 1);
setTimeout(function() {
$('#CSoffset')['eq'](0)['val']('-' + Timing['offset_to_server'])
}, 2000)<file_sep>// ==UserScript==
// @name Resourses Request
// @version 0.2
// @description Request resources to a specific village
// @author <NAME>
// @include https://*screen=market&mode=call*
// @downloadURL https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/ResourcesRequest.user.js
// @updateURL https://github.com/victorgare/tribalwars/raw/master/UserScript/ResourcesRequest.user.js
// @run-at document-end
// @grant none
// ==/UserScript==
(function () {
const resourceRequest = new function () {
const _intervalInMinutes = 10;
const _modelToUse = "Proporção"; // Altere para o modelo desejado
const setModelToUse = function () {
var templates = document.getElementsByName("templates");
for (const template of templates) {
for (const option of template.options) {
if (option.text === _modelToUse) {
option.selected = 'selected';
}
}
}
};
const checkAll = function () {
const checks = document.getElementsByName("select-all");
for (const check of checks) {
check.click();
}
};
const request = function () {
var form = document.querySelectorAll("form[name='call-resources']");
if (form !== null && form !== undefined) {
form[0].submit();
}
};
const bind = function () {
setModelToUse();
setTimeout(function () {
checkAll();
request();
}, _intervalInMinutes * 60000);
};
this.init = function () {
bind();
}
};
resourceRequest.init();
})(window);<file_sep>'use strict';
var divLegendas;
var textAreaCoords;
$(window).on("load", function () {
new CriarTextArea();
//sobrescreve a funcao padrao do JS do game
//adicionando a funcionalidade extra pra pegar as coordenadas
TWMap.mapHandler.onClick = function (e, a, t) {
new AdicionarCoordenadas(e + "|" + a);
var i = TWMap.villages[1e3 * e + a];
if (i) {
if (TWMap.warMode && Warplanner.admin) {
return Warplanner.onVillageClicked(i.id, e, a),
!1;
}
if (!TWMap.context.enabled) {
return (!t || $.browser.msie && ~~$.browser.version < 8) && (window.location.href = TWMap.urls.villageInfo.replace(/__village__/, i.id)),
!0;
}
TWMap.context.spawn(i, e, a)
} else {
TWMap.context.hide();
}
return !1
}
});
function CriarTextArea() {
divLegendas = $("#map_legend");
var textArea = $('<textarea id="txtCoords" style="width: 95%" />');
divLegendas.append(textArea);
}
function AdicionarCoordenadas(coordenada) {
$("#txtCoords").append(" " + coordenada);
}<file_sep>"use strict";
$(document).ready(function () {
(() => {
var aldeiaAlvo = {
x: 400,
y: 538
};
var threadRepeat = null;
var aldeiaRef = Object.values(TWMap.villages).filter(e => e.xy === parseInt(aldeiaAlvo.x + '' + aldeiaAlvo.y))[0];
var url = TWMap.urls.ctx["mp_farm_a"].replace(/__village__/, aldeiaRef.id).replace(/__source__/, game_data.village.id);
function isRecaptchaWindowPresent() {
var isPresent = false;
if (document.querySelector('#bot_check')) {
isPresent = true;
}
if (document.querySelector('#rc-anchor-alert')) {
isPresent = true;
}
if (document.querySelector("#rc-anchor-container")) {
isPresent = true;
}
if (document.querySelector("#recaptcha-token")) {
isPresent = true;
}
if ($(':contains(Proteção contra Bots)').val() !== undefined) {
isPresent = true;
}
if (isPresent) {
console.log("SE FERROU, RECAPTCHA TÁ NA AREA AUHEAUHEAUHAE");
}
return isPresent;
}
function aleatorio(superior, inferior) {
var max = Math.max(superior, inferior);
var min = Math.min(superior, inferior);
numPosibilidades = max - min;
aleat = Math.random() * numPosibilidades;
return parseInt(Math.round(parseInt(inferior) + aleat));
}
function gameOver(message) {
TribalWars.playAttackSound();
TribalWars.playAttackSound();
TribalWars.playAttackSound();
TribalWars.playAttackSound();
clearInterval(threadRepeat);
threadRepeat = null;
alert(message);
}
function isNoUnitsLeft() {
var autoHideBoxX = document.querySelector(".autoHideBox.error");
if (autoHideBoxX) {
return (autoHideBoxX.innerHTML || '').toLowerCase().indexof("não existem unidades suficientes") !== -1;
}
return false;
}
function isRequestLimitsToServer() {
var autoHideBoxX = document.querySelector(".autoHideBox.error");
if (autoHideBoxX) {
return (autoHideBoxX.innerHTML || '').toLowerCase().indexof("limite de requisições") !== -1;
}
return false;
}
function restartThread() {
if (threadRepeat != null) {
clearInterval(threadRepeat);
}
threadRepeat = setInterval(() => {
if (isRecaptchaWindowPresent()) {
return gameOver('SCRIPT PARADO POR CONTA DE RECAPTCHA :P');
}
if (isNoUnitsLeft()) {
console.warn('SCRIPT PARADO POIS NÃO HÁ UNIDADES RESTANTES :(');
return setTimeout(() => restartThread());
}
if (isRequestLimitsToServer()) {
console.warn('LIMITE DE REQUISIÇÕES FEITAS AO SERVIDOR.... AGUARDANDO');
return setTimeout(() => restartThread());
}
TWMap.mapHandler.onClick(aldeiaAlvo.x, aldeiaAlvo.y, new Event('click'));
TribalWars.get(url, null, function (a) {
TWMap.context.ajaxDone(null, url);
}, undefined, undefined);
}, aleatorio(318, 537));
}
restartThread();
setInterval(() => {
restartThread();
}, aleatorio(10000, 18000));
})();
});<file_sep>//quantidade atual de recursos na aldeia
var madeiraAldeia;
var argilaAldeia;
var ferroAldeia;
//quantidade de recursos por PP no mercado
var taxaMadeira;
var taxaArgila;
var taxaFerro;
$(window).on("load", function () {
//preenche o valor dos recursos atuais da aldeia
madeiraAldeia = $("#wood").text();
argilaAldeia = $("#stone").text();
ferroAldeia = $("#iron").text();
//preenche o valor da taxa atual do mercado
taxaMadeira = PremiumExchange.calculateRateForOnePoint("wood");
taxaArgila = PremiumExchange.calculateRateForOnePoint("stone");
taxaFerro = PremiumExchange.calculateRateForOnePoint("iron");
AdicionaPainelConfiguracoes();
//no click do botao salvar, atualiza as configuracoes
$("#btnSalvar").click(function () {
var limiteMadeira = $("#limiteComprarMadeira").val();
var limiteArgila = $("#limiteComprarArgila").val();
var limiteFerro = $("#limiteComprarFerro").val();
SetCookiesPainel("wood", limiteMadeira);
SetCookiesPainel("stone", limiteArgila);
SetCookiesPainel("iron", limiteFerro);
location.reload();
});
});
function GetCookiesPainel(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
var value = c.substring(name.length, c.length);
if (value === '') {
return 0;
}
return value;
}
}
return 0;
}
function SetCookiesPainel(key, value) {
document.cookie = key + "=" + value;
}
//ira criar o painel com as configuracoes do script
function AdicionaPainelConfiguracoes() {
var body = $("#ds_body");
var divPainel = $('<div class="quest" style="position: fixed;top: 65px;left: 84%; width: 15%; height: auto; margin-top: 0;text-align: center;" id="painelConfiguracoes"> </div>');
var labelLimiteComprarMadeira = $('<label class="label label-warning">Limite comprar <span class="icon header wood"> </span></label>');
var txtLimiteComprarMadeira = $('<input type="text" id="limiteComprarMadeira" value="' + GetCookiesPainel("wood") + '" /> </br>');
var labelLimiteComprarArgila = $('<label class="label label-warning">Limite comprar <span class="icon header stone"> </span></label>');
var txtLimiteComprarArgila = $('<input type="text" id="limiteComprarArgila" value="' + GetCookiesPainel("stone") + '"/> </br>');
var labelLimiteComprarFerro = $('<label class="label label-warning">Limite comprar <span class="icon header iron"> </span></label>');
var txtLimiteComprarFerro = $('<input type="text" id="limiteComprarFerro" value="' + GetCookiesPainel("iron") + '"/> </br>');
var btnSalvar = $('</br></br> <input type="button" class="btn" id="btnSalvar" value="Salvar"/>');
divPainel.append(labelLimiteComprarMadeira);
divPainel.append(txtLimiteComprarMadeira);
divPainel.append(labelLimiteComprarArgila);
divPainel.append(txtLimiteComprarArgila);
divPainel.append(labelLimiteComprarFerro);
divPainel.append(txtLimiteComprarFerro);
divPainel.append(btnSalvar);
body.append(divPainel);
}
function CalcularComprarVender(valorTaxa) {
if (valorTaxa <= 250) {
return "comprar";
}
if (valorTaxa >= 300) {
return "vender";
}
return "aguardar";
}
function CalcularMelhorTaxaComprar(taxaMadeira, taxaArgila, taxaFerro) {
let ordemComprar = [];
if (taxaMadeira > taxaArgila && taxaArgila > taxaFerro) {
ordemComprar[0] = "madeira";
ordemComprar[1] = "argila";
ordemComprar[2] = "ferro";
}
if (taxaFerro > taxaMadeira && taxaMadeira > taxaArgila) {
ordemComprar[0] = "ferro";
ordemComprar[1] = "madeira";
ordemComprar[2] = "argila";
}
if (taxaArgila > taxaFerro && taxaFerro > taxaMadeira) {
ordemComprar[0] = "argila";
ordemComprar[1] = "ferro";
ordemComprar[2] = "madeira";
}
return ordemComprar;
}
function CalcularMelhorTaxaVender(taxaMadeira, taxaArgila, taxaFerro) {
let ordemVender = [];
if (taxaMadeira > taxaArgila && taxaArgila > taxaFerro) {
ordemComprar[0] = "madeira";
ordemComprar[1] = "argila";
ordemComprar[2] = "ferro";
}
if (taxaFerro > taxaMadeira && taxaMadeira > taxaArgila) {
ordemComprar[0] = "ferro";
ordemComprar[1] = "madeira";
ordemComprar[2] = "argila";
}
if (taxaArgila > taxaFerro && taxaFerro > taxaMadeira) {
ordemComprar[0] = "argila";
ordemComprar[1] = "ferro";
ordemComprar[2] = "madeira";
}
return ordemComprar;
}<file_sep>//Vende recursos por pontos premiun
var altAldTempo = aleatorio(10000, 100000);
var qtdDisponivelTransporte;
//recursos disponiveis na aldeia
var qtdMadeiraAldeia;
var qtdArgilaAldeia;
var qtdFerroAldeia;
//capacidade maxima de cada recurso
var capacidadeMadeira;
var capacidadeArgila;
var capacidadeFerro;
//quantidade estocada de cada recurso
var estoqueMandeira;
var estoqueArgila;
var estoqueFerro;
//campos para serem preenchidos
var inputVenderMadeira;
var inputVenderArgila;
var inputVenderFerro;
(function () {
'use strict';
qtdDisponivelTransporte = $("#market_merchant_max_transport").text();
capacidadeMadeira = $("#premium_exchange_capacity_wood").text();
capacidadeArgila = $("#premium_exchange_capacity_stone").text();
capacidadeFerro = $("#premium_exchange_capacity_iron").text();
estoqueMandeira = $("#premium_exchange_stock_wood").text();
estoqueArgila = $("#premium_exchange_stock_stone").text();
estoqueFerro = $("#premium_exchange_stock_iron").text();
inputVenderMadeira = $("input[name='sell_wood']");
inputVenderArgila = $("input[name='sell_stone']");
inputVenderFerro = $("input[name='sell_iron']");
qtdMadeiraAldeia = $("#wood").text();
qtdArgilaAldeia = $("#stone").text();
qtdFerroAldeia = $("#iron").text();
var custoMadeira = calcularCusto("wood");
var custoArgila = calcularCusto("stone");
var custoFerro = calcularCusto("iron");
var qtdTotalRecursos;
var qtdVenderMadeira = (calcularQuantidadeVender(capacidadeMadeira, estoqueMandeira, qtdMadeiraAldeia, custoMadeira) * custoMadeira);
var qtdVenderArgila = (calcularQuantidadeVender(capacidadeArgila, estoqueArgila, qtdArgilaAldeia, custoArgila) * custoArgila);
var qtdVenderFerro = (calcularQuantidadeVender(capacidadeFerro, estoqueFerro, qtdFerroAldeia, custoFerro) * custoFerro);
if (qtdVenderMadeira > qtdDisponivelTransporte) {
qtdVenderMadeira = qtdDisponivelTransporte - 1000;
}
if (qtdVenderArgila > qtdDisponivelTransporte) {
qtdVenderMadeira = qtdDisponivelTransporte - 1000;
}
if (qtdVenderFerro > qtdDisponivelTransporte) {
qtdVenderMadeira = qtdDisponivelTransporte - 1000;
}
var algoPraVender = false;
if (qtdVenderFerro > 0 && qtdVenderFerro <= qtdDisponivelTransporte) {
inputVenderFerro.val(qtdVenderFerro);
algoPraVender = true;
} else if (qtdVenderArgila > 0 && qtdVenderArgila <= qtdDisponivelTransporte) {
inputVenderArgila.val(qtdVenderArgila);
algoPraVender = true;
} else if (qtdVenderMadeira > 0 && qtdVenderMadeira <= qtdDisponivelTransporte) {
inputVenderMadeira.val(qtdVenderMadeira);
algoPraVender = true;
} else {
console.log("Nada para vender hoje");
}
if (algoPraVender) {
setTimeout(calcularMelhorOferta, 2000);
}
setInterval(altAldeia, altAldTempo);
})();
function calcularMelhorOferta() {
$(".btn-premium-exchange-buy").click();
setTimeout(confirmarVenda, 1000);
}
function confirmarVenda() {
$(".btn-confirm-yes").click();
}
function calcularQuantidadeVender(capacidade, estoque, qtdDisponivel, custo) {
var quantidadeVender = 0;
var capacidadeDisponivel = capacidade - estoque;
if (capacidadeDisponivel > 0) {
if (qtdDisponivel >= custo) {
quantidadeVender = Math.ceil(qtdDisponivel / custo) - 1;
}
}
return quantidadeVender;
}
function calcularCusto(tipoRecurso) {
var capacidade = PremiumExchange.data.capacity[tipoRecurso];
var stock = PremiumExchange.data.stock[tipoRecurso];
var fator = (PremiumExchange.data.tax.buy, PremiumExchange.calculateMarginalPrice(stock, capacidade));
var resultado = Math.floor(1 / fator);
return resultado;
}
function altAldeia() {
//$('.arrowRight').click();
//$('.groupRight').click();
location.reload(true);
}
function aleatorio(superior, inferior) {
numPosibilidades = superior - inferior;
aleat = Math.random() * numPosibilidades;
return Math.round(parseInt(inferior) + aleat);
}
<file_sep>$(document).ready(function () {
//let coords = getCoordedadas();
var button = document.createElement('button');
button.addEventListener("click", getCoordedadas);
button.innerText = "Coletar Coordenadas";
button.style.textAlign = "center";
button.className = "btn btn-instant-free";
var div = document.createElement('div');
div.style.display = "unset";
div.style.marginLeft = "10px"
div.appendChild(button);
var continente = document.getElementById("content_value");
continente.insertBefore(div, continente.firstChild);
});
function getCoordedadas() {
let villages = TWMap.villages;
let vk = TWMap.villageKey;
let key = {};
let bbs = "";
let contador = 0;
for (j in vk) {
key[contador] = vk[j];
contador++;
}
contador = 0;
for (var k in key) {
var village = villages[key[k]];
if (village.owner == "0") {
var coordAtual = TWMap.CoordByXY(key[k]);
bbs += coordAtual[0] + "|" + coordAtual[1] + " ";
contador++;
}
}
alert(bbs);
return bbs;
}<file_sep>// ==UserScript==
// @name Resources Sender
// @version 0.1
// @description Send resources to a specified village!
// @author <NAME>
// @include https://*screen=market&mode=send*
// @include https://*try=confirm_send*
// @require https://code.jquery.com/jquery-3.3.1.min.js
// @downloadURL https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/ResourcesSender.user.js
// @updateURL https://github.com/victorgare/tribalwars/raw/master/UserScript/ResourcesSender.user.js
// @run-at document-end
// @grant none
// ==/UserScript==
(function () {
const ResourcesSender = new function () {
const _destino = ""; // aldeia de destino
const _minTime = 8000; // 8 segundos em milisegundos
const _maxTime = 15000; // 15 segundos em milisegundos
const _woodPercentage = 0.34; // porcentagem de madeira para enviar
const _stonePercentage = 0.36; // porcentagem de argila pra enviar
const _ironPercentage = 0.30; // porcentagem de ferro apra enviar
const randonNumber = function (min, max) {
return Math.random() * (max - min) + min;
}
const getMerchantsAvailable = function () {
return parseInt(document.getElementById("market_merchant_available_count").innerHTML);
};
const getResourcesAmount = function () {
const wood = parseInt(document.getElementById("wood").innerHTML);
const stone = parseInt(document.getElementById("stone").innerHTML);
const iron = parseInt(document.getElementById("iron").innerHTML);
return {
wood: wood,
stone: stone,
iron: iron
}
};
const setValueToSend = function (value1, value2, input) {
// sempre devera inserir no campo o MENOR valor, para não ocorrer problemas de quantidade
// se os valores forem zero, nem continua com os tramites
if (value1 === 0 || value2 === 0) {
return false;
}
if (value1 > value2) {
input.val(value2);
} else {
input.val(value1);
}
return true;
}
const submitButton = function () {
$("input[type='submit']").click();
}
const sendResources = function () {
// devera sera o destino no campo correto
// clicar no botao OK
$(".target-input-field ").val(_destino);
submitButton();
}
const nextVillage = function () {
document.getElementById("village_switch_right").click();
}
const calculateResources = function () {
const resourcesAvailable = getResourcesAmount();
const availableMerchants = getMerchantsAvailable();
let woodToSend = Math.floor((resourcesAvailable.wood * _woodPercentage) / 1000) * 1000;
let stoneToSend = Math.floor((resourcesAvailable.stone * _stonePercentage) / 1000) * 1000;
let ironToSend = Math.floor((resourcesAvailable.iron * _ironPercentage) / 1000) * 1000;
let merchantToSendWood = Math.floor(availableMerchants * _woodPercentage) * 1000;
let merchantToSendStone = Math.floor(availableMerchants * _stonePercentage) * 1000;
let merchantToSendIron = Math.floor(availableMerchants * _ironPercentage) * 1000;
let woodInput = $('input[name="wood"]');
let stoneInput = $('input[name="stone"]');
let ironInput = $('input[name="iron"]');
// chama metodo que faz a regra dos recursos a serem enviados
// se nao houver recursos a serem enviados, passa para a próxima aldeia
const envioMandeira = setValueToSend(woodToSend, merchantToSendWood, woodInput);
const envioArgila = setValueToSend(stoneToSend, merchantToSendStone, stoneInput);
const envioFerro = setValueToSend(ironToSend, merchantToSendIron, ironInput);
if (envioMandeira || envioArgila || envioFerro) {
// se os tres metodos acima retornarem verdadeiro, deve-se tentar dar o submit
// metodo que devera enviar os recursos
sendResources();
} else {
nextVillage();
}
}
const bind = function () {
// a primeria condição valida se estamos na tela de confirmar envio
// a segunda se estamos na tela para calcular os recursos
if ($("h2").html() === "Confirmar transporte") {
submitButton();
} else {
setTimeout(calculateResources, randonNumber(_minTime, _maxTime));
}
};
this.init = function () {
bind();
};
}
ResourcesSender.init();
})();<file_sep>// ==UserScript==
// @name Farm Mapa
// @namespace
// @version 0.1
// @description farma as aldeias pela aba do mapa usando o AS no modelo --->A<---
// @author <NAME>
// @include https://*&screen=map*
// @require http://code.jquery.com/jquery-1.12.4.min.js
// @downloadURL https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/FarmMapa.user.js
// @updateURL https://github.com/victorgare/tribalwars/raw/master/UserScript/FarmMapa.user.js
// @grant none
// ==/UserScript==
"use strict";
$(document).ready(function () {
var villages = TWMap.villages;
var vk = TWMap.villageKey;
var key = {};
var keySorted = {};
var contador = 0;
var tempo = 350;
var x = 0;
var altAldTempo = aleatorio(180000, 300000);
//var altAldTempo = aleatorio(30000,60000);
var villagesToSkip = []; // add the villages id as string to the array
function aleatorio(superior, inferior) {
numPosibilidades = superior - inferior;
aleat = Math.random() * numPosibilidades;
return Math.round(parseInt(inferior) + aleat);
}
for (var j in vk) {
key[contador] = vk[j];
contador++;
}
var indice = 0;
for (var s = 0; s <= contador; s++) {
var coordsA = TWMap.CoordByXY(key[s]);
villageA = TWMap.context.FATooltip.distance(game_data.village.x, game_data.village.y, coordsA[0], coordsA[1]);
indice = 0;
for (var sb = 0; sb < contador; sb++) {
var coordsB = TWMap.CoordByXY(key[sb]);
villageB = TWMap.context.FATooltip.distance(game_data.village.x, game_data.village.y, coordsB[0], coordsB[1]);
if (villageA > villageB) {
indice++;
}
}
keySorted[indice] = key[s];
}
key = keySorted;
contador = 0;
for (var k in key) {
var village = villages[key[k]];
(function (villageA) {
var tempoAgora = (tempo * ++x) - aleatorio(150, 300);
setTimeout(function () {
if (villageA.owner == "0" && !(villagesToSkip.length > 0 && villagesToSkip.includes(villageA.id))) {
//var coordAtual = TWMap.CoordByXY(key[k]);
console.log(villageA);
var coordAtual = TWMap.CoordByXY(villageA);
TWMap.mapHandler.onClick(coordAtual[0], coordAtual[1], new Event('click'));
var url = TWMap.urls.ctx["mp_farm_a"].replace(/__village__/, villageA.id).replace(/__source__/, game_data.village.id);
TribalWars.get(url, null, function (a) { TWMap.context.ajaxDone(null, url); }, undefined, undefined);
contador++;
}
}, tempoAgora);
})(village);
}
function altAldeia() {
//$('.arrowRight').click();
//$('.groupRight').click();
location.reload();
}
setInterval(altAldeia, altAldTempo);
});<file_sep>// ==UserScript==
// @name Coletar Coordenadas Mapa
// @version 3.0
// @description Coleta as coordenadas ao redor do mapa
// @author <NAME>
// @include https://*&screen=map*
// @require https://code.jquery.com/jquery-2.2.4.min.js
// @downloadURL https://raw.githubusercontent.com/victorgare/tribalwars/master/UserScript/ColetarCoordenadas.user.js
// @updateURL https://github.com/victorgare/tribalwars/raw/master/UserScript/ColetarCoordenadas.user.js
// @grant none
// ==/UserScript==
$(document).ready(function () {
//let coords = getCoordedadas();
var button = document.createElement('button');
button.addEventListener("click", getCoordedadas);
button.innerText = "Coletar Coordenadas";
button.style.textAlign = "center";
button.className = "btn btn-instant-free";
var div = document.createElement('div');
div.style.display = "unset";
div.style.marginLeft = "10px"
div.appendChild(button);
var continente = document.getElementById("content_value");
continente.insertBefore(div, continente.firstChild);
});
function getCoordedadas() {
let villages = TWMap.villages;
let vk = TWMap.villageKey;
let key = {};
let bbs = "";
let contador = 0;
for (j in vk) {
key[contador] = vk[j];
contador++;
}
contador = 0;
for (var k in key) {
var village = villages[key[k]];
if (village.owner == "0") {
var coordAtual = TWMap.CoordByXY(key[k]);
bbs += coordAtual[0] + "|" + coordAtual[1] + " ";
contador++;
}
}
alert(bbs);
return bbs;
}
| 65362aaf2cbcbb336ce8de43eaf92e146e94daa8 | [
"JavaScript",
"Markdown"
] | 16 | JavaScript | victorgare/tribalwars | 4b5da1133a947ee98ef1cffb76173f804b2f8bae | e914720b44a5ed1d1d8ff305258a08aa718a5d72 |
refs/heads/master | <file_sep>json.extract! friendlist, :id, :first_name, :last_name, :gender, :email, :phone, :created_at, :updated_at
json.url friendlist_url(friendlist, format: :json)
| dddec8c53d982a99760a7792468e86ffee0c8ce2 | [
"Ruby"
] | 1 | Ruby | rubyboy-hub/friend | 4f3c796806829cd48afd6d98f19e02137492233c | 96a15891d3de2f0dcd2e17bc0be37511565edbd7 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Policy;
using Robot.Common;
namespace AndriiRomanchak.RobotChallenge
{
public class DistanceHelper
{
public static int FindDistance(Position a, Position b)
{
//return (int)(Math.Pow(a.X - b.X, 2) + Math.Pow(a.Y - b.Y, 2));
return (int)(Math.Max(Math.Abs(a.X - b.X), Math.Abs(a.Y - b.Y)));
}
public static int FindCost(Position a, Position b)
{
return (int)(Math.Pow(a.X - b.X, 2) + Math.Pow(a.Y - b.Y, 2));
}
public static List<EnergyStation> GetNearbyStations(Position position, int maxEnrgy)
{
return
Current.Map.Stations.Where(station => FindCost(position, station.Position) <= maxEnrgy).ToList();
}
public static IList<Robot.Common.Robot> GetNeabyRobots(Position position, int maxEnergy)
{
return Current.RobotList.Where(robot => FindCost(position, robot.Position) <= maxEnergy).ToList();
}
public static Position FindSemiDistance(Position start, Position end, int maxEnergy)
{
if (maxEnergy == 0)
return start;
var curEnd = end;
while (FindCost(start, curEnd) > maxEnergy)
{
if (curEnd.X > start.X)
curEnd.X--;
else if (curEnd.X < start.X)
curEnd.X++;
if (curEnd.Y > start.Y)
curEnd.Y--;
else if (curEnd.Y < start.Y)
curEnd.Y++;
}
return curEnd;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Robot.Common;
using Rb = Robot.Common.Robot;
namespace AndriiRomanchak.RobotChallenge
{
public static class Current
{
public static Map Map;
public static IList<Rb> RobotList;
public static int RobotIndex;
public static Rb Robot;
public static int RobotIndexOf(Rb robot)
{
return RobotList.IndexOf(robot);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using Robot.Common;
using Rb = Robot.Common.Robot;
namespace AndriiRomanchak.RobotChallenge
{
public class AndriiRomanchakAlgorithm : IRobotAlgorithm
{
public static LogRoundEventHandler OnLogRound;
public int RoundNumber;
public int MyRobotsCount;
private const int MaxRobotCount = 200;
public string Author => "<NAME>";
public string Description => "AR Robot Algorithm";
public enum StationUseVariant
{
JoinOrCollect, AttackOnly, SkipOrLeave, JoinReserve
}
public AndriiRomanchakAlgorithm()
{
Logger.OnLogRound += Logger_OnLogRound;
MyRobotsCount = 10;
}
private void Logger_OnLogRound(object sender, LogRoundEventArgs e)
{
RoundNumber = e.Number;
}
public RobotCommand DoStep(IList<Rb> robots, int robotToMoveIndex, Map map)
{
Current.Map = map;
Current.RobotIndex = robotToMoveIndex;
Current.RobotList = robots;
Current.Robot = robots[robotToMoveIndex];
var collectProfit = GetCollectableProfit();
int attackProfit, moveProfit;
var attackPosition = GetBestAttackPosition(Current.Robot.Energy, out attackProfit);
var movePosition = GetBestMovePosition(Current.Robot.Energy, out moveProfit);
if (attackPosition == null && movePosition == null)
{
movePosition = GetBestMovePosition(Current.Robot.Energy * 2, out moveProfit);
movePosition = DistanceHelper.FindSemiDistance(Current.Robot.Position, movePosition,
Current.Robot.Energy/2);
if(!IsCellFree(movePosition))
movePosition = Current.Map.FindFreeCell(movePosition, Current.RobotList);
moveProfit /= 4;
}
var newRobotPosition = map.FindFreeCell(Current.Robot.Position, Current.RobotList);
// how much energy to give to the new robot
var newRobotEnergy = GetNewRobotEnergy(newRobotPosition);
// check which stations will new robot use
var newRobotStations = UsingStations(newRobotPosition);
// count my robots on ^^ stations
var myRobotsOnStationsCount = GetRobotsUsingStations(newRobotStations, true).Count;
// if current robot uses any station
var currentIsUsingStation = UsingAnyStation();
if (newRobotEnergy > 0 && currentIsUsingStation &&
(myRobotsOnStationsCount < newRobotStations.Count*2 || RoundNumber < 10))
{
return new CreateNewRobotCommand() {NewRobotEnergy = newRobotEnergy};
}
if (moveProfit > collectProfit*5 || attackProfit > collectProfit*2)
{
if (attackProfit < 0) attackPosition = movePosition;
var finalPosition = attackProfit*2 > moveProfit ? attackPosition : movePosition;
if (finalPosition != null)
{
if (DistanceHelper.FindCost(Current.Robot.Position, finalPosition) > Current.Robot.Energy)
{
}
else
return new MoveCommand() {NewPosition = finalPosition};
}
}
return new CollectEnergyCommand();
}
/// <summary>
/// Returns energy can be collected now.
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public int GetCollectableProfit(Position position = null)
{
if (position == null)
position = Current.Robot.Position;
var profit =
Current.Map.Stations.Where(
s => DistanceHelper.FindDistance(position, s.Position) <= Constants.EnergyCollectingDistance)
.Sum(s => s.Energy);
return profit == 0 ? int.MinValue : profit;
}
struct StationInfo
{
public Rb AttackRobot;
public StationUseVariant UsageVariant;
}
struct PositionInfo
{
public int Profit;
public Dictionary<EnergyStation, StationInfo> NearestStations; // bool for attackOnly
}
/// <summary>
/// Returns best position to move and profit
/// </summary>
/// <param name="maxEnergy"></param>
/// <param name="profit"></param>
/// <param name="robot"></param>
/// <returns></returns>
public Position GetBestMovePosition(int maxEnergy, out int profit, Rb robot = null)
{
if (robot == null)
robot = Current.Robot;
Position bestPosition = null;
var bestProfit = int.MinValue;
var posVariants = new Dictionary<Position, PositionInfo>();
var stationsInTouch = DistanceHelper.GetNearbyStations(robot.Position, maxEnergy);
foreach (var station in stationsInTouch)
{
for (var i = -Constants.EnergyCollectingDistance; i <= Constants.EnergyCollectingDistance; ++i)
{
for (var j = -Constants.EnergyCollectingDistance; j <= Constants.EnergyCollectingDistance; ++j)
{
var pos = new Position(station.Position.X + i, station.Position.Y + j);
if(DistanceHelper.FindCost(pos, robot.Position) > maxEnergy) continue;
Rb attRob;
var stInfo = new StationInfo()
{
UsageVariant = CheckStaionUsage(station, out attRob),
AttackRobot = attRob
};
if(stInfo.UsageVariant == StationUseVariant.SkipOrLeave) continue;
if (posVariants.ContainsKey(pos))
{
posVariants[pos].NearestStations.Add(station, stInfo);
}
else
{
var posInfo = new PositionInfo
{
NearestStations = new Dictionary<EnergyStation, StationInfo> {{station, stInfo}}
};
posVariants[pos] = posInfo;
}
}
}
}
foreach (var posKV in posVariants)
{
var pos = posKV.Key;
var posInfo = posVariants[posKV.Key];
var joinableStations = 0;
var reserveStations = 0;
posInfo.Profit = 0;
foreach (var stationKV in posInfo.NearestStations)
{
var station = stationKV.Key;
var stInfo = stationKV.Value;
posInfo.Profit += station.Energy;
switch (stInfo.UsageVariant)
{
case StationUseVariant.JoinOrCollect:
joinableStations++;
break;
case StationUseVariant.AttackOnly:
if (pos == stInfo.AttackRobot.Position)
posInfo.Profit += -50 + stInfo.AttackRobot.Energy/20;
else
posInfo.Profit -= station.Energy;
break;
case StationUseVariant.JoinReserve:
posInfo.Profit -= station.Energy;
reserveStations++;
break;
}
}
posInfo.Profit += (int) (posInfo.Profit*((double) joinableStations/2));
posInfo.Profit += (int) (posInfo.Profit*((double) reserveStations/8));
posInfo.Profit -= DistanceHelper.FindCost(robot.Position, pos);
if (posInfo.Profit > bestProfit)
{
bestProfit = posInfo.Profit;
bestPosition = pos;
}
}
profit = bestProfit;
return bestPosition;
}
/// <summary>
/// Checks how many robots are using station and reasonability to move to it
/// </summary>
/// <param name="station"></param>
/// <param name="robotToAttack"></param>
/// <param name="myRobotIndex"></param>
/// <returns></returns>
public StationUseVariant CheckStaionUsage(EnergyStation station, out Rb robotToAttack, int myRobotIndex = -1)
{
if (myRobotIndex == -1)
myRobotIndex = Current.RobotIndex;
robotToAttack = null;
var usingRobots = GetRobotsUsingStation(station);
if (!usingRobots.Any()) return StationUseVariant.JoinOrCollect;
var otherUsingRobots = usingRobots.Where(robot => robot.Owner != Current.Robot.Owner).ToList();
var myUsingRobots = usingRobots.Where(robot => robot.Owner == Current.Robot.Owner).ToList();
var myCount = myUsingRobots.Count;
if (!otherUsingRobots.Any() && myUsingRobots.Any()) // only my robots on station
{
var myMinIndex = myUsingRobots.Min(robot => Current.RobotIndexOf(robot));
if (myMinIndex == myRobotIndex) // cur has the smallest index
{
return myCount == 1 ? StationUseVariant.JoinOrCollect : StationUseVariant.SkipOrLeave;
}
//return myMinIndex < myRobotIndex ? StationUseVariant.JoinOrCollect : StationUseVariant.JoinReserve;
return myMinIndex < myRobotIndex ? StationUseVariant.JoinReserve : StationUseVariant.JoinReserve;
}
else if (otherUsingRobots.Any() && !myUsingRobots.Any()) // only other robots on station
{
otherUsingRobots.Sort((r1, r2) => Current.RobotIndexOf(r1).CompareTo(Current.RobotIndexOf(r2)));
var robotCount = otherUsingRobots.Count;
if (Current.RobotIndexOf(otherUsingRobots[0]) > myRobotIndex) // first myRobotPos index > my
return StationUseVariant.JoinOrCollect;
else if (robotCount >= 2 && Current.RobotIndexOf(otherUsingRobots[1]) > myRobotIndex || robotCount < 2) // other first < my && other second > my || no second
{
if (PushesOutOfStation(station, otherUsingRobots[0], Current.RobotList[myRobotIndex]))
{
robotToAttack = otherUsingRobots[0];
return StationUseVariant.AttackOnly;
}
else return StationUseVariant.SkipOrLeave;
}
else // other first < my && other second < my
{
return StationUseVariant.SkipOrLeave;
}
}
else // other and my robots on station
{
myUsingRobots.Sort((r1, r2) => Current.RobotIndexOf(r1).CompareTo(Current.RobotIndexOf(r2)));
otherUsingRobots.Sort((r1, r2) => Current.RobotIndexOf(r1).CompareTo(Current.RobotIndexOf(r2)));
var otherCount = otherUsingRobots.Count;
if (Current.RobotIndexOf(myUsingRobots[0]) > Current.RobotIndexOf(otherUsingRobots[0]))
{
// my first > other first
if (otherCount >= 2 && Current.RobotIndexOf(myUsingRobots[0]) < Current.RobotIndexOf(otherUsingRobots[1]) || otherCount < 2)
{
// my first < other second || otherCount == 1
if (PushesOutOfStation(station, otherUsingRobots[0], Current.RobotList[myRobotIndex]))
{
robotToAttack = otherUsingRobots[0];
return StationUseVariant.AttackOnly;
}
else return StationUseVariant.SkipOrLeave;
}
else if (myRobotIndex < Current.RobotIndexOf(otherUsingRobots[0]))
{
// my first > other second && cur < other first
return StationUseVariant.JoinOrCollect;
}
else if (myRobotIndex < Current.RobotIndexOf(otherUsingRobots[1]))
{
// cur > other first && cur < other second
if (PushesOutOfStation(station, otherUsingRobots[0], Current.RobotList[myRobotIndex]))
{
robotToAttack = otherUsingRobots[0];
return StationUseVariant.AttackOnly;
}
else return StationUseVariant.SkipOrLeave;
}
else
{
return StationUseVariant.SkipOrLeave;
}
}
else // my first < other first
{
if (myRobotIndex > Current.RobotIndexOf(myUsingRobots[0]))
{
// moving > my first
if (myRobotIndex < Current.RobotIndexOf(otherUsingRobots[0]))
{
// moving < other first
//return StationUseVariant.JoinOrCollect;
return StationUseVariant.JoinReserve;
}
else if (otherCount >= 2 && myRobotIndex < Current.RobotIndexOf(otherUsingRobots[1]) || otherCount < 2)
{
// moving < other second || otherCount == 1
if (PushesOutOfStation(station, otherUsingRobots[0], Current.RobotList[myRobotIndex]))
{
robotToAttack = otherUsingRobots[0];
//return StationUseVariant.AttackOnly;
return StationUseVariant.JoinReserve;
}
else return StationUseVariant.SkipOrLeave;
}
else
{
// moving > other second
return StationUseVariant.SkipOrLeave;
}
}
else
{
// moving < my first
return StationUseVariant.SkipOrLeave;
}
}
}
//return StationUseVariant.JoinOrCollect;
}
/// <summary>
/// Returns true if myRobotPos pushed attackedRobot out of the station influence radius
/// </summary>
/// <param name="station"></param>
/// <param name="myRobot"></param>
/// <param name="attackedRobot"></param>
/// <returns></returns>
public bool PushesOutOfStation(EnergyStation station, Rb attackedRobot, Rb myRobot = null)
{
if (myRobot == null)
myRobot = Current.Robot;
if (myRobot.Owner == attackedRobot.Owner)
return false;
var x = 2*attackedRobot.Position.X - myRobot.Position.X;
var y = 2*attackedRobot.Position.Y - myRobot.Position.Y;
var newPos = Current.Map.FindFreeCell(new Position(x, y), Current.RobotList);
return Math.Abs(newPos.X - station.Position.X) > Constants.EnergyCollectingDistance &&
Math.Abs(newPos.Y - station.Position.Y) > Constants.EnergyCollectingDistance;
}
public int GetAttackProfit(Rb attackedRobot, Rb myRobot = null)
{
if (attackedRobot == null)
return 0;
if (myRobot == null)
myRobot = Current.Robot;
var profit = -DistanceHelper.FindCost(attackedRobot.Position, myRobot.Position)*2 - Constants.EnergyUsedToAttack;
profit += (int) (attackedRobot.Energy*Constants.EnergyStolenPercent);
return profit;
}
public Rb GetRobotOnPosition(Position position, out int index)
{
var robot = Current.RobotList.FirstOrDefault(r => r.Position == position);
index = Current.RobotIndexOf(robot);
return robot;
}
/// <summary>
/// Returns best position to attack and profit
/// </summary>
/// <param name="maxEnergy"></param>
/// <param name="profit"></param>
/// <param name="myRobot"></param>
/// <returns></returns>
public Position GetBestAttackPosition(int maxEnergy, out int profit, Rb myRobot = null)
{
if (myRobot == null)
myRobot = Current.Robot;
var robotsToAttack = DistanceHelper.GetNeabyRobots(myRobot.Position, maxEnergy).Where(robot => robot.Owner != myRobot.Owner);
var bestProfit = int.MinValue;
Position bestPosition = null;
foreach (var robot in robotsToAttack)
{
var curProfit = GetAttackProfit(robot);
if (curProfit > bestProfit)
{
bestProfit = curProfit;
bestPosition = robot.Position;
}
}
profit = bestProfit;
return bestPosition;
}
/// <summary>
/// Returns energy required for new myRobotPos to get to his best station
/// </summary>
/// <returns></returns>
public int GetNewRobotEnergy(Position newPosition)
{
if (MyRobotsCount >= MaxRobotCount || RoundNumber > 40) return 0;
var maxEnergy = Current.Robot.Energy - Constants.EnergyUsedToCreateRobot - 50;
if (maxEnergy <= 0) return 0;
var newRobot = new Rb {Position = newPosition, Owner = Current.Robot.Owner};
int moveProfit, attackProfit;
var movePosition = GetBestMovePosition(maxEnergy, out moveProfit, newRobot);
var attackPosition = GetBestAttackPosition(maxEnergy, out attackProfit);
var finalPosition = moveProfit > attackProfit ? movePosition : attackPosition;
var minEnergy = int.MinValue;
if (finalPosition != null)
minEnergy = DistanceHelper.FindCost(newPosition, finalPosition);
if (minEnergy == int.MinValue)
return 0;
return maxEnergy/2 > minEnergy + 100 ? maxEnergy : Math.Min(minEnergy + 100, maxEnergy);
}
public bool UsingAnyStation(Rb robot = null)
{
if (robot == null)
robot = Current.Robot;
return
Current.Map.Stations.Any(
s => DistanceHelper.FindDistance(s.Position, robot.Position) <= Constants.EnergyCollectingDistance);
}
public bool UsesStation(EnergyStation station, Rb robot = null)
{
if (robot == null)
robot = Current.Robot;
return DistanceHelper.FindDistance(robot.Position, station.Position) <= Constants.EnergyCollectingDistance;
}
public List<Rb> GetRobotsUsingStation(EnergyStation station)
{
var stations = new List<EnergyStation>() { station };
return GetRobotsUsingStations(stations, false).ToList();
}
public List<EnergyStation> UsingStations(Position myRobotPos = null, IList<EnergyStation> inputStations = null)
{
if (inputStations == null)
inputStations = Current.Map.Stations;
if (myRobotPos == null)
myRobotPos = Current.Robot.Position;
return
inputStations.Where(
s => DistanceHelper.FindDistance(s.Position, myRobotPos) <= Constants.EnergyCollectingDistance)
.ToList();
}
public List<Rb> GetRobotsUsingStations(List<EnergyStation> stations, bool onlyMy)
{
var robotList = new List<Rb>();
foreach (var station in stations)
{
robotList.AddRange(
onlyMy
? Current.RobotList.Where(r => UsesStation(station, r) && r.Owner == Current.Robot.Owner)
.ToList()
: Current.RobotList.Where(r => UsesStation(station, r)).ToList());
}
return robotList;
}
public bool IsCellFree(Position cell)
{
return Current.RobotList.Where(robot => robot != Current.Robot).All(robot => robot.Position != cell);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AndriiRomanchak.RobotChallenge
{
class Constants
{
public const int InitialStationsPerRobot = 5;
public const int EnergyUsedToCreateRobot = 100;
public const int MinEnergyGeneratedByStation = 20;
public const int MaxEnergyGeneratedByStation = 40;
public const int EnergyUsedToAttack = 50;
public const double EnergyStolenPercent = 0.05;
public const int EnergyUsedToShiftRobot = 10;
public const int EnergyCollectingDistance = 1;
public const int MaxEnergyCollectedPerMove = 200;
}
}
| 50bbb810378bfff63c3cf883437470b1ee78cb09 | [
"C#"
] | 4 | C# | MrQwert/Serdiuk-RobotChallenge-Algorithm | 80f5c2ddfbbe9a736b1b5c8e996049255b9862ed | 0aa43926f4cd8c62008d21a65cd041d4b8ab4752 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Zombieswalk : MonoBehaviour
{
//Set goals for zombies.
public Transform goal;
public NavMeshAgent agent;
private Animator anim;
private Vector3 pos;
public UI ui;
public Chancontroller chancontroller;
void Start()
{
agent = GetComponent<NavMeshAgent>();
anim = GetComponent<Animator>();
}
void Update()
{
agent.destination = goal.position;
if (Vector3.Distance(transform.position, goal.position) > 1.5f)
{
anim.SetInteger("Condition", 1);
}
else
{
anim.SetInteger("Condition", 2);
anim.SetInteger("Condition", 0);
Destroy(this.gameObject);
ui.Attackplayer();
chancontroller.hit();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PauseScript : MonoBehaviour
{
bool isPause = false;
public GameObject conButton;
public void PauseGame()
{
if (isPause)
{
isPause = false;
}
else
{
conButton.gameObject.SetActive(false);
Time.timeScale = 1;
isPause = true;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class UI : MonoBehaviour
{
public Image HP1;
public static float currentTime = 0f;
float startingTime = 10f;
public Text cooldownTime;
public static bool check = false;
public static float count = 0f;
public Text Key;
public Chancontroller chancontroller;
public GameObject Wave1;
public GameObject Wave2;
public GameObject Wave3;
public GameObject Wave4;
public GameObject Wave5;
public float WaveCount= 0f;
public Text WaveShow;
public GameObject lose;
public Text Ready;
public GameObject WIN;
public GameObject CONTINUE;
public Camerafollow camfoll;
// Start is called before the first frame update
void Start()
{
currentTime = startingTime;
WaveShow.canvasRenderer.SetAlpha(1.0f);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.P))
{
HP1.fillAmount -= 0.1f;
print("E");
//hptype -= 0.01f;
//print(hptype);
}
if (HP1.fillAmount == 0)
{
chancontroller.Dead();
chancontroller.notcontrol();
print("Dead");
}
if (HP1.fillAmount > 0)
{
chancontroller.notDead();
print("notDead");
}
if (Input.GetKeyDown(KeyCode.O))
{
HP1.fillAmount += 0.1f;
print("E");
//hptype -= 0.01f;
//print(hptype);
if (HP1.fillAmount == 1)
{
print("isfull");
}
}
if(HP1.fillAmount == 0)
{
lose.gameObject.SetActive(true);
}
if(count == 5)
{
WIN.gameObject.SetActive(true);
count = 0;
}
if (Input.GetKey(KeyCode.Escape))
{
CONTINUE.gameObject.SetActive(true);
Time.timeScale = 0;
}
currentTime -= 1 * Time.deltaTime;
cooldownTime.text = currentTime.ToString("TIME : 0");
Ready.text = currentTime.ToString("START IN 0");
Ready.color = Color.yellow;
Key.text = count.ToString("Key : 0/5");
Key.color = Color.yellow;
if(count >= 5)
{
count = 5;
}
cooldownTime.color = Color.yellow;
if(currentTime <= 0)
{
Ready.gameObject.SetActive(false);
currentTime = 60;
WaveCount += 1;
Spawnwave();
}
if(currentTime <= 3)
{
cooldownTime.color = Color.red;
}
}
/*public void HPLess()
{
HP1.fillAmount += 0.1f;
print("E");
//hptype -= 0.01f;
//print(hptype);
if (HP1.fillAmount == 1)
{
print("isfull");
}
}*/
public void dontuseitem()
{
print(999);
HP1.fillAmount -= 0.0f;
}
public void Attackplayer()
{
//print(999);
HP1.fillAmount -= 0.1f;
}
public void Spawnwave()
{
if (WaveCount == 1)
{
Wave1.SetActive(true);
WaveShow.gameObject.SetActive(true);
WaveShow.color = Color.yellow;
WaveShow.text = WaveCount.ToString("WAVE 1");
StartCoroutine(Delay());
}
else if (WaveCount == 2)
{
Wave1.SetActive(false);
Wave2.SetActive(true);
WaveShow.gameObject.SetActive(true);
WaveShow.color = Color.yellow;
WaveShow.text = WaveCount.ToString("WAVE 2");
StartCoroutine(Delay());
}
else if (WaveCount == 3)
{
Wave2.SetActive(false);
Wave3.SetActive(true);
WaveShow.gameObject.SetActive(true);
WaveShow.color = Color.yellow;
WaveShow.text = WaveCount.ToString("WAVE 3");
StartCoroutine(Delay());
}
else if (WaveCount == 4)
{
Wave3.SetActive(false);
Wave4.SetActive(true);
WaveShow.gameObject.SetActive(true);
WaveShow.color = Color.yellow;
WaveShow.text = WaveCount.ToString("WAVE 4");
StartCoroutine(Delay());
}
else if (WaveCount == 5)
{
Wave4.SetActive(false);
Wave5.SetActive(true);
WaveShow.gameObject.SetActive(true);
WaveShow.color = Color.yellow;
WaveShow.text = WaveCount.ToString("WAVE 5");
StartCoroutine(Delay());
}
else
{
if(WaveCount == 6)
{
lose.gameObject.SetActive(true);
}
}
}
void fadeOut()
{
WaveShow.gameObject.SetActive(false);
}
public IEnumerator Delay()
{
WaveShow.CrossFadeAlpha(0, 3, false);
yield return new WaitForSeconds(3f);
fadeOut();
}
public void AGAIN()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void Menu()
{
SceneManager.LoadScene("MENU");
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Chancontroller : MonoBehaviour
{
//Script control of the character's movement And storing items in the inventory.
public float speed = 4.0f;
public float runspeed = 10.0f;
public float rotSpeed = 80.0f;
public float rot = 0.0f;
public float gravity = 8.0f;
private bool Run;
private bool Slide;
private float inputH;
private float inputV;
public UI ui;
Vector3 moveDir = Vector3.zero;
Vector3 runDir = Vector3.zero;
Vector3 slideDir = Vector3.zero;
CharacterController controller;
Animator anim;
Chancontroller noscript;
public Inventory inventory;
public InventorySlot iSlot;
private IInventoryItem mCurrentItem = null;
public GameObject Hand;
void Start()
{
controller = GetComponent<CharacterController>();
anim = GetComponent<Animator>();
noscript = GetComponent<Chancontroller>();
Run = false;
}
void Update()
{
if (controller.isGrounded)
{
if (Input.GetKey(KeyCode.W))
{
moveDir = new Vector3(0, 0, 0.1f);
moveDir *= speed;
moveDir = transform.TransformDirection(moveDir);
}
else if (Input.GetKey(KeyCode.S))
{
moveDir = new Vector3(0, 0, -0.1f);
moveDir *= speed;
moveDir = transform.TransformDirection(moveDir);
}
else if (Input.GetKeyDown(KeyCode.E))
{
IInventoryItem item = inventory.ItemTop();
print("use item" + item);
if (item != null)
{
if (mCurrentItem != null)
{
DropCurrentItem();
}
inventory.UseItem(item);
inventory.RemoveItem(item);
ui.HP1.fillAmount += 0.1f;
}
else
{
ui.dontuseitem();
}
}
else if (Input.GetKeyDown(KeyCode.R))
{
if (mCurrentItem != null)
{
print("Drop item" + mCurrentItem);
DropCurrentItem();
}
}
else
{
moveDir = new Vector3(0, 0, 0);
}
if (Input.GetKeyDown("f1"))
{
anim.Play("WAIT01", -1, 0f);
}
if (Input.GetKeyDown("f2"))
{
anim.Play("WAIT02", -1, 0f);
}
if (Input.GetKeyDown("f3"))
{
anim.Play("WAIT03", -1, 0f);
}
if (Input.GetKeyDown("f4"))
{
anim.Play("WAIT04", -1, 0f);
}
if (Input.GetKey(KeyCode.LeftShift))
{
Run = true;
runDir.y -= gravity * Time.deltaTime;
controller.Move(runDir * Time.deltaTime);
}
else
{
Run = false;
moveDir.y -= gravity * Time.deltaTime;
controller.Move(moveDir * Time.deltaTime);
}
if (Input.GetKey(KeyCode.Space))
{
anim.SetBool("Jump", true);
}
else
{
anim.SetBool("Jump", false);
}
if (Input.GetKey(KeyCode.F))
{
anim.SetBool("Slide", true);
//slideDir.y -= gravity * Time.deltaTime; //So the character is on the floor And may cause bugs
controller.Move(slideDir * Time.deltaTime);
}
else
{
anim.SetBool("Slide", false);
}
}
rot += Input.GetAxis("Horizontal") * rotSpeed * Time.deltaTime;
transform.eulerAngles = new Vector3(0, rot, 0);
inputH = Input.GetAxis("Horizontal");
inputV = Input.GetAxis("Vertical");
anim.SetFloat("inputH", inputH);
anim.SetFloat("inputV", inputV);
//Debug.Log(controller.isGrounded);
moveDir.y -= gravity * Time.deltaTime;
controller.Move(moveDir * Time.deltaTime);
anim.SetBool("Run", Run);
if (Run)
{
runDir = new Vector3(0, 0, 1.5f);
runDir *= speed;
runDir = transform.TransformDirection(runDir);
}
if (Slide)
{
slideDir = new Vector3(0, 0, 1.5f);
slideDir *= speed;
slideDir = transform.TransformDirection(slideDir);
}
else
{
slideDir = new Vector3(0, 0, 0);
}
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
IInventoryItem item = hit.collider.GetComponent<IInventoryItem>();
if (item != null)
{
inventory.AddItem(item);
item.OnPickup();
}
if (hit.gameObject.tag == "KEY")
{
print("GET KEY!!");
UI.count += 1;
key();
hit.gameObject.SetActive(false);
}
}
private void Inventory_ItemUsed(object sender, InventoryEventArgs e)
{
if (mCurrentItem != null)
{
SetItemActive(mCurrentItem, false);
}
IInventoryItem item = e.Item;
SetItemActive(item, true);
mCurrentItem = e.Item;
}
private void SetItemActive(IInventoryItem item, bool active)
{
GameObject currentItem = (item as MonoBehaviour).gameObject;
currentItem.SetActive(active);
currentItem.transform.parent = active ? Hand.transform : null;
}
public void DropCurrentItem()
{
anim.SetInteger("condition", 2);
GameObject goItem = (mCurrentItem as MonoBehaviour).gameObject;
goItem.SetActive(true);
goItem.transform.parent = null;
Rigidbody rbItem = goItem.AddComponent<Rigidbody>();
if (rbItem != null)
{
rbItem.AddForce(transform.forward * 20.5f, ForceMode.Force);
Invoke("DoDropItem", 0.75f);
}
}
public void DoDropItem()
{
Destroy((mCurrentItem as MonoBehaviour).GetComponent<Rigidbody>());
mCurrentItem = null;
}
public void key()
{
if (UI.count == 5)
{
print("YOU WIN");
}
}
public void hit()
{
anim.Play("DAMAGED00", -1, 0f);
}
public void Dead()
{
anim.SetBool("Dead", true);
}
public void notDead()
{
anim.SetBool("Dead", false);
}
public void notcontrol()
{
controller.enabled = false;
}
}
<file_sep>Moe Runner
A survival game in which the character is a cute little girl. The girl must escape from the mysterious village.
This game has an Inventory system to collect boxes to increase hp and players must collect all 5 keys to clear the game.

Game Preview

| 12bea6b838d16e0e5676636bbdfbf428b16b116c | [
"Markdown",
"C#"
] | 5 | C# | Zansood/Moe-Runner | 2ac17804fa633a9d13e22e1dd5edf36e8959f0da | 98587a3f52fd8564d3b6aaba3e182f11df37efc0 |
refs/heads/master | <repo_name>maksim-kiryanov/learn-java<file_sep>/src/main/java/ru/mkiryanov/java/annotations/tracker/UseCaseTracker.java
package ru.mkiryanov.java.annotations.tracker;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* User: maksim-kiryanov
* Time: 05.02.17 at 15:25.
*/
public class UseCaseTracker {
public static void trackUseCases(List<Integer> useCases, Class<?> clazz) {
for (Method method : clazz.getDeclaredMethods()) {
UseCase annotation = method.getAnnotation(UseCase.class);
if (annotation != null) {
System.out.println("Found Use Case: " +
annotation.id() + " " + annotation.description());
useCases.remove((Integer)annotation.id());
}
}
if (!useCases.isEmpty()) {
System.out.println("Warning: not found Use Cases " + useCases);
}
}
public static void main(String[] args) {
List<Integer> useCases = new ArrayList<Integer>();
Collections.addAll(useCases, 47, 48, 49, 50);
trackUseCases(useCases, PasswordUtils.class);
}
}
<file_sep>/src/main/java/ru/mkiryanov/java/annotations/database/TableCreationProcessorFactory.java
package ru.mkiryanov.java.annotations.database;
import com.sun.mirror.apt.AnnotationProcessor;
import com.sun.mirror.apt.AnnotationProcessorEnvironment;
import com.sun.mirror.apt.AnnotationProcessorFactory;
import com.sun.mirror.declaration.AnnotationTypeDeclaration;
import com.sun.mirror.declaration.ClassDeclaration;
import com.sun.mirror.declaration.FieldDeclaration;
import com.sun.mirror.declaration.TypeDeclaration;
import com.sun.mirror.util.SimpleDeclarationVisitor;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import static com.sun.mirror.util.DeclarationVisitors.NO_OP;
import static com.sun.mirror.util.DeclarationVisitors.getDeclarationScanner;
/**
* Exec: apt -classpath target/classes/
* -factory ru.mkiryanov.java.annotations.database.TableCreationProcessorFactory
* -s src/main/java/ src/main/java/ru/mkiryanov/java/annotations/database/Member.java
*
* Result of execution is SQL script for entity {@link Member} table creation
*/
public class TableCreationProcessorFactory
implements AnnotationProcessorFactory {
public AnnotationProcessor getProcessorFor(
Set<AnnotationTypeDeclaration> atds,
AnnotationProcessorEnvironment env) {
return new TableCreationProcessor(env);
}
public Collection<String> supportedAnnotationTypes() {
return Arrays.asList(
"ru.mkiryanov.java.annotations.database.DBTable",
"ru.mkiryanov.java.annotations.database.Constraints",
"ru.mkiryanov.java.annotations.database.SQLString",
"ru.mkiryanov.java.annotations.database.SQLInteger");
}
public Collection<String> supportedOptions() {
return Collections.emptySet();
}
private static class TableCreationProcessor
implements AnnotationProcessor {
private final AnnotationProcessorEnvironment env;
private String sql = "";
public TableCreationProcessor(
AnnotationProcessorEnvironment env) {
this.env = env;
}
public void process() {
for (TypeDeclaration typeDecl :
env.getSpecifiedTypeDeclarations()) {
typeDecl.accept(getDeclarationScanner(
new TableCreationVisitor(), NO_OP));
sql = sql.substring(0, sql.length() - 1) + ");";
System.out.println("creation SQL is :\n" + sql);
sql = "";
}
}
private class TableCreationVisitor
extends SimpleDeclarationVisitor {
public void visitClassDeclaration(ClassDeclaration d) {
DBTable dbTable = d.getAnnotation(DBTable.class);
if (dbTable != null) {
sql += "CREATE TABLE ";
sql += (dbTable.name().length() < 1)
? d.getSimpleName().toUpperCase()
: dbTable.name();
sql += " (";
}
}
public void visitFieldDeclaration(FieldDeclaration d) {
String columnName = "";
if (d.getAnnotation(SQLInteger.class) != null) {
SQLInteger sInt = d.getAnnotation(SQLInteger.class);
// Use field name if name not specified
if (sInt.name().length() < 1)
columnName = d.getSimpleName().toUpperCase();
else
columnName = sInt.name();
sql += "\n " + columnName + " INT" +
getConstraints(sInt.constraints()) + ",";
}
if (d.getAnnotation(SQLString.class) != null) {
SQLString sString = d.getAnnotation(SQLString.class);
// Use field name if name not specified.
if (sString.name().length() < 1)
columnName = d.getSimpleName().toUpperCase();
else
columnName = sString.name();
sql += "\n " + columnName + " VARCHAR(" +
sString.value() + ")" +
getConstraints(sString.constraints()) + ",";
}
if (d.getAnnotation(SQLBoolean.class) != null) {
SQLBoolean sBoolean = d.getAnnotation(SQLBoolean.class);
if (sBoolean.value().length() > 1) {
columnName = sBoolean.value();
} else if (sBoolean.name().length() > 1) {
columnName = sBoolean.name();
} else {
columnName = d.getSimpleName().toUpperCase();
}
sql += "\n " + columnName + " BOOLEAN" +
getConstraints(sBoolean.constraints()) + ",";
}
if (d.getAnnotation(SQLDate.class) != null) {
SQLDate sDate = d.getAnnotation(SQLDate.class);
if (sDate.value().length() > 1) {
columnName = sDate.value();
} else if (sDate.name().length() > 1) {
columnName = sDate.name();
} else {
columnName = d.getSimpleName().toUpperCase();
}
sql += "\n " + columnName + " DATE" +
getConstraints(sDate.constraints()) + ",";
}
if (d.getAnnotation(SQLNumeric.class) != null) {
SQLNumeric sNumeric = d.getAnnotation(SQLNumeric.class);
if (sNumeric.value().length() > 1) {
columnName = sNumeric.value();
} else if (sNumeric.name().length() > 1) {
columnName = sNumeric.name();
} else {
columnName = d.getSimpleName().toUpperCase();
}
int precision = sNumeric.precision();
int scale = sNumeric.scale();
sql += "\n " + columnName + " NUMERIC(" + precision + "," + scale + ")" +
getConstraints(sNumeric.constraints()) + ",";
}
}
private String getConstraints(Constraints con) {
String constraints = "";
if (!con.allowNull())
constraints += " NOT NULL";
if (con.primaryKey())
constraints += " PRIMARY KEY";
if (con.unique())
constraints += " UNIQUE";
return constraints;
}
}
}
}
<file_sep>/src/main/java/ru/mkiryanov/java/annotations/database/Member.java
package ru.mkiryanov.java.annotations.database;
import java.math.BigDecimal;
import java.util.Date;
@DBTable(name = "MEMBER")
public class Member {
@SQLString(30)
String firstName;
@SQLString(50)
String lastName;
@SQLInteger
Integer age;
@SQLDate("BIRTH_DAY")
Date birthDay;
@SQLBoolean
boolean active;
@SQLNumeric
BigDecimal salary;
@SQLString(value = 30,
constraints = @Constraints(primaryKey = true))
String handle;
static int memberCount;
public String getHandle() {
return handle;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String toString() {
return handle;
}
public Integer getAge() {
return age;
}
public Date getBirthDay() {
return birthDay;
}
}
<file_sep>/src/main/java/ru/mkiryanov/java/annotations/tracker/UseCase.java
package ru.mkiryanov.java.annotations.tracker;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* User: maksim-kiryanov
* Time: 05.02.17 at 15:09.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCase {
int id();
String description() default "no description";
}
| c03789223d5e1be0e048d733ea1561744352553b | [
"Java"
] | 4 | Java | maksim-kiryanov/learn-java | a9d867482e4292db45c88b0bf71f72fe5c3b38fa | e966cd3afaf6d9444feef239575eedc3826365a1 |
refs/heads/master | <repo_name>lmh246/machine_learning<file_sep>/sklearn/特征工程.py
from sklearn import datasets,preprocessing
if __name__ == '__main__':
data = datasets.load_iris()
iris_x = data.data
iris_y = data.target
print("原始数据:\n",iris_x)
print("标准化:\n",preprocessing.StandardScaler().fit_transform(iris_x))
print("区间放缩法:\n",preprocessing.MinMaxScaler().fit_transform(iris_x))
print("二值化: \n",preprocessing.Binarizer(threshold=3).fit_transform(iris_x))
print("哑编码: \n",preprocessing.OneHotEncoder().fit_transform(iris_y.reshape(-1,1)))
from numpy import vstack, array, nan
print("填充缺失值:\n",preprocessing.Imputer().fit_transform(vstack((array([nan, nan, nan, nan]), iris_x))))
print("多项式变化:\n",preprocessing.PolynomialFeatures().fit_transform(iris_x))
from numpy import log1p
print("自定义转换函数:\n",preprocessing.FunctionTransformer(log1p).fit_transform(iris_x))
from sklearn.feature_selection import VarianceThreshold
print("方差选择法:\n",VarianceThreshold(threshold=3).fit_transform(iris_x))
from sklearn.feature_selection import SelectKBest,chi2
print("卡方检验:\n",SelectKBest(chi2,k=2).fit_transform(iris_x,iris_y))
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
# 参数estimator为基模型
# 参数n_features_to_select为选择的特征个数
print("递归特征消除法:\n",RFE(estimator=LogisticRegression(), n_features_to_select=2).fit_transform(iris_x,iris_y))
from sklearn.feature_selection import SelectFromModel
from sklearn.linear_model import LogisticRegression
print("基于惩罚项的特征选择:\n",SelectFromModel(LogisticRegression(penalty="l1",C=0.1)).fit_transform(iris_x,iris_y))
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import GradientBoostingClassifier
print("基于树模型特征选择:\n",SelectFromModel(GradientBoostingClassifier()).fit_transform(iris_x,iris_y))<file_sep>/sklearn/数据处理.py
from sklearn import preprocessing
import numpy as np
if __name__ == '__main__':
X = np.array([[1.,-1.,2.],
[2.,0.,0.],
[0.,1.,-1.]])
X_mean = X.mean(axis=0) #计算列的平均值
X_std = X.std(axis=0) #计算列的方差
X1 = (X-X_mean)/X_std
X_scale = preprocessing.scale(X)
print("公式计算:",X1)
print("模块计算:",X_scale)
X = np.array([[1.,-1.,2.],
[2.,0.,0.],
[0.,1.,-1.]])
X_norm = preprocessing.normalize(X)
print("正则化:\n",X_norm)<file_sep>/机器学习算法/决策树/c4.5.py
import random
import math
from decimal import Decimal
from collections import Counter
""""
读取文件
使用自助法选取样本与,测试集
"""
def readData():
data = []
#iris
#label = ['sepal length','sepal width','petal length','petal width']
#wine
#label = ['Alcohol','Malic acid','Ash','Alcalinity of ash','Magnesium','Total phenols','Flavanoids','Nonflavanoid phenols','Proanthocyanins','Color intensity','Hue','OD280/OD315 of diluted wines','Proline']
#redWine
#label = ["fixed acidity","volatile acidity","citric acid","residual sugar","chlorides","free sulfur dioxide","total sulfur dioxide","density","pH","sulphates","alcohol"]
#献血
#label = ["R","F","M","T"]
#breastTissue
#label = ["I0","PA500","HFS","DA","AREA","A/DA","MAX IP","DR","P"]
#harberman
#label = ["Age","Patient's year","positive axillary nodes detected"]
#seeds
label = ["area A","perimeter P","compactness C = 4*pi*A/P^2","length of kernel","width of kernel","asymmetry coefficient","length of kernel groove"]
dataSet = []
dataTest = []
with open('../haberman.data','r') as f:
for line in f.readlines():
line = line.strip(' ').strip('\n').split(',')
#针对redWine,whiteWine
#line = line.strip(' ').strip('\n').split(';')
# 针对红酒数据
# line.append(line[0])
# del (line[0])
#breastTissue
#line = line.strip(' ').strip('\n').split('\t')
lineBefore = line[:len(line)-1]
lineBefore = [float(x) for x in lineBefore]
line = line[-1]
lineBefore.append(line)
data.append(lineBefore)
length = int(len(data)*(2/3))
for i in range(length):
index = random.randint(0,100)
dataSet.append(data[index])
dataReduce = [item for item in data if item not in dataSet]
dataTest = dataReduce[:len(dataReduce)-1]
return dataSet,dataReduce,dataTest,label
"""
计算熵
"""
def calshannonEnt(data):
dataLen = len(data)
label = {}
#遍历每一条样本,找出结果
for dataItem in data:
#取出每一条样本的结果,并判断是否在label中
currentResult = dataItem[-1]
if currentResult not in label.keys():
label[currentResult] = 0
label[currentResult] += 1
#求根节点的熵
shannonEnt = 0.0
for key in label:
resultPercent = float(Decimal(str(label[key]))/Decimal(str(dataLen)))
shannonEnt -= resultPercent * math.log(resultPercent,2)
return shannonEnt
"""
划分数据
"""
def splitData(data, index, sign, value):
returnData = []
if sign == "<":
for dataItem in data:
reduceData = []
if(float(dataItem[index]) <= float(value)):
#利用列表截断,来获取每条样本特征前后的属性,并利用extend方法进行拼接
reduceData = dataItem[:index]
reduceData.extend(dataItem[index+1:])
returnData.append(reduceData)
if sign == ">":
for dataItem in data:
reduceData = []
if(float(dataItem[index]) > float(value)):
#利用列表截断,来获取每条样本特征前后的属性,并利用extend方法进行拼接
reduceData = dataItem[:index]
reduceData.extend(dataItem[index+1:])
returnData.append(reduceData)
return returnData
"""
选取最好的特征
"""
def chooseBestFeature(data,label):
featureLen = len(data[0])-1 #属性个数
#print("属性个数:{},标签个数:{}".format(featureLen,len(label)))
baseEnt = calshannonEnt(data) #根节点的熵
bestFeature = 0
featureEnt = 0.0
FeatureDict = {}
#初始化字典,字典保存每个属性的划分点的数值,信息增益,信息增益率
for i in range(featureLen):
FeatureDict[label[i]] = {}
FeatureDict[label[i]]["T"] = ""
FeatureDict[label[i]]["Ent"] = 0.0
FeatureDict[label[i]]["GainRatio"] = 0.0
#遍历样本每个属性
for i in range(featureLen):
featureList = [Item[i] for Item in data]
featureSet = featureList[:]
#print(len(featureSet))
#处理连续值
#将属性值从小到大进行排序
featureSet.sort()
#print(featureSet)
#计算候选划分点
houxuanT = [float((Decimal(str(featureSet[i]))+Decimal(str(featureSet[i+1]))))/2.0 for i in range(len(featureSet)-1)]
#print("属性{0}的候选点有{1}".format(label[i],houxuanT))
#将样本D基于t划分为两部分
bestT = 0.0 #候选点t的值
bestTEnt = 0.0 #候选点t的信息增益
BestGainRatio = 0.0 #候选点t的信息增益率
Iv = 0.0
for value in houxuanT:
if (value >= featureSet[-1]):
continue
Tpos = [] #大于t
Tneg = [] #小于等于t
for item in data:
if item[i] <= value:
Tneg.append(item)
elif item[i] > value:
Tpos.append(item)
TposEnt = calshannonEnt(Tpos)
TnegEnt = calshannonEnt(Tneg)
TposPer = len(Tpos)/len(data)
TnegPer = len(Tneg)/len(data)
#print("候选点:{},TposEnt:{},TposPer:{},TnegEnt:{},TnegPer:{}".format(value,TposEnt,TposPer,TnegEnt,TnegPer))
GainFeatureEntOfT = float(Decimal(str(baseEnt)) - Decimal(str(TposPer*TposEnt)) - Decimal(str(TnegPer*TnegEnt)))
Iv = -(TposPer * math.log(TposPer,2) + TnegPer * math.log(TnegPer,2))
GainRatio = float(Decimal(str(GainFeatureEntOfT))/Decimal(str(Iv)))
#print("划分点 {0} 的信息增益是 {1},信息增益率是{2}".format(value,GainFeatureEntOfT,GainRatio))
if GainFeatureEntOfT > bestTEnt:
bestTEnt = GainFeatureEntOfT
bestT = value
BestGainRatio = GainRatio
#print("属性{0}的划分点为{1},其信息增益为{2},信息增益率为{3}\n".format(label[i],bestT,bestTEnt,BestGainRatio))
FeatureDict[label[i]]["Ent"] = bestTEnt
FeatureDict[label[i]]["T"] = bestT
FeatureDict[label[i]]["GainRatio"] = BestGainRatio
#计算所有属性的平均增益
sum = 0.0
for value in FeatureDict.values():
sum = sum + value["Ent"]
averageEnt = sum/featureLen
#找出属性增益高于平均增益的属性
FeatureHighDict = {k:v for k,v in FeatureDict.items() if v["Ent"] >= averageEnt}
#选择高于平均水平的属性的信息增益率
BestFeatureName = ''
BestFeatureSplit = 0.0
BestRatio = 0.0
for key in FeatureHighDict.keys():
if(FeatureHighDict[key]["GainRatio"]>BestRatio):
BestFeatureName = key
BestFeatureSplit = FeatureHighDict[key]["T"]
#找出属性的下标
for i in range(len(label)):
if(label[i] == BestFeatureName):
bestFeature = i
print("信息增益率最大的属性{0}的划分点为{1},属性在列表中的位置为{2}".format(BestFeatureName,BestFeatureSplit,bestFeature))
return bestFeature,BestFeatureName,BestFeatureSplit
"""
定义生成树
"""
def createTree(data,labels):
value = []
classList = [example[-1] for example in data] #找出所有决策结果
#如果只有一个类别,就返回结果
if classList.count(classList[0]) == len(classList):
return classList[0]
if len(data[0]) == 1: #如果只有一列,返回出现结果最多的类别
result_counts = Counter(classList)
return result_counts.most_common(1)[0][0]
bestFeature,BestFeatureName,BestFeatureSplit = chooseBestFeature(data,labels)
#featureDic.extend([BestFeatureName,BestFeatureSplit])
bestLabel = labels[bestFeature]
myTree = {bestLabel:{}}
#找出出去最优属性的属性列表
del(labels[bestFeature])
#print("剩余标签:",subLabels)
left = "<"+str(BestFeatureSplit)
right = ">"+str(BestFeatureSplit)
value = [left,right]
for x in value:
subLabels = labels[:]
sign = x[0]
splitDataSet = splitData(data,bestFeature,sign,BestFeatureSplit)
myTree[bestLabel][x] = createTree(splitDataSet,subLabels)
#print(myTree)
return myTree
"""
判断测试用例
"""
def classify(myTree,labels,dataTest):
rootFeature = list(myTree.keys())[0]#根节点,判断属性
# 找到该特征下的所有子集
rootItems = myTree[rootFeature]
# 找到根特征在每一条属性标签中所处的位置
rootIndex = labels.index(rootFeature)
# 找到该测试样本该特征的值
rootKey = dataTest[rootIndex]
# 获取该特征具体值下所有的子集
rootItemsKey = float(list(rootItems.keys())[0][1:])
global featureLabelOnce
if rootKey<=rootItemsKey:
featureLabelOnce = '<' + str(rootItemsKey)
elif rootKey>rootItemsKey:
featureLabelOnce = '>' + str(rootItemsKey)
reduce = rootItems[featureLabelOnce]
# 判断有没有结束
if isinstance(reduce, dict):
result = classify(reduce, labels, dataTest)
else:
result = reduce
return result
if __name__ == '__main__':
dataSet,dataReduce, dataTest, label = readData()
print(dataSet)
inputTree = createTree(dataSet,label)
print(inputTree)
#iris
#label = ['sepal length','sepal width','petal length','petal width']
#wine
#label = ['Alcohol','Malic acid','Ash','Alcalinity of ash','Magnesium','Total phenols','Flavanoids','Nonflavanoid phenols','Proanthocyanins','Color intensity','Hue','OD280/OD315 of diluted wines','Proline']
#redWine
#label = ["fixed acidity","volatile acidity","citric acid","residual sugar","chlorides","free sulfur dioxide","total sulfur dioxide","density","pH","sulphates","alcohol"]
#献血
#label = ["R","F","M","T"]
#breastTissue
#label = ["I0","PA500","HFS","DA","AREA","A/DA","MAX IP","DR","P"]
#harberman
#label = ["Age","Patient's year","positive axillary nodes detected"]
#seeds
label = ["area A","perimeter P","compactness C = 4*pi*A/P^2","length of kernel","width of kernel","asymmetry coefficient","length of kernel groove"]
count = 0
for item in dataTest:
result = classify(inputTree, label, item)
Trueresult = item[-1]
if(result == Trueresult):
count = count + 1
TruePer = round(count/len(dataTest),4)
print('正确率为{}%'.format(TruePer*100))
<file_sep>/README.md
# 学习过程中的一些代码
## 机器学习代码实现
### 决策树(C4.5)
### KNN
### K-means
## sklearn的学习
### 5个分类算法
## 天池新人赛O2O优惠券预测
<file_sep>/sklearn/朴素贝叶斯-高斯.py
# 引入模块
from sklearn import datasets,naive_bayes
from sklearn.model_selection import train_test_split
if __name__ == '__main__':
data = datasets.load_iris()
iris_x = data.data
iris_y = data.target
# 划分数据
X_train,X_test,y_train,y_test = train_test_split(iris_x,iris_y,test_size=0.3)
# 初始化高斯贝叶斯对象
gnb = naive_bayes.GaussianNB()
# 进行训练
gnb.fit(X_train,y_train)
# 预测
res = gnb.predict(X_test)
print(gnb.score(X_test,y_test))
#一些属性
print("class_prior_: \n",gnb.class_prior_)
print("class_count_: \n", gnb.class_count_)
print("sigma_ : \n",gnb.sigma_)<file_sep>/sklearn/逻辑回归预测.py
from sklearn.model_selection import train_test_split
from sklearn import datasets,linear_model
from sklearn import metrics
from sklearn import preprocessing
if __name__ == '__main__':
data = datasets.load_iris()
iris_x = data.data
iris_y = data.target
#划分数据
X_train,X_test,y_train,y_test = train_test_split(iris_x,iris_y,test_size=0.3)
#初始化对象
logistic = linear_model.LogisticRegression()
#训练数据
logistic.fit(X_train,y_train)
#预测数据
res = logistic.predict(X_test)
print(res)
print("正确率: ",logistic.score(X_test,y_test))
print(metrics.classification_report(y_test, res))
print(metrics.confusion_matrix(y_test, res))
<file_sep>/机器学习算法/Knn/knn.py
from decimal import Decimal
from collections import Counter
import random
import math
"""
读取文件
返回属性,类别
"""
def readData():
data = []
dataSet = []
dataTest = []
with open('../seeds_dataset.txt','r') as f:
for line in f.readlines():
#line = line.strip(' ').strip('\n').split(',')
# 针对redWine,whiteWine
#line = line.strip(' ').strip('\n').split(';')
#针对红酒数据
# line.append(line[0])
# del(line[0])
# breastTissue
#line = line.strip(' ').strip('\n').split('\t')
#seeds
line = line.strip(" ").strip('\n').split('\t')
line = [float(x) for x in line if x is not '']
lineBefore = line[:len(line) - 1]
lineBefore = [float(x) for x in lineBefore]
line = line[-1]
lineBefore.append(line)
data.append(lineBefore)
length = len(data)
lengthSel = int(len(data) * (2 / 3))
randomdata = range(length)
randomlist = random.sample(randomdata,lengthSel)
for i in randomlist:
dataSet.append(data[i])
for i in range(length):
if i not in randomlist:
dataTest.append(data[i])
return dataSet,dataTest
"""
数据归一化
"""
def autoNorm(data):
length = len(data[0]) #计算属性个数
for i in range(length):
FeatureValue = [item[i] for item in data] #保存一个属性的所有值
minval = min(FeatureValue) #计算属性的最小值
maxVal = max(FeatureValue) #计算属性的最大值
ranges = float(Decimal(str(maxVal)) - Decimal(str(minval))) #计算极差
for item in data:
item[i] = float(Decimal(str((item[i] - minval)))/Decimal(str(ranges)))
return data
"""
计算距离
传入4个参数,测试样本,训练样本,标签,k值
"""
def classify(testDemo,dataSet,label,k):
lengthFeature = len(dataSet[0]) #获取属性个数
lengthTrain = len(dataSet) #获取训练样本个数
dataDic = {} #存放测试样本与每个训练样本的值
#计算距离度量
for index in range(lengthTrain):#取出每个训练样本的下标
result = 0.0
for i in range(lengthFeature):
x = (dataSet[index][i] - testDemo[i])**2
result = result + x
dataDic[index] = math.sqrt(result)
#对字典按照值进行排序
dataDic = sorted(dataDic.items(),key=lambda item: item[1])
#取前k个值
dataFinal = [dataDic[i] for i in range(k)]
#获取前K的值的标签
dataLabel = []
for items in dataFinal:
item = label[items[0]]
dataLabel.append(item[-1])
result_counts = Counter(dataLabel)
return result_counts.most_common(1)[0][0]
if __name__ == '__main__':
label = []
dataSet1,dataTest1 = readData()
#处理数据。去掉类别
dataSet2 = [item[:len(dataSet1[0])-1] for item in dataSet1]
dataTest2 = [item[:len(dataSet1[0])-1] for item in dataTest1]
dataSet = autoNorm(dataSet2)
dataTest = autoNorm(dataTest2)
print(dataSet1)
print(dataTest1)
print("训练样本个数:",len(dataSet))
print("测试样本个数",len(dataTest))
lengthTest = len(dataTest)
count = 0
for index in range(lengthTest):
TrueResult = dataTest1[index][-1]
result = classify(dataTest[index],dataSet,dataSet1,7)
if(result==TrueResult):
count = count+1
print("判断正确个数",count)
TruePer = round(count/lengthTest,3)
print("准确率为{}%".format(TruePer*100))<file_sep>/sklearn/数据集测试.py
import pandas as pd
import numpy as np
from sklearn import datasets
from sklearn import preprocessing
from sklearn.model_selection import GridSearchCV,train_test_split,cross_val_score
import time
#定义Knn算法:
def Knn(Xval,yVal):
from sklearn.neighbors import KNeighborsClassifier
start = time.clock()
X = Xval
X = preprocessing.normalize(X)
y = yVal
k_range = list(range(1, 31))
param_grid = dict(n_neighbors=k_range)
knn = KNeighborsClassifier(n_neighbors=5)
grid = GridSearchCV(knn, param_grid, cv=10, scoring="accuracy")
grid.fit(X, y)
end = time.clock()
print("Knn执行时间",end-start)
return grid.best_score_,grid.best_params_
#定义决策树算法
def jueceshu(Xval,yVal):
from sklearn import tree
start = time.clock()
X = Xval
y = yVal
depth_range = list(range(1,10))
param_grid = dict(max_depth=depth_range)
Dectree = tree.DecisionTreeClassifier(max_depth=5)
grid = GridSearchCV(Dectree,param_grid,cv=10,scoring="accuracy")
grid.fit(X,y)
end = time.clock()
print("决策树执行时间:",end-start)
return grid.best_score_, grid.best_params_
#定义朴素贝叶斯算法
def Gbayes(Xval,yVal):
from sklearn import naive_bayes
start = time.clock()
X = Xval
y = yVal
# 初始化高斯贝叶斯对象
gnb = naive_bayes.GaussianNB()
scores = cross_val_score(gnb,X,y,cv=10,scoring="accuracy")
end = time.clock()
print("朴素贝叶斯执行时间:",end-start)
return scores.mean()
#定义Svm算法
def svmSvc(Xval,yVal):
from sklearn import svm
start = time.clock()
X = Xval
y = yVal
param_grid = {'kernel':('linear','rbf'),'C':[1,10]}
svc = svm.SVC()
grid = GridSearchCV(svc,param_grid,cv=10,scoring="accuracy")
grid.fit(X,y)
end = time.clock()
print("Svm执行时间:",end-start)
return grid.best_score_, grid.best_params_
#定义逻辑回归函数
def Logis(Xval,yVal):
from sklearn import linear_model
start = time.clock()
X = Xval
y = yVal
LogiClass = linear_model.LogisticRegression()
scores = cross_val_score(LogiClass, X, y, cv=10, scoring="accuracy")
end = time.clock()
print("逻辑回归执行时间:",end-start)
return scores.mean()
#读取文件
def readData(url):
X = []
y = []
with open(url, 'r') as f:
data = f.readlines() # txt中所有字符串读入data
for line in data:
#odom = line.strip('').strip('\n').split("\t") # 将单个数据分隔开存好
odom = line.strip('').strip('\n').split(",") # 将单个数据分隔开存好
numbers_float = [float(x) for x in odom[:len(odom)-1] if x is not ''] # 转化为浮点数
X.append(numbers_float)
y.append(odom[-1])
print(X)
print(y)
return X,y
if __name__ == '__main__':
score = []
#dataName = datasets.load_iris()
#dataName = datasets.load_breast_cancer()
#dataName = datasets.load_wine()
# X = dataName.data
# y = dataName.target
#X,y = readData("./seeds.txt")
X,y = readData("cmc.data")
#Knn
Knn_score,Knn_param = Knn(X,y)
score.append(round(Knn_score,4))
#决策树
jueceshu_score, jueceshu_param = jueceshu(X,y)
score.append(round(jueceshu_score, 4))
#贝叶斯
Gbayes_score = Gbayes(X,y)
score.append(round(Gbayes_score, 4))
#Svm
Svm_score,Svm_param = svmSvc(X,y)
score.append(round(Svm_score,4))
#逻辑回归
Logis_score = Logis(X,y)
score.append(round(Logis_score,4))
arr = np.array(score)
result = pd.DataFrame(arr,index=["Knn算法","决策树算法","朴素贝叶斯算法","Svm算法","逻辑回归算法"],columns=["正确率"])
print(result)
<file_sep>/o2o/demo.py
import pandas as pd
if __name__ == '__main__':
off_train = pd.read_csv("./ccf_offline_stage1_train.csv")
print("------------------------------针对线下的数据表------------------------------------")
print("数据总量:",off_train.__len__())
#print("领取了优惠券的记录:",off_train['Date_received'].dropna().__len__())
print("优惠券的种类:",off_train['Coupon_id'].drop_duplicates().__len__())
print("用户个数:",off_train['User_id'].drop_duplicates().__len__())
print("商户个数:",off_train['Merchant_id'].drop_duplicates().__len__())
print("------------------------------针对线上的数据表------------------------------------")
onn_train = pd.read_csv('./ccf_online_stage1_train.csv')
print("数据总量:",onn_train.__len__())
print("用户个数:",onn_train['User_id'].drop_duplicates().__len__())
off_user = off_train['User_id'].drop_duplicates()
onn_user = onn_train['User_id'].drop_duplicates()
numCount = 0
for item in onn_user:
if item in off_user:
numCount = numCount + 1
print("与线下用户重复的用户个数:",numCount)
off_mer = off_train['Merchant_id'].drop_duplicates()
onn_mer = onn_train['Merchant_id'].drop_duplicates()
print("商户个数:",onn_mer.__len__())
merCount = 0
for item in onn_mer:
if item in off_mer:
merCount = merCount + 1
print("与线下商户重复的商户个数:",merCount)
print("------------------------------线下预测的数据表------------------------------------")
off_test = pd.read_csv('./ccf_offline_stage1_test_revised.csv')
print("数据总量:",off_test.__len__())
test_user = off_test['User_id'].drop_duplicates()
print("需要预测的用户的总量:",test_user.__len__())
testUser = 0
for item in test_user:
if item in off_user:
testUser = testUser + 1
print("用户与线下用户重复的个数:",testUser)
test_mer = off_test['Merchant_id'].drop_duplicates()
print("预测样本中商户的个数:",test_mer.__len__())
testmer = 0
for item in test_mer:
if item in off_mer:
testmer = testmer + 1
print("预测样本中商户与线下商户重复的个数:",testmer)
test_con = off_test['Coupon_id'].drop_duplicates()
train_con = off_train['Coupon_id'].drop_duplicates()
print("预测的优惠券的数量:",test_con.__len__())
conCount = 0
for item in test_con:
if item in train_con:
conCount = conCount + 1
print("预测样本中优惠券与线下中优惠券重复的个数:",conCount)
date_test = off_test['Date_received'].drop_duplicates()
print(date_test.sort_values())
<file_sep>/sklearn/交叉验证.py
from sklearn.datasets import load_iris
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score
import matplotlib.pyplot as plt
if __name__ == '__main__':
iris = load_iris()
X = iris.data
y = iris.target
k_range = list(range(1,31))
param_grid = dict(n_neighbours = k_range)
print(param_grid)
k_scores = []
for k in k_range:
knn = KNeighborsClassifier(n_neighbors=k)
scores = cross_val_score(knn, X, y, cv=10, scoring="accuracy")
k_scores.append(scores.mean())
plt.plot(k_range,k_scores)
plt.xlabel("Value of K for Knn")
plt.ylabel("Cross-validated Accuracy")
plt.show()
<file_sep>/sklearn/聚类算法.py
from sklearn.cluster import KMeans
from sklearn import datasets
from sklearn.model_selection import train_test_split
if __name__ == '__main__':
iris = datasets.load_iris()
X_train,X_test,y_train,y_test = train_test_split(iris.data,iris.target,test_size=0.3)
Kmean = KMeans(n_clusters=3,random_state=0)
s = Kmean.fit(X_train)
res = Kmean.predict(X_test)
print("正确率:",Kmean.score(X_test,y_test))
print("簇的中心\n",s.cluster_centers_)
print("每个样本所属的簇:\n",s.labels_)
print("评估簇的个数是否合适:\n",s.inertia_)
<file_sep>/sklearn/KNN.py
#引入模块
from sklearn import neighbors,datasets
from sklearn.model_selection import train_test_split
#随机划分数据的模块
if __name__ == '__main__':
#引入iris数据
iris = datasets.load_iris()
iris_X = iris.data
iris_y = iris.target
#划分数据集
X_train,X_test,y_train,y_test = train_test_split(iris_X,iris_y,test_size=0.3)
#初始化一个对象
knn = neighbors.KNeighborsClassifier()
#进行训练
knn.fit(X_train,y_train)
print(knn.get_params(deep=True))
print("keigh",knn.kneighbors())
#进行预测
knnRes = knn.predict(X_test)
print("正确结果:",y_test)
print("预测结果:",knnRes)
print(knn.predict_proba(X_test))
length = int(len(y_test))
count = 0
for index in range(length):
if(y_test[index] == knnRes[index]):
count = count + 1
print("正确率是:",count/length)
<file_sep>/sklearn/决策树.py
#引入模块
from sklearn import datasets,tree
from sklearn.model_selection import train_test_split
import graphviz
if __name__ == '__main__':
#引入数据
iris = datasets.load_iris()
iris_x = iris.data
iris_y = iris.target
iris_label = iris.feature_names
#划分数据
X_train,X_test,y_train,y_test = train_test_split(iris_x,iris_y,test_size=0.3)
#初始化决策树对象
DecTree = tree.DecisionTreeClassifier()
#进行训练
DecTree.fit(X_train,y_train)
#进行预测
res = DecTree.predict(X_test)
print(DecTree.score(X_test,y_test))
#一些类的属性
# print("Classes_: \n",DecTree.classes_)
# print("feature_importances_: \n",DecTree.feature_importances_)
# print("max_features_: \n",DecTree.max_features_)
# print("n_classes_: \n",DecTree.n_classes_)
# print("n_features_: \n",DecTree.n_features_)
# print("n_outputs_: \n",DecTree.n_outputs_)
# print("tree_",DecTree.tree_)
# print(DecTree.decision_path(X_test))
# print("get_para: \n",DecTree.get_params())
# print("log_prota: \n",DecTree.predict_log_proba(X_test))
# print("proba: \n",DecTree.predict_proba(X_test))
# print("score: \n",DecTree.score(X_test,y_test))
#决策树可视化
# dot_data = tree.export_graphviz(DecTree,out_file=None,
# feature_names=iris.feature_names,
# class_names=iris.target_names,
# filled=True,rounded=True,
# special_characters=True)
# graph = graphviz.Source(dot_data)
# graph.render("iris")
<file_sep>/sklearn/朴素贝叶斯-伯努利.py
# 引入模块
from sklearn import datasets,naive_bayes
from sklearn.model_selection import train_test_split
if __name__ == '__main__':
data = datasets.load_iris()
iris_x = data.data
iris_y = data.target
# 划分数据
X_train,X_test,y_train,y_test = train_test_split(iris_x,iris_y,test_size=0.3)
# 初始化多项式贝叶斯对象
bnb = naive_bayes.BernoulliNB()
# 进行训练
bnb.fit(X_train,y_train)
# 预测
res = bnb.predict(X_test)
print("预测结果:\n",res)
print(bnb.score(X_test,y_test))
# #一些属性
# print("class_log_prior_ : \n",mnb.class_log_prior_)
# print("intercept_ : \n", mnb.intercept_)
# print("feature_log_prob_ : \n",mnb.feature_log_prob_)
# print("coef_ : \n",mnb.coef_)
# print("class_count_ : \n",mnb.class_count_)
# print("feature_count_ : \n",mnb.feature_count_)<file_sep>/sklearn/网格搜索.py
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
from sklearn.model_selection import GridSearchCV
from sklearn import preprocessing,datasets
if __name__ == '__main__':
iris = datasets.load_breast_cancer()
X = iris.data
X = preprocessing.normalize(X)
y = iris.target
k_range = list(range(1,31))
param_grid = dict(n_neighbors = k_range)
knn = KNeighborsClassifier(n_neighbors=5)
grid = GridSearchCV(knn,param_grid,cv=10,scoring="accuracy")
grid.fit(X,y)
grid_mean_score = grid.cv_results_["mean_test_score"]
plt.plot(k_range,grid_mean_score)
plt.xlabel('Value of K for KNN')
plt.ylabel('Cross-Validated Accuracy')
plt.show()
print(grid.best_score_)
print(grid.best_params_)
<file_sep>/sklearn/SVM.py
from sklearn.model_selection import train_test_split
from sklearn import datasets,svm
if __name__ == '__main__':
data = datasets.load_iris()
iris_x = data.data
iris_y = data.target
#划分数据
X_train,X_test,y_train,y_test = train_test_split(iris_x,iris_y,test_size=0.3)
#初始化svm对象
sv = svm.SVC(C=1,kernel='rbf',gamma='auto',decision_function_shape='ovr')
#训练数据
sv.fit(X_train,y_train)
#预测数据
res = sv.predict(X_test)
print("预测结果:",res)
print("正确率: ",sv.score(X_test,y_test))
<file_sep>/机器学习算法/决策树/决策树.py
import math
from collections import Counter
"""
计算根节点的熵
首先定义传入的训练数据类型为(a1,a1,a3,...an,y)其中a代表那个样本的属性,y代表分类的结果
定义的变量:
dataLen: 样本个数
label: 分类结果及其每个结果出现的次数,已字典的形式
shannonEnt: 根节点的熵
"""
def calshannonEnt(data):
dataLen = len(data)
label = {}
#遍历每一条样本,找出结果
for dataItem in data:
#取出每一条样本的结果,并判断是否在label中
currentResult = dataItem[-1]
if currentResult not in label.keys():
label[currentResult] = 0
label[currentResult] += 1
#求根节点的熵
shannonEnt = 0.0
for key in label:
resultPercent = float(label[key])/dataLen
shannonEnt -= resultPercent * math.log(resultPercent,2)
return shannonEnt
"""
按照给定的特征的值,来划分数据
返回值:样本中的特征值与给定的特征的特征值相等的样本,并且去掉该特征
定义的变量:
data: 数据集
index: 特征在每一个样本的下标
value: 特征值
"""
def splitData(data, index, value):
returnData = []
for dataItem in data:
reduceData = []
if(dataItem[index] == value):
#利用列表截断,来获取每条样本特征前后的属性,并利用extend方法进行拼接
reduceData = dataItem[:index]
reduceData.extend(dataItem[index+1:])
returnData.append(reduceData)
return returnData
"""
选择最好的数据集划分方式
判断条件是信息增益
返回值:特征的下标
定义的变量:
featureLen:属性的个数
baseEnt:根节点的熵
featureList:保存属性的所有子属性
gainEnt:信息增益
bestEnt:最好的信息增益
bestFeature:最好的特征,即信息增益最大的熵
"""
def chooseBestFeature(data):
featureLen = len(data[0])-1
baseEnt = calshannonEnt(data)
bestEnt = 0.0
bestFeature = -1
featureEnt = 0.0
#遍历样本每个属性
for i in range(featureLen):
featureList = [Item[i] for Item in data]
#对属性列表去重
featureSet = set(featureList)
#循环遍历每个属性的子属性
for value in featureSet:
reduceData = splitData(data,i,value)
print("特征 {0} 的子特征 {1} 包含的样本:{2}".format(i, value, reduceData))
#计算每个子属性占所有样本的百分比
percent = float(len(reduceData))/len(data)
#计算每个子属性的熵
featureItemEnt = calshannonEnt(reduceData)
print('子特征分类下的样本占总样本 {0} ,其熵为{1}'.format(percent, featureItemEnt))
#计算属性的熵
featureEnt = featureEnt + percent * featureItemEnt
#计算属性的信息增益
gainEnt = baseEnt - featureEnt
print("原始熵 = {0}, 特征的熵 = {1}, 信息增益 = {2}".format(baseEnt, featureEnt, gainEnt))
if(gainEnt > bestEnt):
bestEnt = gainEnt
bestFeature = i
return bestFeature
"""
定义生成树
如果只有一个类别,就直接返回结果
如果每个样本只有一列,就返回出现次数最多的结果
一般情况:
先找出所有属性的最好特征
然后找出最好特征的子属性,并在每一个子属性下找到剩余特征中最好的特征,重复步骤
"""
def createTree(data,labels):
classList = [example[-1] for example in data]
if classList.count(classList[0]) == len(classList):
return classList[0]
if len(data[0]) == 1:
result_counts = Counter(classList)
return result_counts.most_common(1)[0][0]
bestFeature = chooseBestFeature(data)
bestLabel = labels[bestFeature]
myTree = {bestLabel:{}}
featValues = [example[bestFeature] for example in data]
uniqueValues = set(featValues)
for value in uniqueValues:
subLabels = labels[bestFeature + 1:]
myTree[bestLabel][value] = createTree(splitData(data,bestFeature,value),subLabels)
print(myTree)
return myTree
"""
利用决策树来进行分类,思路:
首先找出决策树的根节点的特征在所有属性中的位置
然后找出根特征所有的子集
找出测试用例该特征所属的子集
把该子集做成新的决策树
"""
def classify(inputTree,featLabels,test):
rootFeature = list(inputTree.keys())[0]
#找到该特征下的所有子集
rootItems = inputTree[rootFeature]
#找到根特征在每一条样本中所处的位置
rootIndex = featLabels.index(rootFeature)
#找到该测试样本该特征的值
rootKey = test[rootIndex]
#获取该特征具体值下所有的子集
reduceItem = rootItems[rootKey]
print('+++',rootFeature,'---',rootItems,'<<<',rootKey,'...',reduceItem)
#判断有没有结束
if isinstance(reduceItem,dict):
result = classify(reduceItem,featLabels,test)
else:
result = reduceItem
return result
if __name__ == '__main__':
data = [
[1, 0, 'no'],
[1, 1, 'yes'],
[1, 1, 'yes'],
[0, 1, 'no'],
[0, 1, 'no']
]
labels = ['no surfacing', 'flippers']
inputTree = createTree(data, labels)
classify(inputTree, labels, [0, 0])
<file_sep>/o2o/o2o.py
import pandas as pd
from datetime import datetime
import numpy as np
if __name__ == '__main__':
"""
使用的函数:
"""
def cal_discount(s):
s = str(s)
s = s.split(':')
if len(s)==1:
return float(s[0])
else:
return round(1.0 - float(s[1]) / float(s[0]),4)
def isweek(s):
s = str(s)
week = datetime.strptime(s, '%Y%m%d').weekday() + 1
if week == 5 or week == 6 or week == 7:
return 1
else:
return 0
def classify(s): # 直接优惠记为0,满减记为1
s = str(s)
s = s.split(':')
if len(s) == 1:
return 0
else:
return 1
def is_firstorlast(s):
if s == 0:
return 1
else:
return 0
"""
划分数据集:
"""
off_train = pd.read_csv('./ccf_offline_stage1_train.csv',header=0,low_memory=False)
off_train.columns = ['user_id', 'merchant_id', 'coupon_id', 'discount_rate', 'distance', 'date_received', 'date']
off_test = pd.read_csv('./ccf_offline_stage1_test_revised.csv',header=0,low_memory=False)
off_test.columns = ['user_id', 'merchant_id', 'coupon_id', 'discount_rate', 'distance', 'date_received']
on_train = pd.read_csv('./ccf_online_stage1_train.csv',header=0,low_memory=False)
on_train.columns = ['user_id', 'merchant_id', 'action', 'coupon_id', 'discount_rate', 'date_received', 'date']
dataSet3 = off_test
dataSet3_off_feature3 = off_train[((off_train['date']>=20160301.0) & (off_train['date']<=20160630.0))
|((off_train['date'].isnull()==True)&(off_train['date_received']>=20160301.0)
&(off_train['date_received']<=20160630.0))]
dataSet3_on_feature3 = on_train[((on_train['date']>=20160301.0) & (on_train['date']<=20160630.0))|
((on_train['date'].isnull()==True)&(on_train['date_received']>=20160301.0)
&(on_train['date_received']<=20160630.0))]
dataSet2 = off_train[(off_train['date_received']>=20160601.0)&(off_train["date_received"]<=20160630.0)]
dataSet2_off_feature2 = off_train[((off_train['date']>=20160201.0)&(off_train['date']<=20160530.0))|
((off_train['date'].isnull()==True)&(off_train['date_received']>=20160201.0)&
(off_train['date_received']<=20160530.0))]
dataSet2_on_feature2 = on_train[((on_train['date'] >= 20160201.0) & (on_train['date'] <= 20160530.0))|
((on_train['date'].isnull() == True) & (on_train['date_received'] >= 20160201.0) &
(on_train['date_received'] <= 20160530.0))]
dataSet1 = off_train[(off_train['date_received']>=20160501.0)&(off_train["date_received"]<=20160531.0)]
dataSet1_off_feature1 = off_train[((off_train['date'] >= 20160101.0) & (off_train['date'] <= 20160430.0)) |
((off_train['date'].isnull() == True) & (off_train['date_received'] >= 20160101.0) &
(off_train['date_received'] <= 20160430.0))]
dataSet1_on_feature1 = on_train[((on_train['date'] >= 20160101.0) & (on_train['date'] <= 20160430.0)) |
((on_train['date'].isnull() == True) & (on_train['date_received'] >= 20160101.0) &
(on_train['date_received'] <= 20160430.0))]
""""
提取线上的特征:
每个用户消费的总次数 user_online_buy_total
每个用户使用消费券消费的次数 use_online_buy_coupon
每个用户使用消费券消费的次数占总消费次数的占比 user_online_buy_couponRate
每个用户领取的消费券的总数 user_online_coupon_receivedAll
每个用户使用消费券占领取的消费券的比重 uses_online_coupon_buyRate
每个用户在限时低价时消费的次数 user_online_buy_fixed
每个用户限时低价消费占总消费的比重 user_online_buy_fixedRate
用户购买东西的商店的个数 user_online_buy_merchantCount
每个用户看过的商店的个数包括只点击 user_online_action_merchantCount
每个用户行为的个数(包括点击,消费,领取) user_online_action_count
每个用户点击个数 user_online_click_count
每个用户领取了优惠券没有使用的次数 user_online_notUseReceive_coupon
每个用户没有使用消费券消费的次数 user_online_notUse_coupon
消费的商店占有过行为的商店的比重 user_online_merchantBuyRate
"""
# 对dataSet3_on_feature3
# 每个用户消费的总次数user_online_buy_total
t = pd.DataFrame(dataSet3_on_feature3[['user_id','date']])
t = t[t['date'].notnull() == True]
t = pd.DataFrame(t['user_id'],columns=['user_id'])
t['user_online_buy_total'] = 1
t = t.groupby('user_id',sort=False).agg('sum').reset_index()
# 每个用户使用消费券消费的次数use_online_buy_coupon
t1 = pd.DataFrame(dataSet3_on_feature3[['user_id','action','coupon_id']])
t1 = t1[(t1['action'] == 1)&(t1['coupon_id'].notnull()==True)&(t1['coupon_id']!='fixed')]
t1 = pd.DataFrame(t1['user_id'], columns=['user_id'])
t1['use_online_buy_coupon'] = 1
t1 = t1.groupby('user_id', sort=False).agg('sum').reset_index()
# 每个用户领取的消费券的总数user_online_coupon_receivedAll
t2 = pd.DataFrame(dataSet3_on_feature3[['user_id', 'action', 'coupon_id']])
t2 = t2[(t2['action'] == 2) & (t2['coupon_id'].notnull() == True) & (t2['coupon_id'] != 'fixed')]
t2 = pd.DataFrame(t2['user_id'], columns=['user_id'])
t2['user_online_coupon_receivedAll'] = 1
t2 = t2.groupby('user_id', sort=False).agg('sum').reset_index()
# 每个用户在限时低价时消费的次数user_online_buy_fixed
t3 = pd.DataFrame(dataSet3_on_feature3[['user_id', 'action', 'coupon_id']])
t3 = t3[(t3['action'] == 1) & (t3['coupon_id'] == 'fixed')]
t3 = pd.DataFrame(t3['user_id'], columns=['user_id'])
t3['user_online_buy_fixed'] = 1
t3 = t3.groupby('user_id', sort=False).agg('sum').reset_index()
# 用户购买东西的商店的个数user_online_buy_merchantCount
t4 = pd.DataFrame(dataSet3_on_feature3[['user_id', 'action', 'merchant_id']])
t4 = t4[(t4['action'] == 1) & (t4['merchant_id'].notnull()==True)]
t4 = pd.DataFrame(t4['user_id'], columns=['user_id'])
t4['user_online_buy_merchantCount'] = 1
t4 = t4.groupby('user_id', sort=False).agg('sum').reset_index()
# 每个用户看过的商店的个数包括只点击user_online_action_merchantCount
t5 = pd.DataFrame(dataSet3_on_feature3[['user_id','merchant_id']])
t5 = t5[(t5['merchant_id'].notnull() == True)]
t5 = pd.DataFrame(t5['user_id'], columns=['user_id'])
t5['user_online_action_merchantCount'] = 1
t5 = t5.groupby('user_id', sort=False).agg('sum').reset_index()
# 每个用户行为的个数user_online_action_count
t6 = pd.DataFrame(dataSet3_on_feature3[['user_id', 'action']])
t6 = t6[(t6['action'].notnull() == True)]
t6 = pd.DataFrame(t6['user_id'], columns=['user_id'])
t6['user_online_action_count'] = 1
t6 = t6.groupby('user_id', sort=False).agg('sum').reset_index()
# 每个用户点击个数user_online_click_count
t7 = pd.DataFrame(dataSet3_on_feature3[['user_id', 'action']])
t7 = t7[(t7['action'].notnull() == True)&(t7['action']==0)]
t7 = pd.DataFrame(t7['user_id'], columns=['user_id'])
t7['user_online_click_count'] = 1
t7 = t7.groupby('user_id', sort=False).agg('sum').reset_index()
# 每个用户领取了优惠券没有使用的次数user_online_notUseReceive_coupon
t8 = pd.DataFrame(dataSet3_on_feature3[['user_id', 'action','date']])
t8 = t8[(t8['action'].notnull() == True) & (t8['action'] == 2)&(t8['date'].isnull()==True)]
t8 = pd.DataFrame(t8['user_id'], columns=['user_id'])
t8['user_online_notUseReceive_coupon'] = 1
t8 = t8.groupby('user_id', sort=False).agg('sum').reset_index()
# 每个用户没有使用消费券消费的次数user_online_notUse_coupon
t9 = pd.DataFrame(dataSet3_on_feature3[['user_id', 'coupon_id', 'date']])
t9 = t9[(t9['date'].notnull() == True) & (t9['coupon_id'].isnull() == True)]
t9 = pd.DataFrame(t9['user_id'], columns=['user_id'])
t9['user_online_notUse_coupon'] = 1
t9 = t9.groupby('user_id', sort=False).agg('sum').reset_index()
# 合并数据
left = dataSet3_on_feature3[['user_id']].drop_duplicates()
dataSet3_on_result = pd.merge(left,t,how='left',on=['user_id'])
dataSet3_on_result = pd.merge(dataSet3_on_result,t1,how='left',on='user_id')
dataSet3_on_result = pd.merge(dataSet3_on_result,t2,how='left',on='user_id')
dataSet3_on_result = pd.merge(dataSet3_on_result,t3,how='left',on='user_id')
dataSet3_on_result = pd.merge(dataSet3_on_result,t4,how='left',on='user_id')
dataSet3_on_result = pd.merge(dataSet3_on_result,t5,how='left',on='user_id')
dataSet3_on_result = pd.merge(dataSet3_on_result,t6,how='left',on='user_id')
dataSet3_on_result = pd.merge(dataSet3_on_result,t7,how='left',on='user_id')
dataSet3_on_result = pd.merge(dataSet3_on_result,t8,how='left',on='user_id')
dataSet3_on_result = pd.merge(dataSet3_on_result,t9,how='left',on='user_id')
# 替换每列中的Nan,用平均值来代替
for i in dataSet3_on_result.columns:
meanVal = dataSet3_on_result[i].mean()
dataSet3_on_result[i].fillna(meanVal,inplace=True)
# 使用消费券消费的次数占总消费次数的占比 user_online_buy_couponRate (use_online_buy_coupon/user_online_buy_total)
t10 = dataSet3_on_result['use_online_buy_coupon']
t_10 = dataSet3_on_result['user_online_buy_total']
t10 = t10/t_10
dataSet3_on_result['user_online_buy_couponRate'] = t10
# 用户使用消费券占领取的消费券的比重 uses_online_coupon_buyRate (use_online_buy_coupon/user_online_coupon_receivedAll)
t11 = dataSet3_on_result['use_online_buy_coupon']
t_11 = dataSet3_on_result['user_online_coupon_receivedAll']
t11 = t11/t_11
dataSet3_on_result['uses_online_coupon_buyRate'] = t11
# 每个用户限时低价消费占总消费的比重 user_online_buy_fixedRate (user_online_buy_fixed/user_online_buy_total)
t12 = dataSet3_on_result['user_online_buy_fixed']
t_12 = dataSet3_on_result['user_online_buy_total']
t12 = t12/t_12
dataSet3_on_result['user_online_buy_fixedRate'] = t12
# 消费的商店占有过行为的商店的比重 user_online_merchantBuyRate (user_online_buy_merchantCount/user_online_action_merchantCount)
t13 = dataSet3_on_result['user_online_buy_merchantCount']
t_13 = dataSet3_on_result['user_online_action_merchantCount']
t13 = t13/t_13
dataSet3_on_result['user_online_merchantBuyRate'] = t13
dataSet3_on_result.to_csv('dataSet3_on_feature.csv', index=None)
# # 对dataSet2_on_feature2
#
# # 每个用户消费的总次数user_online_buy_total
# t = pd.DataFrame(dataSet2_on_feature2[['user_id','date']])
# t = t[t['date'].notnull() == True]
# t = pd.DataFrame(t['user_id'],columns=['user_id'])
# t['user_online_buy_total'] = 1
# t = t.groupby('user_id',sort=False).agg('sum').reset_index()
#
# # 每个用户使用消费券消费的次数use_online_buy_coupon
# t1 = pd.DataFrame(dataSet2_on_feature2[['user_id','action','coupon_id']])
# t1 = t1[(t1['action'] == 1)&(t1['coupon_id'].notnull()==True)&(t1['coupon_id']!='fixed')]
# t1 = pd.DataFrame(t1['user_id'], columns=['user_id'])
# t1['use_online_buy_coupon'] = 1
# t1 = t1.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 每个用户领取的消费券的总数user_online_coupon_receivedAll
# t2 = pd.DataFrame(dataSet2_on_feature2[['user_id', 'action', 'coupon_id']])
# t2 = t2[(t2['action'] == 2) & (t2['coupon_id'].notnull() == True) & (t2['coupon_id'] != 'fixed')]
# t2 = pd.DataFrame(t2['user_id'], columns=['user_id'])
# t2['user_online_coupon_receivedAll'] = 1
# t2 = t2.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 每个用户在限时低价时消费的次数user_online_buy_fixed
# t3 = pd.DataFrame(dataSet2_on_feature2[['user_id', 'action', 'coupon_id']])
# t3 = t3[(t3['action'] == 1) & (t3['coupon_id'] == 'fixed')]
# t3 = pd.DataFrame(t3['user_id'], columns=['user_id'])
# t3['user_online_buy_fixed'] = 1
# t3 = t3.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 用户购买东西的商店的个数user_online_buy_merchantCount
# t4 = pd.DataFrame(dataSet2_on_feature2[['user_id', 'action', 'merchant_id']])
# t4 = t4[(t4['action'] == 1) & (t4['merchant_id'].notnull()==True)]
# t4 = pd.DataFrame(t4['user_id'], columns=['user_id'])
# t4['user_online_buy_merchantCount'] = 1
# t4 = t4.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 每个用户看过的商店的个数包括只点击user_online_action_merchantCount
# t5 = pd.DataFrame(dataSet2_on_feature2[['user_id','merchant_id']])
# t5 = t5[(t5['merchant_id'].notnull() == True)]
# t5 = pd.DataFrame(t5['user_id'], columns=['user_id'])
# t5['user_online_action_merchantCount'] = 1
# t5 = t5.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 每个用户行为的个数user_online_action_count
# t6 = pd.DataFrame(dataSet2_on_feature2[['user_id', 'action']])
# t6 = t6[(t6['action'].notnull() == True)]
# t6 = pd.DataFrame(t6['user_id'], columns=['user_id'])
# t6['user_online_action_count'] = 1
# t6 = t6.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 每个用户点击个数user_online_click_count
# t7 = pd.DataFrame(dataSet2_on_feature2[['user_id', 'action']])
# t7 = t7[(t7['action'].notnull() == True)&(t7['action']==0)]
# t7 = pd.DataFrame(t7['user_id'], columns=['user_id'])
# t7['user_online_click_count'] = 1
# t7 = t7.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 每个用户领取了优惠券没有使用的次数user_online_notUseReceive_coupon
# t8 = pd.DataFrame(dataSet2_on_feature2[['user_id', 'action','date']])
# t8 = t8[(t8['action'].notnull() == True) & (t8['action'] == 2)&(t8['date'].isnull()==True)]
# t8 = pd.DataFrame(t8['user_id'], columns=['user_id'])
# t8['user_online_notUseReceive_coupon'] = 1
# t8 = t8.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 每个用户没有使用消费券消费的次数user_online_notUse_coupon
# t9 = pd.DataFrame(dataSet2_on_feature2[['user_id', 'coupon_id', 'date']])
# t9 = t9[(t9['date'].notnull() == True) & (t9['coupon_id'].isnull() == True)]
# t9 = pd.DataFrame(t9['user_id'], columns=['user_id'])
# t9['user_online_notUse_coupon'] = 1
# t9 = t9.groupby('user_id', sort=False).agg('sum').reset_index()
#
# #合并数据
# left = dataSet2_on_feature2[['user_id']].drop_duplicates()
# data2_on_result = pd.merge(left,t,how='left',on=['user_id'])
# data2_on_result = pd.merge(data2_on_result,t1,how='left',on='user_id')
# data2_on_result = pd.merge(data2_on_result,t2,how='left',on='user_id')
# data2_on_result = pd.merge(data2_on_result,t3,how='left',on='user_id')
# data2_on_result = pd.merge(data2_on_result,t4,how='left',on='user_id')
# data2_on_result = pd.merge(data2_on_result,t5,how='left',on='user_id')
# data2_on_result = pd.merge(data2_on_result,t6,how='left',on='user_id')
# data2_on_result = pd.merge(data2_on_result,t7,how='left',on='user_id')
# data2_on_result = pd.merge(data2_on_result,t8,how='left',on='user_id')
# data2_on_result = pd.merge(data2_on_result,t9,how='left',on='user_id')
#
# #替换每列中的Nan,用平均值来代替
# for i in data2_on_result.columns:
# meanVal = data2_on_result[i].mean()
# data2_on_result[i].fillna(meanVal,inplace=True)
#
# # 使用消费券消费的次数占总消费次数的占比 user_online_buy_couponRate (use_online_buy_coupon/user_online_buy_total)
# t10 = data2_on_result['use_online_buy_coupon']
# t_10 = data2_on_result['user_online_buy_total']
# t10 = t10/t_10
# data2_on_result['user_online_buy_couponRate'] = t10
#
# # 用户使用消费券占领取的消费券的比重 uses_online_coupon_buyRate (use_online_buy_coupon/user_online_coupon_receivedAll)
# t11 = data2_on_result['use_online_buy_coupon']
# t_11 = data2_on_result['user_online_coupon_receivedAll']
# t11 = t11/t_11
# data2_on_result['uses_online_coupon_buyRate'] = t11
#
# # 每个用户限时低价消费占总消费的比重 user_online_buy_fixedRate (user_online_buy_fixed/user_online_buy_total)
# t12 = data2_on_result['user_online_buy_fixed']
# t_12 = data2_on_result['user_online_buy_total']
# t12 = t12/t_12
# data2_on_result['user_online_buy_fixedRate'] = t12
#
# # 消费的商店占有过行为的商店的比重 user_online_merchantBuyRate (user_online_buy_merchantCount/user_online_action_merchantCount)
# t13 = data2_on_result['user_online_buy_merchantCount']
# t_13 = data2_on_result['user_online_action_merchantCount']
# t13 = t13/t_13
# data2_on_result['user_online_merchantBuyRate'] = t13
# data2_on_result.to_csv('dataSet2_on_feature.csv', index=None)
#
# # dataSet1_on_feature
# # 每个用户消费的总次数user_online_buy_total
# t = pd.DataFrame(dataSet1_on_feature1[['user_id','date']])
# t = t[t['date'].notnull() == True]
# t = pd.DataFrame(t['user_id'],columns=['user_id'])
# t['user_online_buy_total'] = 1
# t = t.groupby('user_id',sort=False).agg('sum').reset_index()
#
# # 每个用户使用消费券消费的次数use_online_buy_coupon
# t1 = pd.DataFrame(dataSet1_on_feature1[['user_id','action','coupon_id']])
# t1 = t1[(t1['action'] == 1)&(t1['coupon_id'].notnull()==True)&(t1['coupon_id']!='fixed')]
# t1 = pd.DataFrame(t1['user_id'], columns=['user_id'])
# t1['use_online_buy_coupon'] = 1
# t1 = t1.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 每个用户领取的消费券的总数user_online_coupon_receivedAll
# t2 = pd.DataFrame(dataSet1_on_feature1[['user_id', 'action', 'coupon_id']])
# t2 = t2[(t2['action'] == 2) & (t2['coupon_id'].notnull() == True) & (t2['coupon_id'] != 'fixed')]
# t2 = pd.DataFrame(t2['user_id'], columns=['user_id'])
# t2['user_online_coupon_receivedAll'] = 1
# t2 = t2.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 每个用户在限时低价时消费的次数user_online_buy_fixed
# t3 = pd.DataFrame(dataSet1_on_feature1[['user_id', 'action', 'coupon_id']])
# t3 = t3[(t3['action'] == 1) & (t3['coupon_id'] == 'fixed')]
# t3 = pd.DataFrame(t3['user_id'], columns=['user_id'])
# t3['user_online_buy_fixed'] = 1
# t3 = t3.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 用户购买东西的商店的个数user_online_buy_merchantCount
# t4 = pd.DataFrame(dataSet1_on_feature1[['user_id', 'action', 'merchant_id']])
# t4 = t4[(t4['action'] == 1) & (t4['merchant_id'].notnull()==True)]
# t4 = pd.DataFrame(t4['user_id'], columns=['user_id'])
# t4['user_online_buy_merchantCount'] = 1
# t4 = t4.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 每个用户看过的商店的个数包括只点击user_online_action_merchantCount
# t5 = pd.DataFrame(dataSet1_on_feature1[['user_id','merchant_id']])
# t5 = t5[(t5['merchant_id'].notnull() == True)]
# t5 = pd.DataFrame(t5['user_id'], columns=['user_id'])
# t5['user_online_action_merchantCount'] = 1
# t5 = t5.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 每个用户行为的个数user_online_action_count
# t6 = pd.DataFrame(dataSet1_on_feature1[['user_id', 'action']])
# t6 = t6[(t6['action'].notnull() == True)]
# t6 = pd.DataFrame(t6['user_id'], columns=['user_id'])
# t6['user_online_action_count'] = 1
# t6 = t6.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 每个用户点击个数user_online_click_count
# t7 = pd.DataFrame(dataSet1_on_feature1[['user_id', 'action']])
# t7 = t7[(t7['action'].notnull() == True)&(t7['action']==0)]
# t7 = pd.DataFrame(t7['user_id'], columns=['user_id'])
# t7['user_online_click_count'] = 1
# t7 = t7.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 每个用户领取了优惠券没有使用的次数user_online_notUseReceive_coupon
# t8 = pd.DataFrame(dataSet1_on_feature1[['user_id', 'action','date']])
# t8 = t8[(t8['action'].notnull() == True) & (t8['action'] == 2)&(t8['date'].isnull()==True)]
# t8 = pd.DataFrame(t8['user_id'], columns=['user_id'])
# t8['user_online_notUseReceive_coupon'] = 1
# t8 = t8.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 每个用户没有使用消费券消费的次数user_online_notUse_coupon
# t9 = pd.DataFrame(dataSet1_on_feature1[['user_id', 'coupon_id', 'date']])
# t9 = t9[(t9['date'].notnull() == True) & (t9['coupon_id'].isnull() == True)]
# t9 = pd.DataFrame(t9['user_id'], columns=['user_id'])
# t9['user_online_notUse_coupon'] = 1
# t9 = t9.groupby('user_id', sort=False).agg('sum').reset_index()
#
# #合并数据
# left = dataSet1_on_feature1[['user_id']].drop_duplicates()
# dataSet1_on_result = pd.merge(left,t,how='left',on=['user_id'])
# dataSet1_on_result = pd.merge(dataSet1_on_result,t1,how='left',on='user_id')
# dataSet1_on_result = pd.merge(dataSet1_on_result,t2,how='left',on='user_id')
# dataSet1_on_result = pd.merge(dataSet1_on_result,t3,how='left',on='user_id')
# dataSet1_on_result = pd.merge(dataSet1_on_result,t4,how='left',on='user_id')
# dataSet1_on_result = pd.merge(dataSet1_on_result,t5,how='left',on='user_id')
# dataSet1_on_result = pd.merge(dataSet1_on_result,t6,how='left',on='user_id')
# dataSet1_on_result = pd.merge(dataSet1_on_result,t7,how='left',on='user_id')
# dataSet1_on_result = pd.merge(dataSet1_on_result,t8,how='left',on='user_id')
# dataSet1_on_result = pd.merge(dataSet1_on_result,t9,how='left',on='user_id')
#
# #替换每列中的Nan,用平均值来代替
# for i in dataSet1_on_result.columns:
# meanVal = dataSet1_on_result[i].mean()
# dataSet1_on_result[i].fillna(meanVal,inplace=True)
#
# # 使用消费券消费的次数占总消费次数的占比 user_online_buy_couponRate (use_online_buy_coupon/user_online_buy_total)
# t10 = dataSet1_on_result['use_online_buy_coupon']
# t_10 = dataSet1_on_result['user_online_buy_total']
# t10 = t10/t_10
# dataSet1_on_result['user_online_buy_couponRate'] = t10
#
# # 用户使用消费券占领取的消费券的比重 uses_online_coupon_buyRate (use_online_buy_coupon/user_online_coupon_receivedAll)
# t11 = dataSet1_on_result['use_online_buy_coupon']
# t_11 = dataSet1_on_result['user_online_coupon_receivedAll']
# t11 = t11/t_11
# dataSet1_on_result['uses_online_coupon_buyRate'] = t11
#
# # 每个用户限时低价消费占总消费的比重 user_online_buy_fixedRate (user_online_buy_fixed/user_online_buy_total)
# t12 = dataSet1_on_result['user_online_buy_fixed']
# t_12 = dataSet1_on_result['user_online_buy_total']
# t12 = t12/t_12
# dataSet1_on_result['user_online_buy_fixedRate'] = t12
#
# # 消费的商店占有过行为的商店的比重 user_online_merchantBuyRate (user_online_buy_merchantCount/user_online_action_merchantCount)
# t13 = dataSet1_on_result['user_online_buy_merchantCount']
# t_13 = dataSet1_on_result['user_online_action_merchantCount']
# t13 = t13/t_13
# dataSet1_on_result['user_online_merchantBuyRate'] = t13
#
# dataSet1_on_result.to_csv('dataSet1_on_feature.csv', index=None)
"""
用户线下特征:
用户领取优惠券的次数 user_off_couponReceive_count
用户获得了优惠券没有使用的次数 user_off_coupon_notUse
用户领取了优惠券使用的次数 user_off_coupon_use
用户对于消费券的核销率 user_off_couponRate
用户总的消费次数 user_off_buyTotal
用户使用优惠券消费占总消费的比重 user_off_useCoupon_rate
用户核销的消费券的平均折扣率 user_off_coupon_avgDiscount
用户使用消费券消费的商家的平均距离 user_off_merchant_avdDistance
用户使用了消费券的商家的数量 user_off_merchantUse_count
用户使用消费券的平均间隔 user_off_useCoupon_avgday
用户使用消费券是周末还是工作日居多 user_off_payisWeek
"""
# dataSet3
# 用户领取优惠券的次数 user_off_couponReceive_count
# t = pd.DataFrame(dataSet3_off_feature3[['user_id', 'coupon_id','date_received']])
# t = t[(t['coupon_id'].notnull() == True) & (t['date_received'].notnull() == True)]
# t = pd.DataFrame(t['user_id'],columns=['user_id'])
# t['user_off_couponReceive_count'] = 1
# t = t.groupby('user_id',sort=False).agg('sum').reset_index()
#
# # 用户获得了优惠券没有使用的次数 user_off_coupon_notUse
# t1 = pd.DataFrame(dataSet3_off_feature3[['user_id', 'coupon_id', 'date_received','date']])
# t1 = t1[(t1['coupon_id'].notnull() == True) & (t1['date_received'].notnull() == True) & (t1['date'].isnull() == True)]
# t1 = pd.DataFrame(t['user_id'], columns=['user_id'])
# t1['user_off_coupon_notUse'] = 1
# t1 = t1.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 用户领取了优惠券使用的次数 user_off_coupon_use
# t2 = pd.DataFrame(dataSet3_off_feature3[['user_id', 'coupon_id', 'date_received', 'date']])
# t2 = t2[(t2['coupon_id'].notnull() == True) & (t2['date_received'].notnull() == True) & (t2['date'].isnull() == False)]
# t2 = pd.DataFrame(t['user_id'], columns=['user_id'])
# t2['user_off_coupon_use'] = 1
# t2 = t2.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 用户对于消费券的核销率 user_off_couponRate
# t3 = pd.merge(t,t2,how='left',on=['user_id'])
# t3['user_off_couponRate'] = round(t3['user_off_coupon_use']/t3['user_off_couponReceive_count'],4)
# t3 = pd.DataFrame(t3[['user_id','user_off_couponRate']],columns=['user_id','user_off_couponRate'])
#
# # 用户总的消费次数 user_off_buyTotal
# t4 = pd.DataFrame(dataSet3_off_feature3[['user_id','date']])
# t4 = t4[t4['date'].notnull() == True]
# t4 = pd.DataFrame(t4['user_id'],columns=['user_id'])
# t4['user_off_buyTotal'] = 1
# t4 = t4.groupby('user_id',sort=False).agg('sum').reset_index()
#
#
# # 用户使用优惠券消费占总消费的比重 user_off_useCoupon_rate
# t5 = pd.merge(t4, t2, how='left', on=['user_id'])
# t5['user_off_useCoupon_rate'] = round(t5['user_off_coupon_use'] / t5['user_off_buyTotal'], 4)
# t5 = pd.DataFrame(t5[['user_id', 'user_off_useCoupon_rate']], columns=['user_id', 'user_off_useCoupon_rate'])
#
# # 用户核销的消费券的平均折扣率 user_off_coupon_avgDiscount
# t6 = pd.DataFrame(dataSet3_off_feature3[['user_id', 'coupon_id','discount_rate','date_received']])
# t6 = t6[(t6['coupon_id'].notnull() == True) & (t6['date_received'].notnull() == True)]
# t6['user_off_coupon_avgDiscount'] = t6['discount_rate'].apply(cal_discount)
# t6 = pd.DataFrame(t6[['user_id','user_off_coupon_avgDiscount']], columns=['user_id','user_off_coupon_avgDiscount'])
# t6 = t6.groupby('user_id', sort=False).agg('mean').reset_index()
#
#
# # 用户使用消费券消费的商家的平均距离 user_off_merchant_avdDistance
# t7 = pd.DataFrame(dataSet3_off_feature3[['user_id', 'coupon_id', 'distance','date_received','date']])
# t7 = t7[(t7['coupon_id'].notnull() == True) & (t7['date_received'].notnull() == True) & (t7['date'].notnull() == True)][['user_id','distance']]
# t7 = t7.fillna(-1)
# t7['distance'] = t7['distance'].astype('int')
# t7 = t7.groupby('user_id',sort=False).agg('mean').reset_index()
# t7.rename(columns={'distance': 'user_off_merchant_avdDistance'}, inplace=True)
#
# # 用户使用了消费券的商家的数量 user_off_merchantUse_count
# t8 = pd.DataFrame(dataSet3_off_feature3[['user_id', 'merchant_id','coupon_id','date_received','date']])
# t8 = t8[(t8['coupon_id'].notnull() == True) & (t8['date_received'].notnull() == True) & (t8['date'].notnull() == True)]
# t8 = pd.DataFrame(t8[['user_id','merchant_id']], columns=['user_id','merchant_id']).drop_duplicates()
# t8['user_off_merchantUse_count'] = 1
# t8 = t8.groupby('user_id', sort=False).agg('sum').reset_index()
# t8 = pd.DataFrame(t8[['user_id','user_off_merchantUse_count']],columns=['user_id','user_off_merchantUse_count'])
#
# # 用户使用消费券的平均间隔 user_off_useCoupon_avgday
# t9 = pd.DataFrame(dataSet3_off_feature3[['user_id', 'coupon_id', 'date_received', 'date']])
# t9 = t9[(t9['coupon_id'].notnull() == True) & (t9['date_received'].notnull() == True) & (t9['date'].notnull() == True)]
# t9['user_off_useCoupon_avgday'] = t9['date'].apply(int) - t9['date_received'].apply(int)
# t9 = t9.groupby('user_id', sort=False).agg('mean').reset_index()
# t9 = pd.DataFrame(t9[['user_id', 'user_off_useCoupon_avgday']], columns=['user_id', 'user_off_useCoupon_avgday'])
#
# # 用户使用消费券是周末还是工作日居多 user_off_payisWeek
# t10 = pd.DataFrame(dataSet3_off_feature3[['user_id', 'coupon_id', 'date_received', 'date']])
# t10 = t10[(t10['coupon_id'].notnull() == True) & (t10['date_received'].notnull() == True) & (t10['date'].notnull() == True)]
# t10['user_off_payisWeek'] = t10['date'].apply(int).apply(isweek)
# t10 = t10.groupby('user_id', sort=False).agg('mean').reset_index()
# t10['user_off_payisWeek'] = t10['user_off_payisWeek'].apply(round)
# t10 = pd.DataFrame(t10[['user_id', 'user_off_payisWeek']], columns=['user_id', 'user_off_payisWeek'])
# #合并数据
# left = dataSet3_off_feature3[['user_id']].drop_duplicates()
# dataSet3_off_result = pd.merge(left,t,how='left',on=['user_id'])
# dataSet3_off_result = pd.merge(dataSet3_off_result,t1,how='left',on='user_id')
# dataSet3_off_result = pd.merge(dataSet3_off_result,t2,how='left',on='user_id')
# dataSet3_off_result = pd.merge(dataSet3_off_result,t3,how='left',on='user_id')
# dataSet3_off_result = pd.merge(dataSet3_off_result,t4,how='left',on='user_id')
# dataSet3_off_result = pd.merge(dataSet3_off_result,t5,how='left',on='user_id')
# dataSet3_off_result = pd.merge(dataSet3_off_result,t6,how='left',on='user_id')
# dataSet3_off_result = pd.merge(dataSet3_off_result,t7,how='left',on='user_id')
# dataSet3_off_result = pd.merge(dataSet3_off_result,t8,how='left',on='user_id')
# dataSet3_off_result = pd.merge(dataSet3_off_result,t9,how='left',on='user_id')
# dataSet3_off_result = pd.merge(dataSet3_off_result,t10,how='left',on='user_id')
#
# # 计算user_off_payisWeek出现次数最多的
# a = pd.Series(t10['user_off_payisWeek']).value_counts()
# if a[0]>a[1]:
# max = 0
# else:
# max = 1
# dataSet3_off_result.fillna({'user_off_payisWeek':max},inplace=True)
# dataSet3_off_result.fillna(0,inplace=True)
# dataSet3_off_result.to_csv('dataSet3_off_result.csv', index=None)
#
# # dataSet2
# # 用户领取优惠券的次数 user_off_couponReceive_count
# t = pd.DataFrame(dataSet2_off_feature2[['user_id', 'coupon_id', 'date_received']])
# t = t[(t['coupon_id'].notnull() == True) & (t['date_received'].notnull() == True)]
# t = pd.DataFrame(t['user_id'], columns=['user_id'])
# t['user_off_couponReceive_count'] = 1
# t = t.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 用户获得了优惠券没有使用的次数 user_off_coupon_notUse
# t1 = pd.DataFrame(dataSet2_off_feature2[['user_id', 'coupon_id', 'date_received', 'date']])
# t1 = t1[
# (t1['coupon_id'].notnull() == True) & (t1['date_received'].notnull() == True) & (t1['date'].isnull() == True)]
# t1 = pd.DataFrame(t['user_id'], columns=['user_id'])
# t1['user_off_coupon_notUse'] = 1
# t1 = t1.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 用户领取了优惠券使用的次数 user_off_coupon_use
# t2 = pd.DataFrame(dataSet2_off_feature2[['user_id', 'coupon_id', 'date_received', 'date']])
# t2 = t2[
# (t2['coupon_id'].notnull() == True) & (t2['date_received'].notnull() == True) & (t2['date'].isnull() == False)]
# t2 = pd.DataFrame(t['user_id'], columns=['user_id'])
# t2['user_off_coupon_use'] = 1
# t2 = t2.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 用户对于消费券的核销率 user_off_couponRate
# t3 = pd.merge(t, t2, how='left', on=['user_id'])
# t3['user_off_couponRate'] = round(t3['user_off_coupon_use'] / t3['user_off_couponReceive_count'], 4)
# t3 = pd.DataFrame(t3[['user_id', 'user_off_couponRate']], columns=['user_id', 'user_off_couponRate'])
#
# # 用户总的消费次数 user_off_buyTotal
# t4 = pd.DataFrame(dataSet2_off_feature2[['user_id', 'date']])
# t4 = t4[t4['date'].notnull() == True]
# t4 = pd.DataFrame(t4['user_id'], columns=['user_id'])
# t4['user_off_buyTotal'] = 1
# t4 = t4.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 用户使用优惠券消费占总消费的比重 user_off_useCoupon_rate
# t5 = pd.merge(t4, t2, how='left', on=['user_id'])
# t5['user_off_useCoupon_rate'] = round(t5['user_off_coupon_use'] / t5['user_off_buyTotal'], 4)
# t5 = pd.DataFrame(t5[['user_id', 'user_off_useCoupon_rate']], columns=['user_id', 'user_off_useCoupon_rate'])
#
# # 用户核销的消费券的平均折扣率 user_off_coupon_avgDiscount
# t6 = pd.DataFrame(dataSet2_off_feature2[['user_id', 'coupon_id', 'discount_rate', 'date_received']])
# t6 = t6[(t6['coupon_id'].notnull() == True) & (t6['date_received'].notnull() == True)]
# t6['user_off_coupon_avgDiscount'] = t6['discount_rate'].apply(cal_discount)
# t6 = pd.DataFrame(t6[['user_id', 'user_off_coupon_avgDiscount']],
# columns=['user_id', 'user_off_coupon_avgDiscount'])
# t6 = t6.groupby('user_id', sort=False).agg('mean').reset_index()
#
# # 用户使用消费券消费的商家的平均距离 user_off_merchant_avdDistance
# t7 = pd.DataFrame(dataSet2_off_feature2[['user_id', 'coupon_id', 'distance', 'date_received', 'date']])
# t7 = \
# t7[(t7['coupon_id'].notnull() == True) & (t7['date_received'].notnull() == True) & (t7['date'].notnull() == True)][
# ['user_id', 'distance']]
# t7 = t7.fillna(-1)
# t7['distance'] = t7['distance'].astype('int')
# t7 = t7.groupby('user_id', sort=False).agg('mean').reset_index()
# t7.rename(columns={'distance': 'user_off_merchant_avdDistance'}, inplace=True)
#
# # 用户使用了消费券的商家的数量 user_off_merchantUse_count
# t8 = pd.DataFrame(dataSet2_off_feature2[['user_id', 'merchant_id', 'coupon_id', 'date_received', 'date']])
# t8 = t8[
# (t8['coupon_id'].notnull() == True) & (t8['date_received'].notnull() == True) & (t8['date'].notnull() == True)]
# t8 = pd.DataFrame(t8[['user_id', 'merchant_id']], columns=['user_id', 'merchant_id']).drop_duplicates()
# t8['user_off_merchantUse_count'] = 1
# t8 = t8.groupby('user_id', sort=False).agg('sum').reset_index()
# t8 = pd.DataFrame(t8[['user_id', 'user_off_merchantUse_count']], columns=['user_id', 'user_off_merchantUse_count'])
#
# # 用户使用消费券的平均间隔 user_off_useCoupon_avgday
# t9 = pd.DataFrame(dataSet2_off_feature2[['user_id', 'coupon_id', 'date_received', 'date']])
# t9 = t9[
# (t9['coupon_id'].notnull() == True) & (t9['date_received'].notnull() == True) & (t9['date'].notnull() == True)]
# t9['user_off_useCoupon_avgday'] = t9['date'].apply(int) - t9['date_received'].apply(int)
# t9 = t9.groupby('user_id', sort=False).agg('mean').reset_index()
# t9 = pd.DataFrame(t9[['user_id', 'user_off_useCoupon_avgday']], columns=['user_id', 'user_off_useCoupon_avgday'])
#
# # 用户使用消费券是周末还是工作日居多 user_off_payisWeek
# t10 = pd.DataFrame(dataSet2_off_feature2[['user_id', 'coupon_id', 'date_received', 'date']])
# t10 = t10[(t10['coupon_id'].notnull() == True) & (t10['date_received'].notnull() == True) & (
# t10['date'].notnull() == True)]
# t10['user_off_payisWeek'] = t10['date'].apply(int).apply(isweek)
# t10 = t10.groupby('user_id', sort=False).agg('mean').reset_index()
# t10['user_off_payisWeek'] = t10['user_off_payisWeek'].apply(round)
# t10 = pd.DataFrame(t10[['user_id', 'user_off_payisWeek']], columns=['user_id', 'user_off_payisWeek'])
# # 合并数据
# left = dataSet2_off_feature2[['user_id']].drop_duplicates()
# dataSet2_off_result = pd.merge(left, t, how='left', on=['user_id'])
# dataSet2_off_result = pd.merge(dataSet2_off_result, t1, how='left', on='user_id')
# dataSet2_off_result = pd.merge(dataSet2_off_result, t2, how='left', on='user_id')
# dataSet2_off_result = pd.merge(dataSet2_off_result, t3, how='left', on='user_id')
# dataSet2_off_result = pd.merge(dataSet2_off_result, t4, how='left', on='user_id')
# dataSet2_off_result = pd.merge(dataSet2_off_result, t5, how='left', on='user_id')
# dataSet2_off_result = pd.merge(dataSet2_off_result, t6, how='left', on='user_id')
# dataSet2_off_result = pd.merge(dataSet2_off_result, t7, how='left', on='user_id')
# dataSet2_off_result = pd.merge(dataSet2_off_result, t8, how='left', on='user_id')
# dataSet2_off_result = pd.merge(dataSet2_off_result, t9, how='left', on='user_id')
# dataSet2_off_result = pd.merge(dataSet2_off_result, t10, how='left', on='user_id')
#
# # 计算user_off_payisWeek出现次数最多的
# a = pd.Series(t10['user_off_payisWeek']).value_counts()
# if a[0] > a[1]:
# max = 0
# else:
# max = 1
# dataSet2_off_result.fillna({'user_off_payisWeek': max}, inplace=True)
# dataSet2_off_result.fillna(0, inplace=True)
# dataSet2_off_result.to_csv('dataSet2_off_result.csv', index=None)
#
# # dataSet1
# # 用户领取优惠券的次数 user_off_couponReceive_count
# t = pd.DataFrame(dataSet1_off_feature1[['user_id', 'coupon_id', 'date_received']])
# t = t[(t['coupon_id'].notnull() == True) & (t['date_received'].notnull() == True)]
# t = pd.DataFrame(t['user_id'], columns=['user_id'])
# t['user_off_couponReceive_count'] = 1
# t = t.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 用户获得了优惠券没有使用的次数 user_off_coupon_notUse
# t1 = pd.DataFrame(dataSet1_off_feature1[['user_id', 'coupon_id', 'date_received', 'date']])
# t1 = t1[
# (t1['coupon_id'].notnull() == True) & (t1['date_received'].notnull() == True) & (t1['date'].isnull() == True)]
# t1 = pd.DataFrame(t['user_id'], columns=['user_id'])
# t1['user_off_coupon_notUse'] = 1
# t1 = t1.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 用户领取了优惠券使用的次数 user_off_coupon_use
# t2 = pd.DataFrame(dataSet1_off_feature1[['user_id', 'coupon_id', 'date_received', 'date']])
# t2 = t2[
# (t2['coupon_id'].notnull() == True) & (t2['date_received'].notnull() == True) & (t2['date'].isnull() == False)]
# t2 = pd.DataFrame(t['user_id'], columns=['user_id'])
# t2['user_off_coupon_use'] = 1
# t2 = t2.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 用户对于消费券的核销率 user_off_couponRate
# t3 = pd.merge(t, t2, how='left', on=['user_id'])
# t3['user_off_couponRate'] = round(t3['user_off_coupon_use'] / t3['user_off_couponReceive_count'], 4)
# t3 = pd.DataFrame(t3[['user_id', 'user_off_couponRate']], columns=['user_id', 'user_off_couponRate'])
#
# # 用户总的消费次数 user_off_buyTotal
# t4 = pd.DataFrame(dataSet1_off_feature1[['user_id', 'date']])
# t4 = t4[t4['date'].notnull() == True]
# t4 = pd.DataFrame(t4['user_id'], columns=['user_id'])
# t4['user_off_buyTotal'] = 1
# t4 = t4.groupby('user_id', sort=False).agg('sum').reset_index()
#
# # 用户使用优惠券消费占总消费的比重 user_off_useCoupon_rate
# t5 = pd.merge(t4, t2, how='left', on=['user_id'])
# t5['user_off_useCoupon_rate'] = round(t5['user_off_coupon_use'] / t5['user_off_buyTotal'], 4)
# t5 = pd.DataFrame(t5[['user_id', 'user_off_useCoupon_rate']], columns=['user_id', 'user_off_useCoupon_rate'])
#
# # 用户核销的消费券的平均折扣率 user_off_coupon_avgDiscount
# t6 = pd.DataFrame(dataSet1_off_feature1[['user_id', 'coupon_id', 'discount_rate', 'date_received']])
# t6 = t6[(t6['coupon_id'].notnull() == True) & (t6['date_received'].notnull() == True)]
# t6['user_off_coupon_avgDiscount'] = t6['discount_rate'].apply(cal_discount)
# t6 = pd.DataFrame(t6[['user_id', 'user_off_coupon_avgDiscount']],
# columns=['user_id', 'user_off_coupon_avgDiscount'])
# t6 = t6.groupby('user_id', sort=False).agg('mean').reset_index()
#
# # 用户使用消费券消费的商家的平均距离 user_off_merchant_avdDistance
# t7 = pd.DataFrame(dataSet1_off_feature1[['user_id', 'coupon_id', 'distance', 'date_received', 'date']])
# t7 = \
# t7[(t7['coupon_id'].notnull() == True) & (t7['date_received'].notnull() == True) & (t7['date'].notnull() == True)][
# ['user_id', 'distance']]
# t7 = t7.fillna(-1)
# t7['distance'] = t7['distance'].astype('int')
# t7 = t7.groupby('user_id', sort=False).agg('mean').reset_index()
# t7.rename(columns={'distance': 'user_off_merchant_avdDistance'}, inplace=True)
#
# # 用户使用了消费券的商家的数量 user_off_merchantUse_count
# t8 = pd.DataFrame(dataSet1_off_feature1[['user_id', 'merchant_id', 'coupon_id', 'date_received', 'date']])
# t8 = t8[
# (t8['coupon_id'].notnull() == True) & (t8['date_received'].notnull() == True) & (t8['date'].notnull() == True)]
# t8 = pd.DataFrame(t8[['user_id', 'merchant_id']], columns=['user_id', 'merchant_id']).drop_duplicates()
# t8['user_off_merchantUse_count'] = 1
# t8 = t8.groupby('user_id', sort=False).agg('sum').reset_index()
# t8 = pd.DataFrame(t8[['user_id', 'user_off_merchantUse_count']], columns=['user_id', 'user_off_merchantUse_count'])
#
# # 用户使用消费券的平均间隔 user_off_useCoupon_avgday
# t9 = pd.DataFrame(dataSet1_off_feature1[['user_id', 'coupon_id', 'date_received', 'date']])
# t9 = t9[
# (t9['coupon_id'].notnull() == True) & (t9['date_received'].notnull() == True) & (t9['date'].notnull() == True)]
# t9['user_off_useCoupon_avgday'] = t9['date'].apply(int) - t9['date_received'].apply(int)
# t9 = t9.groupby('user_id', sort=False).agg('mean').reset_index()
# t9 = pd.DataFrame(t9[['user_id', 'user_off_useCoupon_avgday']], columns=['user_id', 'user_off_useCoupon_avgday'])
#
# # 用户使用消费券是周末还是工作日居多 user_off_payisWeek
# t10 = pd.DataFrame(dataSet1_off_feature1[['user_id', 'coupon_id', 'date_received', 'date']])
# t10 = t10[(t10['coupon_id'].notnull() == True) & (t10['date_received'].notnull() == True) & (
# t10['date'].notnull() == True)]
# t10['user_off_payisWeek'] = t10['date'].apply(int).apply(isweek)
# t10 = t10.groupby('user_id', sort=False).agg('mean').reset_index()
# t10['user_off_payisWeek'] = t10['user_off_payisWeek'].apply(round)
# t10 = pd.DataFrame(t10[['user_id', 'user_off_payisWeek']], columns=['user_id', 'user_off_payisWeek'])
# # 合并数据
# left = dataSet1_off_feature1[['user_id']].drop_duplicates()
# dataSet1_off_result = pd.merge(left, t, how='left', on=['user_id'])
# dataSet1_off_result = pd.merge(dataSet1_off_result, t1, how='left', on='user_id')
# dataSet1_off_result = pd.merge(dataSet1_off_result, t2, how='left', on='user_id')
# dataSet1_off_result = pd.merge(dataSet1_off_result, t3, how='left', on='user_id')
# dataSet1_off_result = pd.merge(dataSet1_off_result, t4, how='left', on='user_id')
# dataSet1_off_result = pd.merge(dataSet1_off_result, t5, how='left', on='user_id')
# dataSet1_off_result = pd.merge(dataSet1_off_result, t6, how='left', on='user_id')
# dataSet1_off_result = pd.merge(dataSet1_off_result, t7, how='left', on='user_id')
# dataSet1_off_result = pd.merge(dataSet1_off_result, t8, how='left', on='user_id')
# dataSet1_off_result = pd.merge(dataSet1_off_result, t9, how='left', on='user_id')
# dataSet1_off_result = pd.merge(dataSet1_off_result, t10, how='left', on='user_id')
#
# # 计算user_off_payisWeek出现次数最多的
# a = pd.Series(t10['user_off_payisWeek']).value_counts()
# if a[0] > a[1]:
# max = 0
# else:
# max = 1
# dataSet1_off_result.fillna({'user_off_payisWeek': max}, inplace=True)
# dataSet1_off_result.fillna(0, inplace=True)
# dataSet1_off_result.to_csv('dataSet1_off_result.csv', index=None)
"""
商家相关的特征:
商家被消费的次数:merchant_buy_count
商家优惠券被领取的次数 merchant_coupon_receive
商家优惠券被使用的次数 merchant_coupon_use
商家优惠券没有被使用的次数 merchant_coupon_notUse
商家的消费券的类别的个数 merchant_coupon_kinds
商家被核销的消费券类别个数 merchant_couponUse_kinds
商家的消费券的平均折扣率 merchant_coupon_avgDiscount
商家的满减消费券的所需要的平均价格 merchant_coupon_avgManjian
商家满减优惠券满减的平均金额 merchant_coupon_avgPrice
商家满减优惠券的使用次数 merchant_manjian_useCount
直接优惠的优惠券使用次数 merchant_zhijie_useCount
商家的消费券从领取到消费经历的平均天数 merchant_avgDay
商家被核销的消费券到用户的平均距离 merchant_avgDistance
商家优惠券的使用率 merchant_coupon_useRate (merchant_coupon_use/merchant_coupon_receive)
商家满减优惠券的核销率 merchant_manjian_useRate ( merchant_manjian_useCount/merchant_coupon_use)
商家打折优惠券的核销率 merchant_zhijie_useRate (merchant_zhijie_useCount/merchant_coupon_use)
"""
# dataSet3
# 商家被消费的次数:merchant_buy_count
# t = pd.DataFrame(dataSet3_off_feature3[['merchant_id','date']])
# t = t[t['date'].notnull() == True]
# t = pd.DataFrame(t['merchant_id'], columns=['merchant_id'])
# t['merchant_buy_count'] = 1
# t = t.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家优惠券被领取的次数 merchant_coupon_receive
# t1 = pd.DataFrame(dataSet3_off_feature3[['merchant_id', 'coupon_id', 'date_received']])
# t1 = t1[(t1['coupon_id'].notnull() == True) & (t1['date_received'].notnull()==True)]
# t1 = pd.DataFrame(t1['merchant_id'], columns=['merchant_id'])
# t1['merchant_coupon_receive'] = 1
# t1 = t1.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家优惠券被使用的次数 merchant_coupon_use
# t2 = pd.DataFrame(dataSet3_off_feature3[['merchant_id', 'coupon_id', 'date_received', 'date']])
# t2 = t2[(t2['coupon_id'].notnull() == True) & (t2['date_received'].notnull()==True) & (t2['date'].notnull()==True)]
# t2 = pd.DataFrame(t2['merchant_id'], columns=['merchant_id'])
# t2['merchant_coupon_use'] = 1
# t2 = t2.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家优惠券没有被使用的次数 merchant_coupon_notUse
# t3 = pd.DataFrame(dataSet3_off_feature3[['merchant_id', 'coupon_id', 'date_received', 'date']])
# t3 = t3[(t3['coupon_id'].notnull() == True) & (t3['date_received'].notnull() == True) & (t3['date'].notnull() == False)]
# t3 = pd.DataFrame(t3['merchant_id'], columns=['merchant_id'])
# t3['merchant_coupon_notUse'] = 1
# t3 = t3.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家的消费券的类别的个数 merchant_coupon_kinds
# t4 = pd.DataFrame(dataSet3_off_feature3[['merchant_id', 'coupon_id']])
# t4 = t4[t4['coupon_id'].notnull() == True]
# t4 = t4.drop_duplicates()
# t4 = pd.DataFrame(t4['merchant_id'], columns=['merchant_id'])
# t4['merchant_coupon_kinds'] = 1
# t4 = t4.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家被核销的消费券类别个数 merchant_couponUse_kinds
# t5 = pd.DataFrame(dataSet3_off_feature3[['merchant_id', 'coupon_id','date']])
# t5 = t5[(t5['coupon_id'].notnull() == True) & (t5['date'].notnull()==True)]
# t5 = t5[['merchant_id','coupon_id']]
# t5 = t5.drop_duplicates()
# t5 = pd.DataFrame(t5['merchant_id'], columns=['merchant_id'])
# t5['merchant_couponUse_kinds'] = 1
# t5 = t5.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家的消费券的平均折扣率 merchant_coupon_avgDiscount
# def cal_discount(s):
# s = str(s)
# s = s.split(':')
# if len(s)==1:
# return float(s[0])
# else:
# return round(1.0 - float(s[1]) / float(s[0]),4)
#
# t6 = pd.DataFrame(dataSet3_off_feature3[['merchant_id', 'coupon_id','discount_rate']])
# t6 = t6[t6['coupon_id'].notnull() == True]
# t6['coupon_id'] = int(1)
# t6['discount_rate'] = t6['discount_rate'].apply(cal_discount)
# t6 = t6.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t6['merchant_coupon_avgDiscount'] = t6['discount_rate']/t6['coupon_id']
# t6 = pd.DataFrame(t6[['merchant_id','merchant_coupon_avgDiscount']],columns=['merchant_id','merchant_coupon_avgDiscount'])
#
# # 商家的满减消费券的所需要的平均价格 merchant_coupon_avgManjian
# def is_manjian(s):
# s = str(s)
# s = s.split(':')
# if len(s) == 1:
# return int(0)
# else:
# return int(s[0])
# t7 = pd.DataFrame(dataSet3_off_feature3[['merchant_id', 'coupon_id','discount_rate']])
# t7['discount_rate'] = t7['discount_rate'].apply(is_manjian)
# t7 = t7[(t7['coupon_id'].notnull() == True) & (t7['discount_rate']!=0)]
# t7['coupon_id'] = int(1)
# t7 = t7.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t7['merchant_coupon_avgManjian'] = round(t7['discount_rate'] / t7['coupon_id'],4)
# t7 = pd.DataFrame(t7[['merchant_id', 'merchant_coupon_avgManjian']],columns=['merchant_id', 'merchant_coupon_avgManjian'])
#
# # 商家满减优惠券满减的平均金额 merchant_coupon_avgPrice
# def manjian(s):
# s = str(s)
# s = s.split(':')
# if len(s) == 1:
# return int(0)
# else:
# return int(s[1])
# t8 = pd.DataFrame(dataSet3_off_feature3[['merchant_id', 'coupon_id', 'discount_rate']])
# t8['discount_rate'] = t8['discount_rate'].apply(manjian)
# t8 = t8[(t8['coupon_id'].notnull() == True) & (t8['discount_rate'] != 0)]
# t8['coupon_id'] = int(1)
# t8 = t8.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t8['merchant_coupon_avgPrice'] = round(t8['discount_rate'] / t8['coupon_id'], 4)
# t8 = pd.DataFrame(t8[['merchant_id', 'merchant_coupon_avgPrice']],columns=['merchant_id', 'merchant_coupon_avgPrice'])
#
# # 商家满减优惠券的使用次数 merchant_manjian_useCount
# def classify(s): # 直接优惠记为0,满减记为1
# s = str(s)
# s = s.split(':')
# if len(s) == 1:
# return 0
# else:
# return 1
#
#
# t9 = pd.DataFrame(dataSet3_off_feature3[['merchant_id', 'coupon_id', 'discount_rate', 'date']])
# t9['discount_rate'] = t9['discount_rate'].apply(classify)
# # 满减优惠券使用次数
# t9 = t9[(t9['coupon_id'].notnull() == True) & (t9['discount_rate'] == 1) & (t9['date'].notnull()==True)]
# t9['merchant_manjian_useCount'] = 1
# t9 = t9.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t9 = pd.DataFrame(t9[['merchant_id', 'merchant_manjian_useCount']],columns=['merchant_id', 'merchant_manjian_useCount'])
#
# # 直接优惠的优惠券使用次数 merchant_zhijie_useCount
# t10 = pd.DataFrame(dataSet3_off_feature3[['merchant_id', 'coupon_id', 'discount_rate', 'date']])
# t10['discount_rate'] = t10['discount_rate'].apply(classify)
# t10 = t10[(t10['coupon_id'].notnull() == True) & (t10['discount_rate'] == 0) & (t10['date'].notnull() == True)]
# t10['merchant_zhijie_useCount'] = 1
# t10 = t10.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t10 = pd.DataFrame(t10[['merchant_id', 'merchant_zhijie_useCount']],columns=['merchant_id', 'merchant_zhijie_useCount'])
#
# # 商家的消费券从领取到消费经历的平均天数 merchant_avgDay
# t11 = pd.DataFrame(dataSet3_off_feature3[['merchant_id', 'coupon_id', 'date_received', 'date']])
# t11 = t11[(t11['coupon_id'].notnull() == True) & (t11['date_received'].notnull()==True) & (t11['date'].notnull() == True)]
# t11['merchant_avgDay'] = t11['date']-t11['date_received']
# t11['coupon_id'] = 1
# t11 = t11.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t11['merchant_avgDay'] = round(t11['merchant_avgDay']/t11['coupon_id'],4)
# t11 = pd.DataFrame(t11[['merchant_id', 'merchant_avgDay']],columns=['merchant_id', 'merchant_avgDay'])
#
# # 商家被核销的消费券到用户的平均距离 merchant_avgDistance
# t12 = pd.DataFrame(dataSet3_off_feature3[['merchant_id', 'coupon_id', 'distance','date']])
# t12 = t12[(t12['coupon_id'].notnull() == True) & (t12['date'].notnull() == True)][['merchant_id','distance']]
# t12 = t12.fillna(-1)
# t12['distance'] = t12['distance'].astype('int')
# t12 = t12.groupby('merchant_id').agg('mean').reset_index()
# t12.rename(columns={'distance': 'merchant_avgDistance'}, inplace=True)
#
# # 合并数据
# left = dataSet3_off_feature3[['merchant_id']].drop_duplicates()
# dataSet3_off_result = pd.merge(left,t,how='left',on=['merchant_id'])
# dataSet3_off_result = pd.merge(dataSet3_off_result,t1,how='left',on=['merchant_id'])
# dataSet3_off_result = pd.merge(dataSet3_off_result,t2,how='left',on=['merchant_id'])
# dataSet3_off_result = pd.merge(dataSet3_off_result,t3,how='left',on=['merchant_id'])
# dataSet3_off_result = pd.merge(dataSet3_off_result,t4,how='left',on=['merchant_id'])
# dataSet3_off_result = pd.merge(dataSet3_off_result,t5,how='left',on=['merchant_id'])
# dataSet3_off_result = pd.merge(dataSet3_off_result,t6,how='left',on=['merchant_id'])
# dataSet3_off_result = pd.merge(dataSet3_off_result,t7,how='left',on=['merchant_id'])
# dataSet3_off_result = pd.merge(dataSet3_off_result,t8,how='left',on=['merchant_id'])
# dataSet3_off_result = pd.merge(dataSet3_off_result,t9,how='left',on=['merchant_id'])
# dataSet3_off_result = pd.merge(dataSet3_off_result,t10,how='left',on=['merchant_id'])
# dataSet3_off_result = pd.merge(dataSet3_off_result,t11,how='left',on=['merchant_id'])
# dataSet3_off_result = pd.merge(dataSet3_off_result,t12,how='left',on=['merchant_id'])
#
# #填充Nan值
# for i in dataSet3_off_result.columns:
# meanVal = dataSet3_off_result[i].mean()
# dataSet3_off_result[i].fillna(meanVal,inplace=True)
#
# # 商家优惠券的使用率 merchant_coupon_useRate (merchant_coupon_use/merchant_coupon_receive)
# dataSet3_off_result['merchant_coupon_useRate'] = round(
# dataSet3_off_result['merchant_coupon_use']/dataSet3_off_result['merchant_coupon_receive'],4)
#
# # 商家满减优惠券的核销率 merchant_manjian_useRate ( merchant_manjian_useCount/merchant_coupon_use)
# dataSet3_off_result['merchant_manjian_useRate'] = round(
# dataSet3_off_result['merchant_manjian_useCount'] / dataSet3_off_result['merchant_coupon_use'], 4)
#
# # 商家打折优惠券的核销率 merchant_zhijie_useRate (merchant_zhijie_useCount/merchant_coupon_use)
# dataSet3_off_result['merchant_zhijie_useRate'] = round(
# dataSet3_off_result['merchant_zhijie_useCount'] / dataSet3_off_result['merchant_coupon_use'], 4)
#
# dataSet3_off_result.to_csv('dataSet3_off_merchant_feature.csv', index=None)
# dataSet2
# 商家被消费的次数:merchant_buy_count
# t = pd.DataFrame(dataSet2_off_feature2[['merchant_id','date']])
# t = t[t['date'].notnull() == True]
# t = pd.DataFrame(t['merchant_id'], columns=['merchant_id'])
# t['merchant_buy_count'] = 1
# t = t.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家优惠券被领取的次数 merchant_coupon_receive
# t1 = pd.DataFrame(dataSet2_off_feature2[['merchant_id', 'coupon_id', 'date_received']])
# t1 = t1[(t1['coupon_id'].notnull() == True) & (t1['date_received'].notnull()==True)]
# t1 = pd.DataFrame(t1['merchant_id'], columns=['merchant_id'])
# t1['merchant_coupon_receive'] = 1
# t1 = t1.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家优惠券被使用的次数 merchant_coupon_use
# t2 = pd.DataFrame(dataSet2_off_feature2[['merchant_id', 'coupon_id', 'date_received', 'date']])
# t2 = t2[(t2['coupon_id'].notnull() == True) & (t2['date_received'].notnull()==True) & (t2['date'].notnull()==True)]
# t2 = pd.DataFrame(t2['merchant_id'], columns=['merchant_id'])
# t2['merchant_coupon_use'] = 1
# t2 = t2.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家优惠券没有被使用的次数 merchant_coupon_notUse
# t3 = pd.DataFrame(dataSet2_off_feature2[['merchant_id', 'coupon_id', 'date_received', 'date']])
# t3 = t3[(t3['coupon_id'].notnull() == True) & (t3['date_received'].notnull() == True) & (t3['date'].notnull() == False)]
# t3 = pd.DataFrame(t3['merchant_id'], columns=['merchant_id'])
# t3['merchant_coupon_notUse'] = 1
# t3 = t3.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家的消费券的类别的个数 merchant_coupon_kinds
# t4 = pd.DataFrame(dataSet2_off_feature2[['merchant_id', 'coupon_id']])
# t4 = t4[t4['coupon_id'].notnull() == True]
# t4 = t4.drop_duplicates()
# t4 = pd.DataFrame(t4['merchant_id'], columns=['merchant_id'])
# t4['merchant_coupon_kinds'] = 1
# t4 = t4.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家被核销的消费券类别个数 merchant_couponUse_kinds
# t5 = pd.DataFrame(dataSet2_off_feature2[['merchant_id', 'coupon_id','date']])
# t5 = t5[(t5['coupon_id'].notnull() == True) & (t5['date'].notnull()==True)]
# t5 = t5[['merchant_id','coupon_id']]
# t5 = t5.drop_duplicates()
# t5 = pd.DataFrame(t5['merchant_id'], columns=['merchant_id'])
# t5['merchant_couponUse_kinds'] = 1
# t5 = t5.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家的消费券的平均折扣率 merchant_coupon_avgDiscount
# def cal_discount(s):
# s = str(s)
# s = s.split(':')
# if len(s)==1:
# return float(s[0])
# else:
# return round(1.0 - float(s[1]) / float(s[0]),4)
#
# t6 = pd.DataFrame(dataSet2_off_feature2[['merchant_id', 'coupon_id','discount_rate']])
# t6 = t6[t6['coupon_id'].notnull() == True]
# t6['coupon_id'] = int(1)
# t6['discount_rate'] = t6['discount_rate'].apply(cal_discount)
# t6 = t6.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t6['merchant_coupon_avgDiscount'] = t6['discount_rate']/t6['coupon_id']
# t6 = pd.DataFrame(t6[['merchant_id','merchant_coupon_avgDiscount']],columns=['merchant_id','merchant_coupon_avgDiscount'])
#
# # 商家的满减消费券的所需要的平均价格 merchant_coupon_avgManjian
# def is_manjian(s):
# s = str(s)
# s = s.split(':')
# if len(s) == 1:
# return int(0)
# else:
# return int(s[0])
# t7 = pd.DataFrame(dataSet2_off_feature2[['merchant_id', 'coupon_id','discount_rate']])
# t7['discount_rate'] = t7['discount_rate'].apply(is_manjian)
# t7 = t7[(t7['coupon_id'].notnull() == True) & (t7['discount_rate']!=0)]
# t7['coupon_id'] = int(1)
# t7 = t7.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t7['merchant_coupon_avgManjian'] = round(t7['discount_rate'] / t7['coupon_id'],4)
# t7 = pd.DataFrame(t7[['merchant_id', 'merchant_coupon_avgManjian']],columns=['merchant_id', 'merchant_coupon_avgManjian'])
#
# # 商家满减优惠券满减的平均金额 merchant_coupon_avgPrice
# def manjian(s):
# s = str(s)
# s = s.split(':')
# if len(s) == 1:
# return int(0)
# else:
# return int(s[1])
# t8 = pd.DataFrame(dataSet2_off_feature2[['merchant_id', 'coupon_id', 'discount_rate']])
# t8['discount_rate'] = t8['discount_rate'].apply(manjian)
# t8 = t8[(t8['coupon_id'].notnull() == True) & (t8['discount_rate'] != 0)]
# t8['coupon_id'] = int(1)
# t8 = t8.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t8['merchant_coupon_avgPrice'] = round(t8['discount_rate'] / t8['coupon_id'], 4)
# t8 = pd.DataFrame(t8[['merchant_id', 'merchant_coupon_avgPrice']],columns=['merchant_id', 'merchant_coupon_avgPrice'])
#
# # 商家满减优惠券的使用次数 merchant_manjian_useCount
# def classify(s): # 直接优惠记为0,满减记为1
# s = str(s)
# s = s.split(':')
# if len(s) == 1:
# return 0
# else:
# return 1
#
#
# t9 = pd.DataFrame(dataSet2_off_feature2[['merchant_id', 'coupon_id', 'discount_rate', 'date']])
# t9['discount_rate'] = t9['discount_rate'].apply(classify)
# # 满减优惠券使用次数
# t9 = t9[(t9['coupon_id'].notnull() == True) & (t9['discount_rate'] == 1) & (t9['date'].notnull()==True)]
# t9['merchant_manjian_useCount'] = 1
# t9 = t9.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t9 = pd.DataFrame(t9[['merchant_id', 'merchant_manjian_useCount']],columns=['merchant_id', 'merchant_manjian_useCount'])
#
# # 直接优惠的优惠券使用次数 merchant_zhijie_useCount
# t10 = pd.DataFrame(dataSet2_off_feature2[['merchant_id', 'coupon_id', 'discount_rate', 'date']])
# t10['discount_rate'] = t10['discount_rate'].apply(classify)
# t10 = t10[(t10['coupon_id'].notnull() == True) & (t10['discount_rate'] == 0) & (t10['date'].notnull() == True)]
# t10['merchant_zhijie_useCount'] = 1
# t10 = t10.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t10 = pd.DataFrame(t10[['merchant_id', 'merchant_zhijie_useCount']],columns=['merchant_id', 'merchant_zhijie_useCount'])
#
# # 商家的消费券从领取到消费经历的平均天数 merchant_avgDay
# t11 = pd.DataFrame(dataSet2_off_feature2[['merchant_id', 'coupon_id', 'date_received', 'date']])
# t11 = t11[(t11['coupon_id'].notnull() == True) & (t11['date_received'].notnull()==True) & (t11['date'].notnull() == True)]
# t11['merchant_avgDay'] = t11['date']-t11['date_received']
# t11['coupon_id'] = 1
# t11 = t11.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t11['merchant_avgDay'] = round(t11['merchant_avgDay']/t11['coupon_id'],4)
# t11 = pd.DataFrame(t11[['merchant_id', 'merchant_avgDay']],columns=['merchant_id', 'merchant_avgDay'])
#
# # 商家被核销的消费券到用户的平均距离 merchant_avgDistance
# t12 = pd.DataFrame(dataSet2_off_feature2[['merchant_id', 'coupon_id', 'distance','date']])
# t12 = t12[(t12['coupon_id'].notnull() == True) & (t12['date'].notnull() == True)][['merchant_id','distance']]
# t12 = t12.fillna(-1)
# t12['distance'] = t12['distance'].astype('int')
# t12 = t12.groupby('merchant_id').agg('mean').reset_index()
# t12.rename(columns={'distance': 'merchant_avgDistance'}, inplace=True)
#
# # 合并数据
# left = dataSet2_off_feature2[['merchant_id']].drop_duplicates()
# dataSet2_off_result = pd.merge(left,t,how='left',on=['merchant_id'])
# dataSet2_off_result = pd.merge(dataSet2_off_result,t1,how='left',on=['merchant_id'])
# dataSet2_off_result = pd.merge(dataSet2_off_result,t2,how='left',on=['merchant_id'])
# dataSet2_off_result = pd.merge(dataSet2_off_result,t3,how='left',on=['merchant_id'])
# dataSet2_off_result = pd.merge(dataSet2_off_result,t4,how='left',on=['merchant_id'])
# dataSet2_off_result = pd.merge(dataSet2_off_result,t5,how='left',on=['merchant_id'])
# dataSet2_off_result = pd.merge(dataSet2_off_result,t6,how='left',on=['merchant_id'])
# dataSet2_off_result = pd.merge(dataSet2_off_result,t7,how='left',on=['merchant_id'])
# dataSet2_off_result = pd.merge(dataSet2_off_result,t8,how='left',on=['merchant_id'])
# dataSet2_off_result = pd.merge(dataSet2_off_result,t9,how='left',on=['merchant_id'])
# dataSet2_off_result = pd.merge(dataSet2_off_result,t10,how='left',on=['merchant_id'])
# dataSet2_off_result = pd.merge(dataSet2_off_result,t11,how='left',on=['merchant_id'])
# dataSet2_off_result = pd.merge(dataSet2_off_result,t12,how='left',on=['merchant_id'])
#
# #填充Nan值
# for i in dataSet2_off_result.columns:
# meanVal = dataSet2_off_result[i].mean()
# dataSet2_off_result[i].fillna(meanVal,inplace=True)
#
# # 商家优惠券的使用率 merchant_coupon_useRate (merchant_coupon_use/merchant_coupon_receive)
# dataSet2_off_result['merchant_coupon_useRate'] = round(
# dataSet2_off_result['merchant_coupon_use']/dataSet2_off_result['merchant_coupon_receive'],4)
#
# # 商家满减优惠券的核销率 merchant_manjian_useRate ( merchant_manjian_useCount/merchant_coupon_use)
# dataSet2_off_result['merchant_manjian_useRate'] = round(
# dataSet2_off_result['merchant_manjian_useCount'] / dataSet2_off_result['merchant_coupon_use'], 4)
#
# # 商家打折优惠券的核销率 merchant_zhijie_useRate (merchant_zhijie_useCount/merchant_coupon_use)
# dataSet2_off_result['merchant_zhijie_useRate'] = round(
# dataSet2_off_result['merchant_zhijie_useCount'] / dataSet2_off_result['merchant_coupon_use'], 4)
#
# dataSet2_off_result.to_csv('dataSet2_off_merchant_feature.csv', index=None)
# dataSet1
# 商家被消费的次数:merchant_buy_count
# t = pd.DataFrame(dataSet1_off_feature1[['merchant_id','date']])
# t = t[t['date'].notnull() == True]
# t = pd.DataFrame(t['merchant_id'], columns=['merchant_id'])
# t['merchant_buy_count'] = 1
# t = t.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家优惠券被领取的次数 merchant_coupon_receive
# t1 = pd.DataFrame(dataSet1_off_feature1[['merchant_id', 'coupon_id', 'date_received']])
# t1 = t1[(t1['coupon_id'].notnull() == True) & (t1['date_received'].notnull()==True)]
# t1 = pd.DataFrame(t1['merchant_id'], columns=['merchant_id'])
# t1['merchant_coupon_receive'] = 1
# t1 = t1.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家优惠券被使用的次数 merchant_coupon_use
# t2 = pd.DataFrame(dataSet1_off_feature1[['merchant_id', 'coupon_id', 'date_received', 'date']])
# t2 = t2[(t2['coupon_id'].notnull() == True) & (t2['date_received'].notnull()==True) & (t2['date'].notnull()==True)]
# t2 = pd.DataFrame(t2['merchant_id'], columns=['merchant_id'])
# t2['merchant_coupon_use'] = 1
# t2 = t2.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家优惠券没有被使用的次数 merchant_coupon_notUse
# t3 = pd.DataFrame(dataSet1_off_feature1[['merchant_id', 'coupon_id', 'date_received', 'date']])
# t3 = t3[(t3['coupon_id'].notnull() == True) & (t3['date_received'].notnull() == True) & (t3['date'].notnull() == False)]
# t3 = pd.DataFrame(t3['merchant_id'], columns=['merchant_id'])
# t3['merchant_coupon_notUse'] = 1
# t3 = t3.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家的消费券的类别的个数 merchant_coupon_kinds
# t4 = pd.DataFrame(dataSet1_off_feature1[['merchant_id', 'coupon_id']])
# t4 = t4[t4['coupon_id'].notnull() == True]
# t4 = t4.drop_duplicates()
# t4 = pd.DataFrame(t4['merchant_id'], columns=['merchant_id'])
# t4['merchant_coupon_kinds'] = 1
# t4 = t4.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家被核销的消费券类别个数 merchant_couponUse_kinds
# t5 = pd.DataFrame(dataSet1_off_feature1[['merchant_id', 'coupon_id','date']])
# t5 = t5[(t5['coupon_id'].notnull() == True) & (t5['date'].notnull()==True)]
# t5 = t5[['merchant_id','coupon_id']]
# t5 = t5.drop_duplicates()
# t5 = pd.DataFrame(t5['merchant_id'], columns=['merchant_id'])
# t5['merchant_couponUse_kinds'] = 1
# t5 = t5.groupby('merchant_id', sort=False).agg('sum').reset_index()
#
# # 商家的消费券的平均折扣率 merchant_coupon_avgDiscount
# t6 = pd.DataFrame(dataSet1_off_feature1[['merchant_id', 'coupon_id','discount_rate']])
# t6 = t6[t6['coupon_id'].notnull() == True]
# t6['coupon_id'] = int(1)
# t6['discount_rate'] = t6['discount_rate'].apply(cal_discount)
# t6 = t6.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t6['merchant_coupon_avgDiscount'] = t6['discount_rate']/t6['coupon_id']
# t6 = pd.DataFrame(t6[['merchant_id','merchant_coupon_avgDiscount']],columns=['merchant_id','merchant_coupon_avgDiscount'])
#
# # 商家的满减消费券的所需要的平均价格 merchant_coupon_avgManjian
# def is_manjian(s):
# s = str(s)
# s = s.split(':')
# if len(s) == 1:
# return int(0)
# else:
# return int(s[0])
# t7 = pd.DataFrame(dataSet1_off_feature1[['merchant_id', 'coupon_id','discount_rate']])
# t7['discount_rate'] = t7['discount_rate'].apply(is_manjian)
# t7 = t7[(t7['coupon_id'].notnull() == True) & (t7['discount_rate']!=0)]
# t7['coupon_id'] = int(1)
# t7 = t7.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t7['merchant_coupon_avgManjian'] = round(t7['discount_rate'] / t7['coupon_id'],4)
# t7 = pd.DataFrame(t7[['merchant_id', 'merchant_coupon_avgManjian']],columns=['merchant_id', 'merchant_coupon_avgManjian'])
#
# # 商家满减优惠券满减的平均金额 merchant_coupon_avgPrice
# def manjian(s):
# s = str(s)
# s = s.split(':')
# if len(s) == 1:
# return int(0)
# else:
# return int(s[1])
# t8 = pd.DataFrame(dataSet1_off_feature1[['merchant_id', 'coupon_id', 'discount_rate']])
# t8['discount_rate'] = t8['discount_rate'].apply(manjian)
# t8 = t8[(t8['coupon_id'].notnull() == True) & (t8['discount_rate'] != 0)]
# t8['coupon_id'] = int(1)
# t8 = t8.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t8['merchant_coupon_avgPrice'] = round(t8['discount_rate'] / t8['coupon_id'], 4)
# t8 = pd.DataFrame(t8[['merchant_id', 'merchant_coupon_avgPrice']],columns=['merchant_id', 'merchant_coupon_avgPrice'])
#
# # 商家满减优惠券的使用次数 merchant_manjian_useCount
#
#
# t9 = pd.DataFrame(dataSet1_off_feature1[['merchant_id', 'coupon_id', 'discount_rate', 'date']])
# t9['discount_rate'] = t9['discount_rate'].apply(classify)
# # 满减优惠券使用次数
# t9 = t9[(t9['coupon_id'].notnull() == True) & (t9['discount_rate'] == 1) & (t9['date'].notnull()==True)]
# t9['merchant_manjian_useCount'] = 1
# t9 = t9.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t9 = pd.DataFrame(t9[['merchant_id', 'merchant_manjian_useCount']],columns=['merchant_id', 'merchant_manjian_useCount'])
#
# # 直接优惠的优惠券使用次数 merchant_zhijie_useCount
# t10 = pd.DataFrame(dataSet1_off_feature1[['merchant_id', 'coupon_id', 'discount_rate', 'date']])
# t10['discount_rate'] = t10['discount_rate'].apply(classify)
# t10 = t10[(t10['coupon_id'].notnull() == True) & (t10['discount_rate'] == 0) & (t10['date'].notnull() == True)]
# t10['merchant_zhijie_useCount'] = 1
# t10 = t10.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t10 = pd.DataFrame(t10[['merchant_id', 'merchant_zhijie_useCount']],columns=['merchant_id', 'merchant_zhijie_useCount'])
#
# # 商家的消费券从领取到消费经历的平均天数 merchant_avgDay
# t11 = pd.DataFrame(dataSet1_off_feature1[['merchant_id', 'coupon_id', 'date_received', 'date']])
# t11 = t11[(t11['coupon_id'].notnull() == True) & (t11['date_received'].notnull()==True) & (t11['date'].notnull() == True)]
# t11['merchant_avgDay'] = t11['date']-t11['date_received']
# t11['coupon_id'] = 1
# t11 = t11.groupby('merchant_id', sort=False).agg('sum').reset_index()
# t11['merchant_avgDay'] = round(t11['merchant_avgDay']/t11['coupon_id'],4)
# t11 = pd.DataFrame(t11[['merchant_id', 'merchant_avgDay']],columns=['merchant_id', 'merchant_avgDay'])
#
# # 商家被核销的消费券到用户的平均距离 merchant_avgDistance
# t12 = pd.DataFrame(dataSet1_off_feature1[['merchant_id', 'coupon_id', 'distance','date']])
# t12 = t12[(t12['coupon_id'].notnull() == True) & (t12['date'].notnull() == True)][['merchant_id','distance']]
# t12 = t12.fillna(-1)
# t12['distance'] = t12['distance'].astype('int')
# t12 = t12.groupby('merchant_id').agg('mean').reset_index()
# t12.rename(columns={'distance': 'merchant_avgDistance'}, inplace=True)
#
# # 合并数据
# left = dataSet1_off_feature1[['merchant_id']].drop_duplicates()
# dataSet1_off_result = pd.merge(left,t,how='left',on=['merchant_id'])
# dataSet1_off_result = pd.merge(dataSet1_off_result,t1,how='left',on=['merchant_id'])
# dataSet1_off_result = pd.merge(dataSet1_off_result,t2,how='left',on=['merchant_id'])
# dataSet1_off_result = pd.merge(dataSet1_off_result,t3,how='left',on=['merchant_id'])
# dataSet1_off_result = pd.merge(dataSet1_off_result,t4,how='left',on=['merchant_id'])
# dataSet1_off_result = pd.merge(dataSet1_off_result,t5,how='left',on=['merchant_id'])
# dataSet1_off_result = pd.merge(dataSet1_off_result,t6,how='left',on=['merchant_id'])
# dataSet1_off_result = pd.merge(dataSet1_off_result,t7,how='left',on=['merchant_id'])
# dataSet1_off_result = pd.merge(dataSet1_off_result,t8,how='left',on=['merchant_id'])
# dataSet1_off_result = pd.merge(dataSet1_off_result,t9,how='left',on=['merchant_id'])
# dataSet1_off_result = pd.merge(dataSet1_off_result,t10,how='left',on=['merchant_id'])
# dataSet1_off_result = pd.merge(dataSet1_off_result,t11,how='left',on=['merchant_id'])
# dataSet1_off_result = pd.merge(dataSet1_off_result,t12,how='left',on=['merchant_id'])
#
# #填充Nan值
# for i in dataSet1_off_result.columns:
# meanVal = dataSet1_off_result[i].mean()
# dataSet1_off_result[i].fillna(meanVal,inplace=True)
#
# # 商家优惠券的使用率 merchant_coupon_useRate (merchant_coupon_use/merchant_coupon_receive)
# dataSet1_off_result['merchant_coupon_useRate'] = round(
# dataSet1_off_result['merchant_coupon_use']/dataSet1_off_result['merchant_coupon_receive'],4)
#
# # 商家满减优惠券的核销率 merchant_manjian_useRate ( merchant_manjian_useCount/merchant_coupon_use)
# dataSet1_off_result['merchant_manjian_useRate'] = round(
# dataSet1_off_result['merchant_manjian_useCount'] / dataSet1_off_result['merchant_coupon_use'], 4)
#
# # 商家打折优惠券的核销率 merchant_zhijie_useRate (merchant_zhijie_useCount/merchant_coupon_use)
# dataSet1_off_result['merchant_zhijie_useRate'] = round(
# dataSet1_off_result['merchant_zhijie_useCount'] / dataSet1_off_result['merchant_coupon_use'], 4)
#
# dataSet1_off_result.to_csv('dataSet1_off_merchant_feature.csv', index=None)
"""
优惠券特征:
消费券的类型 coupon_kind 直接优惠记为0,满减记为1
消费券的打折力度 coupon_discount
消费券被用户领取的次数 coupon_receive_byUser
消费券被用户消费的次数 coupon_use_byUser
消费券被用户领取到消费经历的平均天数 coupon_avgDay
消费券拥有的商家数 coupon_merchant_count
消费券15天内被使用的占比 coupon_day_rate
消费券被领取一般是周末还是工作日 coupon_receive_isweek
消费券被消费一般是周末还是工作日 coupon_used_isweek
"""
# for dataSet3
# 消费券的类型 coupon_kind
# t = pd.DataFrame(dataSet3_off_feature3[['coupon_id', 'discount_rate']])
# t = t[t['discount_rate'].notnull() == True]
# t['discount_rate'] = t['discount_rate'].apply(classify)
# t = t.drop_duplicates()
# t.rename(columns={'discount_rate': 'coupon_kind '}, inplace=True)
#
# # 消费券的打折力度 coupon_discount
# t1 = pd.DataFrame(dataSet3_off_feature3[['coupon_id', 'discount_rate']])
# t1 = t1[t1['discount_rate'].notnull() == True]
# t1['discount_rate'] = t1['discount_rate'].apply(cal_discount)
# t1 = t1.drop_duplicates()
# t1.rename(columns={'discount_rate': 'coupon_discount '}, inplace=True)
#
# # 消费券被用户领取的次数 coupon_receive_byUser
# t2 = pd.DataFrame(dataSet3_off_feature3[['coupon_id', 'date_received']])
# t2 = t2[(t2['coupon_id'].notnull()==True) & (t2['date_received'].notnull() == True)]
# t2['date_received'] = 1
# t2 = t2.groupby('coupon_id').agg('sum').reset_index()
# t2.rename(columns={'date_received': 'coupon_receive_byUser'}, inplace=True)
#
# # 消费券被用户消费的次数 coupon_use_byUser
# t3 = pd.DataFrame(dataSet3_off_feature3[['coupon_id', 'date_received','date']])
# t3 = t3[(t3['coupon_id'].notnull() == True) & (t3['date_received'].notnull() == True) & (t3['date'].notnull() == True)]
# t3['date_received'] = 1
# t3 = t3.groupby('coupon_id').agg('sum').reset_index()
# t3 = pd.DataFrame(t3[['coupon_id','date_received']],columns=['coupon_id','date_received'])
# t3.rename(columns={'date_received': 'coupon_use_byUser'}, inplace=True)
#
# # 消费券被用户领取到消费经历的平均天数 coupon_avgDay
# t4 = pd.DataFrame(dataSet3_off_feature3[['coupon_id','date_received','date']])
# t4 = t4[(t4['coupon_id'].notnull() == True) & (t4['date_received'].notnull() == True) & (t4['date'].notnull() == True)]
# t4['coupon_avgDay'] = t4['date'] - t4['date_received']
# t4 = t4.groupby('coupon_id',sort=False).agg('mean').reset_index()
# t4 = pd.DataFrame(t4[['coupon_id','coupon_avgDay']],columns=['coupon_id','coupon_angDay'])
#
# # 消费券拥有的商家数 coupon_merchant_count
# t5 = pd.DataFrame(dataSet3_off_feature3[['coupon_id', 'merchant_id']])
# t5 = t5[t5['coupon_id'].notnull() == True].drop_duplicates()[['coupon_id']]
# t5['coupon_merchant_count'] = 1
# t5 = t5.groupby('coupon_id', sort=False).agg('sum').reset_index()
#
# # 消费券15天内被使用的占比 coupon_day_rate
# t6 = pd.DataFrame(dataSet3_off_feature3[['coupon_id', 'date_received','date']])
# t6 = t6[(t6['coupon_id'].notnull() == True) & (t6['date'].notnull() == True) & (t6['date_received'].notnull() == True)]
# t6['spend_day'] = t6['date'] - t6['date_received']
# t6_1 = t6[t6['spend_day']<15.0][['coupon_id','spend_day']]
# t6_1['spend_day'] = 1
# t6_1 = t6_1.groupby('coupon_id',sort=False).agg('sum').reset_index()
# t6_1.rename(columns={'spend_day': 'daymin'}, inplace=True)
# t6_2 = pd.DataFrame(t6[['coupon_id','spend_day']],columns=['coupon_id','spend_day'])
# t6_2['spend_day'] = 1
# t6_2 = t6_2.groupby('coupon_id',sort=False).agg('sum').reset_index()
# t6_2.rename(columns={'spend_day': 'total_day'}, inplace=True)
# t6 = pd.merge(t6_1,t6_2,how='left',on=['coupon_id'])
# t6['coupon_day_rate'] = round(t6['daymin']/t6['total_day'],4)
# t6 = pd.DataFrame(t6[['coupon_id','coupon_day_rate']],columns=['coupon_id','coupon_day_rate'])
#
# # 消费券被领取一般是周末还是工作日 coupon_receive_isweek
# def isweek(s):
# s = str(s)
# week = datetime.strptime(s,'%Y%m%d').weekday()+1
# if week==5 or week==6 or week==7:
# return 1
# else:
# return 0
#
# t7 = pd.DataFrame(dataSet3_off_feature3[['coupon_id', 'date_received']])
# t7 = t7[(t7['coupon_id'].notnull() == True) & (t7['date_received'].notnull() == True)]
# t7['coupon_receive_isweek'] = t7['date_received'].apply(int).apply(isweek)
# t7 = pd.DataFrame(t7[['coupon_id', 'coupon_receive_isweek']], columns=['coupon_id', 'coupon_receive_isweek']).drop_duplicates()
#
# # 消费券被消费一般是周末还是工作日 coupon_used_isweek
# t8 = pd.DataFrame(dataSet3_off_feature3[['coupon_id', 'date_received','date']])
# t8 = t8[(t8['coupon_id'].notnull() == True) & (t8['date_received'].notnull() == True) & (t8['date'].notnull() == True)]
# t8['coupon_used_isweek'] = t8['date'].apply(int).apply(isweek)
# t8 = pd.DataFrame(t8[['coupon_id', 'coupon_used_isweek']],columns=['coupon_id', 'coupon_used_isweek']).drop_duplicates()
#
# # 合并数据
# left = dataSet3_off_feature3[['coupon_id']].drop_duplicates()
# dataSet3_off_coupon = pd.merge(left,t,how='left',on=['coupon_id'])
# dataSet3_off_coupon = pd.merge(dataSet3_off_coupon,t1,how='left',on=['coupon_id'])
# dataSet3_off_coupon = pd.merge(dataSet3_off_coupon,t2,how='left',on=['coupon_id'])
# dataSet3_off_coupon = pd.merge(dataSet3_off_coupon,t3,how='left',on=['coupon_id'])
# dataSet3_off_coupon = pd.merge(dataSet3_off_coupon,t4,how='left',on=['coupon_id'])
# dataSet3_off_coupon = pd.merge(dataSet3_off_coupon,t5,how='left',on=['coupon_id'])
# dataSet3_off_coupon = pd.merge(dataSet3_off_coupon,t6,how='left',on=['coupon_id'])
# dataSet3_off_coupon = pd.merge(dataSet3_off_coupon,t7,how='left',on=['coupon_id'])
# dataSet3_off_coupon = pd.merge(dataSet3_off_coupon,t8,how='left',on=['coupon_id'])
# # 消费券被用户的核销率 coupon_useRate
# dataSet3_off_coupon['coupon_useRate'] = round(dataSet3_off_coupon['coupon_use_byUser']/dataSet3_off_coupon['coupon_receive_byUser'],4)
# dataSet3_off_coupon.to_csv('dataSet3_off_coupon_feature.csv', index=None)
#
# # dataSet2
# # 消费券的类型 coupon_kind
# t = pd.DataFrame(dataSet2_off_feature2[['coupon_id', 'discount_rate']])
# t = t[t['discount_rate'].notnull() == True]
# t['discount_rate'] = t['discount_rate'].apply(classify)
# t = t.drop_duplicates()
# t.rename(columns={'discount_rate': 'coupon_kind '}, inplace=True)
#
# # 消费券的打折力度 coupon_discount
# t1 = pd.DataFrame(dataSet2_off_feature2[['coupon_id', 'discount_rate']])
# t1 = t1[t1['discount_rate'].notnull() == True]
# t1['discount_rate'] = t1['discount_rate'].apply(cal_discount)
# t1 = t1.drop_duplicates()
# t1.rename(columns={'discount_rate': 'coupon_discount '}, inplace=True)
#
# # 消费券被用户领取的次数 coupon_receive_byUser
# t2 = pd.DataFrame(dataSet2_off_feature2[['coupon_id', 'date_received']])
# t2 = t2[(t2['coupon_id'].notnull() == True) & (t2['date_received'].notnull() == True)]
# t2['date_received'] = 1
# t2 = t2.groupby('coupon_id').agg('sum').reset_index()
# t2.rename(columns={'date_received': 'coupon_receive_byUser'}, inplace=True)
#
# # 消费券被用户消费的次数 coupon_use_byUser
# t3 = pd.DataFrame(dataSet2_off_feature2[['coupon_id', 'date_received', 'date']])
# t3 = t3[
# (t3['coupon_id'].notnull() == True) & (t3['date_received'].notnull() == True) & (t3['date'].notnull() == True)]
# t3['date_received'] = 1
# t3 = t3.groupby('coupon_id').agg('sum').reset_index()
# t3 = pd.DataFrame(t3[['coupon_id', 'date_received']], columns=['coupon_id', 'date_received'])
# t3.rename(columns={'date_received': 'coupon_use_byUser'}, inplace=True)
#
# # 消费券被用户领取到消费经历的平均天数 coupon_avgDay
# t4 = pd.DataFrame(dataSet2_off_feature2[['coupon_id', 'date_received', 'date']])
# t4 = t4[
# (t4['coupon_id'].notnull() == True) & (t4['date_received'].notnull() == True) & (t4['date'].notnull() == True)]
# t4['coupon_avgDay'] = t4['date'] - t4['date_received']
# t4 = t4.groupby('coupon_id', sort=False).agg('mean').reset_index()
# t4 = pd.DataFrame(t4[['coupon_id', 'coupon_avgDay']], columns=['coupon_id', 'coupon_angDay'])
#
# # 消费券拥有的商家数 coupon_merchant_count
# t5 = pd.DataFrame(dataSet2_off_feature2[['coupon_id', 'merchant_id']])
# t5 = t5[t5['coupon_id'].notnull() == True].drop_duplicates()[['coupon_id']]
# t5['coupon_merchant_count'] = 1
# t5 = t5.groupby('coupon_id', sort=False).agg('sum').reset_index()
#
# # 消费券15天内被使用的占比 coupon_day_rate
# t6 = pd.DataFrame(dataSet2_off_feature2[['coupon_id', 'date_received', 'date']])
# t6 = t6[
# (t6['coupon_id'].notnull() == True) & (t6['date'].notnull() == True) & (t6['date_received'].notnull() == True)]
# t6['spend_day'] = t6['date'] - t6['date_received']
# t6_1 = t6[t6['spend_day'] < 15.0][['coupon_id', 'spend_day']]
# t6_1['spend_day'] = 1
# t6_1 = t6_1.groupby('coupon_id', sort=False).agg('sum').reset_index()
# t6_1.rename(columns={'spend_day': 'daymin'}, inplace=True)
# t6_2 = pd.DataFrame(t6[['coupon_id', 'spend_day']], columns=['coupon_id', 'spend_day'])
# t6_2['spend_day'] = 1
# t6_2 = t6_2.groupby('coupon_id', sort=False).agg('sum').reset_index()
# t6_2.rename(columns={'spend_day': 'total_day'}, inplace=True)
# t6 = pd.merge(t6_1, t6_2, how='left', on=['coupon_id'])
# t6['coupon_day_rate'] = round(t6['daymin'] / t6['total_day'], 4)
# t6 = pd.DataFrame(t6[['coupon_id', 'coupon_day_rate']], columns=['coupon_id', 'coupon_day_rate'])
#
#
# # 消费券被领取一般是周末还是工作日 coupon_receive_isweek
# def isweek(s):
# s = str(s)
# week = datetime.strptime(s, '%Y%m%d').weekday() + 1
# if week == 5 or week == 6 or week == 7:
# return 1
# else:
# return 0
#
#
# t7 = pd.DataFrame(dataSet2_off_feature2[['coupon_id', 'date_received']])
# t7 = t7[(t7['coupon_id'].notnull() == True) & (t7['date_received'].notnull() == True)]
# t7['coupon_receive_isweek'] = t7['date_received'].apply(int).apply(isweek)
# t7 = pd.DataFrame(t7[['coupon_id', 'coupon_receive_isweek']],
# columns=['coupon_id', 'coupon_receive_isweek']).drop_duplicates()
#
# # 消费券被消费一般是周末还是工作日 coupon_used_isweek
# t8 = pd.DataFrame(dataSet2_off_feature2[['coupon_id', 'date_received', 'date']])
# t8 = t8[
# (t8['coupon_id'].notnull() == True) & (t8['date_received'].notnull() == True) & (t8['date'].notnull() == True)]
# t8['coupon_used_isweek'] = t8['date'].apply(int).apply(isweek)
# t8 = pd.DataFrame(t8[['coupon_id', 'coupon_used_isweek']],
# columns=['coupon_id', 'coupon_used_isweek']).drop_duplicates()
#
# # 合并数据
# left = dataSet2_off_feature2[['coupon_id']].drop_duplicates()
# dataSet2_off_coupon = pd.merge(left, t, how='left', on=['coupon_id'])
# dataSet2_off_coupon = pd.merge(dataSet2_off_coupon, t1, how='left', on=['coupon_id'])
# dataSet2_off_coupon = pd.merge(dataSet2_off_coupon, t2, how='left', on=['coupon_id'])
# dataSet2_off_coupon = pd.merge(dataSet2_off_coupon, t3, how='left', on=['coupon_id'])
# dataSet2_off_coupon = pd.merge(dataSet2_off_coupon, t4, how='left', on=['coupon_id'])
# dataSet2_off_coupon = pd.merge(dataSet2_off_coupon, t5, how='left', on=['coupon_id'])
# dataSet2_off_coupon = pd.merge(dataSet2_off_coupon, t6, how='left', on=['coupon_id'])
# dataSet2_off_coupon = pd.merge(dataSet2_off_coupon, t7, how='left', on=['coupon_id'])
# dataSet2_off_coupon = pd.merge(dataSet2_off_coupon, t8, how='left', on=['coupon_id'])
# # 消费券被用户的核销率 coupon_useRate
# dataSet2_off_coupon['coupon_useRate'] = round(
# dataSet2_off_coupon['coupon_use_byUser'] / dataSet2_off_coupon['coupon_receive_byUser'], 4)
# dataSet2_off_coupon.to_csv('dataSet2_off_coupon_feature.csv', index=None)
#
#
# # dataSet1
# # 消费券的类型 coupon_kind
# t = pd.DataFrame(dataSet1_off_feature1[['coupon_id', 'discount_rate']])
# t = t[t['discount_rate'].notnull() == True]
# t['discount_rate'] = t['discount_rate'].apply(classify)
# t = t.drop_duplicates()
# t.rename(columns={'discount_rate': 'coupon_kind '}, inplace=True)
#
# # 消费券的打折力度 coupon_discount
# t1 = pd.DataFrame(dataSet1_off_feature1[['coupon_id', 'discount_rate']])
# t1 = t1[t1['discount_rate'].notnull() == True]
# t1['discount_rate'] = t1['discount_rate'].apply(cal_discount)
# t1 = t1.drop_duplicates()
# t1.rename(columns={'discount_rate': 'coupon_discount '}, inplace=True)
#
# # 消费券被用户领取的次数 coupon_receive_byUser
# t2 = pd.DataFrame(dataSet1_off_feature1[['coupon_id', 'date_received']])
# t2 = t2[(t2['coupon_id'].notnull() == True) & (t2['date_received'].notnull() == True)]
# t2['date_received'] = 1
# t2 = t2.groupby('coupon_id').agg('sum').reset_index()
# t2.rename(columns={'date_received': 'coupon_receive_byUser'}, inplace=True)
#
# # 消费券被用户消费的次数 coupon_use_byUser
# t3 = pd.DataFrame(dataSet1_off_feature1[['coupon_id', 'date_received', 'date']])
# t3 = t3[
# (t3['coupon_id'].notnull() == True) & (t3['date_received'].notnull() == True) & (t3['date'].notnull() == True)]
# t3['date_received'] = 1
# t3 = t3.groupby('coupon_id').agg('sum').reset_index()
# t3 = pd.DataFrame(t3[['coupon_id', 'date_received']], columns=['coupon_id', 'date_received'])
# t3.rename(columns={'date_received': 'coupon_use_byUser'}, inplace=True)
#
# # 消费券被用户领取到消费经历的平均天数 coupon_avgDay
# t4 = pd.DataFrame(dataSet1_off_feature1[['coupon_id', 'date_received', 'date']])
# t4 = t4[
# (t4['coupon_id'].notnull() == True) & (t4['date_received'].notnull() == True) & (t4['date'].notnull() == True)]
# t4['coupon_avgDay'] = t4['date'] - t4['date_received']
# t4 = t4.groupby('coupon_id', sort=False).agg('mean').reset_index()
# t4 = pd.DataFrame(t4[['coupon_id', 'coupon_avgDay']], columns=['coupon_id', 'coupon_angDay'])
#
# # 消费券拥有的商家数 coupon_merchant_count
# t5 = pd.DataFrame(dataSet1_off_feature1[['coupon_id', 'merchant_id']])
# t5 = t5[t5['coupon_id'].notnull() == True].drop_duplicates()[['coupon_id']]
# t5['coupon_merchant_count'] = 1
# t5 = t5.groupby('coupon_id', sort=False).agg('sum').reset_index()
#
# # 消费券15天内被使用的占比 coupon_day_rate
# t6 = pd.DataFrame(dataSet1_off_feature1[['coupon_id', 'date_received', 'date']])
# t6 = t6[
# (t6['coupon_id'].notnull() == True) & (t6['date'].notnull() == True) & (t6['date_received'].notnull() == True)]
# t6['spend_day'] = t6['date'] - t6['date_received']
# t6_1 = t6[t6['spend_day'] < 15.0][['coupon_id', 'spend_day']]
# t6_1['spend_day'] = 1
# t6_1 = t6_1.groupby('coupon_id', sort=False).agg('sum').reset_index()
# t6_1.rename(columns={'spend_day': 'daymin'}, inplace=True)
# t6_2 = pd.DataFrame(t6[['coupon_id', 'spend_day']], columns=['coupon_id', 'spend_day'])
# t6_2['spend_day'] = 1
# t6_2 = t6_2.groupby('coupon_id', sort=False).agg('sum').reset_index()
# t6_2.rename(columns={'spend_day': 'total_day'}, inplace=True)
# t6 = pd.merge(t6_1, t6_2, how='left', on=['coupon_id'])
# t6['coupon_day_rate'] = round(t6['daymin'] / t6['total_day'], 4)
# t6 = pd.DataFrame(t6[['coupon_id', 'coupon_day_rate']], columns=['coupon_id', 'coupon_day_rate'])
#
#
# # 消费券被领取一般是周末还是工作日 coupon_receive_isweek
# def isweek(s):
# s = str(s)
# week = datetime.strptime(s, '%Y%m%d').weekday() + 1
# if week == 5 or week == 6 or week == 7:
# return 1
# else:
# return 0
#
#
# t7 = pd.DataFrame(dataSet1_off_feature1[['coupon_id', 'date_received']])
# t7 = t7[(t7['coupon_id'].notnull() == True) & (t7['date_received'].notnull() == True)]
# t7['coupon_receive_isweek'] = t7['date_received'].apply(int).apply(isweek)
# t7 = pd.DataFrame(t7[['coupon_id', 'coupon_receive_isweek']],
# columns=['coupon_id', 'coupon_receive_isweek']).drop_duplicates()
#
# # 消费券被消费一般是周末还是工作日 coupon_used_isweek
# t8 = pd.DataFrame(dataSet1_off_feature1[['coupon_id', 'date_received', 'date']])
# t8 = t8[
# (t8['coupon_id'].notnull() == True) & (t8['date_received'].notnull() == True) & (t8['date'].notnull() == True)]
# t8['coupon_used_isweek'] = t8['date'].apply(int).apply(isweek)
# t8 = pd.DataFrame(t8[['coupon_id', 'coupon_used_isweek']],
# columns=['coupon_id', 'coupon_used_isweek']).drop_duplicates()
#
# # 合并数据
# left = dataSet1_off_feature1[['coupon_id']].drop_duplicates()
# dataSet1_off_coupon = pd.merge(left, t, how='left', on=['coupon_id'])
# dataSet1_off_coupon = pd.merge(dataSet1_off_coupon, t1, how='left', on=['coupon_id'])
# dataSet1_off_coupon = pd.merge(dataSet1_off_coupon, t2, how='left', on=['coupon_id'])
# dataSet1_off_coupon = pd.merge(dataSet1_off_coupon, t3, how='left', on=['coupon_id'])
# dataSet1_off_coupon = pd.merge(dataSet1_off_coupon, t4, how='left', on=['coupon_id'])
# dataSet1_off_coupon = pd.merge(dataSet1_off_coupon, t5, how='left', on=['coupon_id'])
# dataSet1_off_coupon = pd.merge(dataSet1_off_coupon, t6, how='left', on=['coupon_id'])
# dataSet1_off_coupon = pd.merge(dataSet1_off_coupon, t7, how='left', on=['coupon_id'])
# dataSet1_off_coupon = pd.merge(dataSet1_off_coupon, t8, how='left', on=['coupon_id'])
# # 消费券被用户的核销率 coupon_useRate
# dataSet1_off_coupon['coupon_useRate'] = round(
# dataSet1_off_coupon['coupon_use_byUser'] / dataSet1_off_coupon['coupon_receive_byUser'], 4)
# dataSet1_off_coupon.to_csv('dataSet1_off_coupon_feature.csv', index=None)
"""
用户与商家的特征:
每个用户在每个商家消费的次数 user-merchant_use_count
每个用户领取的每个商家的优惠券的次数 user_merchant_receiveCoupon_count
每个用户领取了商家的优惠券后使用的次数 user_merchant_useCoupon_count
"""
# dataSet3
# 每个用户在每个商家消费的次数 user-merchant_use_count
# t = pd.DataFrame(dataSet3_off_feature3[['user_id','merchant_id', 'date']])
# t = t[t['date'].notnull() == True]
# t['date'] = 1
# t = t.groupby(['user_id','merchant_id'], sort=False).agg('sum').reset_index()
# t.rename(columns={'date': 'user-merchant_use_count'}, inplace=True)
#
# # 每个用户领取的每个商家的优惠券的次数 user_merchant_receiveCoupon_count
# t1 = pd.DataFrame(dataSet3_off_feature3[['user_id', 'merchant_id', 'date_received']])
# t1 = t1[t1['date_received'].notnull() == True]
# t1['date_received'] = 1
# t1 = t1.groupby(['user_id', 'merchant_id'], sort=False).agg('sum').reset_index()
# t1.rename(columns={'date_received': 'user_merchant_receiveCoupon_count'}, inplace=True)
#
# # 每个用户领取了商家的优惠券后使用的次数 user_merchant_useCoupon_count
# t2 = pd.DataFrame(dataSet3_off_feature3[['user_id', 'merchant_id', 'date_received','date']])
# t2 = t2[(t2['date_received'].notnull() == True) & (t2['date'].notnull() == True)]
# t2['user_merchant_useCoupon_count'] = 1
# t2 = t2.groupby(['user_id', 'merchant_id'], sort=False).agg('sum').reset_index()
# t2 = pd.DataFrame(t2[['user_id','merchant_id','user_merchant_useCoupon_count']],columns=['user_id','merchant_id','user_merchant_useCoupon_count'])
#
# # 用户不领取消费券直接消费的次数 user_merchant_notCoupon_count
# t3 = pd.DataFrame(dataSet3_off_feature3[['user_id', 'merchant_id', 'date_received','date']])
# t3 = t3[(t3['date_received'].notnull() == False) & (t3['date'].notnull() == True)]
# t3['user_merchant_notCoupon_count'] = 1
# t3 = t3.groupby(['user_id', 'merchant_id'], sort=False).agg('sum').reset_index()
# t3 = pd.DataFrame(t3[['user_id','merchant_id','user_merchant_notCoupon_count']],columns=['user_id','merchant_id','user_merchant_notCoupon_count'])
#
# # 每个用户平均核销每个商家几张消费券 user_merchant_avgCoupon
# t4 = pd.DataFrame(dataSet3_off_feature3[['user_id', 'merchant_id', 'date_received','date']])
# t4 = t4[(t4['date_received'].notnull() == True) & (t4['date'].notnull() == True)]
# t4['user_merchant_avgCoupon'] = 1
# t4 = t4.groupby(['user_id','merchant_id'],sort=False).agg('mean').reset_index()
# t4 = pd.DataFrame(t4[['user_id', 'merchant_id', 'user_merchant_avgCoupon']],
# columns=['user_id', 'merchant_id', 'user_merchant_avgCoupon'])
#
# # 每个用户对于商家的消费券的使用间隔 user_merchant_avgDay
# t5 = pd.DataFrame(dataSet3_off_feature3[['user_id', 'merchant_id', 'date_received', 'date']])
# t5 = t5[(t5['date_received'].notnull() == True) & (t5['date'].notnull() == True)]
# t5['user_merchant_avgDay'] = t5['date'].apply(int) - t5['date_received'].apply(int)
# t5 = t5.groupby(['user_id','merchant_id'],sort=False).agg('mean').reset_index()
# t5 = pd.DataFrame(t5[['user_id','merchant_id','user_merchant_avgDay']],columns=['user_id','merchant_id','user_merchant_avgDay'])
#
# # 每个用户对于商家的核销率 user_merchant_useRate (user_merchant_useCoupon_count/user_merchant_receiveCoupon_count)
# t6 = pd.merge(t1,t2,how='left',on=['user_id','merchant_id'])
# t6 = t6.fillna(0)
# t6['user_merchant_useRate'] = t6['user_merchant_useCoupon_count']/t6['user_merchant_receiveCoupon_count']
# t6 = pd.DataFrame(t6[['user_id','merchant_id','user_merchant_useRate']],columns=['user_id','merchant_id','user_merchant_useRate'])
#
# # 合并数据
# left = dataSet3_off_feature3[['user_id','merchant_id']].drop_duplicates()
# dataSet3_off_userMerchant_feature3 = pd.merge(left,t,how='left',on=['user_id','merchant_id'])
# dataSet3_off_userMerchant_feature3 = pd.merge(dataSet3_off_userMerchant_feature3, t1, how='left', on=['user_id', 'merchant_id'])
# dataSet3_off_userMerchant_feature3 = pd.merge(dataSet3_off_userMerchant_feature3, t2, how='left',
# on=['user_id', 'merchant_id'])
# dataSet3_off_userMerchant_feature3 = pd.merge(dataSet3_off_userMerchant_feature3, t3, how='left',
# on=['user_id', 'merchant_id'])
# dataSet3_off_userMerchant_feature3 = pd.merge(dataSet3_off_userMerchant_feature3, t4, how='left',
# on=['user_id', 'merchant_id'])
# dataSet3_off_userMerchant_feature3 = pd.merge(dataSet3_off_userMerchant_feature3, t5, how='left',
# on=['user_id', 'merchant_id'])
# dataSet3_off_userMerchant_feature3 = pd.merge(dataSet3_off_userMerchant_feature3, t6, how='left',
# on=['user_id', 'merchant_id'])
# dataSet3_off_userMerchant_feature3 = dataSet3_off_userMerchant_feature3.fillna(0)
# print(dataSet3_off_userMerchant_feature3.columns)
# dataSet3_off_userMerchant_feature3.to_csv('dataSet3_off_userMerchant_feature3.csv', index=None)
#
# # dataSet2
# t = pd.DataFrame(dataSet2_off_feature2[['user_id', 'merchant_id', 'date']])
# t = t[t['date'].notnull() == True]
# t['date'] = 1
# t = t.groupby(['user_id', 'merchant_id'], sort=False).agg('sum').reset_index()
# t.rename(columns={'date': 'user-merchant_use_count'}, inplace=True)
#
# # 每个用户领取的每个商家的优惠券的次数 user_merchant_receiveCoupon_count
# t1 = pd.DataFrame(dataSet2_off_feature2[['user_id', 'merchant_id', 'date_received']])
# t1 = t1[t1['date_received'].notnull() == True]
# t1['date_received'] = 1
# t1 = t1.groupby(['user_id', 'merchant_id'], sort=False).agg('sum').reset_index()
# t1.rename(columns={'date_received': 'user_merchant_receiveCoupon_count'}, inplace=True)
#
# # 每个用户领取了商家的优惠券后使用的次数 user_merchant_useCoupon_count
# t2 = pd.DataFrame(dataSet2_off_feature2[['user_id', 'merchant_id', 'date_received', 'date']])
# t2 = t2[(t2['date_received'].notnull() == True) & (t2['date'].notnull() == True)]
# t2['user_merchant_useCoupon_count'] = 1
# t2 = t2.groupby(['user_id', 'merchant_id'], sort=False).agg('sum').reset_index()
# t2 = pd.DataFrame(t2[['user_id', 'merchant_id', 'user_merchant_useCoupon_count']],
# columns=['user_id', 'merchant_id', 'user_merchant_useCoupon_count'])
#
# # 用户不领取消费券直接消费的次数 user_merchant_notCoupon_count
# t3 = pd.DataFrame(dataSet2_off_feature2[['user_id', 'merchant_id', 'date_received', 'date']])
# t3 = t3[(t3['date_received'].notnull() == False) & (t3['date'].notnull() == True)]
# t3['user_merchant_notCoupon_count'] = 1
# t3 = t3.groupby(['user_id', 'merchant_id'], sort=False).agg('sum').reset_index()
# t3 = pd.DataFrame(t3[['user_id', 'merchant_id', 'user_merchant_notCoupon_count']],
# columns=['user_id', 'merchant_id', 'user_merchant_notCoupon_count'])
#
# # 每个用户平均核销每个商家几张消费券 user_merchant_avgCoupon
# t4 = pd.DataFrame(dataSet2_off_feature2[['user_id', 'merchant_id', 'date_received', 'date']])
# t4 = t4[(t4['date_received'].notnull() == True) & (t4['date'].notnull() == True)]
# t4['user_merchant_avgCoupon'] = 1
# t4 = t4.groupby(['user_id', 'merchant_id'], sort=False).agg('mean').reset_index()
# t4 = pd.DataFrame(t4[['user_id', 'merchant_id', 'user_merchant_avgCoupon']],
# columns=['user_id', 'merchant_id', 'user_merchant_avgCoupon'])
#
# # 每个用户对于商家的消费券的使用间隔 user_merchant_avgDay
# t5 = pd.DataFrame(dataSet2_off_feature2[['user_id', 'merchant_id', 'date_received', 'date']])
# t5 = t5[(t5['date_received'].notnull() == True) & (t5['date'].notnull() == True)]
# t5['user_merchant_avgDay'] = t5['date'].apply(int) - t5['date_received'].apply(int)
# t5 = t5.groupby(['user_id', 'merchant_id'], sort=False).agg('mean').reset_index()
# t5 = pd.DataFrame(t5[['user_id', 'merchant_id', 'user_merchant_avgDay']],
# columns=['user_id', 'merchant_id', 'user_merchant_avgDay'])
#
# # 每个用户对于商家的核销率 user_merchant_useRate (user_merchant_useCoupon_count/user_merchant_receiveCoupon_count)
# t6 = pd.merge(t1, t2, how='left', on=['user_id', 'merchant_id'])
# t6 = t6.fillna(0)
# t6['user_merchant_useRate'] = t6['user_merchant_useCoupon_count'] / t6['user_merchant_receiveCoupon_count']
# t6 = pd.DataFrame(t6[['user_id', 'merchant_id', 'user_merchant_useRate']],
# columns=['user_id', 'merchant_id', 'user_merchant_useRate'])
#
# # 合并数据
# left = dataSet2_off_feature2[['user_id', 'merchant_id']].drop_duplicates()
# dataSet2_off_userMerchant_feature2 = pd.merge(left, t, how='left', on=['user_id', 'merchant_id'])
# dataSet2_off_userMerchant_feature2 = pd.merge(dataSet2_off_userMerchant_feature2, t1, how='left',
# on=['user_id', 'merchant_id'])
# dataSet2_off_userMerchant_feature2 = pd.merge(dataSet2_off_userMerchant_feature2, t2, how='left',
# on=['user_id', 'merchant_id'])
# dataSet2_off_userMerchant_feature2 = pd.merge(dataSet2_off_userMerchant_feature2, t3, how='left',
# on=['user_id', 'merchant_id'])
# dataSet2_off_userMerchant_feature2 = pd.merge(dataSet2_off_userMerchant_feature2, t4, how='left',
# on=['user_id', 'merchant_id'])
# dataSet2_off_userMerchant_feature2 = pd.merge(dataSet2_off_userMerchant_feature2, t5, how='left',
# on=['user_id', 'merchant_id'])
# dataSet2_off_userMerchant_feature2 = pd.merge(dataSet2_off_userMerchant_feature2, t6, how='left',
# on=['user_id', 'merchant_id'])
# dataSet2_off_userMerchant_feature2 = dataSet2_off_userMerchant_feature2.fillna(0)
# print(dataSet2_off_userMerchant_feature2.columns)
# dataSet2_off_userMerchant_feature2.to_csv('dataSet2_off_userMerchant_feature2.csv', index=None)
#
# # dataSet1
# t = pd.DataFrame(dataSet1_off_feature1[['user_id', 'merchant_id', 'date']])
# t = t[t['date'].notnull() == True]
# t['date'] = 1
# t = t.groupby(['user_id', 'merchant_id'], sort=False).agg('sum').reset_index()
# t.rename(columns={'date': 'user-merchant_use_count'}, inplace=True)
#
# # 每个用户领取的每个商家的优惠券的次数 user_merchant_receiveCoupon_count
# t1 = pd.DataFrame(dataSet1_off_feature1[['user_id', 'merchant_id', 'date_received']])
# t1 = t1[t1['date_received'].notnull() == True]
# t1['date_received'] = 1
# t1 = t1.groupby(['user_id', 'merchant_id'], sort=False).agg('sum').reset_index()
# t1.rename(columns={'date_received': 'user_merchant_receiveCoupon_count'}, inplace=True)
#
# # 每个用户领取了商家的优惠券后使用的次数 user_merchant_useCoupon_count
# t2 = pd.DataFrame(dataSet1_off_feature1[['user_id', 'merchant_id', 'date_received', 'date']])
# t2 = t2[(t2['date_received'].notnull() == True) & (t2['date'].notnull() == True)]
# t2['user_merchant_useCoupon_count'] = 1
# t2 = t2.groupby(['user_id', 'merchant_id'], sort=False).agg('sum').reset_index()
# t2 = pd.DataFrame(t2[['user_id', 'merchant_id', 'user_merchant_useCoupon_count']],
# columns=['user_id', 'merchant_id', 'user_merchant_useCoupon_count'])
#
# # 用户不领取消费券直接消费的次数 user_merchant_notCoupon_count
# t3 = pd.DataFrame(dataSet1_off_feature1[['user_id', 'merchant_id', 'date_received', 'date']])
# t3 = t3[(t3['date_received'].notnull() == False) & (t3['date'].notnull() == True)]
# t3['user_merchant_notCoupon_count'] = 1
# t3 = t3.groupby(['user_id', 'merchant_id'], sort=False).agg('sum').reset_index()
# t3 = pd.DataFrame(t3[['user_id', 'merchant_id', 'user_merchant_notCoupon_count']],
# columns=['user_id', 'merchant_id', 'user_merchant_notCoupon_count'])
#
# # 每个用户平均核销每个商家几张消费券 user_merchant_avgCoupon
# t4 = pd.DataFrame(dataSet1_off_feature1[['user_id', 'merchant_id', 'date_received', 'date']])
# t4 = t4[(t4['date_received'].notnull() == True) & (t4['date'].notnull() == True)]
# t4['user_merchant_avgCoupon'] = 1
# t4 = t4.groupby(['user_id', 'merchant_id'], sort=False).agg('mean').reset_index()
# t4 = pd.DataFrame(t4[['user_id', 'merchant_id', 'user_merchant_avgCoupon']],
# columns=['user_id', 'merchant_id', 'user_merchant_avgCoupon'])
#
# # 每个用户对于商家的消费券的使用间隔 user_merchant_avgDay
# t5 = pd.DataFrame(dataSet1_off_feature1[['user_id', 'merchant_id', 'date_received', 'date']])
# t5 = t5[(t5['date_received'].notnull() == True) & (t5['date'].notnull() == True)]
# t5['user_merchant_avgDay'] = t5['date'].apply(int) - t5['date_received'].apply(int)
# t5 = t5.groupby(['user_id', 'merchant_id'], sort=False).agg('mean').reset_index()
# t5 = pd.DataFrame(t5[['user_id', 'merchant_id', 'user_merchant_avgDay']],
# columns=['user_id', 'merchant_id', 'user_merchant_avgDay'])
#
# # 每个用户对于商家的核销率 user_merchant_useRate (user_merchant_useCoupon_count/user_merchant_receiveCoupon_count)
# t6 = pd.merge(t1, t2, how='left', on=['user_id', 'merchant_id'])
# t6 = t6.fillna(0)
# t6['user_merchant_useRate'] = t6['user_merchant_useCoupon_count'] / t6['user_merchant_receiveCoupon_count']
# t6 = pd.DataFrame(t6[['user_id', 'merchant_id', 'user_merchant_useRate']],
# columns=['user_id', 'merchant_id', 'user_merchant_useRate'])
#
# # 合并数据
# left = dataSet1_off_feature1[['user_id', 'merchant_id']].drop_duplicates()
# dataSet1_off_userMerchant_feature1 = pd.merge(left, t, how='left', on=['user_id', 'merchant_id'])
# dataSet1_off_userMerchant_feature1 = pd.merge(dataSet1_off_userMerchant_feature1, t1, how='left',
# on=['user_id', 'merchant_id'])
# dataSet1_off_userMerchant_feature1 = pd.merge(dataSet1_off_userMerchant_feature1, t2, how='left',
# on=['user_id', 'merchant_id'])
# dataSet1_off_userMerchant_feature1 = pd.merge(dataSet1_off_userMerchant_feature1, t3, how='left',
# on=['user_id', 'merchant_id'])
# dataSet1_off_userMerchant_feature1 = pd.merge(dataSet1_off_userMerchant_feature1, t4, how='left',
# on=['user_id', 'merchant_id'])
# dataSet1_off_userMerchant_feature1 = pd.merge(dataSet1_off_userMerchant_feature1, t5, how='left',
# on=['user_id', 'merchant_id'])
# dataSet1_off_userMerchant_feature1 = pd.merge(dataSet1_off_userMerchant_feature1, t6, how='left',
# on=['user_id', 'merchant_id'])
# dataSet1_off_userMerchant_feature1 = dataSet1_off_userMerchant_feature1.fillna(0)
# print(dataSet1_off_userMerchant_feature1.columns)
# dataSet1_off_userMerchant_feature1.to_csv('dataSet1_off_userMerchant_feature1.csv', index=None)
"""
从预测的样本中提取特征:
"""
# 用户当天领取的优惠券的数目 user_date_receiveCoupon
t = pd.DataFrame(dataSet3[['user_id', 'date_received']])
t = t[t['date_received'].notnull() == True]
t['user_date_receiveCoupon'] = 1
t = t.groupby(['user_id','date_received'], sort=False).agg('sum').reset_index()
# 用户当天领取的满减优惠券的数目 user_date_receiveManjian
t1 = pd.DataFrame(dataSet3[['user_id','discount_rate','date_received']])
t1['discount_rate'] = t1['discount_rate'].apply(classify)
t1 = t1[(t1['discount_rate']==1) & (t1['date_received'].notnull() == True)]
t1['user_date_receiveManjian'] = 1
t1 = t1.groupby(['user_id', 'date_received'], sort=False).agg('sum').reset_index()
t1 = pd.DataFrame(t1[['user_id', 'date_received', 'user_date_receiveManjian']],
columns=['user_id', 'date_received', 'user_date_receiveManjian'])
# 用户当天领取的折扣优惠券的数目 user_date_receiveZhijie
t2 = pd.DataFrame(dataSet3[['user_id', 'discount_rate', 'date_received']])
t2['discount_rate'] = t2['discount_rate'].apply(classify)
t2 = t2[(t2['discount_rate'] == 0) & (t2['date_received'].notnull() == True)]
t2['user_date_receiveZhijie'] = 1
t2 = t2.groupby(['user_id', 'date_received'], sort=False).agg('sum').reset_index()
t2 = pd.DataFrame(t2[['user_id', 'date_received', 'user_date_receiveZhijie']],
columns=['user_id', 'date_received', 'user_date_receiveZhijie'])
# 是否是第一次领取优惠券 is_first
t3 = pd.DataFrame(dataSet3[['user_id', 'coupon_id', 'date_received']])
t3['date_received'] = t3['date_received'].apply(str)
t3 = t3[t3['date_received'].notnull() == True]
t3 = t3.groupby(['user_id', 'coupon_id'])['date_received'].agg(lambda x: ':'.join(x)).reset_index()
# t3['receive_number'] = t3['date_received'].apply(lambda s: len(s.split(':')))
# t3 = t3[t3['receive_number'] > 1]
t3['max_receive_date'] = t3['date_received'].apply(lambda x: max([int(d) for d in x.split(':')]))
t3['min_receive_date'] = t3['date_received'].apply(lambda x: min([int(d) for d in x.split(':')]))
t3 = pd.DataFrame(t3[['user_id','coupon_id','max_receive_date','min_receive_date']])
t3_1 = dataSet3[['user_id', 'coupon_id', 'date_received']]
t3_1 = pd.merge(t3_1, t3, on=['user_id', 'coupon_id'], how='left')
t3_1['user_receive_lastone'] = t3_1['max_receive_date'] - t3_1['date_received'].apply(int)
t3_1['user_receive_firstone'] = t3_1['date_received'] - t3_1['min_receive_date'].apply(int)
t3_1['is_first'] = t3_1['user_receive_firstone'].apply(is_firstorlast)
t3_1['is_last'] = t3_1['user_receive_lastone'].apply(is_firstorlast)
t3 = pd.DataFrame(t3_1[['user_id','coupon_id','is_first','is_last']])
# 用户领取了优惠券的商家的个数 user_coupon_merchant
t4 = pd.DataFrame(dataSet3[['user_id', 'merchant_id', 'date_received']])
t4 = t4[(t4['date_received'].notnull() == True)]
t4['user_coupon_merchant'] = 1
t4 = pd.DataFrame(t4[['user_id', 'merchant_id', 'user_coupon_merchant']]).drop_duplicates()
t4 = t4.groupby(['user_id'], sort=False).agg('sum').reset_index()
t4 = pd.DataFrame(t4[['user_id', 'user_coupon_merchant']],
columns=['user_id', 'user_coupon_merchant'])
# 用户领取优惠券是工作日还是周末 user_coupon_isWeek
t5 = pd.DataFrame(dataSet3[['user_id', 'coupon_id', 'date_received']])
t5 = t5[(t5['date_received'].notnull() == True)]
t5['user_coupon_isWeek'] = t5['date_received'].apply(int).apply(isweek)
t5 = pd.DataFrame(t5[['user_id', 'coupon_id','user_coupon_isWeek']],
columns=['user_id', 'coupon_id','user_coupon_isWeek'])
# 合并数据
left = dataSet3
dataSet3_feature3 = pd.merge(left, t, how='left', on=['user_id', 'date_received'])
dataSet3_feature3 = pd.merge(dataSet3_feature3, t1, how='left',on=['user_id', 'date_received'])
dataSet3_feature3 = pd.merge(dataSet3_feature3, t2, how='left',on=['user_id', 'date_received'])
dataSet3_feature3 = pd.merge(dataSet3_feature3, t3, how='left',on=['user_id', 'coupon_id'])
dataSet3_feature3 = pd.merge(dataSet3_feature3, t4, how='left',on=['user_id'])
dataSet3_feature3 = pd.merge(dataSet3_feature3, t5, how='left',on=['user_id', 'coupon_id'])
dataSet3_feature3 = dataSet3_feature3.fillna(0)
dataSet3_feature3.to_csv('dataSet3_feature3.csv', index=None)
# 用户当天领取的优惠券的数目 user_date_receiveCoupon
t = pd.DataFrame(dataSet2[['user_id', 'date_received']])
t = t[t['date_received'].notnull() == True]
t['user_date_receiveCoupon'] = 1
t = t.groupby(['user_id', 'date_received'], sort=False).agg('sum').reset_index()
# 用户当天领取的满减优惠券的数目 user_date_receiveManjian
t1 = pd.DataFrame(dataSet2[['user_id', 'discount_rate', 'date_received']])
t1['discount_rate'] = t1['discount_rate'].apply(classify)
t1 = t1[(t1['discount_rate'] == 1) & (t1['date_received'].notnull() == True)]
t1['user_date_receiveManjian'] = 1
t1 = t1.groupby(['user_id', 'date_received'], sort=False).agg('sum').reset_index()
t1 = pd.DataFrame(t1[['user_id', 'date_received', 'user_date_receiveManjian']],
columns=['user_id', 'date_received', 'user_date_receiveManjian'])
# 用户当天领取的折扣优惠券的数目 user_date_receiveZhijie
t2 = pd.DataFrame(dataSet2[['user_id', 'discount_rate', 'date_received']])
t2['discount_rate'] = t2['discount_rate'].apply(classify)
t2 = t2[(t2['discount_rate'] == 0) & (t2['date_received'].notnull() == True)]
t2['user_date_receiveZhijie'] = 1
t2 = t2.groupby(['user_id', 'date_received'], sort=False).agg('sum').reset_index()
t2 = pd.DataFrame(t2[['user_id', 'date_received', 'user_date_receiveZhijie']],
columns=['user_id', 'date_received', 'user_date_receiveZhijie'])
# 是否是第一次领取优惠券 is_first
t3 = pd.DataFrame(dataSet2[['user_id', 'coupon_id', 'date_received']])
t3['date_received'] = t3['date_received'].apply(int).apply(str)
t3 = t3[t3['date_received'].notnull() == True]
t3 = t3.groupby(['user_id', 'coupon_id'])['date_received'].agg(lambda x: ':'.join(x)).reset_index()
# t3['receive_number'] = t3['date_received'].apply(lambda s: len(s.split(':')))
# t3 = t3[t3['receive_number'] > 1]
t3['max_receive_date'] = t3['date_received'].apply(lambda x: max([int(d) for d in x.split(':')]))
t3['min_receive_date'] = t3['date_received'].apply(lambda x: min([int(d) for d in x.split(':')]))
t3 = pd.DataFrame(t3[['user_id', 'coupon_id', 'max_receive_date', 'min_receive_date']])
t3_1 = dataSet2[['user_id', 'coupon_id', 'date_received']]
t3_1 = pd.merge(t3_1, t3, on=['user_id', 'coupon_id'], how='left')
t3_1['user_receive_lastone'] = t3_1['max_receive_date'] - t3_1['date_received'].apply(int)
t3_1['user_receive_firstone'] = t3_1['date_received'] - t3_1['min_receive_date'].apply(int)
t3_1['is_first'] = t3_1['user_receive_firstone'].apply(is_firstorlast)
t3_1['is_last'] = t3_1['user_receive_lastone'].apply(is_firstorlast)
t3 = pd.DataFrame(t3_1[['user_id', 'coupon_id', 'is_first', 'is_last']])
# 用户领取了优惠券的商家的个数 user_coupon_merchant
t4 = pd.DataFrame(dataSet2[['user_id', 'merchant_id', 'date_received']])
t4 = t4[(t4['date_received'].notnull() == True)]
t4['user_coupon_merchant'] = 1
t4 = pd.DataFrame(t4[['user_id', 'merchant_id', 'user_coupon_merchant']]).drop_duplicates()
t4 = t4.groupby(['user_id'], sort=False).agg('sum').reset_index()
t4 = pd.DataFrame(t4[['user_id', 'user_coupon_merchant']],
columns=['user_id', 'user_coupon_merchant'])
# 用户领取优惠券是工作日还是周末 user_coupon_isWeek
t5 = pd.DataFrame(dataSet2[['user_id', 'coupon_id', 'date_received']])
t5 = t5[(t5['date_received'].notnull() == True)]
t5['user_coupon_isWeek'] = t5['date_received'].apply(int).apply(isweek)
t5 = pd.DataFrame(t5[['user_id', 'coupon_id', 'user_coupon_isWeek']],
columns=['user_id', 'coupon_id', 'user_coupon_isWeek'])
# 合并数据
left = dataSet2
dataSet2_feature3 = pd.merge(left, t, how='left', on=['user_id', 'date_received'])
dataSet2_feature3 = pd.merge(dataSet2_feature3, t1, how='left', on=['user_id', 'date_received'])
dataSet2_feature3 = pd.merge(dataSet2_feature3, t2, how='left', on=['user_id', 'date_received'])
dataSet2_feature3 = pd.merge(dataSet2_feature3, t3, how='left', on=['user_id', 'coupon_id'])
dataSet2_feature3 = pd.merge(dataSet2_feature3, t4, how='left', on=['user_id'])
dataSet2_feature3 = pd.merge(dataSet2_feature3, t5, how='left', on=['user_id', 'coupon_id'])
dataSet2_feature3 = dataSet2_feature3.fillna(0)
dataSet2_feature3.to_csv('dataSet2_feature3.csv', index=None)
# 用户当天领取的优惠券的数目 user_date_receiveCoupon
t = pd.DataFrame(dataSet1[['user_id', 'date_received']])
t = t[t['date_received'].notnull() == True]
t['user_date_receiveCoupon'] = 1
t = t.groupby(['user_id', 'date_received'], sort=False).agg('sum').reset_index()
# 用户当天领取的满减优惠券的数目 user_date_receiveManjian
t1 = pd.DataFrame(dataSet1[['user_id', 'discount_rate', 'date_received']])
t1['discount_rate'] = t1['discount_rate'].apply(classify)
t1 = t1[(t1['discount_rate'] == 1) & (t1['date_received'].notnull() == True)]
t1['user_date_receiveManjian'] = 1
t1 = t1.groupby(['user_id', 'date_received'], sort=False).agg('sum').reset_index()
t1 = pd.DataFrame(t1[['user_id', 'date_received', 'user_date_receiveManjian']],
columns=['user_id', 'date_received', 'user_date_receiveManjian'])
# 用户当天领取的折扣优惠券的数目 user_date_receiveZhijie
t2 = pd.DataFrame(dataSet1[['user_id', 'discount_rate', 'date_received']])
t2['discount_rate'] = t2['discount_rate'].apply(classify)
t2 = t2[(t2['discount_rate'] == 0) & (t2['date_received'].notnull() == True)]
t2['user_date_receiveZhijie'] = 1
t2 = t2.groupby(['user_id', 'date_received'], sort=False).agg('sum').reset_index()
t2 = pd.DataFrame(t2[['user_id', 'date_received', 'user_date_receiveZhijie']],
columns=['user_id', 'date_received', 'user_date_receiveZhijie'])
# 是否是第一次领取优惠券 is_first
t3 = pd.DataFrame(dataSet1[['user_id', 'coupon_id', 'date_received']])
t3['date_received'] = t3['date_received'].apply(int).apply(str)
t3 = t3[t3['date_received'].notnull() == True]
t3 = t3.groupby(['user_id', 'coupon_id'])['date_received'].agg(lambda x: ':'.join(x)).reset_index()
# t3['receive_number'] = t3['date_received'].apply(lambda s: len(s.split(':')))
# t3 = t3[t3['receive_number'] > 1]
t3['max_receive_date'] = t3['date_received'].apply(lambda x: max([int(d) for d in x.split(':')]))
t3['min_receive_date'] = t3['date_received'].apply(lambda x: min([int(d) for d in x.split(':')]))
t3 = pd.DataFrame(t3[['user_id', 'coupon_id', 'max_receive_date', 'min_receive_date']])
t3_1 = dataSet1[['user_id', 'coupon_id', 'date_received']]
t3_1 = pd.merge(t3_1, t3, on=['user_id', 'coupon_id'], how='left')
t3_1['user_receive_lastone'] = t3_1['max_receive_date'] - t3_1['date_received'].apply(int)
t3_1['user_receive_firstone'] = t3_1['date_received'] - t3_1['min_receive_date'].apply(int)
t3_1['is_first'] = t3_1['user_receive_firstone'].apply(is_firstorlast)
t3_1['is_last'] = t3_1['user_receive_lastone'].apply(is_firstorlast)
t3 = pd.DataFrame(t3_1[['user_id', 'coupon_id', 'is_first', 'is_last']])
# 用户领取了优惠券的商家的个数 user_coupon_merchant
t4 = pd.DataFrame(dataSet1[['user_id', 'merchant_id', 'date_received']])
t4 = t4[(t4['date_received'].notnull() == True)]
t4['user_coupon_merchant'] = 1
t4 = pd.DataFrame(t4[['user_id', 'merchant_id', 'user_coupon_merchant']]).drop_duplicates()
t4 = t4.groupby(['user_id'], sort=False).agg('sum').reset_index()
t4 = pd.DataFrame(t4[['user_id', 'user_coupon_merchant']],
columns=['user_id', 'user_coupon_merchant'])
# 用户领取优惠券是工作日还是周末 user_coupon_isWeek
t5 = pd.DataFrame(dataSet1[['user_id', 'coupon_id', 'date_received']])
t5 = t5[(t5['date_received'].notnull() == True)]
t5['user_coupon_isWeek'] = t5['date_received'].apply(int).apply(isweek)
t5 = pd.DataFrame(t5[['user_id', 'coupon_id', 'user_coupon_isWeek']],
columns=['user_id', 'coupon_id', 'user_coupon_isWeek'])
# 合并数据
left = dataSet1
dataSet1_feature3 = pd.merge(left, t, how='left', on=['user_id', 'date_received'])
dataSet1_feature3 = pd.merge(dataSet1_feature3, t1, how='left', on=['user_id', 'date_received'])
dataSet1_feature3 = pd.merge(dataSet1_feature3, t2, how='left', on=['user_id', 'date_received'])
dataSet1_feature3 = pd.merge(dataSet1_feature3, t3, how='left', on=['user_id', 'coupon_id'])
dataSet1_feature3 = pd.merge(dataSet1_feature3, t4, how='left', on=['user_id'])
dataSet1_feature3 = pd.merge(dataSet1_feature3, t5, how='left', on=['user_id', 'coupon_id'])
dataSet1_feature3 = dataSet1_feature3.fillna(0)
dataSet1_feature3.to_csv('dataSet1_feature3.csv', index=None)
<file_sep>/机器学习算法/K-means/k-means.py
import math
from decimal import Decimal
import random
from collections import Counter
"""
读取文件
返回属性,类别
"""
def readData():
data = []
dataLable = []
with open('../seeds_dataset.txt','r') as f:
for line in f.readlines():
# seeds
line = line.strip(" ").strip('\n').split('\t')
line = [float(x) for x in line if x is not '']
# 针对redWine,whiteWine
#line = line.strip(' ').strip('\n').split(';')
#line = line.strip(' ').strip('\n').split(',')
# 针对红酒数据
# line.append(line[0])
# del (line[0])
# line = line.strip(' ').strip('\n').split('\t')
dataLable .append(line[:len(line)])
lineBefore = line[:len(line) - 1]
lineBefore = [float(x) for x in lineBefore]
data.append(lineBefore)
return data,dataLable
"""
计算两个样本的距离
选用欧氏距离
"""
def calDistance(sample,test):
length = len(data[0]) #计算每个样本属性个数
sum = 0
for index in range(length):
subtraction = float(Decimal(str(test[index]))-Decimal(str(sample[index])))
sum = sum + subtraction**2
result = math.sqrt(sum)
return result
"""
随机选取样本集中K个样本作为初始值
"""
def SelectK(data,k):
length = len(data)
kList = []
randomdata = range(length)
kList = random.sample(randomdata, k)
kValue = [data[i] for i in kList]
return kValue
"""
求均值向量
"""
def means(dataSet,data):
length = len(dataSet[data[0]])
dataLen = len(data)
newVec = []
for i in range(length):
result = 0
for index in range(dataLen):
result = result + dataSet[data[index]][i]
newVec.append(result/dataLen)
return newVec
"""
比较列表
"""
def compareList(list1,list2):
count = 0
if len(list1)==len(list2):
for i in range(len(list1)):
if list1[i] == list2[i]:
count = count + 1
if count == len(list1):
return 1
else:
return 0
else:
return 0
"""
K-means函数体
"""
def kMeans(data,k):
dataLen = len(data) #计算数据个数
centroids = SelectK(data,k) #s随机选取k个样本
clusterChanged = True #判断集群是否变化,初始值为True
count = 1 #计算循环次数
while clusterChanged:
#print("旧的质点为",centroids)
clusterAssment = [list() for i in range(k)] # 存放分类
clusterChanged = False
closeIndex = 0 #存放与当前样本距离最近的质点的下标
for index in range(dataLen):
distance = 10000000 #存放当前样本与质点的距离
for i in range(k):
distanceOrign = calDistance(centroids[i],data[index])
if distanceOrign < distance:
distance = distanceOrign
closeIndex = i
clusterAssment[closeIndex].append(index) #将样本下标存入最近的质点
print("第{}次迭代".format(count))
for i in range(k):
print("第{}个分类有{}个样本".format(i,len(clusterAssment[i])))
for i in range(k):
newVec = means(data,clusterAssment[i])
value = compareList(centroids[i],newVec)
if value == 0:
clusterChanged = True
centroids[i] = newVec
#print("新的选取的质点为",centroids)
count = count + 1
return clusterAssment,centroids
def autoNorm(data):
length = len(data[0]) #计算属性个数
for i in range(length):
FeatureValue = [item[i] for item in data] #保存一个属性的所有值
minval = min(FeatureValue) #计算属性的最小值
maxVal = max(FeatureValue) #计算属性的最大值
ranges = float(Decimal(str(maxVal)) - Decimal(str(minval))) #计算极差
for item in data:
item[i] = float(Decimal(str((item[i] - minval)))/Decimal(str(ranges)))
return data
if __name__ == '__main__':
k = 3
Meanslabel = []
data,dataLable = readData()
data = autoNorm(data)
clusterAssment, centroids = kMeans(data,k)
#判断每一类的类别
for i in range(k):
lable = []
for index in clusterAssment[i]:
lable.append(dataLable[index][-1])
result_counts = Counter(lable)
Meanslabel.append(result_counts.most_common(1)[0][0])
print("最终聚类的结果")
for i in range(k):
print("第{}类有{}个样本,他的类别是{}".format(i+1,len(clusterAssment[i]),Meanslabel[i]))
print("原始数据为")
huizong = {}
for item in dataLable:
current = item[-1]
if current not in huizong.keys():
huizong[current] = 0
huizong[current] += 1
print(huizong)
| 5a2ac4df4b2eee273a88ab5f2e92ad4542451ac6 | [
"Markdown",
"Python"
] | 19 | Python | lmh246/machine_learning | 8932cb09f7809c1fef54d192b200d49799aacdff | 03ef6c231ada2fe115b51d4ca446694fdb450e27 |
refs/heads/master | <file_sep>module.exports = require('pages-tasks')
<file_sep># x-pages
[![Build Status][travis-image]][travis-url]
[![Coverage Status][codecov-image]][codecov-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![NPM Version][version-image]][version-url]
[![License][license-image]][license-url]
[![Dependency Status][dependency-image]][dependency-url]
[![devDependency Status][devdependency-image]][devdependency-url]
[![Code Style][style-image]][style-url]
> A static site development workflow (Convention over Configuration)
## Installation
```shell
$ yarn add x-pages --dev
# or npm
$ npm install x-pages --dev
```
package.json
```json
{
"scripts": {
"clean": "x-pages clean",
"lint": "x-pages lint",
"serve": "x-pages serve",
"build": "x-pages build",
"start": "x-pages start",
"deploy": "x-pages deploy --production"
}
}
```
## CLI Usage
```shell
$ yarn <task> [options]
```
### e.g.
```shell
$ yarn serve --port 5210 --open
$ yarn build --production
```
## Examples
- [zce/x-pages-example](https://github.com/zce/x-pages-example/tree/x-pages) - x-pages examples
## Folder Structure
```
└── my-project ······································· proj root
├─ public ········································· static dir (unprocessed)
├─ src ············································ source dir
│ ├─ assets ······································ assets dir
│ │ ├─ fonts ···································· fonts dir (imagemin)
│ │ ├─ images ··································· images dir (imagemin)
│ │ ├─ scripts ·································· scripts dir (babel / uglify)
│ │ └─ styles ··································· styles dir (scss / postcss)
│ ├─ layouts ····································· layouts dir (dont output)
│ ├─ partials ···································· partials dir (dont output)
│ └─ index.html ·································· page file (use layout & partials)
├─ .editorconfig ·································· editor config file
├─ .gitignore ····································· git ignore file
├─ .travis.yml ···································· travis ci config file
├─ README.md ······································ repo readme
├─ gulpfile.js ···································· gulp tasks file
└─ package.json ··································· package file
```
## Related
- [zce/pages-boilerplate](https://github.com/zce/pages-boilerplate) - Always a pleasure scaffolding your awesome static sites.
- [zce/pages-tasks](https://github.com/zce/pages-tasks) - A preset static pages project gulp tasks
## Contributing
1. **Fork** it on GitHub!
2. **Clone** the fork to your own machine.
3. **Checkout** your feature branch: `git checkout -b my-awesome-feature`
4. **Commit** your changes to your own branch: `git commit -am 'Add some feature'`
5. **Push** your work back up to your fork: `git push -u origin my-awesome-feature`
6. Submit a **Pull Request** so that we can review your changes.
> **NOTE**: Be sure to merge the latest from "upstream" before making a pull request!
## License
[MIT](LICENSE) © [汪磊](https://zce.me)
[travis-image]: https://img.shields.io/travis/zce/x-pages.svg
[travis-url]: https://travis-ci.org/zce/x-pages
[codecov-image]: https://img.shields.io/codecov/c/github/zce/x-pages.svg
[codecov-url]: https://codecov.io/gh/zce/x-pages
[downloads-image]: https://img.shields.io/npm/dm/x-pages.svg
[downloads-url]: https://npmjs.org/package/x-pages
[version-image]: https://img.shields.io/npm/v/x-pages.svg
[version-url]: https://npmjs.org/package/x-pages
[license-image]: https://img.shields.io/github/license/zce/x-pages.svg
[license-url]: https://github.com/zce/x-pages/blob/master/LICENSE
[dependency-image]: https://img.shields.io/david/zce/x-pages.svg
[dependency-url]: https://david-dm.org/zce/x-pages
[devdependency-image]: https://img.shields.io/david/dev/zce/x-pages.svg
[devdependency-url]: https://david-dm.org/zce/x-pages?type=dev
[style-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg
[style-url]: http://standardjs.com
| 2ca571fd5f10bfd77c20afdef7dbee4feedccfcc | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | huoqishi/x-pages | 27dba7b3244dbfa821699ed44f296b190e1faec2 | dd1d62bb1a3d3bb2f78587255dbe2a3a0139f53c |
refs/heads/master | <repo_name>felipecesr/codility-lessons<file_sep>/__tests__/frog_jmp.spec.js
const solution = require("../src/frog_jmp");
test("should return the minimal number of jumps", () => {
expect(solution(10, 85, 30)).toBe(3);
});
<file_sep>/__tests__/binary_gap.spec.js
const solution = require("../src/binary_gap");
test("should return the correct values", () => {
expect(solution(9)).toBe(2);
expect(solution(529)).toBe(4);
expect(solution(20)).toBe(1);
});
<file_sep>/__tests__/cyclic_rotation.spec.js
const solution = require("../src/cyclic_rotation");
test("should return correct rotations", () => {
expect(solution([3, 8, 9, 7, 6], 3)).toEqual([9, 7, 6, 3, 8]);
expect(solution([0, 0, 0], 1)).toEqual([0, 0, 0]);
expect(solution([1, 2, 3, 4], 4)).toEqual([1, 2, 3, 4]);
});
test("K equal 0", () => {
expect(solution([1, 2], 0)).toEqual([1, 2]);
});
test("extreme empty", () => {
expect(solution([])).toEqual([]);
});
<file_sep>/__tests__/perm_missing_elem.spec.js
const solution = require("../src/perm_missing_elem");
test("should return the value of the missing element", () => {
expect(solution([2, 3, 1, 5])).toBe(4);
expect(solution([1, 3, 5, 6, 4])).toBe(2);
});
| 6229187218b3f85080c863dacf9a37b3b3d2108c | [
"JavaScript"
] | 4 | JavaScript | felipecesr/codility-lessons | 5a5c26a845044dfa9a5d60c989634462e13f3523 | ad9e986dff8965ffd480a94fef7a4d3cd6b8161e |
refs/heads/master | <repo_name>anhtuan80/chrome-hostadmin<file_sep>/container/chrome/timer.js
;(function(HostAdmin){
var host_admin = HostAdmin.core;
HostAdmin.dontgc = setInterval(function(){
host_admin.refresh();
}, 1000);
})(window.HostAdmin);
<file_sep>/npapi/src/hostadmin.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "hostadmin.h"
#include "const.h"
static void logmsg(const char *msg) {
FILE *out = fopen("/tmp/x.log", "a");
if(out) {
fputs(msg, out);
fputs("\n", out);
fclose(out);
}
}
static NPNetscapeFuncs* npnfuncs;
bool NP_HasProperty(NPObject *npobj, NPIdentifier propName){
char * name = npnfuncs->utf8fromidentifier(propName);
return
strcmp(name, PROP_OS) == 0
|| strcmp(name, PROP_WHERE) == 0 ;
}
bool NP_GetProperty(NPObject *npobj, NPIdentifier propName, NPVariant *result){
char * name = npnfuncs->utf8fromidentifier(propName);
if(strcmp(name, PROP_OS) == 0){
size_t l = strlen(OSNAME);
char * s = (char *)npnfuncs->memalloc(l + 1);
memcpy(s, OSNAME, l);
s[l] = '\0';
STRINGN_TO_NPVARIANT(s, l, *result);
return true;
#ifdef XP_WIN
}else if(strcmp(name, PROP_WHERE) == 0){
char * buf = (char *)npnfuncs->memalloc(MAX_PATH);
GetSystemDirectory(buf, MAX_PATH + 1);
STRINGN_TO_NPVARIANT(buf, strlen(buf) , *result);
return true;
#endif
}
return false;
}
bool NP_HasMethod(NPObject *obj, NPIdentifier methodName){
char * name = npnfuncs->utf8fromidentifier(methodName);
//logmsg(name);
return
(strcmp(name, METHOD_TIME) == 0 )
|| (strcmp(name, METHOD_GET) == 0)
|| (strcmp(name, METHOD_SET) == 0)
;
}
static char * ArgToStr(const NPVariant arg) {
NPString str = NPVARIANT_TO_STRING(arg);
char * r = (char *)malloc(str.UTF8Length + 1);
memcpy(r, str.UTF8Characters, str.UTF8Length);
r[str.UTF8Length] = '\0';
return r;
}
#if XP_WIN
static bool HasNonAscii(const char * str ,size_t len){
for(size_t i=0; i< len; i++)
if(str[i] > 127)
return true;
return false;
}
#endif
bool NP_Invoke(NPObject* obj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result){
char * name = npnfuncs->utf8fromidentifier(methodName);
if(strcmp(name, METHOD_TIME) == 0 && argCount > 0 &&
NPVARIANT_IS_STRING(args[0])
){
char * filename = ArgToStr(args[0]);
struct stat * buf = (struct stat *)malloc(sizeof(struct stat));
stat(filename, buf);
free(filename);
INT32_TO_NPVARIANT(buf->st_mtime, *result);
free(buf);
return true;
}else
if(strcmp(name, METHOD_GET) == 0 && argCount > 0 &&
NPVARIANT_IS_STRING(args[0])
){
char * filename = ArgToStr(args[0]);
//logmsg(filename);
FILE * f = fopen(filename, "rb");
if(f) {
fseek(f, 0 , SEEK_END);
long int size = ftell(f);
rewind(f);
char * buf = (char *)npnfuncs->memalloc(size);
memset(buf, 0, size);
fread(buf, 1, size, f);
fclose(f);
#if XP_WIN
/* make sure text are utf8*/
if(strncmp(buf, UTF8BOM, strlen(UTF8BOM)) != 0){
if(HasNonAscii(buf, size)){
int usize = MultiByteToWideChar(CP_ACP, 0, buf, size, NULL, 0);
wchar_t * ubuf = (wchar_t *)malloc((usize + 1) * sizeof(wchar_t));
memset(ubuf, 0, (usize + 1) * sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, buf, size, ubuf, usize);
size = WideCharToMultiByte(CP_UTF8, 0, ubuf, usize, NULL, 0, NULL, NULL);
npnfuncs->memfree(buf);
buf = (char *)npnfuncs->memalloc(size + 1);
memset(buf, 0, size + 1);
WideCharToMultiByte(CP_UTF8, 0, ubuf, usize, buf, size, NULL,NULL);
free(ubuf);
}
} else{
char * oldbuf = buf;
size -= strlen(UTF8BOM);
buf = (char *)npnfuncs->memalloc(size);
memcpy(buf, oldbuf + strlen(UTF8BOM), size);
npnfuncs->memfree(oldbuf);
}
#endif
STRINGN_TO_NPVARIANT(buf, size, *result);
//npnfuncs->memfree(buf);
}
free(filename);
return true;
}else
if(strcmp(name, METHOD_SET) == 0 && argCount > 1 &&
NPVARIANT_IS_STRING(args[0]) && NPVARIANT_IS_STRING(args[1])
){
char * filename = ArgToStr(args[0]);
char * content = ArgToStr(args[1]);
FILE * f = fopen(filename, "wb");
bool succ = false;
if(f) {
#if XP_WIN
if(HasNonAscii(content, strlen(content)))
fputs(UTF8BOM, f);
#endif
fputs(content, f);
succ = ferror(f) == 0;
fclose(f);
}
free(filename);
free(content);
BOOLEAN_TO_NPVARIANT(succ, *result);
return true;
}
return false;
}
static struct NPClass hostadmin_class = {
NP_CLASS_STRUCT_VERSION,
NULL,
NULL,
NULL,
NP_HasMethod,
NP_Invoke,
NULL,
NP_HasProperty,
NP_GetProperty,
NULL,
NULL,
NULL,
NULL,
};
static NPObject * hostadmin_helper;
const char*
NP_GetMIMEDescription(){
return MIMETYPE_S;
}
NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16_t mode, int16_t argc, char* argn[], char* argv[], NPSavedData* saved) {
#ifdef __APPLE_CC__
NPBool supportsCoreGraphics = false;
if (npnfuncs->getvalue(instance, NPNVsupportsCoreGraphicsBool, &supportsCoreGraphics) == NPERR_NO_ERROR && supportsCoreGraphics) {
npnfuncs->setvalue(instance, NPPVpluginDrawingModel, (void*)NPDrawingModelCoreGraphics);
}
NPBool supportsCocoaEvents = false;
if (npnfuncs->getvalue(instance, NPNVsupportsCocoaBool, &supportsCocoaEvents) == NPERR_NO_ERROR && supportsCocoaEvents) {
npnfuncs->setvalue(instance, NPPVpluginEventModel, (void*)NPEventModelCocoa);
}
#endif
return NPERR_NO_ERROR;
}
NPError NPP_Destroy(NPP instance, NPSavedData** save) {
if(!hostadmin_helper) {
npnfuncs->releaseobject(hostadmin_helper);
hostadmin_helper = NULL;
}
return NPERR_NO_ERROR;
}
NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) {
switch(variable) {
case NPPVpluginScriptableNPObject:
if(!hostadmin_helper) {
hostadmin_helper = npnfuncs->createobject(instance, &hostadmin_class);
npnfuncs->retainobject(hostadmin_helper);
}
*(NPObject **)value = hostadmin_helper;
break;
case NPPVpluginNeedsXEmbed:
*((bool *)value) = true;
break;
default:
return NPERR_GENERIC_ERROR;
}
return NPERR_NO_ERROR;
}
void HookbFuncs(NPNetscapeFuncs* bFuncs){
npnfuncs = bFuncs;
}
void HookpFuncs(NPPluginFuncs* pFuncs){
pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR;
pFuncs->size = sizeof(pFuncs);
pFuncs->newp = NPP_New;
pFuncs->destroy = NPP_Destroy;
pFuncs->getvalue = NPP_GetValue;
}
#ifdef XP_UNIX
NP_EXPORT(NPError)
NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs){
HookbFuncs(bFuncs);
HookpFuncs(pFuncs);
return NPERR_NO_ERROR;
}
//#elif XP_WIN
#else
NPError OSCALL
NP_GetEntryPoints(NPPluginFuncs* pFuncs) {
HookpFuncs(pFuncs);
return NPERR_NO_ERROR;
}
NPError OSCALL
NP_Initialize(NPNetscapeFuncs* bFuncs) {
HookbFuncs(bFuncs);
return NPERR_NO_ERROR;
}
#endif
#ifdef XP_UNIX
NP_EXPORT(NPError)
//#elif XP_WIN
#else
NPError OSCALL
#endif
NP_Shutdown(){
return NPERR_NO_ERROR;
}
<file_sep>/container/firefox/timer.js
;(function(HostAdmin){
var timer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
timer.init((function(){
var host_admin = HostAdmin.core;
return {
observe: function(subject, topic, data){
host_admin.refresh();
},
};
})(), 1000, Components.interfaces.nsITimer.TYPE_REPEATING_SLACK);
HostAdmin.dontgc = timer; //prevent form being gc
})(window.HostAdmin);
<file_sep>/dist
#!/bin/bash
function dist-clean(){
rm -f *.xpi
rm -f *.zip
rm -f *.crx
echo "Cleaned"
}
function dist-check(){
ALLJS=`find . -name '*.js'`
CHECKCONSOLE=`grep console -n $ALLJS`
if [ "x$CHECKCONSOLE" != "x" ];then
echo "Console decteted"
echo $CHECKCONSOLE
exit;
fi
}
if [ -e "dist-$1.sh" ]; then
"./dist-$1.sh"
elif [ "$1" == "clean" ]; then
dist-clean
else
dist-check
for i in `ls dist-*.sh` ;do
"./$i" ;
done
echo "All Done"
fi
for i in `ls *.zip *.xpi *.crx 2>/dev/null `;do
md5sum $i
done
<file_sep>/container/firefox/host_file_wrapper.js
// HostAdmin
// by T.G.(<EMAIL>)
//
// file wrapper module
// enable hostadmin read and set hosts file
//
(function(HostAdmin){
// copy from io.js
// http://kb.mozillazine.org/Dev_:_Extensions_:_Example_Code_:_File_IO_:_jsio
var FileIO = {
localfileCID : '@mozilla.org/file/local;1',
localfileIID : Components.interfaces.nsIFile,
finstreamCID : '@mozilla.org/network/file-input-stream;1',
finstreamIID : Components.interfaces.nsIFileInputStream,
foutstreamCID : '@mozilla.org/network/file-output-stream;1',
foutstreamIID : Components.interfaces.nsIFileOutputStream,
sinstreamCID : '@mozilla.org/scriptableinputstream;1',
sinstreamIID : Components.interfaces.nsIScriptableInputStream,
suniconvCID : '@mozilla.org/intl/scriptableunicodeconverter',
suniconvIID : Components.interfaces.nsIScriptableUnicodeConverter,
open : function(path) {
try {
var file = Components.classes[this.localfileCID]
.createInstance(this.localfileIID);
file.initWithPath(path);
return file;
}
catch(e) {
return false;
}
},
read : function(file, charset) {
try {
var data = new String();
var fiStream = Components.classes[this.finstreamCID]
.createInstance(this.finstreamIID);
var siStream = Components.classes[this.sinstreamCID]
.createInstance(this.sinstreamIID);
fiStream.init(file, 1, 0, false);
siStream.init(fiStream);
data += siStream.read(-1);
siStream.close();
fiStream.close();
if (charset) {
data = this.toUnicode(charset, data);
}
return data;
}
catch(e) {
return false;
}
},
write : function(file, data, mode, charset) {
try {
var foStream = Components.classes[this.foutstreamCID]
.createInstance(this.foutstreamIID);
if (charset) {
data = this.fromUnicode(charset, data);
}
var flags = 0x02 | 0x08 | 0x20; // wronly | create | truncate
if (mode == 'a') {
flags = 0x02 | 0x10; // wronly | append
}
foStream.init(file, flags, 0664, 0);
foStream.write(data, data.length);
// foStream.flush();
foStream.close();
return true;
}
catch(e) {
return false;
}
},
create : function(file) {
try {
file.create(0x00, 0664);
return true;
}
catch(e) {
return false;
}
},
unlink : function(file) {
try {
file.remove(false);
return true;
}
catch(e) {
return false;
}
},
path : function(file) {
try {
return 'file:///' + file.path.replace(/\\/g, '\/')
.replace(/^\s*\/?/, '').replace(/\ /g, '%20');
}
catch(e) {
return false;
}
},
toUnicode : function(charset, data) {
try{
var uniConv = Components.classes[this.suniconvCID]
.createInstance(this.suniconvIID);
uniConv.charset = charset;
data = uniConv.ConvertToUnicode(data);
}
catch(e) {
// foobar!
}
return data;
},
fromUnicode : function(charset, data) {
try {
var uniConv = Components.classes[this.suniconvCID]
.createInstance(this.suniconvIID);
uniConv.charset = charset;
data = uniConv.ConvertFromUnicode(data);
// data += uniConv.Finish();
}
catch(e) {
// foobar!
}
return data;
}
};
var fire_config = (function(){
var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
prefs = prefs.getBranch("extensions.hostadmin.");
return {
get: function(key){
if (prefs.prefHasUserValue(key)) {
return prefs.getComplexValue(key, Components.interfaces.nsISupportsString).data;
}else{
return null;
}
},
run_when_not_equal: function(key, value, f){
var v = this.get(key);
if(v && v != value){
f(v);
}
}
};
})();
var host_file_wrapper = (function(){
const os = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime).OS;
var splitchar = "\n";
var file_names = [];
fire_config.run_when_not_equal("hostsfilepath", "default", function(configpath){
file_names.push(configpath);
});
if (os == "WINNT"){
splitchar = "\r\n";
try {
var winDir = Components.classes["@mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).get("WinD", Components.interfaces.nsIFile);
file_names.push(winDir.path + "\\system32\\drivers\\etc\\hosts");
}
catch (err) {}
file_names.push("C:\\windows\\system32\\drivers\\etc\\hosts");
}else if(os == "Linux"){
file_names.push("/etc/hosts");
}else if(os == "Darwin"){
file_names.push("/etc/hosts");
}
var file_name;
for(var i in file_names){
file_name = file_names[i];
var _f = FileIO.open(file_name);
if(_f && _f.exists()){
break;
}
}
var charset = "utf8"; // null means auto
// detect using jschardet
// but maybe unqualified
if(!charset){
// -- temp for windows before charset detector
if (os == "WINNT"){
charset = 'gbk';
}
//var file = FileIO.open(file_name);
//charset = jschardet.detect(FileIO.read(file));
//charset = charset ? charset.encoding : "utf8";
}
fire_config.run_when_not_equal("charset", "auto", function(c){
charset = c;
});
return {
get : function(){
var file = FileIO.open(file_name);
return FileIO.read(file, charset);
}
,
set : function(data){
if (os == "WINNT"){
data = data.replace(/([^\r])\n/g, "$1\r\n");
}
var file = FileIO.open(file_name);
return FileIO.write(file, data, '', charset);
}
,
time : function(){
var file = FileIO.open(file_name);
return file.lastModifiedTime;
}
,
splitchar : splitchar
};
})();
HostAdmin.host_file_wrapper = host_file_wrapper;
})(window.HostAdmin);
<file_sep>/core/editor.html
<!doctype html>
<html>
<head>
<title>HostAdmin Host Editor</title>
<meta charset="utf-8">
<link rel="stylesheet" href="lib/CodeMirror/lib/codemirror.css">
<script src="lib/CodeMirror/lib/codemirror.js"></script>
<script src="lib/CodeMirror/mode/hostadmin/hostadmin.js"></script>
<script src="lib/CodeMirror/addon/selection/active-line.js"></script>
<script src="lib/jquery-1.8.3.min.js"></script>
<link href="lib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="lib/bootstrap/js/bootstrap.min.js"></script>
<style type="text/css">
.CodeMirror {
border: 1px solid #CCC;
border-radius:4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
}
.container-narrow {
margin: 0 auto;
max-width: 940px;
}
.CodeMirror-activeline-background {background: #e8f2ff !important;}
</style>
</head>
<body>
<div class="container-narrow">
<button id="btnSave" class="btn btn-large btn-primary pull-right">Save</button>
<h1>HostAdmin Host Editor</h1>
<div class="alert hide" id="savefailed">
Write hosts file failed check permissions, <a href="#">Learn more</a>
</div>
<hr />
<textarea id="code" name="code"></textarea>
<hr />
<div id="syntaxhelp" style="height: 200px;overflow: auto;">
<pre id="syntax-common">
<span class="label label-success">Common Hosts File Syntax</span>
[#] IP HOSTNAME [# COMMENT]
<span class="label label-info">Note</span>
Setting 'hide' as comment could prevent this line from managing by HostAdmin
</pre>
<pre id="syntax-grouping">
<span class="label label-success">Grouping</span>
[#] IP HOSTNAME [# COMMENT]
#==== GROUPNAME
[...]
#====
<span class="label label-info">Example</span>
#==== Project 1
#127.0.0.1 localhost1
127.0.0.1 localhost2
127.0.0.1 localhost3
#====
#==== Project 2
#127.0.0.1 localhost1
#127.0.0.1 localhost2
#127.0.0.1 localhost3
#====
</pre>
<pre>
<span class="label label-success">Bulk Hide</span>
#hide_all_of_below
....
#All text here will be parsed as comment
....
</pre>
</div>
<hr />
<div id="footer" class="row" style="text-align:center">
<p>
Editor powered by <a href="http://codemirror.net/" target="_blank">CodeMirror</a> |
<a href="http://code.google.com/p/fire-hostadmin/issues" target="_blank">Feedback</a>
</p>
</div>
</div>
<div id="contentchanged" class="modal hide fade">
<div class="modal-body">
<p>Host file has changed outside! Reload ? </p>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal" aria-hidden="true">Don't Reload</a>
<a id="mreload" href="#" class="btn btn-warning">Reload, Changes will lose</a>
</div>
</div>
<script src="glue.js"></script>
<script src="editor.js"></script>
<a href="https://github.com/tg123/chrome-hostadmin" target="_blank"><img style="position: absolute; top: 0; left: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_left_gray_6d6d6d.png" alt="Fork me on GitHub"></a>
</body>
</html>
<file_sep>/core/popup.js
run_from_glue(function(HostAdmin){
var host_admin = HostAdmin.core;
var event_host = HostAdmin.event_host;
var container = HostAdmin.container;
var searchval = container.curhost();
var opentab = container.opentab;
var searchbar = $("#search input");
var save_alert = function(r){
if(r){
$(".alert").hide('slow');
}else{
$(".alert").show('slow');
}
};
var host_ul = $("#list");
var weight = function(stra, strb){
var l = new Levenshtein(stra, strb);
l = l.distance / l.longestDistance();
// Rule
var p = strb.indexOf(stra);
if(p === 0) l -= 0.15;
if(p > 0) l -= 0.1;
if(stra[0] == strb[0]) l -= 0.1;
return l;
};
var GROUP_PLACE_HOLDER_KEY = '@GROUP';
var findhost = function(wanted, hosts, group_names){
var found = [];
var min_groupl = 1;
for (var h in hosts){
var minl = weight(wanted, h);
for(var i in hosts[h]){
var host = hosts[h][i];
var gn = group_names[host.group];
if (gn) {
var gl = weight(wanted, gn);
minl = Math.min(minl, gl);
min_groupl = Math.min(min_groupl, gl);
}
var comment = host.comment;
if (comment) {
minl = Math.min(minl, weight(wanted, comment));
}
}
found.push({'host': h , 'ld': minl});
}
found.push({'host': GROUP_PLACE_HOLDER_KEY , 'ld': min_groupl});
// TODO insert might be better
found.sort(function(a,b) { return a.ld - b.ld; });
return found;
};
var make_host_item = function(host,h,i){
var a = $('<a href="#"><i class="icon-"></i>' +
host.addr + (host.comment ? '<em class="badge pull-right hostcomment" title="' + host.comment + '">' + host.comment + '</em>' : '' ) +
// '<i class="hostgroup pull-right hide"></i></a>');
'</a>');
a.click(function(){
save_alert(host_admin.host_toggle_and_save(h, i));
});
var em = $('<i class="icon-edit pull-right hide"></i>');
em.click(function(){
opentab('EDITOR', host.line);
});
var li = $("<li/>").append(a);
li.prepend(em);
if(host.using){
li.find('i.icon-').addClass('icon-ok');
}
if(host.group > 0){
a.hover(function(){
var group = li.find('i.hostgroup');
group.addClass('icon-folder-open');
});
}
return li;
};
var make_host_header = function(h){
var em = $('<i class="icon-globe pull-right hide"></i>');
em.attr('title', 'Open http://' + h);
em.click(function(){
opentab('http://' + h);
});
var li = $('<li class="nav-header"></li>');
li.text(h);
li.prepend(em);
return li;
};
var make_group_item = function(group_name, group_id, host_list){
var a = $('<a href="#"><i class="icon-"></i>' + group_name + '<em class="pull-right">' + '' +'</em></a>');
a.click(function(){
save_alert(host_admin.group_toggle_and_save(host_list, group_id));
});
var li = $("<li/>").append(a);
if(host_admin.group_checked(host_list, group_id)){
li.find('i').addClass('icon-ok');
}
return li;
};
var redraw = function(){
var wanted = searchbar.val();
wanted = $.trim(wanted);
var oldcontainer = host_ul.find("div");
var newcontainer = $("<div></div>");
var hosts = host_admin.get_hosts();
var group_names = host_admin.get_groups();
var groups = [];
var group_place_holder = null;
findhost(wanted, hosts, group_names).forEach(function(h){
h = h.host;
var hul = $("<ul/>");
hul.addClass('nav nav-list');
if(h === GROUP_PLACE_HOLDER_KEY){
group_place_holder = hul;
}else{
var added = false;
var addblock = {};
for(var i in hosts[h]){
var host = hosts[h][i];
if(host.hide){
continue;
}
if(!added){
hul.append(make_host_header(h));
added = true;
}
var g = host.group;
var gn = group_names[g];
if(gn){
if(typeof groups[g] == "undefined"){
groups[g] = [];
}
groups[g].push(h);
if(!host.comment){
host.comment = gn;
}
}
// auto merge blocker
// do not block if has comment
if(host.comment || !addblock[host.addr]){
addblock[host.addr] = true;
hul.append(make_host_item(host, h, i));
}
}
}
newcontainer.append(hul);
});
if ( groups.length > 0){
var gul = group_place_holder;
gul.append($('<li class="nav-header">' + '<i class="icon-folder-open"></i>GROUPS' + '</li>'));
for(var group_id in groups){
var group_name = group_names[group_id];
var host_list = groups[group_id];
gul.append(make_group_item(group_name, group_id, host_list));
}
}else{
// because of #hide
group_place_holder.remove();
}
oldcontainer.replaceWith(newcontainer);
};
searchbar.keyup(function(){
redraw();
//host_ul.animate({scrollTop:0}, 'fast');
host_ul.scrollTop(0);
});
$(document.body).keydown(function(){
searchbar.focus();
});
$("#openeditor").click(function(){
opentab('EDITOR');
});
$(".alert a").click(function(){
opentab('PERMHELP');
});
event_host.addEventListener('HostAdminRefresh', function(e) {
redraw();
}, false);
// -- init
host_admin.refresh();
searchval = host_admin.real_hostname(searchval);
searchbar.val(searchval).select();
redraw();
host_ul.scrollTop(0);
}
);
<file_sep>/defaults/preferences/prefs.js
pref("extensions.hostadmin.hostsfilepath", "default");
pref("extensions.hostadmin.charset", "auto");
pref("extensions.hostadmin.firstrun", true);
// https://developer.mozilla.org/en/Localizing_extension_descriptions
pref("extensions.{bd54afa8-b14a-4d7a-aecf-37e34e882796}.description", "chrome://hostadmin/locale/overlay.properties");
<file_sep>/container/firefox/firstrun.js
// HostAdmin
// by T.G.(<EMAIL>)
//
// MPL v2
// http://code.google.com/p/fire-hostadmin/
(function(){
// {{{
// copy from https://developer.mozilla.org/en/Code_snippets/Toolbar
function installButton(toolbarId, id, afterId) {
if (!document.getElementById(id)) {
var toolbar = document.getElementById(toolbarId);
// If no afterId is given, then append the item to the toolbar
var before = null;
if (afterId) {
var elem = document.getElementById(afterId);
if (elem && elem.parentNode == toolbar)
before = elem.nextElementSibling;
}
toolbar.insertItem(id, before);
toolbar.setAttribute("currentset", toolbar.currentSet);
document.persist(toolbar.id, "currentset");
if (toolbarId == "addon-bar")
toolbar.collapsed = false;
}
}
// }}}
var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
prefs = prefs.getBranch("extensions.hostadmin.");
var firstrun = prefs.getBoolPref("firstrun");
if (firstrun) {
prefs.setBoolPref("firstrun", false);
window.addEventListener("load", function(){
installButton("nav-bar", "hostadmin-toolbar-button");
}, false);
}
})();
<file_sep>/core/editor.js
run_from_glue(function(HostAdmin){
var host_admin = HostAdmin.core;
var event_host = HostAdmin.event_host;
var container = HostAdmin.container;
var opentab = container.opentab;
var changed = false;
var codeMirror = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
styleActiveLine: true
});
var save = $("#btnSave");
codeMirror.on("change", function(){
changed = true;
save.attr("disabled", null);
});
codeMirror.setValue(host_admin.load());
var move_cursor = function(cursorline){
if(cursorline || cursorline === 0){
codeMirror.setCursor(cursorline);
codeMirror.scrollIntoView({line: cursorline}, 150);
codeMirror.focus();
}
}
move_cursor(HostAdmin.cursorline);
var renew = function(){
changed = false;
save.attr("disabled", "disabled");
$(".alert").hide('slow');
};
var reload = function(){
var pos = codeMirror.getScrollInfo()
codeMirror.setValue(host_admin.load());
renew();
codeMirror.scrollTo(pos.left, pos.top);
};
$("#mreload").click(function(){
$("#contentchanged").modal('hide');
reload();
});
event_host.addEventListener('HostAdminRefresh', function(e) {
if(!changed){
reload();
}else{
$("#contentchanged").modal('show');
}
}, false);
event_host.addEventListener('HostAdminReqCursorLine', function(e) {
move_cursor(e.detail.cursorline);
}, false);
save.click(function(e) {
if(changed){
changed = false;
var pos = codeMirror.getScrollInfo()
if(host_admin.save(codeMirror.getValue())){
renew();
codeMirror.scrollTo(pos.left, pos.top);
}else{
$(".alert").show('slow');
}
}
});
$(document).keydown(function(event){
if (event.which == 83 && (event.ctrlKey||event.metaKey)) {
event.preventDefault();
save.click();
return false;
}
return true;
});
$(".alert a").click(function(){
opentab('PERMHELP');
});
renew();
});
<file_sep>/npapi/src/const.h
#ifdef XP_WIN
#define OSNAME "WINNT"
#else
#define OSNAME "Linux"
#endif
#define PROP_OS "os"
#define PROP_WHERE "where"
#define METHOD_SET "set"
#define METHOD_GET "get"
#define METHOD_TIME "time"
#define MIMETYPE "application/x-hostadmin-helper"
#define MIMETYPE_S "application/x-hostadmin-helper::HostAdmin"
#define UTF8BOM "\xEF\xBB\xBF"
<file_sep>/container/chrome/host_file_wrapper.js
;(function(HostAdmin){
var helper = document.getElementById("host_admin_helper");
var splitchar = "\n";
var os = helper.os;
var file_name;
if (os == "WINNT"){
splitchar = "\r\n";
file_name = helper.where + "\\drivers\\etc\\hosts";
}else if(os == "Linux"){
file_name = "/etc/hosts";
}else if(os == "Darwin"){
file_name = "/etc/hosts";
}
HostAdmin.host_file_wrapper = {
get : function(){
return helper.get(file_name);
},
set : function(data){
if (os == "WINNT"){
data = data.replace(/([^\r])\n/g, "$1\r\n");
}
return helper.set(file_name, data);
},
time : function(){
return helper.time(file_name);
},
splitchar : splitchar
};
})(window.HostAdmin);
<file_sep>/container/firefox/container.js
;(function(HostAdmin){
var EDITOR_URL = 'chrome://hostadmin/content/editor.html';
var PERM_HELP_URL = HostAdmin.PERM_HELP_URL;
// {{{ copy from https://developer.mozilla.org/en-US/docs/Code_snippets/Tabbed_browser
function openAndReuseOneTabPerURL(url) {
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var browserEnumerator = wm.getEnumerator("navigator:browser");
// Check each browser instance for our URL
var found = false;
while (!found && browserEnumerator.hasMoreElements()) {
var browserWin = browserEnumerator.getNext();
var tabbrowser = browserWin.gBrowser;
// Check each tab of this browser instance
var numTabs = tabbrowser.browsers.length;
for (var index = 0; index < numTabs; index++) {
var currentBrowser = tabbrowser.getBrowserAtIndex(index);
//if (url == currentBrowser.currentURI.spec) {
if (currentBrowser.currentURI.spec.indexOf(url) == 0) {
// The URL is already opened. Select this tab.
tabbrowser.selectedTab = tabbrowser.tabContainer.childNodes[index];
// Focus *this* browser-window
browserWin.focus();
found = true;
break;
}
}
}
// Our URL isn't open. Open it now.
if (!found) {
var recentWindow = wm.getMostRecentWindow("navigator:browser");
if (recentWindow) {
// Use an existing browser window
recentWindow.delayedOpenTab(url, null, null, null, null);
}
else {
// No browser windows are open, so open a new one.
window.open(url);
}
}
}
// }}}
var cur_host = "";
var tabchange = function(e){
var browser = gBrowser.selectedBrowser;
cur_host = browser.contentWindow.window.location.hostname;
};
var opentab = function(t, line){
var url = null;
if(t == 'EDITOR'){
url = EDITOR_URL;
}else if (t == 'PERMHELP'){
url = PERM_HELP_URL;
}else{
url = t;
}
if(url){
HostAdmin.cursorline = line;
openAndReuseOneTabPerURL(url);
document.getElementById("hostadmin-menu-panel").hidePopup();
HostAdmin.requestCursorLine(line)
}
};
HostAdmin.container = {
opentab : opentab,
curhost : function(){ return cur_host; }
};
var popuphelper = {
HostAdmin : HostAdmin
};
var host_admin = HostAdmin.core;
window.addEventListener('DOMWindowCreated', function(e){
if(
e.target.documentURI.indexOf(document.getElementById('hostadmin-menu-content').getAttribute('src')) === 0
||
e.target.documentURI.indexOf(EDITOR_URL) === 0
){
e.target.defaultView.window.firefox = popuphelper;
}
}, true);
window.addEventListener("load", function(){
gBrowser.tabContainer.addEventListener("TabOpen", tabchange, false);
gBrowser.tabContainer.addEventListener("TabSelect", tabchange, false);
gBrowser.tabContainer.addEventListener("TabAttrModified", tabchange, false);
document.getElementById('hostadmin-toolbar-button').addEventListener('command', function(e){
var menucontent = document.getElementById('hostadmin-menu-content').contentWindow;
menucontent.focus();
// TODO dup code from popup.js
host_admin.refresh();
var $ = menucontent.window.$;
var searchval = host_admin.real_hostname(cur_host);
$("#search input").val(searchval).select().keyup();
}, false);
}, false);
})(window.HostAdmin);
<file_sep>/dist-chrome.sh
#/bin/bash
VER=`grep '"version".*:.*".*"' manifest.json -P -o | sed -e 's/["| ]//g' | cut -d : -f 2`
TARGET=chrome-hostadmin-$VER
CHROME_PROVIDERS="container/chrome/ core/ icons/ npapi/"
# clean
rm -f $TARGET.zip
rm -f $TARGET.crx
# build for store
zip -r $TARGET.zip $CHROME_PROVIDERS manifest.json -x 'npapi/src/*' '**/.*'
echo $TARGET.zip "DONE"
if [ "$1" != "crx" ];then
exit
fi
# build crx useless ....
TMP=`mktemp -d`
PLUGINDIR="$TMP/plugin"
mkdir -p $PLUGINDIR
unzip -d $PLUGINDIR/$TARGET $TARGET.zip
CHROME="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
if [ ! -e "$CHROME" ]
then
CHROME='google-chrome' # ubuntu
fi
"$CHROME" --pack-extension=$PLUGINDIR/$TARGET
cp $PLUGINDIR/$TARGET.crx .
echo $TARGET.crx "DONE"
<file_sep>/npapi/src/hostadmin.h
#ifdef XP_WIN
#include <windows.h>
#endif
#include "npapi_headers/npapi.h"
#include "npapi_headers/npfunctions.h"
<file_sep>/CONTRIBUTING.markdown
Contributing to HostAdmin
=========================
Patchs are welcomed. Follow instructions below to make some change to HostAdmin
Envirment
---------
### Getting sources
git clone https://github.com/tg123/chrome-hostadmin.git
### Firefox
1. Create your dev profile. You can get detail from [Setting up an extension development environment](https://developer.mozilla.org/en/docs/Setting_up_extension_development_environment)
1. Link HostAdmin to Firefox dev profile (Linux)
ln -s /path/to/chrome-hostadmin/ ~/.mozilla/firefox/YOURDEVPROFILENAME/extensions/\{bd54afa8-b14a-4d7a-aecf-37e34e882796\}
1. Start dev firefox with dev profile
firefox -P dev
### Chrome
1. Open [chrome://extensions/](chrome://extensions/)
1. Enable `Developer mode` and use `Load unpacked extension` to load HostAdmin. You can get more help from [Getting Started: Building a Chrome Extension](https://developer.chrome.com/extensions/getstarted.html)
1. NPAPI (Optional)
You may want edit NPAPI, you can find source at `npapi/src`
* Build on Linux (gcc, Just make to build hostadmin.so)
* Mac (open hostadmin.xcodeproj with XCode, Command + B to build hostadmin.plugin)
* Windows (open hostadmin.sln with Visual Studio Express 2008, build .dll)
Build Distributions
-------------------
You can build .xpi(Firefox) and .zip(Chrome) using dist script. *Notice:* If you are building on Mac, you need `gnu coreutils` ratcher built-in `BSD coreutils`.
Build all
./dist
Clean up
./dist clean
Sometimes, you may want .crx version.
./dist-chrome.sh crx
<file_sep>/npapi/src/Makefile
FLAG = -Wall -fPIC -DXP_UNIX=1 -O2
CC = cc
define SO
hostadmin.$(1).so: hostadmin.$(1).o
$(CC) $(FLAG) -shared -m$(2) hostadmin.$(1).o -o hostadmin.$(1).so
hostadmin.$(1).o: hostadmin.c hostadmin.h const.h
$(CC) $(FLAG) -m$(2) -c -o hostadmin.$(1).o hostadmin.c
endef
all: hostadmin.x86.so hostadmin.amd64.so
/bin/cp *.so ../
$(eval $(call SO,x86,32))
$(eval $(call SO,amd64,64))
clean :
rm -f hostadmin.*.o hostadmin.*.so
.PHONY: all clean
<file_sep>/README.markdown
HostAdmin
=====================
Saving your time when you switch domain-ip mapping between different environment
Installing
-----------------------------
* [Chrome WebStore](https://chrome.google.com/webstore/detail/oklkidkfohahankieehkeenbillligdn)
* [Firefox AddonSite](https://addons.mozilla.org/firefox/addon/hostadmin)
* [Download from Google Code](http://code.google.com/p/fire-hostadmin/downloads/list)
How HostAdmin analyze the Hosts file
------------------------------------
[Syntax detail](http://code.google.com/p/fire-hostadmin/wiki/HOST_SYNTAX)
* ``Common``
IP DOMAIN [#COMMENT]
*Example:*
127.0.0.1 localhost #comment here
NOTE: A line with a comment, 'hide' (case-insensitive), would be hiden from HostAdmin.
* ``Grouping``
#==== Groupname
# some mappings
#====
*Example:*
#==== Project 1
#127.0.0.1 localhost1
127.0.0.1 localhost2
127.0.0.1 localhost3
#====
#==== Project 2
#127.0.0.1 localhost1
#127.0.0.1 localhost2
#127.0.0.1 localhost3
#====
* ``Bulk Hide``
#hide_all_of_below
...
#All text here will be parsed as comment
...
WRITE Permission to Hosts File
------------------------------
*WRITE Permission* to Hosts is needed, thus HostAdmin could modify your Host Files.
XP users need NO additional setting.
Here is a guide for you to gain write privilege for Vista/7/Linux/MacOS users
http://code.google.com/p/fire-hostadmin/wiki/GAIN_HOSTS_WRITE_PERM
DNS Auto refreshing
-------------------
* ``Firefox``
HostAdmin borrowed code from [DNS flusher](https://addons.mozilla.org/en-US/firefox/addon/dns-flusher/)
to refresh dns when hosts file is modified.
* ``Chrome``
Since Chrome 21, Chrome will auto refresh dns by itself.
More info at this [ticket](http://code.google.com/p/chromium/issues/detail?id=125599)
| c05c23ff89c1183df0a876c44eed1c5e62ded85e | [
"HTML",
"JavaScript",
"Markdown",
"Makefile",
"C",
"Shell"
] | 18 | JavaScript | anhtuan80/chrome-hostadmin | fd16496a7da74c6f65ea5ba40bbeb03a257ee641 | 3fca9d6fe8008c4134b4bf6ac7af1213dba61155 |
refs/heads/master | <repo_name>zh-konopleova/SO<file_sep>/src/app/admin/admin.component.ts
import { Component, OnInit } from '@angular/core';
import { QuestionService } from '../question.service';
import { AuthService } from '../auth.service';
import { Observable } from 'rxjs';
import { Question } from '../question.model';
@Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {
adminQuestionList: Observable<Question[]>;
isLoading: boolean = true;
constructor(private questionService: QuestionService, private authService: AuthService) {}
ngOnInit(): void {
this.adminQuestionList = this.questionService.getInitialAll();
this.questionService.getInitialAll().subscribe(() => this.isLoading = false);
}
approve(question) {
question.status = 'approved';
this.questionService.update(question);
}
reject(question) {
question.status = 'rejected';
this.questionService.update(question);
}
}
<file_sep>/src/app/question/question.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute} from '@angular/router';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { QuestionService } from '../question.service';
import { AuthService } from '../auth.service';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Question } from '../question.model';
@Component({
selector: 'app-question',
templateUrl: './question.component.html',
styleUrls: ['./question.component.css']
})
export class QuestionComponent implements OnInit {
question: Question;
isLoading: boolean = true;
form: FormGroup = new FormGroup({
answer: new FormControl('', [
Validators.required
])
});
constructor(private questionService: QuestionService, private authService: AuthService, private activateRoute: ActivatedRoute) {
let id = this.activateRoute.snapshot.params['id'];
this.questionService.get(id).subscribe((question) => {
this.question = question;
this.isLoading = false
});
}
ngOnInit(): void {}
onSubmit(): void {
let answer = this.form.get('answer').value;
this.question.answers.push(answer);
this.form.reset();
this.questionService.update(this.question);
}
isControlValid(control: string): boolean {
return this.form.controls[control].valid;
}
// isEnabledAnswer(): boolean {
// return this.form.valid && !!this.authService.isAuthUser().subscribe(() => this.user);
// }
//
}
<file_sep>/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { environment } from '../environments/environment';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AppHeaderComponent } from './app-header/app-header.component';
import { QuestionListComponent } from './question-list/question-list.component';
import { AuthorizationComponent } from './authorization/authorization.component';
import { RegistrationComponent } from './registration/registration.component';
import { QuestionComponent } from './question/question.component';
import { AngularFireModule } from '@angular/fire';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { AuthGuard } from './auth.guard';
import { UnauthGuard } from './unauth.guard';
import { AuthService } from './auth.service';
import { QuestionFormComponent } from './question-form/question-form.component';
import { QuestionService } from './question.service';
import { SpinnerComponent } from './spinner/spinner.component';
import { AdminComponent } from './admin/admin.component';
import { TagsComponent } from './tags/tags.component';
@NgModule({
declarations: [
AppComponent,
AppHeaderComponent,
QuestionListComponent,
AuthorizationComponent,
RegistrationComponent,
QuestionComponent,
QuestionFormComponent,
SpinnerComponent,
AdminComponent,
TagsComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFireAuthModule,
AngularFirestoreModule
],
providers: [AuthService, AuthGuard, UnauthGuard, QuestionService],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { QuestionListComponent } from './question-list/question-list.component';
import { AuthorizationComponent } from './authorization/authorization.component';
import { RegistrationComponent } from './registration/registration.component';
import { QuestionComponent } from './question/question.component';
import { AuthGuard } from './auth.guard';
import { UnauthGuard } from './unauth.guard';
import { AdminGuard } from './admin.guard';
import { QuestionFormComponent } from './question-form/question-form.component';
import { AdminComponent } from './admin/admin.component';
const routes: Routes = [
{path: '', component: QuestionListComponent},
{path: 'login', component: AuthorizationComponent, canActivate: [AuthGuard]},
{path: 'signup', component: RegistrationComponent, canActivate: [AuthGuard]},
{path: 'question/:id', component: QuestionComponent},
{path: 'question-form', component: QuestionFormComponent, canActivate: [UnauthGuard]},
{path: 'admin', component: AdminComponent, canActivate: [AdminGuard]}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>/src/app/question-form/question-form.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { FormGroup, FormControl, Validators } from '@angular/forms';
import{ QuestionService } from '../question.service';
import { Question } from '../question.model';
@Component({
selector: 'app-question-form',
templateUrl: './question-form.component.html',
styleUrls: ['./question-form.component.css']
})
export class QuestionFormComponent implements OnInit {
form: FormGroup = new FormGroup({
title: new FormControl('', [
Validators.required
]),
description: new FormControl('', [
Validators.required
])
});
constructor(private questionService: QuestionService, private router: Router) { }
ngOnInit(): void {}
onSubmit(): void {
let question = new Question().deserialize(this.form.value);
this.questionService.create(question);
this.form.reset();
this.router.navigate(['/']);
}
isControlValid(control: string) {
return this.form.controls[control].valid;
}
}
<file_sep>/src/app/question.model.ts
export class Question {
id?: string;
title: string;
description: string;
createdAt: number;
status: string;
answers: string[];
constructor() {
this.createdAt = +new Date();
this.status = 'initial';
}
serialize(): any {
return {
title: this.title,
description: this.description,
createdAt: this.createdAt,
answers: this.answers,
status: this.status
}
}
deserialize({ id, title, description, answers, createdAt, status }: any): this {
this.id = id;
this.title = title;
this.description = description;
this.answers = answers || [];
this.createdAt = createdAt || this.createdAt;
this.status = status || 'initial';
return this;
}
static compare(a: Question, b: Question) {
return b.createdAt - a.createdAt;
}
}
<file_sep>/src/app/registration/registration.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { FormGroup, FormControl, Validators } from "@angular/forms";
import { AuthService } from '../auth.service';
@Component({
selector: 'app-registration',
templateUrl: './registration.component.html',
styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {
error: string;
form: FormGroup = new FormGroup({
email: new FormControl('',[
Validators.required,
Validators.email
]),
password: new FormControl('', [
Validators.required,
Validators.minLength(6)
])
});
constructor(private authService: AuthService, private router: Router) {}
ngOnInit(): void {}
onSubmit(): void {
let email = this.form.get('email').value,
password = this.form.get('password').value;
this.authService.createUser(email, password)
.subscribe(
(data) => {
this.authService.sendEmailVerification(data.user);
this.router.navigate(['/'])
this.form.reset();
},
(error) => { this.error = error }
);
}
onClickGoogle(): void {
this.authService.logInWithGoogle();
}
isControlValid(control: string) {
return this.form.controls[control].valid;
}
}
<file_sep>/src/environments/environment.prod.ts
export const environment = {
production: true,
firebaseConfig: {
apiKey: "<KEY>",
authDomain: "myso-ccb72.firebaseapp.com",
databaseURL: "https://myso-ccb72.firebaseio.com",
projectId: "myso-ccb72",
storageBucket: "myso-ccb72.appspot.com",
messagingSenderId: "134886238768"
}
};
<file_sep>/src/app/auth.service.ts
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { User, auth } from 'firebase/app';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { from } from 'rxjs';
import { first, tap } from 'rxjs/operators';
@Injectable()
export class AuthService {
user: Observable<User>;
constructor(private authFire: AngularFireAuth) {
this.user = authFire.authState;
}
logInWithEmail(email, password): Observable<any> {
return from(this.authFire.auth.signInWithEmailAndPassword(email, password));
}
logInWithGoogle(): void {
this.authFire.auth.signInWithPopup(new auth.GoogleAuthProvider());
}
createUser(email, password): Observable<any> {
return from(this.authFire.auth.createUserWithEmailAndPassword(email ,password));
}
sendEmailVerification(user): void {
user.sendEmailVerification()
}
logOut(): void {
this.authFire.auth.signOut();
}
isLoggedIn() {
return this.authFire.authState.pipe(first())
}
isAuthUser() {
this.isLoggedIn().pipe(
tap(user => {
if (user) {
return true;
} else {
return false
}
})
)
.subscribe()
}
// isAdmin() {
// this.authFire.authState.subscribe(user => {
// if(user.email === '<EMAIL>')
// return true;
// })
// }
}
<file_sep>/src/app/question.service.ts
import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { map } from 'rxjs/operators';
import { Observable, BehaviorSubject, combineLatest } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { Question } from './question.model';
@Injectable()
export class QuestionService {
constructor(private db: AngularFirestore) {
}
create(question: Question): void {
this.db.collection('questions').add(question.serialize());
}
update(question: Question): void {
this.db.collection('questions').doc(question.id).update(question.serialize());
}
getAll(): Observable<Question[]> {
return this.db.collection('questions').snapshotChanges()
.pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
});
}),
map((questions) => {
return questions.map((question) => new Question().deserialize(question));
}),
map((questions) => {
return questions.sort(Question.compare)
})
);
}
getInitialAll(): Observable<Question[]> {
return this.getAll().pipe(
map(questions => {
return questions.filter(question => {
return question.status === 'initial' || null;
})
})
)
}
getApprovedAll(): Observable<Question[]> {
return this.getAll().pipe(
map(questions => {
return questions.filter(question => {
return question.status === 'approved';
})
})
);
}
get(id): Observable<Question> {
return this.db.collection('questions').doc(id).valueChanges().pipe(
map((question) => {
question['id'] = id;
return new Question().deserialize(question);
})
);
}
}
| 4e88f699adb6f7170139bbdb75295904c0410a25 | [
"TypeScript"
] | 10 | TypeScript | zh-konopleova/SO | 30407832905ae63704c1cd90009b6da225158ef0 | fa818c094d2fd1481ec8ff612e6418fc7f1621ee |
refs/heads/master | <repo_name>boyhavoc/Jquery-fileupload-rails-4-example<file_sep>/app/models/upload.rb
class Upload < ActiveRecord::Base
has_attached_file :upload, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
validates_attachment :upload, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
include Rails.application.routes.url_helpers
def to_jq_upload
{
"name" => read_attribute(:upload_file_name),
"size" => read_attribute(:upload_file_size),
"url" => upload.url(:original),
"thumbnailUrl" => upload.url(:thumb),
"deleteUrl" => upload_path(self),
"deleteType" => "DELETE"
}
end
end
<file_sep>/app/controllers/uploads_controller.rb
class UploadsController < ApplicationController
before_filter :load_upload, only: [:edit, :update, :destroy, :show]
def index
end
def create
@upload = Upload.new(:upload => params[:files].first)
respond_to do |format|
if @upload.save
format.html {render :json => {files: [@upload.to_jq_upload].to_json}, :content_type => 'text/html', :layout => false}
format.json { render json: {files: [@upload.to_jq_upload]}, status: :created, location: uploads_path }
else
format.html { render action: "new" }
format.json { render json: @upload.errors, status: :unprocessable_entity }
end
end
end
def destroy
@upload.destroy
respond_to do |format|
format.html { redirect_to uploads_path }
format.json { head :no_content }
end
end
private
def load_upload
@upload = Upload.find(params[:id])
end
end
<file_sep>/README.md
# Demo application for uploading files
## Description
The application provides a basic demo of Jquery Fileupload Plugin in action using paperclip in Rails.
## Setup
* Download the application.
* bundle install
* rake db:create
* rake db:migrate
* Start the application (rails s)
* Visit http:://localhost:3000
## Requirements
* Ruby version >= 2.0
* Rails version >= 4.0
* Note: ImageMagick must be installed(on your machine) and Paperclip must have access to it for processing images.
## Sources
* [jquery-fileupload-rails](https://github.com/tors/jquery-fileupload-rails)
* [Paperclip](https://github.com/thoughtbot/paperclip)
* [Twitter Bootstrap rails](https://github.com/seyhunak/twitter-bootstrap-rails).
* [ImageMagick](http://www.imagemagick.org/)
<file_sep>/config/routes.rb
Rails.application.routes.draw do
resources "uploads" do
collection do
get "with_dropzone_area"
end
end
root 'uploads#index'
end
| 0322ca0d762ad9fa84931766f052fe18648e132a | [
"Markdown",
"Ruby"
] | 4 | Ruby | boyhavoc/Jquery-fileupload-rails-4-example | 0187f4f6f6ebf390c6993f40edc9332b6a1b65ee | 9fc4b3adb18da8a1708616b3b16299f7c05b6b75 |
refs/heads/master | <file_sep>const Footer = ({ numOfRemaining, handleClearDone }) => {
return (
<footer>
<p>剩餘項目: {numOfRemaining}</p>
<button className={"btn-reset btn-clear "} onClick={handleClearDone}>清除項目已完成</button>
</footer>
)
}
export default Footer;<file_sep>import clsx from "clsx";
const AddTodo = ({ inputValue, setInputValue, handleChange, handleAdd }) => {
return (
<div className={clsx("add-todo", { active: inputValue.length > 0 })}>
<label className="add-todo-icon icon" htmlFor="add-todo-input"></label>
<div className="add-todo-input">
<input id="add-todo-input" onChange={handleChange} value={inputValue} type="text" placeholder="新增工作" />
</div>
<div className="add-todo-action">
<button className="btn-reset btn-add" onClick={handleAdd}> 新增 </button>
</div>
</div>
)
}
export default AddTodo;<file_sep>import clsx from "clsx"
const TodoItem = ({ todo, handleDelete, handleIsDone }) => {
return (
<div className={clsx("task-item", { done: todo.isDone })} key={todo.id}>
<div className="task-item-checked">
<span className="icon icon-checked" onClick={handleIsDone(todo.id)}>
</span>
</div>
<div className="task-item-body">
<span className="task-item-body-text">{todo.title}</span>
<input className="task-item-body-input" type="text" placeholder="新增工作" />
</div>
<div className="task-item-action">
<button className="btn-reset btn-destroy icon" onClick={handleDelete(todo.id)}> </button>
</div>
</div>
)
}
export default TodoItem; | bf296354b9c8ae77c61284b8bd9b45c404306cc7 | [
"JavaScript"
] | 3 | JavaScript | AnnHuang-tool/todo-mvc-react | 9fec503745df5e593cc0f3684039c8c5e64ee6a0 | 64ed42aa0a010c4f3c9877404f7d35a94df79a20 |
refs/heads/main | <repo_name>Trevo525/Data-Structures-and-Algorithms-in-Java<file_sep>/README.md
# Data Structures and Algorithms in Java
I did [this course](https://www.udemy.com/course/data-structures-and-algorithms-deep-dive-using-java/) on Udemy. This is the project files I created following the course.
After making this app in Java I created it in C#. This can be found [here](https://github.com/Trevo525/Data-Structures-and-Algorithms).
<file_sep>/Heaps 1 Insert/src/Heap.java
public class Heap {
private int[] heap;
private int size;
public Heap(int capacity) {
heap = new int[capacity];
}
public void insert(int value) {
if (isFull()) {
throw new IndexOutOfBoundsException("Heap is full");
}
heap[size++] = value;
fixHeapAbove(size);
size++;
}
private void fixHeapAbove(int index) {
int newValue = heap[index];
while (index > 0 && newValue > heap[getParent(index)]) {
heap[index] = heap[getParent(index)];
index = getParent(index);
}
heap[index] = newValue;
}
public boolean isFull() {
return size == heap.length;
}
public int getParent(int index) {
return (index - 1) / 2;
}
}
<file_sep>/Section Challenges/Sort Algorithms Challenge 2/src/academy/learnprogramming/challenge2/Main.java
package academy.learnprogramming.challenge2;
public class Main {
public static void main(String[] args) {
int[] intArray = { 20, 35, -15, 7, 55, 1, -22 };
// insertion sort
// insertionSort(intArray);
// insertionSortRecursive(intArray);
insertionSortVideoExample(intArray, intArray.length);
// print array
for (int i = 0; i < intArray.length; i++) {
System.out.println(intArray[i]);
}
}
private static void insertionSort(int[] intArray) {
for (int firstUnsortedIndex = 1; firstUnsortedIndex < intArray.length; firstUnsortedIndex++) {
int newElement = intArray[firstUnsortedIndex];
int i;
for (i = firstUnsortedIndex; i > 0 && intArray[i - 1] > newElement; i--) {
intArray[i] = intArray[i - 1];
}
intArray[i] = newElement;
}
}
private static void insertionSortRecursive(int[] intArray) {
// My attempt at making the insertion sort recursive. It works but it wasn't exactly what the video wanted.
for (int firstUnsortedIndex = 1; firstUnsortedIndex < intArray.length; firstUnsortedIndex++) {
int newElement = intArray[firstUnsortedIndex];
// start recursive call here
int i = recursiveSort(intArray, newElement, firstUnsortedIndex);
// insert into array at index
intArray[i] = newElement;
}
}
private static int recursiveSort(int[] intArray, int newElement, int index) {
// break the recursion
if (index == 0) {
return 0;
}
if (intArray[index - 1] <= newElement) {
return index;
} else {
intArray[index] = intArray[index - 1];
return recursiveSort(intArray, newElement, index - 1);
}
}
public static void insertionSortVideoExample(int[] input, int numItems){
/*
*This is the example from the video
*/
if (numItems < 2) {
return;
}
insertionSortVideoExample(input, numItems - 1);
int newElement = input[numItems -1];
int i;
for (i = numItems -1; i > 0 && input [i -1]> newElement; i--){
input[i] = input[i-1];
}
input[i] = newElement;
}
}
| bfddf37a0e3ecc75554d4e9bdc9925da044eec13 | [
"Markdown",
"Java"
] | 3 | Markdown | Trevo525/Data-Structures-and-Algorithms-in-Java | d325e37d45015c8ad3c5d257914909e11abbc728 | 34f30ac404467c20ceebdcf1efaa56b7b14508e5 |
HEAD | <repo_name>hsarkar/programming<file_sep>/spoj/src/done/PT07Z.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class PT07Z {
static class Graph {
private final int V;
private Set<Integer>[] adj;
public Graph(int V) {
this.V = V;
adj = (HashSet<Integer>[]) new HashSet[V];
for (int v = 0; v < V; v++) {
adj[v] = new HashSet<Integer>();
}
}
public int V() {
return V;
}
public void addEdge(int v, int w) {
adj[v].add(w);
adj[w].add(v);
}
public Iterable<Integer> adj(int v) {
return adj[v];
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
for (int i = 0; i < V; i++) {
b.append(i + " -> ");
for(int w : adj[i]) {
b.append(w + " ");
}
b.append("\n");
}
return b.toString();
}
}
static class DFS {
private boolean[] marked;
private int[] edgeTo;
private int[] depth;
private int s; // source
private Graph G;
private int farthestNode;
private int longestPathLength;
public DFS(Graph G, int s) {
this.G = G;
this.s = s;
marked = new boolean[G.V()];
Arrays.fill(marked, false);
edgeTo = new int[G.V()];
Arrays.fill(edgeTo, -1);
depth = new int[G.V()];
Arrays.fill(depth, 0);
edgeTo[s] = s;
farthestNode = s;
longestPathLength = depth[s];
}
public void traverse() {
Stack<Integer> stack = new Stack<Integer>();
stack.add(s);
while(!stack.isEmpty()) {
int v = stack.pop();
for(int w : G.adj(v)) {
if(!marked[w]) {
marked[w] = true;
edgeTo[w] = v;
depth[w] = depth[v] + 1;
if(depth[w] > longestPathLength) {
longestPathLength = depth[w];
farthestNode = w;
}
stack.push(w);
}
}
}
}
public Stack<Integer> getLogestPath() {
Stack<Integer> stack = new Stack<Integer>();
int n = farthestNode;
while(n != s) {
stack.push(n);
n = edgeTo[n];
}
return stack;
}
public int getLongestPathLength() {
return longestPathLength;
}
public int getFarthestNode() {
return farthestNode;
}
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(reader.readLine());
int N = Integer.parseInt(st.nextToken());
Graph g = new Graph(N);
for (int i = 0; i < N - 1; i++) {
st = new StringTokenizer(reader.readLine());
int v = Integer.parseInt(st.nextToken());
int w = Integer.parseInt(st.nextToken());
g.addEdge(v - 1, w - 1);
}
DFS d = new DFS(g, 0);
d.traverse();
int newS = d.getFarthestNode();
d = new DFS(g, newS);
d.traverse();
System.out.println(d.getLongestPathLength());
}
}
<file_sep>/ml/CI/test.py
# row1 = [1, 2, 3]
# row2 = [4, 5, 6]
# row3 = [-3, 0, 5]
# rows = [row1, row2, row3]
# range = [(min([row[i] for row in rows]), max([row[i] for row in rows]))
# for i in range(len(rows[0]))]
# print range
# BeautifulSoup
from BeautifulSoup import BeautifulSoup<file_sep>/spoj/src/done/PALIN_TLE.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class PALIN_TLE {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(reader.readLine());
for(int i = 0 ; i < N ; i++) {
String number = reader.readLine();
int l = number.length();
int endIndexFirst = l % 2 == 0 ? l / 2 : l / 2 + 1; // end index for first part (exclusive)
String reverseFirstHalf = new StringBuilder(number.substring(0, l / 2)).reverse().toString();
String secondHalf = number.substring(endIndexFirst);
String preFirstHalf = number.substring(0, endIndexFirst);
// string compare suffices
if(reverseFirstHalf.compareTo(secondHalf) <= 0) {
BigInteger firstHalf = new BigInteger(preFirstHalf);
firstHalf = firstHalf.add(BigInteger.ONE);
String newFirstHalf = firstHalf.toString();
int postLen = newFirstHalf.length();
StringBuilder builder = new StringBuilder(newFirstHalf);
String secondHalfPalin = builder.reverse().toString();
if(l % 2 == 1) {
secondHalfPalin = secondHalfPalin.substring(1);
}
int preLen = preFirstHalf.length();
if(postLen > preLen) {
secondHalfPalin = secondHalfPalin.substring(1);
}
System.out.println(firstHalf + secondHalfPalin);
} else {
System.out.println(preFirstHalf + reverseFirstHalf);
}
}
}
}<file_sep>/eclipse/workspace/programming/src/graph/Graph.java
package graph;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class Graph<V extends Vertex, E extends Edge<V>>
{
public final Map<V, ArrayList<V>> adj; // adjacency list
private final boolean isDirected;
public Graph(final boolean isDirected)
{
adj = new LinkedHashMap<V, ArrayList<V>>();
this.isDirected = isDirected;
}
public Graph(final int size, final boolean isDirected)
{
adj = new HashMap<V, ArrayList<V>>(size);
this.isDirected = isDirected;
}
public void addVertex(final V vertex)
{
// lookup is inexpensive in map
if (adj.containsKey(vertex))
{
System.out.printf("Vertex %s already exists\n", vertex);
}
else
{
adj.put(vertex, new ArrayList<V>());
}
}
public void addEdge(final E edge)
{
if (!adj.containsKey(edge.v1))
{
adj.put(edge.v1, new ArrayList<V>());
}
if (!adj.containsKey(edge.v2))
{
adj.put(edge.v2, new ArrayList<V>());
}
// add edge v1->v2
if (!adj.get(edge.v1).contains(edge.v2))
{
adj.get(edge.v1).add(edge.v2);
}
else
{
System.out.printf("Edge %s->%s is already present", edge.v1, edge.v2);
}
// if not directed then add v2->v1 also
if (!isDirected)
{
if (!adj.get(edge.v2).contains(edge.v1))
{
adj.get(edge.v2).add(edge.v1);
}
else
{
System.out.printf("Edge %s->%s is already present", edge.v2, edge.v1);
}
}
}
public V getGraphHandle()
{
return (V) adj.keySet().toArray()[0];
}
public Iterator getGraphIterator()
{
return adj.entrySet().iterator();
}
public static void main(final String... args)
{
Vertex<String> v1 = new Vertex<String>("vertex1");
Vertex<String> v2 = new Vertex<String>("vertex2");
Edge<Vertex> edge = new Edge<Vertex>(v1, v2);
Graph<Vertex, Edge<Vertex>> graph = new Graph<Vertex, Edge<Vertex>>(true);
graph.addEdge(edge);
System.out.print(graph.adj);
}
}
<file_sep>/spoj/src/done/ONP.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class ONP {
public static void main(String[] args) throws IOException {
// precedence table for operators except (, )
Map<Character, Integer> priority = new HashMap<Character, Integer>();
priority.put(')', -2);
priority.put('(', -1);
priority.put('+', 0);
priority.put('-', 1);
priority.put('+', 2);
priority.put('*', 3);
priority.put('/', 4);
priority.put('^', 5);
Set<Character> operator = new HashSet<Character>(Arrays.asList(new Character[]
{'+', '-', '+', '*', '/', '^', '(', ')'}));
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Stack<Character> stack = new Stack<Character>();
int N = Integer.parseInt(reader.readLine());
for(int i = 0 ; i < N ; i++) {
stack.clear();
// postfix builder
StringBuilder pBuilder = new StringBuilder();
String infix = reader.readLine();
int len = infix.length();
for(int j = 0 ; j < len ; j++) {
Character c = infix.charAt(j);
// if operator
if(operator.contains(c)) {
switch(c) {
case '(' :
stack.push(c);
break;
case ')' :
char tempC;
while((tempC = stack.pop()) != '(') {
pBuilder.append(tempC);
}
break;
default :
// if incoming operators priority is higher than top of stack, push it to stack
if(stack.isEmpty() || priority.get(c) > priority.get(stack.peek())) {
stack.push(c);
} else {
while(!stack.isEmpty() && priority.get(c) < priority.get(stack.peek())) {
pBuilder.append(stack.pop());
}
}
}
}
// else operand
else {
pBuilder.append(c);
}
}
System.out.println(pBuilder);
}
}
}<file_sep>/eclipse/workspace/programming/src/CuttingRod.java
/* problem statement */
import java.io.*;
import java.util.*;
public class CuttingRod {
static int[] price1 = {1, 5, 8, 9, 10, 17, 17, 20};
static int[] price2 = {1, 5, 8, 9, 10, 7, 17, 20};
public int maxPrice(int n, int[] price) {
int ret_price = Integer.MIN_VALUE;
int temp_price = 0;
if(n == 0)
ret_price = price[0];
else
for(int i = 0 ; i <= n ; i++) {
temp_price = (int)Math.max(price[i], price[i] + maxPrice(n - 1 - i, price));
if (ret_price < temp_price)
ret_price = temp_price;
}
return ret_price;
}
public static void main(String[] args) {
CuttingRod cr = new CuttingRod();
for (int i = 0 ; i < price2.length; i++)
System.out.println(cr.maxPrice(i, price2));
}
}
<file_sep>/eclipse/workspace/programming/src/lightoj/beginners/Prob1010cpp.java
package lightoj.beginners;
import java.io.IOException;
/**
* @author himadri.sarkar
*
*/
public class Prob1010cpp
{
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(final String[] args) throws NumberFormatException, IOException
{
// int m, n, l1, l2, b1, b2, A, mod;
// BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//
// int T = Integer.parseInt(reader.readLine());
// String[] words = new String[2];
// for (int i = 0; i < T; i++)
// {
// words = reader.readLine().split(" ");
// m = Integer.parseInt(words[0]);
// n = Integer.parseInt(words[1]);
//
// if (m < n)
// {
// // swaping without using extra variables
// m = m + n; // this might lead to overflow
// n = m - n;
// m = m - n;
// }
//
// if (n == 1)
// {
// A = m;
// }
// else if (n == 2)
// {
// A = (m / 4) * 4;
// mod = m % 4;
// if (mod == 1)
// A += 2;
// else if (mod == 2 || mod == 3)
// A += 4;
// }
// else
// {
// l1 = (m + 1) / 2;
// l2 = m - l1;
// b1 = (n + 1) / 2;
// b2 = n - b1;
// A = l1 * b1 + l2 * b2;
// }
// System.out.printf("Case %d: %d\n", i + 1, A);
// }
// reader.close();
}
}
<file_sep>/ml/CI/recommendations.py
# A dictionary of movie critics and their ratings of a small
# set of movies
critics={'<NAME>': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,
'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,
'The Night Listener': 3.0},
'<NAME>': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,
'Just My Luck': 1.5, 'Superman Returns': 5.0, 'The Night Listener': 3.0,
'You, Me and Dupree': 3.5},
'<NAME>': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0,
'Superman Returns': 3.5, 'The Night Listener': 4.0},
'<NAME>': {'Snakes on a Plane': 3.5, 'Just My Luck': 3.0,
'The Night Listener': 4.5, 'Superman Returns': 4.0,
'You, Me and Dupree': 2.5},
'<NAME>': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
'Just My Luck': 2.0, 'Superman Returns': 3.0, 'The Night Listener': 3.0,
'You, Me and Dupree': 2.0},
'<NAME>': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
'The Night Listener': 3.0, 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5},
'Toby': {'Snakes on a Plane':4.5,'You, Me and Dupree':1.0,'Superman Returns':4.0}}
from math import sqrt
# Returns a distance-based similarity score for person1 and person2
def sim_distance(prefs, person1, person2):
# Get the list of shared_items
si={}
for item in prefs[person1]:
if item in prefs[person2]:
si[item]=1
# if they have no ratings in common, return 0
if len(si)==0: return 0
# Add up the squares of all the differences
sum_of_squares=sum([pow(prefs[person1][item] - prefs[person2][item], 2)
for item in prefs[person1] if item in prefs[person2]])
# +1 in denominator to avoid division by 0
return 1/(1 + sum_of_squares)
# Returns the Pearson correlation coefficient for p1 and p2
def sim_pearson(prefs, p1, p2):
# Get the list of mutually related items
si = []
for item in prefs[p1]:
if item in prefs[p2]:
si.append(item);
# Find the number of elements
n = len(si)
# if there are no ratings in common, return 0
if n == 0:
return 0
# Add up all the preferences
sum1 = sum([prefs[p1][item] for item in si])
sum2 = sum([prefs[p2][item] for item in si])
# Add up the squares of all preferences
sum1Sq = sum([prefs[p1][item] ** 2 for item in si])
sum2Sq = sum([prefs[p2][item] ** 2 for item in si])
# sum of product of preferences
pSum = sum(prefs[p1][item] * prefs[p2][item] for item in si)
# Calculate Pearson score
num = pSum - (sum1 * sum2 / n)
den = sqrt((sum1Sq - sum1 ** 2 / n) * (sum2Sq - sum2 ** 2 / n))
if den == 0:
return 0
r = num / den
return r
# Returns the best matches for person from the prefs dictionary.
# Number of results and similarity function are optional params.
def topMatches(prefs,person,n=5,similarity=sim_pearson):
scores=[(similarity(prefs,person,other),other) for other in prefs if other != person]
#Sort the list so the highest scores appear at the top
scores.sort()
scores.reverse()
return scores[:n]
# Gets recommendations for a person by using a weighted average
# of every other user's rankings
def getRecommendaitons(prefs, person, similarity=sim_pearson):
totals = {}
simSums = {}
for other in prefs:
# don't compare me to myself
if other == person:
continue
sim = similarity(prefs, person, other)
# ignore scores of zero or lower
if sim <= 0:
continue
for item in prefs[other]:
#only score movies I haven't seen yet
if item not in prefs[person] or prefs[person][item] == 0:
# Similarity * Score
totals.setdefault(item, 0)
totals[item] += prefs[other][item] * sim
#Sum of similarities
simSums.setdefault(item, 0)
simSums[item] += sim
# create the normalized list
rankings = [(total / simSums[item], item) for item, total in totals.items()]
# Return the sorted list
rankings.sort()
rankings.reverse()
return rankings
# print "Correlation using euclidean distance", sim_distance(critics,'<NAME>','<NAME>')
# print "Using pearson correlation", sim_pearson(critics, '<NAME>', '<NAME>')
# print topMatches(critics, 'Toby', n=3)
# print getRecommendaitons(critics,'Toby')
"""get top movies similar to other movies
first transform ctirics data
dictionary from:
{'<NAME>': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5},
'<NAME>': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5}}
to:
{'Lady in the Water':{'<NAME>':2.5,'<NAME>':3.0},
'Snakes on a Plane':{'<NAME>':3.5,'<NAME>eymour':3.5}} etc..
"""
def transformPrefs(prefs):
result={}
for person in prefs:
for item in prefs[person]:
result.setdefault(item, {})
#flip item and person
result[item][person] = prefs[person][item]
return result
# movies = transformPrefs(critics)
# topMatches(movies, 'Superman Returns')
def calculateSimilarItems(prefs, n = 10):
# Create a dictionary of items showing which other items they are similar to
result = {}
#Invert the preference matrix to be item-centric
itemPrefs = transformPrefs(prefs)
c = 0
for item in itemPrefs:
# Status updates for large datasets
c += 1
if c % 100 == 0: print "%d / %d" % (c, len(itemPrefs))
# Find the most simillar items to this one
scores = topMatches(itemPrefs, item, n = n, similarity=sim_distance)
result[item] = scores
return result
itemsim = calculateSimilarItems(critics)
print itemsim
def getRecommendedItems(prefs, itemMatch, user):
userRatings = prefs[user]
print userRatings
scores = {}
totalSim = {}
#Loop over items rated by this user
for (item, rating) in userRatings.items():
#Loop over items similar to this one
for (similarity, item2) in itemMatch[item]:
#Ignore if this user has already rated this item
if item2 in userRatings:
continue
# weighted sum of rating times similarity
scores.setdefault(item2, 0)
scores[item2] += similarity * rating
# sum of all the similarities
totalSim.setdefault(item2, 0)
totalSim[item2] += similarity
# divide each total score by total weighting to get an average
rankings = [(score / totalSim[item], item) for item, score in scores.items()]
# return the rankings from highest to lowest
rankings.sort()
rankings.reverse()
return rankings
print getRecommendedItems(critics, itemsim, 'Toby')
<file_sep>/spoj/src/done/TEST.java
package done;
import java.util.Scanner;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class TEST {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(true) {
int num = in.nextInt();
if(num != 42) {
System.out.println(num);
} else {
break;
}
}
}
}
<file_sep>/eclipse/workspace/programming/src/skiena/chapter8/EditDistanceNaive.java
package skiena.chapter8;
/**
* @author himadri.sarkar
*
*/
public class EditDistanceNaive
{
int MATCH = 0;
int INSERT = 1;
int DELETE = 2;
// cost of insert or delete
int indel(final char c)
{
return 1;
}
int match(final char c, final char d)
{
if (c == d)
return 0;
else
return 1;
}
int stringCompare(final String s, final String t, final int i, final int j)
{
int k;
int[] opt = new int[3];
int lowestCost;
if (i == 0)
return j * indel(' ');
if (j == 0)
return i * indel(' ');
opt[MATCH] = stringCompare(s, t, i - 1, j - 1) + match(s.charAt(i), t.charAt(j));
opt[INSERT] = stringCompare(s, t, i, j - 1) + indel(t.charAt(j));
opt[DELETE] = stringCompare(s, t, i - 1, j) + indel(s.charAt(i));
System.out.printf("%s %s\n", s.substring(0, i), t.substring(0, j));
lowestCost = opt[MATCH];
for (k = INSERT; k <= DELETE; k++)
{
if (opt[k] < lowestCost)
lowestCost = opt[k];
}
return lowestCost;
}
public static void main(final String[] args)
{
EditDistanceNaive ed = new EditDistanceNaive();
String s = "himadri";
String t = "adr";
System.out.println(ed.stringCompare(s, t, s.length() - 1, t.length() - 1));
}
}
<file_sep>/ml/distance.py
#!/usr/bin/python
from math import sqrt
from recommendations import critics
# Returns a distance-based similarity score for person1 and person2
def sim_distance(prefs, person1, person2):
# Get the list of shared_items
si={}
for item in prefs[person1]:
if item in prefs[person2]:
si[item]=1
# if they have no ratings in common, return 0
if len(si)==0: return 0
# Add up the squares of all the differences
sum_of_squares=sum([pow(prefs[person1][item] - prefs[person2][item], 2)
for item in prefs[person1] if item in prefs[person2]])
# +1 in denominator to avoid division by 0
return 1/(1 + sum_of_squares)
<file_sep>/spoj/src/done/FASHION.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* User: himadri.sarkar
* Date: 24/12/13
*/
public class FASHION {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(reader.readLine());
for(int i = 0 ; i < N ; i++) {
int persons = Integer.parseInt(reader.readLine());
List<Short> mensRating = new ArrayList<Short>(persons);
List<Short> womensRating = new ArrayList<Short>(persons);
String[] word = reader.readLine().split(" ");
for(int j = 0 ; j < persons ; j++) {
mensRating.add(Short.parseShort(word[j]));
}
word = reader.readLine().split(" ");
for(int j = 0 ; j < persons ; j++) {
womensRating.add(Short.parseShort(word[j]));
}
Collections.sort(mensRating);
Collections.sort(womensRating);
long netRating = 0;
for(int j = 0 ; j < persons ; j++) {
netRating += mensRating.get(j) * womensRating.get(j);
}
System.out.println(netRating);
}
}
}
<file_sep>/eclipse/workspace/programming/src/ChessKnight.java
import java.util.*;
public class ChessKnight {
int []dx = {-2, -2, -1, -1, 1, 1, 2, 2};
int []dy = {-1, 1, -2, 2, -2, 2, -1, 1};
double[][][] memo;
public double probablility(int x, int y, int n) {
memo = new double [8][8][n + 1];
for(int i = 0; i < memo.length; i++) {
for(int j = 0 ; j < memo[i].length; j++) {
Arrays.fill(memo[i][j], -1);
}
}
return doit(x - 1, y - 1, n);
}
double doit(int x, int y, int n) {
if (x < 0 || y < 0 || x >= 8 || y >= 8) return 0;
if(n == 0) return 1;
if(memo[x][y][n] != -1) return memo[x][y][n];
double ret = 0;
for(int i = 0 ; i < dx.length; i++) {
ret += doit(x+dx[i], y + dy[i], n - 1);
}
ret /= 8;
memo[x][y][n] = ret;
return ret;
}
public static void main(String[] args) {
ChessKnight ck = new ChessKnight();
System.out.println(ck.probablility(1, 1, 5));
}
}
<file_sep>/algs4/src/Subset.java
/**
* @author himadri.sarkar
*
*/
public class Subset {
public static void main(final String[] args) {
int k = Integer.parseInt(args[0]);
RandomizedQueue<String> rq = new RandomizedQueue<String>();
String input[] = StdIn.readStrings();
for (String element : input) {
rq.enqueue(element);
}
while (k-- > 0) {
System.out.println(rq.dequeue());
}
}
}
<file_sep>/spoj/src/done/ADDREV.java
package done;
import java.util.Scanner;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class ADDREV {
private static String reverse(String s) {
StringBuilder b = new StringBuilder(s);
return b.reverse().toString();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
for(int i = 0 ; i < N ; i++) {
String s1 = in.next();
String s2 = in.next();
int n1 = Integer.parseInt(reverse(s1));
int n2 = Integer.parseInt(reverse(s2));
int revSum = n1 + n2;
String sum = reverse(String.valueOf(revSum));
System.out.println(Integer.parseInt(sum));
}
}
}
<file_sep>/eclipse/workspace/cpp/src/Prob1010.cpp
//============================================================================
// Name : Main.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <stdio.h>
using namespace std;
int main(int argc, char** argv)
{
int m, n, l1, l2, b1, b2, A, mod, T;
scanf("%d", &T);
for (int i = 0; i < T; i++)
{
scanf("%d %d", &m, &n);
if (m < n)
{
// swaping without using extra variables
m = m + n; // this might lead to overflow
n = m - n;
m = m - n;
}
if (n == 1)
{
A = m;
}
// in case of
else if (n == 2)
{
A = (m / 4) * 4;
mod = m % 4;
if (mod == 1)
A += 2;
else if (mod == 2 || mod == 3)
A += 4;
}
else
{
l1 = (m + 1) / 2;
l2 = m - l1;
b1 = (n + 1) / 2;
b2 = n - b1;
A = l1 * b1 + l2 * b2;
}
printf("Case %d: %d\n", i + 1, A);
}
return 0;
}
<file_sep>/spoj/src/done/ARMY_TLE.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class ARMY_TLE {
static String[] split(String line, int N, String delim) {
String[] words = new String[N];
int pos = 0, end, n = 0;
while((end = line.indexOf(delim, pos)) >= 0) {
words[n] = line.substring(pos, end);
pos = end + delim.length();
n++;
}
// extract last token
if(pos != line.length() && !line.substring(pos).equals(delim)) {
words[n] = line.substring(pos);
}
return words;
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(reader.readLine());
for(int i = 0 ; i < T ; i++) {
reader.readLine(); // read endline
String[] word = split(reader.readLine(), 2, " ");
int NG = Integer.parseInt(word[0]);
int NM = Integer.parseInt(word[1]);
word = split(reader.readLine(), NG, " ");
int g = Integer.MIN_VALUE;
for (int j = 0; j < NG; j++) {
g = Math.max(g, Integer.parseInt(word[j]));
}
word = split(reader.readLine(), NM, " ");
int m = Integer.MIN_VALUE;
for (int j = 0; j < NM; j++) {
m = Math.max(m, Integer.parseInt(word[j]));
}
if (g >= m) {
System.out.println("Godzilla");
} else {
System.out.println("MechaGodzilla");
}
}
}
}<file_sep>/algs4/exercises/DrawRectangle.java
/**
* @author himadri.sarkar
*
*/
public class DrawRectangle
{
public static void main(final String[] args)
{
double xlo = Double.parseDouble(args[0]);
double xhi = Double.parseDouble(args[1]);
double ylo = Double.parseDouble(args[2]);
double yhi = Double.parseDouble(args[3]);
Interval1D x = new Interval1D(xlo, xhi);
Interval1D y = new Interval1D(ylo, yhi);
Interval2D box = new Interval2D(x, y);
box.draw();
}
}
<file_sep>/eclipse/workspace/programming/src/main/Prob1241.java
package main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author himadri.sarkar
*
*/
public class Prob1241
{
public static void main(final String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(reader.readLine());
String[] words = null;
int n, lies, mod, diff;
int[] A = new int[10];
for (int i = 0; i < T; i++)
{
n = Integer.parseInt(reader.readLine());
words = reader.readLine().split(" ");
lies = 0;
for (int j = 0; j < n; j++)
{
A[j] = Integer.parseInt(words[j]);
}
if (A[0] > 2)
{
lies += (A[0] - 2) / 5;
if ((A[0] - 2) % 5 > 0)
lies++;
}
for (int j = 1; j < n; j++)
{
diff = A[j] - A[j - 1];
if (diff > 0)
{
lies += diff / 5;
if (diff % 5 > 0)
{
lies++;
}
}
}
System.out.printf("Case %d: %d\n", i + 1, lies);
}
}
}
<file_sep>/algs4/src/PercolationStats.java
/**
* @author himadri.sarkar
*
*/
public class PercolationStats {
private final double[] X;
private final int N;
private final int T;
// perform T independent computational experiments on an N-by-N grid
public PercolationStats(final int N, final int T) {
if (N <= 0 || T <= 0) {
throw new IllegalArgumentException();
}
this.N = N;
this.T = T;
X = new double[T];
for (int t = 0; t < T; t++) {
Percolation per = new Percolation(N);
double openSites = 0;
while (true) {
int i = StdRandom.uniform(1, N + 1);
int j = StdRandom.uniform(1, N + 1);
if (!per.isOpen(i, j)) {
per.open(i, j);
openSites++;
if (per.percolates()) {
X[t] = openSites / (N * N);
break;
}
}
}
}
}
// sample mean of percolation threshold
public double mean() {
return StdStats.mean(X);
}
// sample standard deviation of percolation threshold
public double stddev() {
return StdStats.stddev(X);
}
// returns lower bound of the 95% confidence interval
public double confidenceLo() {
double mu = mean();
double sigma = stddev();
return mu - (1.96 * sigma) / Math.sqrt(T);
}
// returns upper bound of the 95% confidence interval
public double confidenceHi() {
double mu = mean();
double sigma = stddev();
return mu + (1.96 * sigma) / Math.sqrt(T);
}
// test client, described below
public static void main(final String[] args) {
PercolationStats pStats = new PercolationStats(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
StdOut.printf("mean = %f\n", pStats.mean());
StdOut.printf("stddev = %f\n", pStats.stddev());
StdOut.printf("95%% confidence interval = %f, %f\n", pStats.confidenceLo(), pStats.confidenceHi());
}
}
<file_sep>/spoj/src/done/ABSYS.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class ABSYS {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(reader.readLine());
for(int i = 0 ; i < N ; i++) {
reader.readLine(); // to skip blank lines
String[] word = reader.readLine().split(" ");
if(word[0].contains("machula")) {
int o2 = Integer.parseInt(word[2]);
int o3 = Integer.parseInt(word[4]);
System.out.println((o3 - o2) + " + " + o2 + " = " + o3);
} else if(word[2].contains("machula")) {
int o1 = Integer.parseInt(word[0]);
int o3 = Integer.parseInt(word[4]);
System.out.println(o1 + " + " + (o3 - o1) + " = " + o3);
} else {
int o1 = Integer.parseInt(word[0]);
int o2 = Integer.parseInt(word[2]);
System.out.println(o1 + " + " + o2 + " = " + (o1 + o2));
}
}
}
}<file_sep>/spoj/src/helper/DFS.java
package helper;
import java.util.Arrays;
/**
* User: himadri.sarkar
* Date: 01/01/14
*/
public class DFS {
private boolean[] marked;
private int[] edgeTo;
private int s; // source
public DFS(Graph G, int s) {
marked = new boolean[G.V()];
Arrays.fill(marked, false);
edgeTo = new int[G.V()];
Arrays.fill(edgeTo, -1);
edgeTo[s] = s;
dfs(G, s);
}
private void dfs(Graph G, int v) {
marked[v] = true;
for(int w : G.adj(v))
if(!marked[w]) {
dfs(G, w);
edgeTo[w] = v;
}
}
public static void main(String[] args) {
Graph g = new Graph(5);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(0, 1);
DFS dfs = new DFS(g, 0);
System.out.println(Arrays.toString(dfs.marked));
System.out.println(Arrays.toString(dfs.edgeTo));
}
}
<file_sep>/algs4/src/PointSET.java
import java.util.Set;
import java.util.TreeSet;
/**
* @author himadri.sarkar
*
*/
public class PointSET {
private final Set<Point2D> set;
// construct an empty set of points
public PointSET() {
set = new TreeSet<Point2D>();
}
// is the set empty?
public boolean isEmpty() {
return set.size() == 0;
}
// number of points in the set
public int size() {
return set.size();
}
// add the point p to the set (if it is not already in the set)
public void insert(final Point2D p) {
set.add(p);
}
// does the set contain the point p?
public boolean contains(final Point2D p) {
return set.contains(p);
}
// draw all of the points to standard draw
public void draw() {
for (Point2D point : set) {
point.draw();
}
}
// all points in the set that are inside the rectangle
public Iterable<Point2D> range(final RectHV rect) {
Set<Point2D> queue = new TreeSet<Point2D>();
for (Point2D point : set) {
if (rect.contains(point)) {
queue.add(point);
}
}
return queue;
}
// a nearest neighbor in the set to p; null if set is empty
public Point2D nearest(final Point2D p) {
double leastDistance = Double.MAX_VALUE;
Point2D nearest = null;
for (Point2D point : set) {
double distance = p.distanceTo(point);
if (Double.compare(distance, leastDistance) < 0) {
nearest = point;
leastDistance = distance;
}
}
return nearest;
}
// client
public static void main(final String[] args) {
}
}<file_sep>/eclipse/workspace/programming/src/testprograms/Test.java
package testprograms;
/**
* @author himadri.sarkar
*
*/
public class Test
{
public static void main(final String[] args)
{
}
}
<file_sep>/algs4/src/Point.java
/*************************************************************************
* Name:
* Email:
*
* Compilation: javac Point.java
* Execution:
* Dependencies: StdDraw.java
*
* Description: An immutable data type for points in the plane.
*
*************************************************************************/
import java.util.Comparator;
public class Point implements Comparable<Point> {
// compare points by slope
public final Comparator<Point> SLOPE_ORDER = new SlopeOrder();
private final int x; // x coordinate
private final int y; // y coordinate
// create the point (x, y)
public Point(final int x, final int y) {
/* DO NOT MODIFY */
this.x = x;
this.y = y;
}
// plot this point to standard drawing
public void draw() {
/* DO NOT MODIFY */
StdDraw.point(x, y);
}
// draw line between this point and that point to standard drawing
public void drawTo(final Point that) {
/* DO NOT MODIFY */
StdDraw.line(this.x, this.y, that.x, that.y);
}
// slope between this point and that point
public double slopeTo(final Point that) {
if (compareTo(that) == 0)
return Double.NEGATIVE_INFINITY;
else if (this.x == that.x)
return Double.POSITIVE_INFINITY;
// otherwise concluding else might return either NEGATIVE_INFINITY or POSITIVE_INFINITY
else if (this.y == that.y)
return 0.0;
else
return (double) (this.y - that.y) / (this.x - that.x);
}
// is this point lexicographically smaller than that one?
// comparing y-coordinates and breaking ties by x-coordinates
@Override
public int compareTo(final Point that) {
return (this.y != that.y) ? this.y - that.y : this.x - that.x;
}
// return string representation of this point
@Override
public String toString() {
/* DO NOT MODIFY */
return "(" + x + ", " + y + ")";
}
private class SlopeOrder implements Comparator<Point> {
@Override
public int compare(final Point p1, final Point p2) {
return Double.compare(slopeTo(p1), slopeTo(p2));
}
}
// unit test
public static void main(final String[] args) {
Point p1 = new Point(19000, 10000);
Point p2 = new Point(18000, 10000);
Point p3 = new Point(1800, 10000);
System.out.println(p1.SLOPE_ORDER.compare(p2, p3));
}
}
<file_sep>/eclipse/workspace/programming/src/puzzlers/Oddity.java
package puzzlers;
public class Oddity {
public static void main(String... args) {
System.out.println(-3 % 2 == 1);
}
}
<file_sep>/eclipse/workspace/programming/src/ThreeNumZeroSum.java
/* using 3 pointers */
import java.util.Arrays;
public class ThreeNumZeroSum {
public void printTrio(int[] A) {
Arrays.sort(A);
int s = 0, e = 0;
for(int i = 0 ; i < A.length ; i++) {
s = 0;
e = A.length - 1;
while(s < e) {
if (A[i] + A[s] + A[e] == 0 && s != i && i != e && e != s)
{
System.out.println("Numbers are: " + A[i] + " " + A[s] + " " + A[e]);
s++;
}
else if(A[i] + A[e] + A[s] > 0)
e--;
else
s++;
}
}
}
public static void main(String[] args) {
int[] A = {-5, -3, -1, -6, -4, 8, 9, 13, 3};
ThreeNumZeroSum tnzs = new ThreeNumZeroSum();
tnzs.printTrio(A);
}
}
<file_sep>/algs4/src/KdTree.java
import java.util.Set;
import java.util.TreeSet;
/**
* @author himadri.sarkar
*
*/
public class KdTree {
private Node root;
private int N; // number of elements in KdTree
private class Node {
private final Point2D point;
private Node left, right;
int depth;
RectHV rect;
public Node(final Point2D point, final int depth) {
this.point = point;
this.depth = depth;
}
}
private class NearestNode {
private Node node;
private Double distance;
public NearestNode(final Node node, final Double distance) {
this.node = node;
this.distance = distance;
}
}
// construct an empty set of points
public KdTree() {
root = null;
N = 0;
}
// is the set empty?
public boolean isEmpty() {
return N == 0;
}
// number of points in the set
public int size() {
return N;
}
// compare points after determining the correct dimension
// i.e. compare x coordinate at odd depths and compare y coordinates at even depths
private int chooseSubTree(final Node parent, final Point2D p) {
if (parent.depth % 2 == 0)
return Double.compare(p.x(), parent.point.x());
else
return Double.compare(p.y(), parent.point.y());
}
// insert node
private Node insert(final Node parent, final Point2D p, final int depth) {
if (parent == null) {
N++;
return new Node(p, depth);
}
// do not insert duplicate points as this is a set
if (p.compareTo(parent.point) == 0)
return parent;
if (chooseSubTree(parent, p) < 0) {
parent.left = insert(parent.left, p, depth + 1);
if (parent.depth % 2 == 0)
parent.left.rect = new RectHV(parent.rect.xmin(), parent.rect.ymin(), parent.point.x(), parent.rect.ymax());
else
parent.left.rect = new RectHV(parent.rect.xmin(), parent.rect.ymin(), parent.rect.xmax(), parent.point.y());
} else {
parent.right = insert(parent.right, p, depth + 1);
if (parent.depth % 2 == 0)
parent.right.rect = new RectHV(parent.point.x(), parent.rect.ymin(), parent.rect.xmax(), parent.rect.ymax());
else
parent.right.rect = new RectHV(parent.rect.xmin(), parent.point.y(), parent.rect.xmax(), parent.rect.ymax());
}
return parent;
}
// add the point p to the set (if it is not already in the set)
public void insert(final Point2D p) {
root = insert(root, p, 0);
if (root.rect == null) {
// constant for this problem
root.rect = new RectHV(0, 0, 1.0, 1.0);
}
}
// search for point in given subtree
private Node get(final Node x, final Point2D p) {
if (x == null)
return null;
if (p.compareTo(x.point) == 0)
return x;
if (chooseSubTree(x, p) < 0) {
return get(x.left, p);
} else {
return get(x.right, p);
}
}
// does the set contain the point p?
public boolean contains(final Point2D p) {
return get(root, p) != null;
}
private void draw(final Node x) {
if (x == null)
return;
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.setPenRadius(.01);
x.point.draw();
StdDraw.setPenRadius();
if (x.depth % 2 == 0) {
StdDraw.setPenColor(StdDraw.RED);
StdDraw.line(x.point.x(), x.rect.ymin(), x.point.x(), x.rect.ymax());
} else {
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.line(x.rect.xmin(), x.point.y(), x.rect.xmax(), x.point.y());
}
draw(x.left);
draw(x.right);
}
// draw all of the points to standard draw
public void draw() {
draw(root);
}
// dosen't check for contains in rectangle
private int chooseSubTree(final Node x, final RectHV rect) {
if (x.depth % 2 == 0)
// dosen't matter whether xmin or xmax is taken as contians in rectangle has already been checked in calling function
return Double.compare(rect.xmax(), x.point.x());
else
return Double.compare(rect.ymax(), x.point.y());
}
// returns true if x1 <= x <= x2
private boolean between(final double x1, final double x2, final double x) {
return Double.compare(x1, x) <= 0 && Double.compare(x, x2) <= 0;
}
// if current point is inside rectange then explore both sides
// check if the line through the
private void range(final Node x, final RectHV rect, final Set<Point2D> resultSet) {
if (x == null)
return;
boolean right = false;
boolean left = false;
if (rect.contains(x.point)) {
right = true;
left = true;
resultSet.add(x.point);
} else {
if ((x.depth % 2 == 0 && between(rect.xmin(), x.point.x(), rect.xmax()))
|| (x.depth % 2 == 1 && between(rect.ymin(), x.point.y(), rect.ymax()))) {
left = true;
right = true;
} else {
if (chooseSubTree(x, rect) < 0)
left = true;
else
right = true;
}
}
if (left) {
range(x.left, rect, resultSet);
}
if (right) {
range(x.right, rect, resultSet);
}
}
// all points in the set that are inside the rectangle
public Iterable<Point2D> range(final RectHV rect) {
Set<Point2D> resultSet = new TreeSet<Point2D>();
range(root, rect, resultSet);
return resultSet;
}
// return perpendicular distance between p and line passing through x.point
private Double perpendicular(final Node x, final Point2D p) {
if (x.depth % 2 == 0)
return Math.abs(x.point.x() - p.x());
else
return Math.abs(x.point.y() - p.y());
}
// if a smaller nearest neighbor was found on the side being traversed then there is no need to traverse the other side
private NearestNode nearest(final Node x, final NearestNode nearestSoFar, final Point2D p) {
if (x == null)
return nearestSoFar;
// explore left side first, if the closest node on left has horizontal/vertical distance
// (depending on even or odd depth) go to right
Double distance = p.distanceSquaredTo(x.point);
if (distance < nearestSoFar.distance) {
nearestSoFar.node = x;
nearestSoFar.distance = distance;
}
boolean left = false;
boolean right = false;
NearestNode newNearest;
if (chooseSubTree(x, p) < 0) {
newNearest = nearest(x.left, nearestSoFar, p);
right = true;
} else {
newNearest = nearest(x.right, nearestSoFar, p);
left = true;
}
if (perpendicular(x, p) < newNearest.distance) {
if (right)
newNearest = nearest(x.right, newNearest, p);
else
newNearest = nearest(x.left, newNearest, p);
}
return newNearest;
}
// a nearest neighbor in the set to p; null if set is empty
public Point2D nearest(final Point2D p) {
NearestNode nearest = nearest(root, new NearestNode(null, Double.MAX_VALUE), p);
if (nearest.node == null)
return null;
return nearest.node.point;
}
// client
public static void main(final String[] args) {
}
}
<file_sep>/eclipse/workspace/programming/src/tooeasy/BigLoop.java
package tooeasy;
import java.io.*;
public class BigLoop {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
for(int i = 0 ; i < Math.pow(10, 9) ; i++);
long endTime = System.currentTimeMillis();
System.out.println((endTime - startTime)/(1000.0f*60.0f));
}
}
<file_sep>/eclipse/workspace/programming/src/lightoj/beginners/Prob1227.java
package lightoj.beginners;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
* @author himadri.sarkar
*
*/
public class Prob1227
{
public static void main(final String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(reader.readLine());
String[] words = null;
int n, P, Q, sumWeight, numEggs;
int[] A = new int[30];
for (int i = 0; i < T; i++)
{
words = reader.readLine().split(" ");
n = Integer.parseInt(words[0]);
P = Integer.parseInt(words[1]);
Q = Integer.parseInt(words[2]);
words = reader.readLine().split(" ");
sumWeight = 0;
numEggs = 0;
for (int j = 0; j < n; j++)
{
A[j] = Integer.parseInt(words[j]);
}
Arrays.sort(A, 0, n - 1);
for (int j = 0; j < n && j < P && sumWeight + A[j] <= Q; j++)
{
numEggs++;
sumWeight += A[j];
}
System.out.printf("Case %d: %d\n", i + 1, numEggs);
}
}
}
<file_sep>/eclipse/workspace/programming/src/QuickSort.java
import java.util.*;
public class QuickSort {
public int partition(int[] A, int start, int end) {
int p = start;
int q = start + 1;
int r = end;
while(q < r) {
while(A[q] < A[p] && q < r)
q++;
while(A[r] > A[p] && q < r)
r--;
int temp = A[q];
A[q] = A[r];
A[r] = temp;
}
if(A[p] > A[q])
{
int temp = A[p];
A[p] = A[q];
A[q] = temp;
}
return q;
}
public void qsort(int[] A, int start, int end) {
if(start < end) {
int part = partition(A, start, end);
qsort(A, start, part - 1);
qsort(A, part + 1, end);
}
}
public static void main(String[] args) {
int[] A = {10, 4, -3, 6, 90, 3};
QuickSort qs = new QuickSort();
qs.qsort(A, 0, A.length - 1);
System.out.println(Arrays.toString(A));
}
}
<file_sep>/spoj/src/done/ACPC10A.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class ACPC10A {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while(true) {
String[] word = reader.readLine().split(" ");
int n1 = Integer.parseInt(word[0]);
int n2 = Integer.parseInt(word[1]);
int n3 = Integer.parseInt(word[2]);
if(n1 == 0 && n2 == 0 && n3 == 0) {
break;
}
if(n2 - n1 == n3 - n2) {
System.out.println("AP " + (n3 + n3 - n2));
} else {
System.out.println("GP " + n3 * (n2 / n1));
}
}
}
}<file_sep>/spoj/src/done/FCTRL.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class FCTRL {
public static void main(String[] args) throws IOException {
// 5^12 < 1000000000 < 5^13
int MAX_DIV_IDX = 12;
int[] divisors = new int[MAX_DIV_IDX];
divisors[0] = 5;
for(int i = 1 ; i < divisors.length ; i++) {
divisors[i] = divisors[i - 1] * 5;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(reader.readLine());
for(int i = 0 ; i < N ; i++) {
int n = Integer.parseInt(reader.readLine());
int tz = 0; // trailing zeros
for(int d : divisors) {
if(d <= n) {
tz += n / d;
} else {
break;
}
}
System.out.println(tz);
}
}
}
<file_sep>/eclipse/workspace/programming/src/lightoj/beginners/Prob1182.java
package lightoj.beginners;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author himadri.sarkar
*
*/
public class Prob1182
{
public static void main(final String[] args) throws NumberFormatException, IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(reader.readLine());
int setbits;
String answer;
String even = "even";
String odd = "odd";
for (int i = 0; i < T; i++)
{
int n = Integer.parseInt(reader.readLine());
setbits = 0;
while (n > 0)
{
n = n & (n - 1);
setbits++;
}
if (setbits % 2 == 0)
answer = even;
else
answer = odd;
System.out.printf("Case %d: %s\n", i + 1, answer);
}
reader.close();
}
}
<file_sep>/algs4/src/Deque.java
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* @author himadri.sarkar
*
*/
public class Deque<Item> implements Iterable<Item> {
private Node first, last;
private int size;
private class Node {
Item item;
Node next;
Node previous;
public Node(final Item item) {
this.item = item;
this.next = null;
this.previous = null;
}
}
// here if you say DequeIterator<Item> then enclosing class Item will be hidden
private class DequeIterator implements Iterator<Item> {
private Node current = first;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public Item next() {
if (current == null)
throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
public Deque() {
first = last = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
private void validateItem(final Item item) {
if (item == null)
throw new NullPointerException();
}
public void addFirst(final Item item) {
validateItem(item);
Node oldfirst = first;
first = new Node(item);
first.next = oldfirst;
// if this is the first element
if (oldfirst != null)
oldfirst.previous = first;
if (last == null)
last = first;
size++;
}
public void addLast(final Item item) {
validateItem(item);
Node oldlast = last;
last = new Node(item);
// if this is the first element
if (oldlast != null)
oldlast.next = last;
last.previous = oldlast;
if (first == null)
first = last;
size++;
}
public Item removeFirst() {
if (size == 0)
throw new NoSuchElementException();
Item item = first.item;
if (size == 1) {
first = last = null;
} else {
first = first.next;
first.previous = null;
}
size--;
return item;
}
public Item removeLast() {
if (size == 0)
throw new NoSuchElementException();
Item item = last.item;
if (size == 1) {
first = last = null;
} else {
last = last.previous;
last.next = null;
}
size--;
return item;
}
@Override
public Iterator<Item> iterator() {
return new DequeIterator();
}
public static void main(final String[] args) {
Deque<Integer> dq = new Deque<Integer>();
int[] problems = { 1024, 2048, 16384, 128000, 256000, 1024000, 2048000 };
for (int size : problems) {
long start = System.currentTimeMillis();
for (int i = 0; i < size; i++) {
dq.addFirst(i);
}
for (Integer str : dq) {
;
}
System.out.println("Elapsed time: " + (System.currentTimeMillis() - start) / 1000 + " sec");
}
}
}
<file_sep>/spoj/src/helper/Graph.java
package helper;
import java.util.HashSet;
import java.util.Set;
/**
* User: himadri.sarkar
* Date: 01/01/14
*/
public class Graph {
private final int V;
private Set<Integer>[] adj;
public Graph(int V) {
this.V = V;
adj = (HashSet<Integer>[]) new HashSet[V];
for (int v = 0; v < V; v++) {
adj[v] = new HashSet<Integer>();
}
}
public int V() {
return V;
}
public void addEdge(int v, int w) {
adj[v].add(w);
adj[w].add(v);
}
public Iterable<Integer> adj(int v) {
return adj[v];
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
for (int i = 0; i < V; i++) {
b.append(i + " -> ");
for(int w : adj[i]) {
b.append(w + " ");
}
b.append("\n");
}
return b.toString();
}
public static void main(String[] args) {
Graph g = new Graph(5);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(0, 1);
System.out.println(g);
}
}
<file_sep>/eclipse/workspace/programming/src/tooeasy/BST.java
package tooeasy;
import java.io.*;
import java.util.*;
class Node {
int info;
Node left;
Node right;
public Node(int info) {
this.info = info;
left = null;
right = null;
}
}
public class BST {
private Node _root;
public BST() {
_root = null;
}
public void insert(Node node, int info) {
if (_root == null)
{
_root = new Node(info);
return;
} else if (info < node.info) {
if (node.left != null)
insert(node.left, info);
else
node.left = new Node(info);
} else {
if (node.right != null)
insert(node.right, info);
else
node.right = new Node(info);
}
}
public void traverse(Node root) {
if(root == null)
return;
else {
traverse(root.left);
System.out.println(root.info);
traverse(root.right);
}
}
public void process() {
int input = 0;
Scanner in = new Scanner(System.in);
while(true) {
input = in.nextInt();
if (input == -1) break;
insert(_root, input);
}
traverse(_root);
}
public static void main(String[] args) {
BST bst = new BST();
bst.process();
}
}
<file_sep>/spoj/src/done/AE00.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class AE00 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
int r = 0; // rectangles
for (int i = 1; i <= n ; i++) {
for (int j = 1; j <= i ; j++) {
if ( i % j == 0 ) {
int q = i / j;
if(q < j) {
break;
} else {
r++;
}
}
}
}
System.out.println(r);
}
}<file_sep>/eclipse/workspace/programming/src/caeercup/google/NumberLinkedList.java
package caeercup.google;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author himadri.sarkar
*
* http://www.careercup.com/question?id=14945498
*/
public class NumberLinkedList
{
private static class Node
{
private int value;
private Node next;
public Node(final int value)
{
this.value = value;
}
}
private Node start;
private int length;
public void insertNode(final Node newNode)
{
if (start == null)
{
start = newNode;
length = 1;
}
else
{
newNode.next = start;
start = newNode;
length++;
}
}
public void printNumber()
{
for (Node node = start; node != null; node = node.next)
{
System.out.print(node.value);
}
System.out.println();
}
public int incrementNumber(final Node node, final int singleDigitNumber)
{
if (singleDigitNumber > 9)
{
System.out.println("Please enter single digit number");
return -1;
}
if (node == null)
{
System.out.println("Null node");
return -1;
}
if (node.next == null)
{
node.value = node.value + singleDigitNumber;
int carry = node.value / 10;
node.value %= 10;
return carry;
}
else
{
int carry = incrementNumber(node.next, singleDigitNumber);
int newCarry = (node.value + carry) / 10;
node.value = (node.value + carry) % 10;
return newCarry;
}
}
public static void main(final String... args) throws IOException
{
NumberLinkedList list = new NumberLinkedList();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] words = reader.readLine().split(" ");
for (String word : words)
{
list.insertNode(new Node(Integer.parseInt(word)));
}
list.printNumber();
int carry = list.incrementNumber(list.start, 1);
if (carry > 0)
{
list.insertNode(new Node(carry));
}
list.printNumber();
}
}
<file_sep>/eclipse/workspace/programming/src/concurrency/PrintThreadName.java
package concurrency;
public class PrintThreadName implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String... args) {
Thread[] threads = new Thread[10];
int i = 0;
for(Thread thread : threads) {
thread = new Thread(new PrintThreadName());
thread.setName("Custom thread " + i++);
thread.start();
}
for(Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
// do nothing
}
}
}
}
<file_sep>/spoj/src/done/CANDY3.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class CANDY3 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(reader.readLine());
for(int i = 0 ; i < T ; i++) {
reader.readLine(); // skip blank line
long N = Long.parseLong(reader.readLine());
long sum = 0;
for (int j = 0; j < N ; j++) {
long n = Long.parseLong(reader.readLine());
sum = (sum + n) % N;
}
if(sum == 0) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}<file_sep>/eclipse/workspace/programming/src/skiena/graphs/EdgeNode.java
package skiena.graphs;
/**
* @author himadri.sarkar
*
*/
public class EdgeNode
{
public int y;
public int weight;
public EdgeNode next;
public EdgeNode(final int y, final int weight)
{
this.y = y;
this.weight = weight;
this.next = null;
}
public EdgeNode(final int y, final int weight, final EdgeNode next)
{
this.y = y;
this.weight = weight;
this.next = next;
}
}
<file_sep>/algs4/exercises/_1_1_16.java
/**
* @author himadri.sarkar
*
*/
public class _1_1_16
{
public static String exR1(final int n)
{
if (n <= 0)
return "";
else
return exR1(n - 3) + n + exR1(n - 2) + n;
}
public static void main(final String... args)
{
StdOut.println(exR1(6));
}
}
<file_sep>/eclipse/workspace/programming/src/lightoj/beginners/Prob1136.java
package lightoj.beginners;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author himadri.sarkar
*
*/
public class Prob1136
{
public static void main(final String[] args) throws NumberFormatException, IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(reader.readLine());
String[] word = null;
int A, B, count, mod;
for (int i = 0; i < T; i++)
{
word = reader.readLine().split(" ");
A = Integer.parseInt(word[0]);
B = Integer.parseInt(word[1]);
if (A == B)
{
if ((A - 1) % 3 != 0)
count = 1;
else
count = 0;
}
else
{
count = 2 * ((B - A + 1) / 3);
mod = (B - A + 1) % 3;
if (mod == 1 || mod == 2)
{
if ((B - 1) % 3 != 0)
count++;
}
if (mod == 2)
{
if ((B - 2) % 3 != 0)
count++;
}
}
System.out.printf("Case %d: %d\n", i + 1, count);
}
reader.close();
}
}
<file_sep>/spoj/src/done/PALIN.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Arrays;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class PALIN {
// returns true if reverse(firstHalf) > secondHalf
static boolean compareHalfs(char[] number, int firstHalfEnd, int secondHalfStart) {
while(firstHalfEnd > 0) {
if(number[firstHalfEnd] > number[secondHalfStart]) {
return true;
} else if (number[firstHalfEnd] < number[secondHalfStart]) {
return false;
}
firstHalfEnd--;
secondHalfStart++;
}
return false;
}
// returns true if there is a carryover
static void addOne(char[] number, int end) {
boolean carryOver = true;
while(carryOver && end >= 0) {
if(number[end] == '9') {
number[end] = '0';
} else {
number[end] += 1;
carryOver = false;
}
end--;
}
}
static void copyChars(char[] number, int firstEnd, int secondStart, int leastIndex) {
while(firstEnd >= leastIndex) {
number[secondStart] = number[firstEnd];
secondStart++;
firstEnd--;
}
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(reader.readLine());
char[] number = new char[1000001];
for(int i = 0 ; i < N ; i++) {
number[0] = '0'; // to account for carry
int length = 1;
while((number[length++] = (char)reader.read()) != '\n');
length--;
boolean oddDigits;
int firstHalfEnd;
if(length % 2 == 0) {
firstHalfEnd = length / 2 - 1;
oddDigits = true;
} else {
firstHalfEnd = length / 2;
oddDigits = false;
}
int secondHalfStart = length / 2 + 1;
// if reverse of 1st half is < second half, increment 1st half by 1
boolean firstGreaterThanSecond = compareHalfs(number, firstHalfEnd, secondHalfStart);
if(!firstGreaterThanSecond) {
if(oddDigits) {
addOne(number, firstHalfEnd + 1);
} else {
addOne(number, firstHalfEnd);
}
if(number[0] == '1') {
firstHalfEnd--;
}
}
String output;
if(number[0] == '1') {
copyChars(number, firstHalfEnd, secondHalfStart, 0);
output = new String(number, 0, length);
} else {
copyChars(number, firstHalfEnd, secondHalfStart, 1);
output = new String(number, 1, length - 1);
}
System.out.println(output);
}
}
}<file_sep>/spoj/src/done/LASTDIG_SE.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class LASTDIG_SE {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(reader.readLine());
Map<Integer, Integer[]> d = new HashMap<Integer, Integer[]>();
d.put(0, new Integer[]{0});
d.put(1, new Integer[]{1});
d.put(2, new Integer[]{6, 2, 4, 8});
d.put(3, new Integer[]{1, 3, 9, 7});
d.put(4, new Integer[]{4, 6});
d.put(5, new Integer[]{5});
d.put(6, new Integer[]{6});
d.put(7, new Integer[]{1, 7, 9, 3});
d.put(8, new Integer[]{6, 8, 4, 2});
d.put(9, new Integer[]{1, 9});
for(int i = 0 ; i < N ; i++) {
String[] words = reader.readLine().split(" ");
int base = Integer.parseInt(words[0]);
int index = Integer.parseInt(words[1]);
int ans;
if(index == 0) {
ans = 1;
} else {
base = base % 10;
int l = d.get(base).length;
if(l == 1) {
ans = base;
} else {
ans = d.get(base)[index % l];
}
}
System.out.println(ans);
}
}
}<file_sep>/tutorial/test.py
#!/usr/bin/python
line = "abc".strip()
a = set()
a.add(line)
if "abc" in a:
print "contains"<file_sep>/spoj/src/done/HANGOVER.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class HANGOVER {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
while(true) {
double target = Double.parseDouble(reader.readLine());
if(target <= 0.00) {
break;
}
double n = 0.0;
long i;
for (i = 1; n < target; i++) {
n += 1.0 / (1.0 + i);
}
System.out.println(i - 1 + " card(s)");
}
}
}<file_sep>/eclipse/workspace/programming/src/bitwise/UnsingnedRightShift.java
package bitwise;
/**
* @author himadri.sarkar
*
*/
public class UnsingnedRightShift
{
/**
* @param args
*/
public static void main(final String[] args)
{
int i = 8; // 8 = 1000, 4 = 100
int j = -8;
// unsigned right shift in java
System.out.printf("%d %d\n", i >>> 1, j >>> 1);
// signed right shift in java
System.out.printf("%d %d\n", i >> 1, j >> 1);
// there is no unsigned left shift
System.out.printf("%d %d\n", i << 1, j << 1);
}
}
// Output
//
// 4 2147483644
// 4 -4
<file_sep>/spoj/src/done/SAMER08F.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class SAMER08F {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n;
while((n = Integer.parseInt(reader.readLine())) != 0) {
System.out.println( (n * ( n + 1 ) * ( 2 * n + 1 ) ) / 6);
}
}
}<file_sep>/spoj/src/todo/JULKA.java
package todo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class JULKA {
}<file_sep>/spoj/src/done/TOANDFRO.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class TOANDFRO {
static void reverse(char[] str, int s, int e) {
while(s < e) {
char temp = str[s];
str[s] = str[e];
str[e] = temp;
s += 1;
e -= 1;
}
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int c = 0;
while((c = Integer.parseInt(reader.readLine())) != 0) {
String code = reader.readLine();
// to store zig zag into flattened string
char[] flatten = code.toCharArray();
int n = code.length();
int r = n / c;
for(int i = c ; i < n ; i += 2 * c) {
reverse(flatten, i, i + c - 1);
}
char[] decode = new char[n];
int k = 0;
for(int i = 0 ; i < c ; i++) {
for(int j = 0 ; j < r ; j++) {
decode[k++] = flatten[i + j * c];
}
}
System.out.println(new String(decode));
}
}
}<file_sep>/eclipse/workspace/programming/src/tooeasy/Enormous.java
/* Scanner is too slow compared to BufferedReader */
package tooeasy;
import java.io.*;
import java.util.*;
public class Enormous {
public static void main(String args[]) throws Exception {
int output = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
String words[] = line.split(" ");
int numCases = Integer.parseInt(words[0]);
int div = Integer.parseInt(words[1]);
for (int i = 0 ; i < numCases ; i++) {
if (Integer.parseInt(br.readLine()) % div == 0)
output++;
}
System.out.println(output);
}
}<file_sep>/eclipse/workspace/programming/src/tooeasy/StringTest.java
package tooeasy;
import java.io.*;
import java.util.*;
public class StringTest {
public static void main(String[] args) {
String str = "Hello";
char[] strArr = str.toCharArray();
System.out.println(strArr);
}
}
<file_sep>/spoj/src/test/Main.java
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class Main {
public static void main(String[] args) throws IOException {
// BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println(10 % 11);
}
}
<file_sep>/eclipse/workspace/programming/src/MergeSequence.java
/* given a1, a2....b1, b2....c1, c2....
* merge them to form a sequecne of the form
* a1,b1, c1, ....
* in place
*/
import java.io.*;
import java.util.*;
public class MergeSequence {
}
<file_sep>/ml/CI/exec_deliciousrec.py
from deliciousrec import *
<file_sep>/spoj/src/done/LASTDIG.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class LASTDIG {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(reader.readLine());
for(int i = 0 ; i < N ; i++) {
String[] words = reader.readLine().split(" ");
BigInteger base = new BigInteger(words[0]);
BigInteger index = new BigInteger(words[1]);
System.out.println(base.modPow(index, BigInteger.TEN));
}
}
}<file_sep>/eclipse/workspace/programming/src/Balances.java
import java.io.*;
import java.util.*;
class Node {
int w_left;
int w_right;
int add_left;
int add_right;
int[] bal_left_num;
int[] bal_right_num;
public Node(int w_left, int w_right, int[] bal_left_num, int[] bal_right_num) {
this.w_left = w_left;
this.w_right = w_right;
this.bal_left_num = bal_left_num;
this.bal_right_num = bal_right_num;
this.add_right = 0;
this.add_left = 0;
}
}
public class Balances {
public void printAll(Node[] nodes) {
for(int i = 0 ; i < nodes.length ; i++) {
System.out.print("\n" + nodes[i].w_left);
for (int j = 0 ; j < nodes[i].bal_left_num.length ; j++)
System.out.print(" " + nodes[i].bal_left_num[j]);
System.out.print("\n" + nodes[i].w_right);
for (int j = 0 ; j < nodes[i].bal_right_num.length ; j++)
System.out.print(" " + nodes[i].bal_right_num[j]);
}
}
public void printIndex(Node[] nodes) {
for (int i = 0 ; i < nodes.length ; i++) {
System.out.println(i + ": " + nodes[i].add_left + " " + nodes[i].add_right);
}
}
public int balance(Node[] nodes, int node_index) {
int ret_value = 0;
int left_weight = 0;
int right_weight = 0;
for(int i = 0 ; i < nodes[node_index].bal_left_num.length ; i++)
left_weight += balance(nodes, nodes[node_index].bal_left_num[i]);
for(int i = 0 ; i < nodes[node_index].bal_right_num.length ; i++)
right_weight += balance(nodes, nodes[node_index].bal_right_num[i]);
if (left_weight + nodes[node_index].w_left > right_weight + nodes[node_index].w_right)
nodes[node_index].add_right = left_weight + nodes[node_index].w_left - right_weight - nodes[node_index].w_right;
else
nodes[node_index].add_left = right_weight + nodes[node_index].w_right - left_weight - nodes[node_index].w_left;
ret_value = left_weight + right_weight + nodes[node_index].w_left + nodes[node_index].w_right
+ nodes[node_index].add_left + nodes[node_index].add_right + 10;
return ret_value;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);
Node[] nodes = new Node[N];
int w_left = 0;
int w_right = 0;
int[] bal_left_num;
int[] bal_right_num;
for(int i = 0 ; i < N ; i++) {
String line1 = br.readLine();
String line2 = br.readLine();
String words1[] = line1.split(" ");
String words2[] = line2.split(" ");
w_left = Integer.parseInt(words1[0]);
w_right = Integer.parseInt(words2[0]);
bal_left_num = new int[words1.length - 1];
bal_right_num = new int[words2.length - 1];
for(int j = 0 ; j < bal_left_num.length; j++)
bal_left_num[j] = Integer.parseInt(words1[j + 1]);
for(int j = 0 ; j < bal_right_num.length; j++)
bal_right_num[j] = Integer.parseInt(words2[j + 1]);
nodes[i] = new Node(w_left, w_right, bal_left_num, bal_right_num);
}
Balances sol = new Balances();
for(int i = 0 ; i < nodes.length ; i++)
sol.balance(nodes, i);
sol.printIndex(nodes);
}
}
<file_sep>/spoj/src/done/PERMUT2.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class PERMUT2 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n;
while((n = Integer.parseInt(reader.readLine())) != 0) {
String[] word = reader.readLine().split(" ");
int[] p = new int[n];
boolean printed = false;
for (int j = 0; j < n; j++) {
p[j] = Integer.parseInt(word[j]);
// this check might prevent traversing all numbers
if (p[j] - 1 <= j && j + 1 != p[p[j] - 1]) {
System.out.println("not ambiguous");
printed = true;
break;
}
}
if(!printed)
for (int j = 0; j < n ; j++) {
if(j + 1 != p[p[j] - 1]) {
System.out.println("not ambiguous");
printed = true;
break;
}
}
if(!printed)
System.out.println("ambiguous");
}
}
}<file_sep>/eclipse/workspace/programming/src/lightoj/beginners/Prob1069.java
package lightoj.beginners;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author himadri.sarkar
*
*/
public class Prob1069
{
public static void main(final String[] args) throws NumberFormatException, IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(reader.readLine());
String[] word = new String[2];
int me, lift;
for (int i = 0; i < T; i++)
{
word = reader.readLine().split(" ");
me = Integer.parseInt(word[0]);
lift = Integer.parseInt(word[1]);
System.out.printf("Case %d: %d\n", i + 1, (Math.abs(lift - me) + me) * 4 + 19);
}
reader.close();
}
}
<file_sep>/algs4/src/Brute.java
import java.util.Arrays;
/**
* @author himadri.sarkar
*
*/
public class Brute {
public static void main(final String[] args) {
// read points
int[] coord = In.readInts(args[0]);
Point[] point = new Point[coord[0]];
for (int i = 0; i < point.length; i++) {
point[i] = new Point(coord[2 * i + 1], coord[2 * i + 2]);
}
Arrays.sort(point);
StdDraw.setXscale(0, 32768);
StdDraw.setYscale(0, 32768);
for (Point p : point) {
p.draw();
}
// detect lines containing 4 points by brute force method
for (int j = 0; j < point.length; j++)
for (int k = j + 1; k < point.length; k++)
for (int l = k + 1; l < point.length; l++)
for (int m = l + 1; m < point.length; m++) {
int so1 = point[j].SLOPE_ORDER.compare(point[k], point[l]);
int so2 = point[j].SLOPE_ORDER.compare(point[l], point[m]);
if (so1 == 0 && so2 == 0) {
System.out.printf("%s -> %s -> %s -> %s\n", point[j], point[k], point[l], point[m]);
point[j].drawTo(point[m]);
}
}
}
}
<file_sep>/eclipse/workspace/programming/src/skiena/graphs/Graph.java
package skiena.graphs;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
* @author himadri.sarkar
*
*/
public class Graph
{
public static final int MAXV = 1000; /* max number of vertices */
public EdgeNode[] edges; /* adjacency info */
public int[] degree; /* outdegree of each vertex */
public int nvertices; /* number of vertices in graph */
public int nedges; /* number of edges in graph */
public boolean directed; /* is the graph directed */
public Graph()
{
edges = new EdgeNode[MAXV];
degree = new int[MAXV];
this.nvertices = 0;
this.nedges = 0;
this.directed = false;
Arrays.fill(degree, 0);
Arrays.fill(edges, null);
}
public void insertEdge(final int x, final int y, final int weight, final boolean directed)
{
EdgeNode p = new EdgeNode(y, weight);
p.next = edges[x];
edges[x] = p;
degree[x]++;
if (!directed)
{
insertEdge(y, x, weight, true);
}
else
{
nedges++;
}
}
public void readGraph()
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try
{
directed = Boolean.parseBoolean(reader.readLine());
String[] words = new String[3];
words = reader.readLine().split(" ");
nvertices = Integer.parseInt(words[0]);
int numEdges = Integer.parseInt(words[1]);
int weight = Integer.MAX_VALUE;
for (int i = 0; i < numEdges; i++)
{
words = reader.readLine().split(" ");
if (words.length == 3)
{
weight = Integer.parseInt(words[2]);
}
insertEdge(Integer.parseInt(words[0]), Integer.parseInt(words[1]), weight, directed);
}
}
catch (NumberFormatException e)
{
throw new RuntimeException(e);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
void printGraph()
{
EdgeNode p = null;
for (int i = 0; i < nvertices; i++)
{
System.out.printf("%d: ", i);
p = edges[i];
while (p != null)
{
if (p.weight != Integer.MAX_VALUE)
System.out.printf(" %d(%d)", p.y, p.weight);
else
System.out.printf(" %d", p.y);
p = p.next;
}
System.out.println();
}
}
public static void main(final String... args)
{
Graph graph = new Graph();
graph.readGraph();
graph.printGraph();
}
}
/*
* input.txt
*/
<file_sep>/spoj/src/done/CANTON.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class CANTON {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(reader.readLine());
for(int i = 0 ; i < N ; i++) {
long X = Long.parseLong(reader.readLine());
long n = (long)Math.ceil((-1.0 + Math.sqrt(1 + 8 * X)) / 2);
// R -> L
long s = (n * ( n - 1 )) / 2 + 1;
long d = X - s;
String o = null;
if( n % 2 == 0 ) {
o = (1 + d) + "/" + (n - d);
}
// L -> R
else {
o = (n - d) + "/" + (1 + d);
}
System.out.println("TERM " + X + " IS " + o);
}
}
}<file_sep>/spoj/src/done/FENCE1.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* User: himadri.sarkar
* Date: 22/12/13
*/
public class FENCE1 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int L;
while((L = Integer.parseInt(reader.readLine())) != 0) {
System.out.printf("%.2f\n", Math.round( ( Math.pow(L, 2) / (2.0 * Math.PI ) ) * 100.0 ) / 100.0);
}
}
}<file_sep>/spoj/src/done/MCOINS.java
package done;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
* User: himadri.sarkar
* Date: 03/01/14
*/
public class MCOINS {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(reader.readLine());
int k = Integer.parseInt(st.nextToken());
int l = Integer.parseInt(st.nextToken());;
int m = Integer.parseInt(st.nextToken());;
StringBuilder o = new StringBuilder();
st = new StringTokenizer(reader.readLine());
boolean[] d = new boolean[1000001];
int c = 1; // max cached
d[c] = true;
for(int i = 0 ; i < m ; i++) {
int n = Integer.parseInt(st.nextToken());
if(n > c) { // else return from cache
for (; c <= n; c++) {
d[c] = !d[c - 1];
if(c >= k && !d[c - k]) {
d[c] = true;
}
if(c >= l && !d[c - l]) {
d[c] = true;
}
}
}
if(d[n] == true) {
o.append("A");
} else {
o.append("B");
}
}
System.out.println(o);
}
}
<file_sep>/eclipse/workspace/programming/src/coursera/algorithms/InversionCount.java
package coursera.algorithms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* @author himadri.sarkar
*
*/
public class InversionCount {
public static long count(final int[] A, final int s, final int e) {
if (s == e) {
return 0;
} else {
int mid = s + (e - s) / 2;
// count left side
long x = count(A, s, mid);
// count right side
long y = count(A, mid + 1, e);
// count cross inversions
long z = 0; // inversions across left and right
int[] tempA = new int[e - s + 1];
int l = 0; // current index of tempA
int i = s;
int j = mid + 1;
while (i <= mid && j <= e) {
if (A[i] > A[j]) {
z += mid - i + 1;
tempA[l++] = A[j++];
} else {
tempA[l++] = A[i++];
}
}
while (i <= mid) {
tempA[l++] = A[i++];
}
while (j <= e) {
tempA[l++] = A[j++];
}
// lay tempA over A
for (int o = 0; o < tempA.length; o++) {
A[s + o] = tempA[o];
}
return x + y + z;
}
}
public static void main(final String[] args) {
Scanner in = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();
while (in.hasNext()) {
int n = Integer.parseInt(in.nextLine());
list.add(n);
}
int[] A = new int[list.size()];
for (int i = 0; i < A.length; i++) {
A[i] = list.get(i);
}
System.out.println(count(A, 0, A.length - 1));
}
}
| 4e015808bc9347c941cd5ccb32ee351503196ab7 | [
"Java",
"Python",
"C++"
] | 67 | Java | hsarkar/programming | 7c0c277dd35b8d2a627c599f4b6e9607dede6ca4 | e44b2b83f52d724154a60d45eacd27c4b7b7b16e |
refs/heads/master | <repo_name>babloogpb1/ComputerGraphics<file_sep>/functions.h
#include<bits/stdc++.h>
#include<graphics.h>
using namespace std;
void ddaLine(int x1,int y1,int x2,int y2,int a)
{
if(x1==x2)
{
if(y1<y2)
while(y1<=y2)
{
putpixel(x1,y1,a);
y1+=1;//round(float(y1)-((x1-i)*m));
//delay(2);
}
else
while(y1>=y2)
{
putpixel(x1,y1,a);
y1-=1;//round(float(y1)-((x1-i)*m));
//delay(2);
}
}
else
{
float m=(float)(y2-y1)/(x2-x1);
//cout<<m<<endl;
int y=y1;
if(x1<x2)
for(int i=x1;i<x2;i++)
{
putpixel(i,y,a);
y=round(float(y1)+((i-x1)*m));
// delay(2);
}
else
for(int i=x1;i>x2;i--)
{
putpixel(i,y,a);
y=round(float(y1)-((x1-i)*m));
//delay(2);
}
}
}
void ddaCircle(float x,float y,float r)
{
float x1,y1;
float e=1/pow(2,ceil(log10(r)/log10(2)));
//cout<<e;
x1 = 0;
y1 = r;
putpixel(x,y,GREEN);
while(x1<=r)
{
putpixel(x+x1,y+y1,RED);
putpixel(x+x1,y-y1,RED);
putpixel(x-x1,y-y1,RED);
putpixel(x-x1,y+y1,RED);
x1+=(y1*e);
y1-=(x1*e);
}
//delay(30);
/*putpixel(x+x1,y+y1,GREEN);
putpixel(x+x1,y-y1,GREEN);
putpixel(x-x1,y-y1,GREEN);
putpixel(x-x1,y+y1,GREEN);
//delay(30);
}
putpixel(x+x1,y+y1,RED);
putpixel(x+x1,y-y1,RED);
putpixel(x-x1,y-y1,RED);
putpixel(x-x1,y+y1,RED);*/
//getchar();
}
<file_sep>/code.py
A = [7,8,9,10,11,1,4,3,2,5,6,13,14,12,15]
n = len(A)
k = n
t = 0
for i in range(n):
if(A[n-1-i]==n-i):
k = k-1
else:
break
#print(k)
while k>0:
m = 0
if A[m]==k:
t = t+k-1
k = k-1
A.pop(0)
z = k
for i in range(z):
if(A[z-1-i]==z-i):
k = k-1
else:
break
else:
for i in range(k):
if A[i]>A[m]:
m=i
print(m)
t =t + (m*(m+1)/2)
x=A.pop(m)
A.insert(m,A[0])
A[0]=x
#if k==3:
# break
#print(A)
m = pow(10,9)+7
print(t%m)
<file_sep>/brsnhmCircle.cpp
// C++ program for circle drawing using Bresenham’s Algorithm
#include<bits/stdc++.h>
#include <graphics.h>
using namespace std;
void brsnhmCircle(int xc, int yc, int r)
{
int x = 0, y = r;
int d = 3 - 2 * r;
while (y >= x)
{
putpixel(xc+x, yc+y, RED);
putpixel(xc-x, yc+y, RED);
putpixel(xc+x, yc-y, RED);
putpixel(xc-x, yc-y, RED);
putpixel(xc+y, yc+x, RED);
putpixel(xc-y, yc+x, RED);
putpixel(xc+y, yc-x, RED);
putpixel(xc-y, yc-x, RED);
x++;
if (d > 0)
{
y--;
d = d + 4 * (x - y) + 10;
}
else
d = d + 4 * x + 6;
delay(30);
}
}
int main()
{
int xc = 50, yc = 50, r = 30;
int gd = DETECT, gm;
initgraph(&gd, &gm, NULL);
brsnhmCircle(xc, yc, r);
getchar();
}
<file_sep>/brsnhmLine.cpp
// C++ program for brsnhm’s Line Generation.
#include<bits/stdc++.h>
#include<graphics.h>
using namespace std;
void brsnhm(int x1, int y1, int x2, int y2)
{
int m = 2 * (y2 - y1);
int d = m - (x2 - x1);
for (int x = x1; x <= x2; x++)
{
putpixel(x, y1, WHITE);
d += m;
if (d >= 0)
{
y1++;
d -= 2 * (x2 - x1);
}
}
}
int main()
{
int x1 = 0 , y1 = 20, x2 = 200, y2 = 400;
int gd=DETECT,gm;
initgraph(&gd,&gm,NULL);
brsnhm(x1, y1, x2, y2);
getchar();
return 0;
}
<file_sep>/ddaCircle.cpp
//C++ program to draw Circle using DDA algorithm.
#include<bits/stdc++.h>
#include<graphics.h>
using namespace std;
void ddaCircle(float x,float y,float r)
{
float x1,y1;
float e=1/pow(2,ceil(log10(r)/log10(2)));
cout<<e;
x1 = 0;
y1 = r;
putpixel(x,y,GREEN);
int c=getpixel(x,y);
cout<<c;
while(x1<=r)
{
putpixel(x+x1,y+y1,RED);
putpixel(x+x1,y-y1,RED);
putpixel(x-x1,y-y1,RED);
putpixel(x-x1,y+y1,RED);
x1+=(y1*e);
y1-=(x1*e);
delay(30);
}
/*putpixel(x+x1,y+y1,GREEN);
putpixel(x+x1,y-y1,GREEN);
putpixel(x-x1,y-y1,GREEN);
putpixel(x-x1,y+y1,GREEN);
delay(30);
}
putpixel(x+x1,y+y1,RED);
putpixel(x+x1,y-y1,RED);
putpixel(x-x1,y-y1,RED);
putpixel(x-x1,y+y1,RED);
//floodfill(x,y,GREEN);*/
}
int main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,NULL);
float x1,y1,x2,y2,x,y,r,z;
cout<<"Enter the centre and the radius of the circle...\n";
cin>>x>>y>>r;
ddaCircle(x,y,r);
getchar();
}
<file_sep>/bounceBall.cpp
//C++ program illustrating bouncing ball.
#include<bits/stdc++.h>
#include<graphics.h>
#include "functions.h"
using namespace std;
void draw(float x,float y,float r)
{
setcolor(15);
circle(x,y,r);
floodfill(x,y,2);
delay(30);
setcolor(0);
circle(x,y,r);
floodfill(x,y,0);
setcolor(15);
ddaLine(0, 150, 310, 150, WHITE);
ddaLine(640, 150, 330, 150, WHITE);
ddaLine(0, 300, 310, 150, WHITE);
ddaLine(640, 300, 330, 150, WHITE);
}
int main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,NULL);
int y=100,z=1;
int d=150, i=5, a=320, b=150,r=1,p=0,q=0;
draw(320,150,1);
//draw(320,150,5);
for(int o=0;0<20;o++)
{
while(i<=800)
{
int c=log2(i),k=2;
for(int j=1;j<=i&&j<500;j+=i/3)
{
if(i%4==0)
{
//cleardevice();
r++;
if(b+q-j-r<500 )
draw(a,b+q-j-r,r);
p=j;
}
}
k = 0;
for(int j=1;j<=i&&j<500;j+=i/3)
{
if(i%4==0)
{
//cleardevice();
r++;
draw(a,b-p+j-r,r);
q=j;
}
}
i*=2;
//if(i%10==0)
//z*=2;
}
i=5;
r=1;
}
//cleardevice();
//cout<<"here ";
getchar();
}
<file_sep>/ddaLine.cpp
//C++ program to draw line using DDA algorithm.
#include<iostream>
#include<graphics.h>
using namespace std;
void ddaLine(int x1,int y1,int x2,int y2)
{
if(x1==x2)
{
if(y1<y2)
while(y1<=y2)
{
putpixel(x1,y1,GREEN);
y1+=1;//round(float(y1)-((x1-i)*m));
delay(20);
}
else
while(y1>=y2)
{
putpixel(x1,y1,GREEN);
y1-=1;//round(float(y1)-((x1-i)*m));
delay(20);
}
}
else
{
float m=(float)(y2-y1)/(x2-x1);
cout<<m<<endl;
int y=y1;
if(x1<x2)
for(int i=x1;i<x2;i++)
{
putpixel(i,y,CYAN);
y=round(float(y1)+((i-x1)*m));
delay(20);
}
else
for(int i=x1;i>x2;i--)
{
putpixel(i,y,GREEN);
y=round(float(y1)-((x1-i)*m));
delay(20);
}
}
getchar();
}
int main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,NULL);
int x1,y1,x2,y2;
cout<<"Enter the initial and final points\n";
cin>>x1>>y1>>x2>>y2;
putpixel(x1,y1,RED);
delay(2000);
putpixel(x2,y2,RED);
delay(2000);
ddaLine(x1,y1,x2,y2);
}
<file_sep>/house.cpp
//C++ program to draw a house
#include<bits/stdc++.h>
#include<graphics.h>
#include "functions.h"
using namespace std;
int main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,NULL);
ddaLine(150, 200, 300, 220, WHITE);
ddaLine(150, 275, 300, 320, WHITE);
ddaLine(200, 290, 200, 245, WHITE);//door
ddaLine(175, 283, 175, 238, WHITE);
ddaLine(175, 238, 200, 245, WHITE); //door bar
ddaLine(150, 200, 150, 275, WHITE);
ddaLine(300, 220, 300, 320, WHITE);
ddaLine(150, 200, 225, 135, WHITE);
ddaLine(300, 220, 225, 135, WHITE);
ddaLine(425, 135, 225, 135, WHITE);
ddaLine(300, 220, 480, 200, WHITE);
ddaLine(425, 135, 480, 200, WHITE);
ddaLine(300, 320, 480, 275, WHITE);
ddaLine(480, 200, 480, 275, WHITE);
ddaLine(175, 238, 185, 245, WHITE);
ddaLine(175, 283, 185, 275, WHITE);
ddaLine(185, 245, 185, 275, WHITE);
ddaLine(185, 245, 185, 275, WHITE);
ddaLine(370, 245, 420, 235, WHITE); //window
ddaLine(370, 245, 370, 270, WHITE);
ddaLine(370, 270, 420, 260, WHITE);
ddaLine(420, 235, 420, 260, WHITE);
ddaLine(420, 260, 410, 255, WHITE);
ddaLine(370, 263, 410, 255, WHITE);
ddaLine(410, 255, 410, 238, WHITE); //bars
ddaLine(411, 255, 411, 238, WHITE);
ddaLine(400, 257, 400, 240, WHITE);
ddaLine(390, 259, 390, 242, WHITE);
ddaLine(380, 261, 380, 244, WHITE);
ddaLine(240, 240, 240, 270, WHITE); //windowFront
ddaLine(265, 244, 265, 278, WHITE);
ddaLine(240, 240, 265, 244, WHITE);
ddaLine(265, 278, 240, 270, WHITE);
ddaLine(244, 246, 262, 249, WHITE);
ddaLine(244, 246, 244, 267, WHITE);
ddaLine(244, 267, 262, 272, WHITE);
ddaLine(262, 249, 262, 272, WHITE);
ddaLine(244, 256, 262, 260, WHITE);
ddaLine(253, 247, 253, 270, WHITE);
ddaLine(410, 135, 410, 122, WHITE);
ddaLine(400, 135, 400, 121, WHITE);
ddaLine(392, 135, 392, 122, WHITE);
ddaLine(400, 121, 392, 122, WHITE);
ddaLine(410, 122, 400, 121, WHITE);
//setfillstyle(STA_FLL,RED);
//floodfill(300,300,WHITE);
//window1
//floodfill(370,150,BROWN, WHITE);
//int a=410-370,b=240,c=370,d=245,a1=;
//ddaLine(175, 238, 200, 240, WHITE);
/*ddaLine(150, 200, 350, 220, WHITE);
ddaLine(150, 300, 350, 320, WHITE);
ddaLine(200, 306, 200, 240, WHITE);//door
ddaLine(175, 304, 175, 238, WHITE);
ddaLine(175, 238, 200, 240, WHITE); //door bar
ddaLine(150, 200, 150, 300, WHITE);
ddaLine(350, 220, 350, 320, WHITE);
*/
getchar();
}
| 56dc63a177aa04b139a6a8a767f88a0f213183f1 | [
"Python",
"C++"
] | 8 | C++ | babloogpb1/ComputerGraphics | 704b7ffd4f402d403b40400c5f05935c8d18c6c0 | 46275e4476eabf296efa7e42a4a0b475678f482f |
refs/heads/main | <repo_name>Sanjeev-Karthick/idiscuss-coding-forum<file_sep>/partials/_dbconnect.php
<?php
$servername = "localhost";
$password ="";
$username="root";
$database = "idiscuss";
$connection = mysqli_connect($servername,$username,$password,$database);
if($connection){
}
?><file_sep>/partials/_footer.php
<?php
echo ' <footer class="footer">
<div class="container-fluid bg-dark text-center text-light">
<span >Copyright © iDiscuss coding forums 2021 | All rights reserved</span>
</div>
</footer>';
?><file_sep>/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
integrity="<KEY>" crossorigin="anonymous" />
<title>Welcome to iDiscuss - The Coding forums</title>
</head>
<body>
<?php
include 'partials/_header.php';
?>
<?php
include 'partials/_dbconnect.php';
?>
<div id="carouselExampleFade" class="carousel slide carousel-fade" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="https://source.unsplash.com/2400x800/?coding,python" class="d-block w-100" alt="..." />
</div>
<div class="carousel-item">
<img src="https://source.unsplash.com/2400x800/?hacking,text" class="d-block w-100" alt="..." />
</div>
<div class="carousel-item">
<img src="https://source.unsplash.com/2400x800/?computers,microsoft" class="d-block w-100" alt="..." />
</div>
</div>
<a class="carousel-control-prev " href="#carouselExampleFade" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next " href="#carouselExampleFade" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<div class="container">
<h1 class="text-center my-4">iDiscuss - Browse categories</h1>
<?php
$sql_query = "SELECT * FROM `categories`";
$result = mysqli_query($connection,$sql_query);
?>
<div class="row">
<?php
while($row = mysqli_fetch_assoc($result))
{
$des = substr($row["category_description"],0,110);
$id = $row['category_id'];
echo '<div class="col-md-4">
<div class="card my-4" style="width: 18rem">
<img src="https://source.unsplash.com/400x300/?coding,'.$row["category_name"].'" class="card-img-top" alt="..." />
<div class="card-body">
<h5 class="card-title text-center"><a href="threadlist.php?catid='.$id.'">'.$row["category_name"].'</a></h5>
<p class="card-text">
'.$des.'....
</p>
<a href="threadlist.php?catid='.$id.'" class="btn btn-success text-center">View Threads</a>
</div>
</div>
</div>';
}
?>
</div>
</div>
<?php
include 'partials/_footer.php';
?>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="<KEY>" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"
integrity="<KEY>" crossorigin="anonymous">
</script>
<!-- Option 2: jQuery, Popper.js, and Bootstrap JS
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
-->
</body>
</html><file_sep>/README.md
This is a coding forum created for programmers to connect with each other
<file_sep>/partials/_handlelogin.php
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
include '_dbconnect.php';
$user_email = $_POST['lemail'];
$pass = $_POST['lp<PASSWORD>'];
$sql ="select * from users where user_email ='$user_email'";
$result = mysqli_query($connection,$sql);
$numRows = mysqli_num_rows(($result));
if ($numRows == 1){
$row = mysqli_fetch_assoc($result);
if(password_verify($pass, $row['user_pass'])){
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['sno'] = $row['sno'];
$_SESSION['useremail'] = $user_email;
header("Location: /codingforum/index.php");
}else{
echo '';
}
}
}
<file_sep>/partials/_handleSignup.php
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
include '_dbconnect.php';
$user_email = $_POST['signupemail'];
$pass = $_POST['signup<PASSWORD>'];
$cpass = $_POST['signupcpassword'];
$existSQL ="select * from users where user_email ='$user_email'";
$result = mysqli_query($connection,$existSQL);
$numRows = mysqli_num_rows(($result));
if($numRows>0){
$showError = "Email already in use";
}
else{
if($pass==$cpass){
$hash = password_hash($pass,PASSWORD_DEFAULT);
$sql = "INSERT INTO `users` (`sno`, `user_email`, `user_pass`, `timestamp`) VALUES (NULL, '$user_email', '$hash', current_timestamp())";
$result = mysqli_query($connection,$sql);
if($result){
$showAlert = true ;
header("Location: /codingforum/index.php?signupsuccess=true");
}
}
else{
header("Location: /codingforum/index.php?signupsuccess=false");
}
}
}
?> | e9d8396efe2a3cef6bd01b91ec9ea9db0f190c7a | [
"Markdown",
"PHP"
] | 6 | PHP | Sanjeev-Karthick/idiscuss-coding-forum | 7b3deaeffe21cbd72d5d4bd7a165efdca38ec0e8 | fce0a65e9ef055fee5ebbcc007d196dba8b0fbdb |
refs/heads/master | <file_sep>angular.module('app', [
'ui.router',
'ngMaterial',
'ngMessages',
'smoothScroll'
])
/**
* Route the user to the appropriate template and controller
*/
.config(function ($stateProvider, $urlRouterProvider, $locationProvider, $windowProvider) {
$locationProvider.hashPrefix('!');
$stateProvider
.state('404', {
url: '/404',
templateUrl: './app/components/error/404/index.html',
controller: 'Error404Controller'
})
.state('home', {
url: '/home',
templateUrl: './app/components/home/index.html',
controller: 'HomeController'
});
$urlRouterProvider
.when('', function ($injector) {
// html5Mode false
var $state = $injector.get('$state');
$state.go('home');
})
.when('/', function ($injector) {
// html5Mode true
var $state = $injector.get('$state');
$state.go('home', null, {
location: false
});
})
.otherwise(function ($injector) {
var $state = $injector.get('$state');
$state.go('404', null, {
location: false
});
});
})
/**
* Run App
*/
.run(function ($rootScope, $document, $state) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
$rootScope.page = toState.url.substr(toState.url.indexOf('/') + 1);
$rootScope.siteTitle = 'Angular-App';
$rootScope.tagLine = 'Test';
$document[0].title = $rootScope.siteTitle + ' : ' + $rootScope.page;
});
});<file_sep># Angular App
### Description
* Scaffolding for a basic Angular single page app.
* This app is ment to run on an existing web server such as Apache, NGINX, or IIS.
### Requirements
* <a href="https://www.npmjs.com/" target="_blank">NPM - Node Package Manager</a>
## Before running application
* run "npm install" from the project's root directory to install dependencies
* run "gulp install" to perform preprosessing tasks
* google web fonts
* downloads google web fonts found in fonts.list file
* creates or updates _fonts.scss found in /src/scss
* For more information on usauge, visit: <a href="https://fonts.google.com/" target="_blank">Google Fonts</a>
* google material icons
* downloads google material icons fonts
* creates or updates _material-icons.scss file found in /src/scss
* For Modern Browsers: <i class="material-icons">home</i>
* For IE9 or below: <i class="material-icons"></i>
* For more information on usuage, visit: <a href="https://material.io/icons/#ic_home" target="_blank">Google Material Icons</a>
## Running with Gulp
* run "gulp" to build the project in development mode (Uncompressed)
* run "gulp --production" to build the project in production mode (Compressed)<file_sep>angular.module('app')
.controller('HomeController', [
'$scope',
'$stateParams',
'$http',
HomeController]);
function HomeController(
$scope,
$stateParams,
$http
) {
var self = this;
$scope.content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In eu nunc vestibulum, malesuada mi quis, interdum tellus. Sed id risus elit. Sed eget viverra orci. In eget rhoncus tellus. Duis ac diam a nisl imperdiet egestas in et dolor. Praesent vitae lorem ut mi posuere blandit. Ut lacinia euismod felis ac efficitur. Phasellus vel nunc elit.";
/**
* Simple example of importing data from json.
*/
$http.get('data/test.json')
.then(function success(resp){
console.log(resp.data);
}, function error(resp){
console.log(resp);
});
} | f2ceb4a52527886d2ae7a555093a53b86d073fff | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | mikematos84/angularjs-app | 81bd0fd390b72fb70fd0a7b150ea443e41f822b6 | aacd6ae3b4901aae0bd824a421c7f6a438129689 |
refs/heads/master | <file_sep># Intro-to-databases
Day 15 - Introduction to Databases
<file_sep>rooms_events = { 'data':
{ 'rooms':
[ { 'id': 1, 'room_number': "201", 'capacity': 50}, { 'id': 2, 'room_number': "301", 'capacity': 200 }, { 'id': 3, 'room_number': "1B", 'capacity': 100}
],
'events': [
{ 'id': 1, 'room_id': 2, 'start_time': 18, 'end_time': 20, 'attendees': 75 },
{ 'id': 2, 'room_id': 1, 'start_time': 10, 'end_time': 18, 'attendees': 25 },
{ 'id': 3, 'room_id': 2, 'start_time': 10, 'end_time': 18, 'attendees': 20 },
{ 'id': 4, 'room_id': 3, 'start_time': 18, 'end_time': 21, 'attendees': 56 },
]
}
}
# for key, value in rooms_events.items():
# print(value)
# print(type(value))
room_201 = rooms_events['data']['rooms'][0]['capacity']
print(room_201)
# room_201_events = []
for data in rooms_events['data']['events']:
if data['room_id'] == 1:
if data['attendees'] <= room_201:
print('ok')
| a640eefb500ee758df7826ddc77f899ecc201293 | [
"Markdown",
"Python"
] | 2 | Markdown | cudjoeab/Intro-to-databases | 641690a626797458819bb2d20ca4d255e8a8e3ea | 7f3ac4778355d86af825e39bd430be2331cbbf15 |
refs/heads/master | <file_sep>require 'spec_helper'
describe Mongoid::Preferences::Preferenceable do
let(:file_default_preferences_hash) {
HashWithIndifferentAccess.new( YAML.load_file(File.join(File.dirname(__FILE__),
'models_preferences',
'dummy.yml')))
}
let(:view_preferences_hash) { file_default_preferences_hash[:view][:preferences] }
let(:default_preferences_hash) {
# remove the type key form preferences
preferences_hash = HashWithIndifferentAccess.new()
file_default_preferences_hash[:view][:preferences].each { |p|
preferences_hash[p[:name]] = p[:value]
}
preferences_hash
}
let(:custom_preferences_hash) { HashWithIndifferentAccess.new ({'pref1' => false, 'pref2' => false, 'pref3' => false})}
let(:merged_preferences_hash) {
# returns an hash of preferences (merge between custom and default) with format {key => value, ecc..}
default_preferences_hash.merge(custom_preferences_hash)
}
# Instance that has saved preferences
let(:model_with_preferences) {
Dummy.new(:preferences => merged_preferences_hash)
}
# Instance with empty preferences hash
let(:model_with_empty_preferences) { Dummy.new }
before :each do
# Clear cached preferences
Dummy.remove_class_variable(:@@default_preferences) if Dummy.class_variable_defined? :@@default_preferences
end
describe '#default_preferences' do
context 'when default preferences file found' do
before { set_right_preferences_path }
it 'returns a hash with the default preferences' do
# Use send method for testing private method
expect(model_with_empty_preferences.send(:default_preferences)).to eq(file_default_preferences_hash)
end
end
context 'when default preferences file not found' do
before { set_wrong_preferences_path }
it 'returns an empty hash' do
# Use send method for testing private method
expect(model_with_empty_preferences.send(:default_preferences)).to be_empty
end
end
end
describe '#write_pref' do
it 'returns the value of preference' do
expect(model_with_preferences.write_pref(:custom_pref, false)).to be_false
end
context 'when default preferences file found' do
before { set_right_preferences_path }
context 'when add a new custom preference' do
it 'has a hash of preferences which include the new preference' do
new_pref_key = 'custom_pref'
new_pref_value = false
model_with_preferences.write_pref(new_pref_key, new_pref_value)
model_with_preferences.save
expect(model_with_preferences.preferences).to include(new_pref_key)
end
end
context 'when change the value of a default preference' do
it 'has a hash of preferences with default preference changed in value' do
default_pref_key = 'show_tabs_control'
# Change the default value from true to false
new_default_pref_value = false
model_with_preferences.write_pref(default_pref_key, new_default_pref_value)
model_with_preferences.save
expect(model_with_preferences.preferences[default_pref_key]).to eq(new_default_pref_value)
end
end
context 'when add a new preference for another instance' do
before {
@new_pref_key = 'new_pref'
@new_pref_value = true
@new_instance = Dummy.new
@new_instance.write_pref(@new_pref_key, @new_pref_value)
@new_instance.save
}
it 'new instance include the new preference' do
expect(@new_instance.preferences).to include(@new_pref_key)
end
it 'existing instance does not include the new preference' do
expect(model_with_preferences.preferences).to_not include(@new_pref_key)
end
end
context 'when change the value of a default preference for another instance' do
before {
@default_pref_key = 'show_tabs_control'
# Change the default value from true to false
@new_default_pref_value = false
@new_instance = Dummy.new
@new_instance.write_pref(@default_pref_key, @new_default_pref_value)
@new_instance.save
}
it 'new instance has a default preference changed in value' do
expect(@new_instance.preferences[@default_pref_key]).to eq(@new_default_pref_value)
end
it 'existing instance has a default preference not changed in value' do
expect(model_with_preferences.preferences[@default_pref_key]).to_not eq(@new_default_pref_value)
end
end
end
context 'when default preferences file not found' do
before { set_wrong_preferences_path }
context 'when add a new custom preference' do
it 'has a hash of preferences which include the new preference' do
new_pref_key = 'custom_pref'
new_pref_value = false
model_with_empty_preferences.write_pref(new_pref_key, new_pref_value)
model_with_empty_preferences.save
expect(model_with_empty_preferences.preferences).to include(new_pref_key)
end
end
context 'when add a new preference for another instance' do
before {
@new_pref_key = 'new_pref'
@new_pref_value = true
@new_instance = Dummy.new
@new_instance.write_pref(@new_pref_key, @new_pref_value)
@new_instance.save
}
it 'new instance include the new preference' do
expect(@new_instance.preferences).to include(@new_pref_key)
end
it 'existing instance does not include the new preference' do
expect(model_with_empty_preferences.preferences).to_not include(@new_pref_key)
end
end
end
end
describe '#preferences' do
context 'when default preferences file not found' do
before { set_wrong_preferences_path }
context 'when model has empty preferences' do
it 'returns an empty hash' do
expect(model_with_empty_preferences.preferences).to be_empty
end
end
context 'when model has preferences' do
it 'returns a hash with merged preferences' do
expect(model_with_preferences.preferences).to eq(merged_preferences_hash)
end
end
end
context 'when default preferences file found' do
before { set_right_preferences_path }
context 'when model has empty preferences' do
it 'returns a hash with default preferences' do
expect(model_with_empty_preferences.preferences).to eq(default_preferences_hash)
end
end
context 'when model has preferences' do
it 'returns a hash with merged preferences' do
expect(model_with_preferences.preferences).to eq(merged_preferences_hash)
end
end
end
end
describe '#pref' do
context 'when preference exist' do
it 'returns the preference value' do
expect(model_with_preferences.pref(:show_tabs_control)).to eq(true)
end
end
context 'when preference not exist' do
it 'returns nil' do
expect(model_with_preferences.pref(:wrong_pref)).to be_nil
end
end
context 'when add new preference with string key' do
before {
@pref_value = true
model_with_preferences.write_pref('preference_key', @pref_value)
model_with_preferences.save
}
it 'returns the preference value accessing with string key' do
# Force reload of instance
reloaded_instance = Dummy.last
expect(reloaded_instance.pref('preference_key')).to eq(@pref_value)
end
it 'returns the preference value accessing with symbol key' do
# Force reload of instance
reloaded_instance = Dummy.last
expect(reloaded_instance.pref(:preference_key)).to eq(@pref_value)
end
end
context 'when add new preference with symbol key' do
before {
@pref_value = true
model_with_preferences.write_pref(:preference_key, @pref_value)
model_with_preferences.save
}
it 'returns the preference value accessing with string key' do
# Force reload of instance
reloaded_instance = Dummy.last
expect(reloaded_instance.pref('preference_key')).to eq(@pref_value)
end
it 'returns the preference value accessing with symbol key' do
# Force reload of instance
reloaded_instance = Dummy.last
expect(reloaded_instance.pref(:preference_key)).to eq(@pref_value)
end
end
end
describe '#displayable_preferences' do
context 'when default preferences file found' do
before { set_right_preferences_path }
context 'when preferences group exist' do
it 'returns a hash of preferences for the group' do
expect(model_with_empty_preferences.displayable_preferences(:view)).to eq(view_preferences_hash)
end
context 'when change the value of preference' do
before {
@default_pref_key = 'show_wall_page'
@new_pref_value = false
# change the value from true to false
model_with_empty_preferences.write_pref(:show_wall_page, false)
model_with_empty_preferences.save
}
it 'returns a hash which include the preference changed in value' do
#expect(model_with_empty_preferences.displayable_preferences(:view_preferences)[@default_pref_key]).
end
end
end
context 'when preferences group not exist' do
it 'returns nil' do
expect(model_with_empty_preferences.displayable_preferences(:wrong_group)).to be_nil
end
end
end
context 'when default preferences file not found' do
before { set_wrong_preferences_path }
context 'when preferences group exist' do
it 'returns nil' do
expect(model_with_empty_preferences.displayable_preferences(:view)).to be_nil
end
end
context 'when preferences group not exist' do
it 'returns nil' do
expect(model_with_empty_preferences.displayable_preferences(:wrong_group)).to be_nil
end
end
end
end
describe '#has_pref?' do
context 'when preference exist' do
before { set_right_preferences_path }
it 'returns true' do
expect(model_with_empty_preferences.has_pref? :show_wall_page).to be_true
end
end
context 'when preference not exist' do
before { set_right_preferences_path }
it 'returns false' do
expect(model_with_empty_preferences.has_pref? :wrong_pref).to be_false
end
end
end
end<file_sep>[](http://badge.fury.io/rb/mongoid-preferences)
[](https://travis-ci.org/matito/mongoid-preferences)
[](https://codeclimate.com/github/matito/mongoid-preferences)
[](https://coveralls.io/r/matito/mongoid-preferences)
# Mongoid::Preferences
Add preferences hash to Mongoid model.
## Installation
Add this line to your application's Gemfile:
gem 'mongoid-preferences'
And then execute:
$ bundle
Or install it yourself as:
$ gem install mongoid-preferences
## Usage
TODO: Write usage instructions here
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
<file_sep>require 'mongoid-preferences/preferences'<file_sep>$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib"))
MODELS = File.join(File.dirname(__FILE__), "models")
require 'coveralls'
Coveralls.wear!
require 'rubygems'
require 'bundler/setup'
require 'rspec'
require 'mongoid'
require 'mongoid-preferences'
require 'database_cleaner'
require 'mongoid-rspec'
require 'pathname'
Dir["#{MODELS}/*.rb"].each { |f| require f }
Mongoid.configure do |config|
config.connect_to "mongoid_preferences"
end
Mongoid.logger = Logger.new($stdout)
DatabaseCleaner.orm = "mongoid"
RSpec.configure do |config|
config.include Mongoid::Matchers
config.before(:all) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
#Helper method for setting the RIGHT path for the preferences file
def set_right_preferences_path
Mongoid::Preferences.configure do |config|
# model preferences path to dummy model
config.model_preferences_path = File.join(File.dirname(__FILE__), "models_preferences")
end
end
#Helper method for setting the WRONG path for the preferences file
def set_wrong_preferences_path
Mongoid::Preferences.configure do |config|
# model preferences path to dummy model
config.model_preferences_path = 'wrong/path/to/preferences/file'
end
end
<file_sep>class Dummy
include Mongoid::Document
include Mongoid::Preferences::Preferenceable
end<file_sep>require 'mongoid-preferences/preferences/preferenceable'
require 'mongoid-preferences/preferences/version'
module Mongoid
module Preferences
include ActiveSupport::Configurable
config_accessor :model_preferences_path
end
end
###
# Use this code into an initializer for configure the path of preferences yaml
##
#Mongoid::Preferences.configure do |config|
# # set default preferences path
# config.model_preferences_path = Rails.root.join('app','models_preferences')
#end
<file_sep>module Mongoid
module Preferences
module Preferenceable
extend ActiveSupport::Concern
included do
field :preferences, :type => Hash, :default => Proc.new { HashWithIndifferentAccess.new() }
after_initialize :load_preferences
# Returns all the preferences
def preferences
@_prefs ||= merged_preferences
end
# Returns the value of preference or nil if the preference is not found
def pref(name)
self.preferences[name]
end
# Retruns true if the model has the preference, else returns false
def has_pref?(name)
return false unless self.preferences.has_key?(name)
true
end
# Set the value of specified preference or add a new preference, and returns the value
def write_pref(name, value)
#override the preference value or add new preference if not exist
preferences[name] = value
write_attribute(:preferences, preferences)
value
end
# Returns an array of hash of preferences
def displayable_preferences(group)
default_preferences_hash = default_preferences
if default_preferences_hash.has_key?(group)
default_preferences_hash[group][:preferences].each do |preference|
name = preference[:name]
if self.preferences.has_key?(name)
# overwrite default preference value with the model preference value
preference[:value] = self.preferences[name]
end
end
default_preferences_hash[group][:preferences]
else
nil
end
end
private
def load_preferences
if read_attribute(:preferences).blank?
write_attribute(:preferences, preferences)
end
end
# Returns a hash of default preferences loaded from file
def default_preferences
return self.class.class_variable_get :@@default_preferences if self.class.class_variable_defined? :@@default_preferences
default_preferences_path = File.join(Preferences.model_preferences_path, "#{self.class.name.downcase}.yml")
if File.exist?(default_preferences_path)
self.class.class_variable_set :@@default_preferences, HashWithIndifferentAccess.new(YAML.load_file(default_preferences_path)) # for access with symbols
else
logger.error "PreferencesModelError##{self.class.name}: File not found"
self.class.class_variable_set :@@default_preferences, {}
end
end
# Returns a hash of preferences merged from file and model
def merged_preferences
# get the preferences from model
model_preferences_hash = HashWithIndifferentAccess.new(self.read_attribute(:preferences))
# get the default preferences form file
default_preferences_hash = default_preferences
# merge the preferences
default_preferences_hash.each_key do |key|
default_preferences_hash[key][:preferences].each do |preference|
name = preference[:name]
default_value = preference[:value]
# if the preference on model does not exist
unless model_preferences_hash.has_key? name
# add the new preference(read from file) to the model preferences hash
model_preferences_hash[name] = default_value
end
end
end
model_preferences_hash
end
end
end
end
end<file_sep># -*- encoding: utf-8 -*-
require File.expand_path('../lib/mongoid-preferences/preferences/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["<NAME>"]
gem.email = ["<EMAIL>"]
gem.description = %q{Preferences with Mongoid}
gem.summary = %q{Add preferences hash to Mongoid model}
gem.homepage = "https://github.com/matito/mongoid-preferences.git"
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "mongoid-preferences"
gem.require_paths = ["lib"]
gem.version = Mongoid::Preferences::VERSION
gem.add_dependency('mongoid', '~> 3')
gem.add_development_dependency('rake', '~> 10.0')
gem.add_development_dependency('rspec', '~> 2.12')
gem.add_development_dependency('yard', '~> 0.8')
gem.add_development_dependency('mongoid-rspec', '~> 1.4.4')
gem.add_development_dependency('database_cleaner', '~> 1.0')
gem.add_development_dependency('redcarpet', '~> 2.2')
gem.add_development_dependency('json', '~> 1.7.7')
end
| 9de614eca832f7460a6a3e5b36ddf650fde5bae5 | [
"Markdown",
"Ruby"
] | 8 | Ruby | mtoso/mongoid-preferences | 7ca8e5c598f8e92e97c161d8ab121dba73c68d5e | 866b76a81b8defff2341bfb592015639f2237714 |
refs/heads/master | <file_sep># Bistromathique
This is a fast calculator (faster than bc on some big operation!). It deal with arbitrary base, arbitrary symbol arithmetic and arbitrary number size.
It is design for 64 bits architecture yet run pretty fast on 32 bits too.
Run "make" in a terminal to compile.
>/!\ Big endian robot or other computing stuff, pass your way, your are not welcome /!\
>/!\ This is a Little endian bistro, you might get seriously drunk results here /!\
## Usage :
./calc <base_symbols> <operators> <operation_size> < <operation_file>
Note that every symbol in the operation must be defined in \<base_symbols\> or \<operators\>, even space. Otherwise calc throws Syntax error.
## Supported operations :
()+-*/% Symbols must be defined by typing them in the same order
## Examples :
echo '30-2*(4-1234%17)' | ./calc '0123456789' '()+-*/%' 16
> output : 42
echo '10001x[~00011+00101]\01011' | ./calc '01' '[]+~x/\' 26
> output : 1
## 3 additional scripts using ./calc :
* ./bc_vs_calc \<operation\>
compute \<operation\> with classical symbols,
compare performance and result with the UNIX calculator bc
* ./ultimate_bc_vs_calc :
benchmark test for both calc and bc using a giant random operation
* ./simple_calc \<operation\> [\<base_symbols\> [\<operators\>]]:
simply compute \<operation\> without need to specify anything else if you dont want to.
## About :
This program is originaly an exercice for entrance in the school 42 (www.42.fr)
The original compilation flag have been turn off and replace with -O3 for performance.
The team epically failed to debug the program in time,
hopefully after changing two lines and 3 characters you can now enjoy it.
In addition of temporay tables to optimize mult, div and mod, the main trick is to add or substract 8 digits instantly over 64 bits integers (each digit stands in a byte, max base size is 128).
Some binary sweets propagate the carry instantly over the 8 digits.
If you are interested in more documentation over the code, send me your motivation at <EMAIL>
PS : I will not help student to cheat, I am far too expensive
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* eval_expr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mguinin <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2013/08/02 14:13:03 by mguinin #+# #+# */
/* Updated: 2013/08/09 23:34:16 by mguinin ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/bistromathique.h"
#include "../includes/const.h"
t_big eval(t_elem elem)
{
t_big res;
if (!elem->op)
{
return (read_struct(elem));
}
res = elem->op(eval(elem->a), eval(elem->b));
res->sgn *= elem->sgn;
return (res);
}
int ft_strlen2(char *strlen)
{
int i;
i = 0;
while (strlen[i] != 0)
{
i = i + 1;
}
return (i);
}
void init_global(char *base, char *oper)
{
t_ulong ul1;
ul1= 1ULL;
g_base = ft_strlen2(base);
g_compl = 256 - g_base;
g_compl_8 = g_compl * 0x0101010101010101;
g_zero_big = create_big(0, 0);
g_little_endian = *(char*)&ul1;
g_oper = oper;
g_bra = oper[0];
g_ket = oper[1];
g_plus = oper[2];
g_minus = oper[3];
g_mult = oper[4];
g_div = oper[5];
g_mod = oper[6];
}
int eval_expr(char *base, char *oper, char *str)
{
t_elem parsed;
if (init_test_tab(base, oper))
{
init_global(base, oper);
g_op = init_fptr();
parsed = parse(&str);
if (parsed)
{
parsed = parse_op(parsed, &str, '\0');
if (parsed)
{
ft_putconvert(base, eval(parsed));
return (0);
}
}
}
ft_putstr(SYNTAXE_ERROR_MSG, 2);
return (2);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* util_operation.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mguinin <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2013/08/08 19:56:31 by mguinin #+# #+# */
/* Updated: 2013/08/09 23:02:20 by mguinin ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/bistromathique.h"
#include "../../includes/const.h"
#include <stdlib.h>
t_big *create_table(t_big x)
{
t_big *res;
int i;
res = malloc(sizeof(*res) * g_base);
i = g_base;
while (i--)
{
res[i] = NULL;
}
res[1] = x;
return (res);
}
void destruct_table(t_big *table)
{
int i;
i = g_base;
while (--i)
{
destruct_big(table[i]);
}
}
t_big get_mult(t_uchar c, t_big *table)
{
t_big half;
if (!table[c])
{
half = cp_big(get_mult((c >> 1) + (c & 1), table));
offset_add(half, get_mult(c >> 1, table), 0);
adjust_length(half);
table[c] = half;
}
return (table[c]);
}
long long cmp_big(t_big a, t_big b, int offset)
{
t_ulong *ia;
t_ulong *ib;
t_ulong *end;
int res;
res = a->len - b->len - offset;
if (res == 0)
{
ia = (t_ulong*)(a->data + a->len) - 1;
ib = (t_ulong*)(b->data + b->len) - 1;
end = ib - ((b->len - 1) >> 3);
while (ib != end && *ia == *ib)
{
ia--;
ib--;
}
return (*ia - *ib);
}
return (res);
}
<file_sep>#! /bin/bash
if test $(echo $2 | wc -c) != 1
then
BASE=$2
else
BASE=0123456789
fi
if test $(echo $3 | wc -c) == 8
then
OPER=$3
else
OPER='()+-*/%'
fi
LEN=$(($(echo $1 | wc -c)-1))
echo "$1" | ./calc $BASE $OPER $LEN
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* util_big.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mguinin <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2013/08/07 18:01:57 by mguinin #+# #+# */
/* Updated: 2013/08/09 23:26:19 by mguinin ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/bistromathique.h"
#include "../../includes/const.h"
#include <stdlib.h>
t_big create_big(int len, int fill_zero)
{
t_big res;
t_ulong *i;
t_ulong *end;
res = malloc(sizeof(*res));
res->buf_len = ((len + EXTRA_BUF) | 7) + 1;
res->data = malloc(res->buf_len + 16) + 8;
res->len = len;
res->sgn = 1;
*(t_ulong*)(res->data - 8) = 0;
i = (t_ulong*)res->data + (fill_zero ? 0 : (res->len >> 3) - 1);
end = (t_ulong*)res->data + (res->buf_len >> 3) + 1;
while (i != end)
{
*i = 0;
i++;
}
return (res);
}
t_big cp_big(t_big x)
{
int i;
t_big res;
t_ulong *xdata;
t_ulong *resdata;
res = create_big(x->len, 0);
res->sgn = x->sgn;
i = (x->len >> 3) + 1;
resdata = (t_ulong*)res->data;
xdata = (t_ulong*)x->data;
while (i--)
{
resdata[i] = xdata[i];
}
return (res);
}
void extend_buf(t_big *x)
{
t_big tmp;
tmp = cp_big(*x);
destruct_big(*x);
*x = tmp;
}
void destruct_big(t_big x)
{
if (x && x != g_zero_big)
{
free(x->data - 8);
free(x);
}
}
void adjust_length(t_big x)
{
while (x->data[x->len])
{
x->len++;
}
while (x->len && !x->data[x->len - 1])
{
x->len--;
}
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* add_sub.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mguinin <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2013/08/07 12:49:24 by mguinin #+# #+# */
/* Updated: 2013/08/09 23:33:42 by mguinin ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/bistromathique.h"
#include "../../includes/const.h"
t_big add_big(t_big a, t_big b)
{
if (a->len < b->len
|| (a->len == b->len
&& a->sgn != b->sgn
&& cmp_big(a, b, 0) < 0))
{
return (add_big(b, a));
}
if (a->sgn == b->sgn && a->buf_len <= a->len)
{
extend_buf(&a);
}
(a->sgn == b->sgn ? offset_add : offset_sub)(a, b, 0);
destruct_big(b);
adjust_length(a);
return (a);
}
void offset_add(t_big a, t_big b, int offset)
{
add_data((t_ulong*)(a->data + offset), (t_ulong*)b->data, L_END(b));
}
void offset_sub(t_big a, t_big b, int offset)
{
sub_data((t_ulong*)(a->data + offset), (t_ulong*)b->data, L_END(b));
}
void add_data(t_ulong *la, t_ulong *lb, t_ulong *lb_end)
{
t_ulong ret;
t_ulong res;
ret = 0;
while (lb != lb_end)
{
res = *la + *lb + g_compl_8 + ret;
ret = ~res >> 63;
*la = res - ((res & RET_BITS)>>7) * g_compl;
la++;
lb++;
}
while (ret)
{
res = *la + g_compl_8 + ret;
ret = ~res >> 63;
*la = res - ((res & RET_BITS)>>7) * g_compl;
la++;
}
}
void sub_data(t_ulong *la, t_ulong *lb, t_ulong *lb_end)
{
t_ulong ret;
t_ulong res;
ret = 1;
while (lb != lb_end)
{
res = *la + ~*lb + ret;
ret = ~res >> 63;
*la = res - ((res & RET_BITS)>>7) * g_compl;
la++;
lb++;
}
while (!ret)
{
res = *la - 1;
ret = ~res >> 63;
*la = res - ((res & RET_BITS)>>7) * g_compl;
la++;
}
}
<file_sep>#! /bin/bash
rand_num()
{
echo "generation number about $[$N*5] digits"
while test $N != 0
do
N=$[$N-1];
echo -n $RANDOM >> _operation_
done
}
echo -n '' > _operation_
N=10000
rand_num
echo -n '*' >> _operation_
N=10000
rand_num
echo -n '/' >> _operation_
N=4242
rand_num
echo -n '%' >> _operation_
N=1234
rand_num
echo -n '+' >> _operation_
N=1234
rand_num
echo -n '-' >> _operation_
N=1234
rand_num
echo >> _operation_
echo 'begining calcul'
LEN=$[$(cat _operation_ | wc -c)-1]
echo "input length = $LEN"
cat _operation_ | time -f "calc %E sec" ./calc "0123456789" "()+-*/%" $LEN > calc_res
cat _operation_ | time -f "bc %E sec" bc | tr -d '\\\n' > bc_res; echo >> bc_res
echo
if test $(diff calc_res bc_res | wc -c) = 0
then
echo "calc and bc give same result"
else
echo "different results"
fi
rm calc_res bc_res #_operation_
<file_sep>#! /bin/sh
LEN=$(($(echo $1 | wc -c)-1))
echo "input length = $LEN"
echo $1 | time -f "calc %E sec" ./calc "0123456789" "()+-*/%" $LEN > calc_res
echo $1 | time -f "bc %E sec" bc | tr -d '\\\n' > bc_res; echo >> bc_res
echo
if test $(diff calc_res bc_res | wc -c) = 0
then
cat calc_res
else
echo "different result"
echo 'calc : ' $(cat calc_res)
echo 'bc : ' $(cat bc_res)
fi
rm calc_res bc_res
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parse.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mguinin <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2013/08/09 16:37:30 by mguinin #+# #+# */
/* Updated: 2013/08/09 22:50:18 by mguinin ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "../includes/bistromathique.h"
#include "../includes/const.h"
t_elem create_elem(t_elem a, t_elem b, t_fbig op)
{
t_elem res;
res = malloc(sizeof(*res));
res->sgn = 1;
res->a = a;
res->b = b;
res->op = op;
return (res);
}
int read_sgn(char **res)
{
int sign;
char *str;
str = *res;
sign = 1;
while (*str == g_plus || *str == g_minus)
{
if (*str == g_minus)
{
sign = -sign;
}
str++;
}
*res = str;
return (sign);
}
t_elem parse_digit(char **s)
{
char digit;
t_elem x;
char *str;
str = *s;
x = create_elem(NULL, NULL, NULL);
x->start = str;
while ((digit = g_tab_test[(int)*str]) >= 0)
{
*str = digit;
str++;
}
if (x->start == str)
{
return (NULL);
}
x->len = str - x->start;
while (x->len && *x->start == 0)
{
x->start++;
x->len--;
}
*s = str;
return (x);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* bistro.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mguinin <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2013/08/07 12:48:11 by mguinin #+# #+# */
/* Updated: 2013/08/09 23:34:35 by mguinin ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef BISTRO_H
# define BISTRO_H
# define RET_BITS 0x8080808080808080
# define EXTRA_BUF 256
# define L_END(x) (((t_ulong*)x->data) + (((x)->len + 7) >> 3))
# define SYNTAXE_ERROR_MSG "syntax error\n"
# define MINUS -5
# define PLUS -4
# define ZERO 0
# include <stdio.h>
typedef unsigned long long t_ulong;
typedef unsigned char t_uchar;
typedef struct s_big_char
{
t_uchar *data;
int len;
int buf_len;
int sgn;
} t_big_char;
typedef t_big_char *t_big;
typedef t_big (*t_fbig)(t_big, t_big);
typedef struct s_element
{
int sgn;
struct s_element *a;
struct s_element *b;
t_fbig op;
char *start;
int len;
} t_element;
typedef t_element *t_elem;
t_elem parse(char **str);
t_elem parse_prio(t_elem a, char **str, char close);
t_elem parse_op(t_elem a, char **str, char close);
t_elem create_elem(t_elem a, t_elem b, t_fbig op);
int read_sgn(char **res);
t_elem parse_digit(char **s);
t_big create_big(int len, int init_zero);
t_big add_big(t_big a, t_big b);
t_big *create_table(t_big x);
t_big mult_big(t_big a, t_big b);
long long cmp_big(t_big a, t_big b, int offset);
t_big divmod_big(t_big a, t_big b);
int eval_expr(char *base, char *oper, char *str);
t_big eval(t_elem elem);
t_big read_struct(t_elem elem);
void ft_putstr(char *str, int output);
int ft_length_nbr(char *str);
int init_test_tab(char *base, char *oper);
t_fbig *init_fptr();
int ft_strlen2(char *str);
void ft_putconvert(char *base, t_big a);
void extend_buf(t_big *x);
void offset_add(t_big a, t_big b, int offset);
void offset_sub(t_big a, t_big b, int offset);
void destruct_big(t_big x);
void adjust_length(t_big x);
void add_data(t_ulong *la, t_ulong *lb, t_ulong *lb_end);
void sub_data(t_ulong *la, t_ulong *lb, t_ulong *lb_end);
t_big div_big(t_big a, t_big b);
t_big mod_big(t_big a, t_big b);
void divmod_data(t_big a, t_big *mult_b, t_big res);
void destruct_table(t_big *table);
t_big get_mult(t_uchar c, t_big *table);
void mult_data(t_big *mult_a, t_big b, t_big res);
t_big cp_big(t_big x);
#endif /* BISTRO_H */
<file_sep>#******************************************************************************#
# #
# ::: :::::::: #
# Makefile :+: :+: :+: #
# +:+ +:+ +:+ #
# By: ybouvet <<EMAIL>> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2013/08/09 10:45:53 by ybouvet #+# #+# #
# Updated: 2013/08/09 19:36:03 by mguinin ### ########.fr #
# #
#******************************************************************************#
NAME = calc
SRC = main.c \
evalexpr/eval_expr.c \
evalexpr/parse_op.c \
evalexpr/parse.c \
evalexpr/read.c \
evalexpr/operation/add_sub.c \
evalexpr/operation/div_mod.c \
evalexpr/operation/mult.c \
evalexpr/utility/ft_test.c \
evalexpr/utility/util_big.c \
evalexpr/utility/util_operation.c \
INCLUDE = includes/
OBJ = $(SRC:.c=.o)
#CFLAGS = -Wall -Wextra -Werror
CFLAGS = -O3
all: $(NAME)
$(NAME): $(OBJ)
gcc -o $(NAME) -I$(INCLUDE) $(OBJ)
clean:
/bin/rm -f $(OBJ)
fclean: clean
/bin/rm -f $(NAME)
re: fclean all
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ybouvet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2013/08/05 15:26:52 by ybouvet #+# #+# */
/* Updated: 2013/08/09 11:20:39 by ybouvet ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include "includes/bistromathique.h"
static size_t ft_strlen(char *strlen)
{
size_t i;
i = 0;
while (strlen[i] != 0)
{
i = i + 1;
}
return (i);
}
static unsigned int ft_uatoi(char *nbr)
{
unsigned int res;
res = 0;
while (*nbr)
{
res = *nbr - '0' + res * 10;
nbr = nbr + 1;
}
return (res);
}
static int ft_fill_buff(char* buf, size_t size)
{
size_t size_read;
ssize_t ret;
size_read = 0;
ret = read(0, buf, size);
if (ret == -1)
{
write(2, SYNTAXE_ERROR_MSG, ft_strlen(SYNTAXE_ERROR_MSG));
return (1);
}
while (ret != 0)
{
size_read = size_read + ret;
ret = read(0, buf, size - size_read);
if (ret == -1)
{
write(2, SYNTAXE_ERROR_MSG, ft_strlen(SYNTAXE_ERROR_MSG));
return (1);
}
}
buf[size_read] = 0;
return (0);
}
static int ft_check_args_n_malloc_buf(int argc, char **argv, char **buf)
{
size_t size;
if (argc != 4)
{
write(2, SYNTAXE_ERROR_MSG, ft_strlen(SYNTAXE_ERROR_MSG));
return (1);
}
size = ft_uatoi(argv[3]);
*buf = malloc(sizeof(**buf) * (size + 1));
if (*buf == 0)
{
write(2, SYNTAXE_ERROR_MSG, ft_strlen(SYNTAXE_ERROR_MSG));
return (1);
}
return (ft_fill_buff(*buf, size));
}
int main(int argc, char **argv)
{
char *buf;
if (ft_check_args_n_malloc_buf(argc, argv, &buf))
{
return (1);
}
return (eval_expr(argv[1], argv[2], buf));
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* div_mod.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mguinin <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2013/08/08 19:51:37 by mguinin #+# #+# */
/* Updated: 2013/08/09 12:46:20 by mguinin ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/bistromathique.h"
#include "../../includes/const.h"
#include <stdlib.h>
t_big div_big(t_big a, t_big b)
{
t_big res;
if (b->len == 0)
{
return (NULL);
}
res = divmod_big(a, b);
adjust_length(res);
destruct_big(a);
return (res);
}
t_big mod_big(t_big a, t_big b)
{
if (b->len == 0)
{
return (NULL);
}
destruct_big(divmod_big(a, b));
adjust_length(a);
return (a);
}
t_big divmod_big(t_big a, t_big b)
{
t_big *mult_b;
t_big res;
if (a->len >= b->len)
{
mult_b = create_table(b);
res = create_big(a->len - b->len + 1, 0);
res->sgn = a->sgn * b->sgn;
divmod_data(a, mult_b, res);
destruct_table(mult_b);
return (res);
}
return (g_zero_big);
}
t_uchar calc_digit(t_uchar *lead_a, int lead_b)
{
int digit;
digit = ((lead_a[2] * g_base + lead_a[1]) * g_base
+ *lead_a + 1) / lead_b;
return (digit >= g_base ? digit - 1 : digit);
}
void divmod_data(t_big a, t_big *mult_b, t_big res)
{
t_big m;
t_uchar digit;
int offset;
t_uchar *lead_a;
int lead_b;
lead_a = mult_b[1]->data + mult_b[1]->len - 2;
lead_b = lead_a[1] * g_base + lead_a[0];
offset = res->len;
lead_a = (t_uchar*)(a->data + a->len - 2);
while (offset--)
{
if ((digit = calc_digit(lead_a--, lead_b)))
{
m = get_mult(digit, mult_b);
digit -= cmp_big(a, m, offset) < 0;
if (digit)
{
m = get_mult(digit, mult_b);
offset_sub(a, m, offset);
adjust_length(a);
}
}
res->data[offset] = digit;
}
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parse_op.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mguinin <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2013/08/02 14:14:33 by mguinin #+# #+# */
/* Updated: 2013/08/09 21:48:14 by mguinin ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "../includes/bistromathique.h"
#include "../includes/const.h"
t_elem parse(char **str)
{
t_elem res;
int sgn;
sgn = read_sgn(str);
if (**str == g_bra)
{
(*str)++;
res = parse_op(parse(str), str, g_ket);
}
else
{
res = parse_digit(str);
}
if (res)
{
res->sgn = sgn;
}
return (res);
}
t_elem parse_prio(t_elem a, char **str, char close)
{
t_fbig op;
t_elem b;
op = g_op[(int)(**str)];
if (op)
{
if (op == add_big)
{
return (a);
}
(*str)++;
b = parse(str);
if (b)
{
return (parse_prio(create_elem(a, b, op), str, close));
}
}
return (**str == close ? a : NULL);
}
t_elem parse_op(t_elem a, char **str, char close)
{
t_elem b;
t_fbig op;
if (**str == close)
{
(*str)++;
return (a);
}
op = g_op[(int)**str];
if (op)
{
(*str) += op != add_big;
b = parse(str);
if (b)
{
b = (op == add_big) ? parse_prio(b, str, close) : b;
return (b ? parse_op(create_elem(a, b, op), str, close) : NULL);
}
}
return (NULL);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_test.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ybouvet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2013/08/06 17:08:57 by ybouvet #+# #+# */
/* Updated: 2013/08/09 22:28:03 by mguinin ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/bistromathique.h"
#include "../../includes/const.h"
#include <unistd.h>
#include <stdlib.h>
void ft_putstr(char *str, int output)
{
while (*str)
{
write(output, str, 1);
str++;
}
}
int ft_length_nbr(char *str)
{
int i;
i = 0;
while (g_tab_test[(int)str[i]] >= 0)
{
i++;
}
return (i);
}
int init_test_tab(char *base, char *oper)
{
int i;
i = 256;
while (i)
{
g_tab_test[--i] = -1;
}
while (*base && g_tab_test[(int)*base] == -1)
{
g_tab_test[(int)*base] = i++;
base++;
}
i = -2;
while (*oper && g_tab_test[(int)*oper] == -1)
{
g_tab_test[(int)*oper] = i--;
oper++;
}
return (!*base && !*oper);
}
t_fbig *init_fptr()
{
t_fbig *op;
int i;
op = malloc(sizeof(*op) * 256);
i = 0;
while (i < 256)
{
op[i++] = NULL;
}
op[(int)g_plus] = &add_big;
op[(int)g_minus] = &add_big;
op[(int)g_mult] = &mult_big;
op[(int)g_div] = &div_big;
op[(int)g_mod] = &mod_big;
return (op);
}
void ft_putconvert(char *base, t_big a)
{
int i;
i = a->len;
if (a->len == 0)
{
write(1, base, 1);
}
else if (a->sgn == -1)
{
write(1, "-", 1);
}
while (i--)
{
write(1, &base[(int)(a->data[i])], 1);
}
write(1, "\n", 1);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* mult.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mguinin <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2013/08/08 20:37:21 by mguinin #+# #+# */
/* Updated: 2013/08/09 23:33:35 by mguinin ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/bistromathique.h"
#include "../../includes/const.h"
t_big mult_big(t_big a, t_big b)
{
t_big *mult_a;
t_big res;
if (b->len > a->len)
{
return (mult_big(b, a));
}
if (b->len == 0)
{
return (g_zero_big);
}
mult_a = create_table(a);
res = create_big(a->len + b->len + 1, 1);
res->sgn = a->sgn * b->sgn;
mult_data(mult_a, b, res);
destruct_table(mult_a);
destruct_big(b);
adjust_length(res);
return (res);
}
void mult_data(t_big *mult_a, t_big b, t_big res)
{
t_uchar *ib;
t_uchar *end;
int offset;
offset = 0;
ib = b->data;
end = b->data + b->len;
while (ib != end)
{
if (*ib)
{
offset_add(res, get_mult(*ib, mult_a), offset);
}
ib++;
offset++;
}
}
| 72aa7bea5402054aababd2f4ae4becc9a1c8f9ee | [
"Markdown",
"C",
"Makefile",
"Shell"
] | 16 | Markdown | maginth/bistromathique | 0efc188d339ac71a43368030f4b7df963548a3ab | 712ca8eb95aaf26c306973e4c65e2e910b06a767 |
refs/heads/master | <repo_name>Aaaaaashu/Aaaaaashu.github.io<file_sep>/bird/build/precache-manifest.fa00c4626f8332e2516e046508d0d5f2.js
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "c3a46d6ef437245b2c2d122bfd235288",
"url": "/index.html"
},
{
"revision": "cc002f9d78d2ed93ca20",
"url": "/static/css/main.bb6b9b86.chunk.css"
},
{
"revision": "ab7d9f9d0b182ab45cc9",
"url": "/static/js/2.9019707f.chunk.js"
},
{
"revision": "b1bd7d111be11bf1a60de02093538313",
"url": "/static/js/2.9019707f.chunk.js.LICENSE"
},
{
"revision": "cc002f9d78d2ed93ca20",
"url": "/static/js/main.1e553c0a.chunk.js"
},
{
"revision": "1ea93026740272f1d446",
"url": "/static/js/runtime-main.ad1be643.js"
}
]); | f4b3007f0906238e741b6d9703ab3c508a5596cc | [
"JavaScript"
] | 1 | JavaScript | Aaaaaashu/Aaaaaashu.github.io | d1843b1e82d600bb98db8a6537596311826c3880 | f5a51c134d1ec127d512961fa0f61c051c19f5af |
refs/heads/master | <repo_name>splice-aldis/XSAN_Mounter<file_sep>/main.py
import os
import sys
from subprocess import call
from kivy.app import App
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
# xsan_volumes = {"LAMBERT","WILLIAMS", "PRATT"}
xsan_volumes = []
class XSANMounterApp(App):
cache_file = open('cachefile', 'r')
for line in cache_file:
volume_name = line.split(" - ")[0]
volume_mounted = line.split(" - ")[1].replace('\n', '')
if volume_mounted == "not mounted":
# print volume_name + " is " + volume_mounted
xsan_volumes.append([volume_name, volume_mounted])
else:
# print volume_name + " is mounted"
xsan_volumes.append([volume_name, "mounted"])
cache_file.close()
# this is the button maker to toggle whether volumes are mounted or not.
def build(self):
app_stage = BoxLayout(orientation="vertical")
message_box = TextInput(text='You have three volumes to mount:', font_size=30)
for vol in xsan_volumes:
app_stage.add_widget(self.bm(vol))
app_stage.add_widget(message_box)
return app_stage
def btn_mnt_state(self, vol):
if vol[1] == "not mounted":
return "normal"
else:
return "down"
def btn_unmnt_state(self, vol):
if vol[1] == "not mounted":
return "down"
else:
return "normal"
def mount_volume(self, test):
f = open("cachefile", "w")
try:
call(["ls", "-l"]) # , stdout=f
f.close()
except (OSError, SyntaxError):
print "this failed OS"
f.close()
cache_file = open('cachefile2', 'r')
for line in cache_file:
volume_name = line.split(" - ")[0]
volume_mounted = line.split(" - ")[1].replace('\n', '')
mount_button_name = 'mount_btn_' + volume_name
unmount_button_name = 'unmount_btn_' + volume_name
if volume_mounted == "not mounted":
unmount_button_name.state = "down"
mount_button_name.state = "normal"
else:
mount_button_name.state = "down"
unmount_button_name.state = "normal"
def bm(self, vol):
xsan_layout = BoxLayout(orientation="horizontal")
mount_button_name = 'mount_btn_' + vol[0]
unmount_button_name = 'unmount_btn_' + vol[0]
mount_button_name = ToggleButton(text='MOUNT', group=vol[0], state=self.btn_mnt_state(vol), allow_no_selection=False, font_size=30, id=self.btn_unmnt_state(vol))
mount_button_name.bind(on_press=self.mount_volume)
unmount_button_name = ToggleButton(text='UNMOUNT', group=vol[0], state=self.btn_unmnt_state(vol),allow_no_selection=False, font_size=30, id=self.btn_unmnt_state(vol))
unmount_button_name.bind(on_press=self.mount_volume)
volume_name = Label(text=vol[0], font_size=40, size_hint_x=2)
xsan_layout.add_widget(volume_name)
xsan_layout.add_widget(mount_button_name)
xsan_layout.add_widget(unmount_button_name)
return xsan_layout
if __name__ == "__main__":
XSANMounterApp().run()<file_sep>/temp.py
from subprocess import call
# cache_file = open('cachefile', 'r')
# xsan_volumes = []
#
# for line in cache_file:
# volume_name = line.split(" - ")[0]
# volume_mounted = line.split(" - ")[1].replace('\n', '')
#
# if volume_mounted == "not mounted":
# print volume_name + " is " + volume_mounted
# xsan_volumes.append([volume_name, volume_mounted])
# else:
# print volume_name + " is mounted"
# xsan_volumes.append([volume_name, "mounted"])
#
# print xsan_volumes
# ######################################
def mount_volume(self):
f = open("cachefile", "w")
try:
call(["ls", "-l"]) #, stdout=f
f.close()
except (OSError, SyntaxError):
print "this failed OS"
cache_file = open('cachefile', 'r')
for line in cache_file:
volume_name = line.split(" - ")[0]
volume_mounted = line.split(" - ")[1].replace('\n', '')
mount_button_name = 'mount_btn_' + volume_name
unmount_button_name = 'unmount_btn_' + volume_name
if volume_mounted == "not mounted":
print volume_name + " is not " + volume_mounted
unmount_button_name.state = "down"
mount_button_name.state = "normal"
else:
print volume_name + " is mounted"
mount_button_name.state = "down"
unmount_button_name.state = "normal"
mount_volume(self)
PRATT - / Volumes / PRATT
# WILLIAMS - not mounted
# LAMBERT - /Volumes/LAMBERT
# | 6ad1b002b9ee7172df5e501881c7941fe8756dbb | [
"Python"
] | 2 | Python | splice-aldis/XSAN_Mounter | 1eaa922e79a6d6e4f21d700468a175b72758969e | b6fa807fc3c072bbb471f4c1cca163aa17d9f0f8 |
refs/heads/master | <repo_name>ronengi/generic-textual-table<file_sep>/p1.cpp
#include <iostream>
#include <locale>
#include <string>
#include <sstream>
using namespace std;
const int X = 14;
const int Y = 16;
const int SN = 3;
const int SL = 1;
const int SR = 1;
const int S0 = 8;
const wchar_t SPC = U'\U00000020';
const wchar_t CLT = U'\U0000256d';
const wchar_t CRT = U'\U0000256e';
const wchar_t CHH = U'\U00002500';
const wchar_t CVV = U'\U00002502';
const wchar_t CLB = U'\U00002514';
const wchar_t CRB = U'\U00002518';
const wchar_t CTR = U'\U0000251c';
const wchar_t CTL = U'\U00002524';
const wchar_t CHV = U'\U0000253c';
const wchar_t CTD = U'\U0000252c';
const wchar_t CTU = U'\U00002534';
wstring spaces(int i) {
wostringstream ss;
while (i > 0) {
ss << SPC;
--i;
}
return ss.str();
}
wstring repeated(wchar_t c, int i) {
wostringstream ss;
while (i > 0) {
ss << c;
--i;
}
return ss.str();
}
wstring header() {
wostringstream ss;
ss << CLT << repeated(CHH, SL + SN + SR);
for (int i = 1; i < X; ++i)
ss << CTD << repeated(CHH, SL + SN + SR);
ss << CRT << endl;
return ss.str();
}
wstring footer() {
wostringstream ss;
ss << CLB << repeated(CHH, SL + SN + SR);
for (int i = 1; i < X; ++i)
ss << CTU << repeated(CHH, SL + SN + SR);
ss << CRB;
return ss.str();
}
wstring separator() {
wostringstream ss;
ss << CTR << repeated(CHH, SL + SN + SR);
for (int i = 1; i < X; ++i)
ss << CHV << repeated(CHH, SL + SN + SR);
ss << CTL;
return ss.str();
}
int n_length(int n) {
wostringstream ss;
ss << n;
return ss.str().length();
}
wstring number(int n) {
wostringstream ss;
int l = SN - n_length(n);
l = (l < 0) ? 0 : l;
ss << CVV << repeated(SPC, SL) << repeated(SPC, l) << n << repeated(SPC, SR);
return ss.str();
}
int main() {
setlocale(LC_CTYPE,"he_IL.UTF-8");
wcout << endl << repeated(SPC, S0) << header();
for (int i = 1; i <= Y; ++i) {
wcout << repeated(SPC, S0);
for (int j = 1; j <= X; ++j)
wcout << number(i * j);
wcout << CVV << endl;
if (i < Y)
wcout << repeated(SPC, S0) << separator() << endl;
}
wcout << repeated(SPC, S0) << footer() << endl << endl;
}
| 13b89b4f6f77d7c19e3b5c0cb5b08cc2ec3a6dbd | [
"C++"
] | 1 | C++ | ronengi/generic-textual-table | 7f0ad908df087838e47e15ba77804ad0764d7b5c | 4534d41f33ff953c4648aa213559b167486823a9 |
refs/heads/master | <repo_name>dimaty26/SimpleTasks<file_sep>/Collections/src/Collections/java/Collections.java
package Collections.java;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class Collections {
}
<file_sep>/Collections/src/Collections/java/Main.java
package Collections.java;
import java.util.*;
class Book {
String nameAuthor;
public Book(String nameAuthor) {
this.nameAuthor = nameAuthor;
}
@Override
public String toString() {
return "Book{" +
"nameAuthor='" + nameAuthor + '\'' +
'}';
}
}
public class Main {
public static void main(String[] args) {
Collection collection = new LinkedHashSet();
collection.add("3");
collection.add("2");
collection.add("1");
for (Object o : collection)
{
System.out.println(o);
}
}
}
<file_sep>/StepikWebServer/stepic_java_webserver-master/ShiftChipher/src/ZmeevHome/ShiftEncode.java
package ZmeevHome;
public class ShiftEncode {
String string;
public ShiftEncode(String str){
this.string = str;
}
public String encode(int key) {
String string1 = "abcdefghijklmnopqrstuvwxyz";
char[] ch1 = string1.toCharArray();
char[] ch = string.toCharArray();
for(int j = 0; j < ch.length; j++){
for(int i = 0; i < ch1.length; i++){
if(ch[j] == ch1[i]){
char[] result = new char[ch1.length];
for(int k = 0; k < ch1.length - key; k++){
result[k] = ch1[key + k];
}
for(int k = 0; k < key; k++) {
result[ch1.length - key + k] = ch1[k];
}
ch[j] = result[i];
break;
}
}
}
return String.valueOf(ch);
}
}
<file_sep>/Attempts/src/Attempts/java/Main.java
package Attempts.java;
public interface Main {
static void main(String[] args) {
// write your code here
}
public interface Corable {
}
public class Car {
}
}
class Cat {
}
interface Movable {}
<file_sep>/StepikWebServer/stepic_java_webserver-master/ShiftChipher/src/ZmeevHome/Main.java
package ZmeevHome;
import java.util.Arrays;
public class Main {
int[] arr;
public Main(int[] arr){
this.arr = arr;
}
public int[] shift(int n){
int[] result = new int[arr.length];
for(int i = 0; i < arr.length - n; i++){
result[i] = arr[n + i];
}
for(int i = 0; i < n; i++) {
result[arr.length - n + i] = arr[i];
}
return result;
}
public static void main(String[] args) {
int[] arr = new int[10];
for(int i = 0; i < arr.length; i++){
arr[i] = i;
}
Main arrMain = new Main(arr);
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(arrMain.shift(7)));
ShiftEncode shiftEncode = new ShiftEncode("happy wedding");
String encodeStr = shiftEncode.encode(3);
System.out.println(encodeStr);
ShiftDecode shiftDecode = new ShiftDecode(encodeStr);
String decodeStr = shiftDecode.decode(3);
System.out.println(decodeStr);
}
}
<file_sep>/Massive/src/Massive/java/Main.java
package Massive.java;
public class Main {
public static void main(String[] args) {
MyArrays arrays = new MyArrays();
arrays.foo();
}
}
<file_sep>/JustTry/src/ZmeevHome/Main.java
package ZmeevHome;
public class Main {
public String name;
public static void main(String args[]) {
Main m = new Main();
anotherMethod(m);
}
static void anotherMethod(Main m) {
m.name = "anotherName";
System.out.println(m.name);
}
static int returnByte() {
byte a = 10;
return a;
}
}
<file_sep>/JDBCTutorial/src/test/resources/test.sql
insert into users (name, age, email) values('Steve', 24, '<EMAIL>');
#select name, age from users where id = 1;
#select * from users;
#update users set name = 'Steve', age=24 where id = 2;
#delete from users where id=4;
#SET SQL_SAFE_UPDATES=0;<file_sep>/MyTree/src/TreePackage/java/Main.java
package TreePackage.java;
public class Main {
public static void main(String[] args) {
MyTreeNode n1 = new MyTreeNode(1);
MyTreeNode n2 = new MyTreeNode(1);
MyTreeNode n3 = new MyTreeNode(1);
MyTreeNode n4 = new MyTreeNode(1);
MyTreeNode n5 = new MyTreeNode(1);
n1.nodeRight = n3;
n1.nodeLeft = n2;
n3.nodeRight = n5;
n2.nodeLeft = n4;
System.out.println(n1.countNumber());
}
}
| ec67d4be94d21e844855e4e318cf6ec0a6277723 | [
"Java",
"SQL"
] | 9 | Java | dimaty26/SimpleTasks | 9106721313e9b5390f4b1ea002e8e58ecd3e5a1d | 512fb3c37a2f6103d0dd72d532aad2b3e88e6e9b |
refs/heads/master | <file_sep>Basketball
==========
Basketball Plugin by TheRealBuckshot.
<file_sep>package me.therealbuckshot.basketball;
import java.util.ArrayList;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Slime;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.ScoreboardManager;
public class Main extends JavaPlugin implements Listener {
private ArrayList<Entity> balls = new ArrayList<Entity>();
private ArrayList<Player> shooter = new ArrayList<Player>();
private ArrayList<Player> red = new ArrayList<Player>();
private ArrayList<Player> blue = new ArrayList<Player>();
int redscore = 0;
int bluescore = 0;
int testint = 900;
int countdown = 20;
int startcountdown = 0;
int startgame = 0;
World w;
Location pos;
Scoreboard board;
Scoreboard cboard;
Score rScore;
Score bScore;
Score c;
Score online;
Score test;
Objective obj;
Objective obj1;
@Override
public void onEnable() {
this.getServer().getPluginManager().registerEvents(this, this);
ScoreboardManager sbManager = Bukkit.getScoreboardManager();
board = sbManager.getNewScoreboard();
obj = board.registerNewObjective("score", "dummy");
getConfig().options().copyDefaults(true);
saveConfig();
w =Bukkit.getWorld(getConfig().getString("arena.world"));
pos = new Location(w, getConfig().getInt("arena.x"), getConfig().getInt("arena.y"), getConfig().getInt("arena.z"));
obj.setDisplaySlot(DisplaySlot.SIDEBAR);
obj.setDisplayName(ChatColor.AQUA + "Scoreboard");
test = obj.getScore(Bukkit.getServer().getOfflinePlayer(
ChatColor.BLUE + "" + ChatColor.BOLD + "Time"));
test.setScore(testint);
rScore = obj.getScore(Bukkit.getServer().getOfflinePlayer(
ChatColor.RED + "RedScore"));
bScore = obj.getScore(Bukkit.getServer().getOfflinePlayer(
ChatColor.BLUE + "BlueScore"));
rScore.setScore(redscore);
bScore.setScore(bluescore);
cboard = sbManager.getNewScoreboard();
obj1 = cboard.registerNewObjective("score", "dummy");
obj1.setDisplaySlot(DisplaySlot.SIDEBAR);
obj1.setDisplayName(ChatColor.AQUA + "Countdown");
c = obj1.getScore(Bukkit.getServer().getOfflinePlayer(
ChatColor.ITALIC + "" + ChatColor.BOLD + "Time Left"));
online = obj1.getScore(Bukkit.getServer().getOfflinePlayer(
ChatColor.GREEN + "" + ChatColor.BOLD + "Players"));
c.setScore(countdown);
}
@SuppressWarnings("deprecation")
@Override
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (label.equalsIgnoreCase("addarena")) {
Player p = (Player) sender;
w = p.getWorld();
String world = w.getName();
getConfig().set("arena.world", world);
int X = pos.getBlockX();
int Y = pos.getBlockY();
int Z = pos.getBlockZ();
getConfig().set("arena.x", X);
getConfig().set("arena.y", Y);
getConfig().set("arena.z", Z);
saveConfig();
}
if (label.equalsIgnoreCase("addscorered")) {
if (!(sender instanceof Player)) {
redscore++;
rScore.setScore(redscore);
for (Entity en : w
.getEntitiesByClasses(Slime.class))
en.remove();
Slime ball = (Slime) w
.spawnEntity(pos, EntityType.SLIME);
ball.setRemoveWhenFarAway(false);
ball.setSize(1);
LivingEntity lv = (LivingEntity) ball;
lv.setCustomNameVisible(true);
lv.setCustomName(ChatColor.RED + "Basketball");
balls.add(ball);
obj.setDisplayName(ChatColor.RED + "Red Scores!");
this.getServer().getScheduler().scheduleAsyncDelayedTask(this, new Runnable(){
public void run(){
obj.setDisplayName(ChatColor.AQUA + "Scoreboard");
}
}, 200L);
if(redscore == 25){
this.getServer().reload();
for (Player p : Bukkit.getServer()
.getOnlinePlayers()) {
p.kickPlayer(ChatColor.GOLD + "GAME OVER " + ChatColor.RED + "" + ChatColor.BOLD + "RED WINS!");
}
}
}
}
if (label.equalsIgnoreCase("addscoreblue")) {
if (!(sender instanceof Player)) {
bluescore++;
bScore.setScore(bluescore);
for (Entity en : w
.getEntitiesByClasses(Slime.class))
en.remove();
Slime ball = (Slime) w
.spawnEntity(pos, EntityType.SLIME);
ball.setRemoveWhenFarAway(false);
ball.setSize(1);
LivingEntity lv = (LivingEntity) ball;
lv.setCustomNameVisible(true);
lv.setCustomName(ChatColor.RED + "Basketball");
balls.add(ball);
obj.setDisplayName(ChatColor.BLUE + "Blue Scores!");
this.getServer().getScheduler().scheduleAsyncDelayedTask(this, new Runnable(){
public void run(){
obj.setDisplayName(ChatColor.AQUA + "Scoreboard");
}
}, 200L);
if(bluescore == 25){
this.getServer().reload();
for (Player p : Bukkit.getServer()
.getOnlinePlayers()) {
p.kickPlayer(ChatColor.GOLD + "GAME OVER " + ChatColor.BLUE + "" + ChatColor.BOLD + "BLUE WINS!");
}
}
}
}
return false;
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onRightClick(PlayerInteractEntityEvent event) {
if (balls.contains(event.getRightClicked())) {
event.setCancelled(true);
event.getRightClicked().setVelocity(
event.getPlayer().getLocation().getDirection().normalize()
.multiply(2));
}
}
@SuppressWarnings("deprecation")
@EventHandler
public void onEntityDdeath(EntityDamageByEntityEvent e) {
if (balls.contains(e.getEntity())) {
final Player p = (Player) e.getDamager();
shooter.add(p);
p.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "Shoot!");
p.getInventory().setItemInHand(new ItemStack(Material.SLIME_BALL));
this.getServer().getScheduler()
.scheduleAsyncDelayedTask(this, new Runnable() {
@Override
public void run() {
if (shooter.contains(p)) {
p.setHealth(0);
p.setLevel(0);
p.setExp(0f);
Slime ball = (Slime) w.spawnEntity(pos,
EntityType.SLIME);
ball.setRemoveWhenFarAway(false);
ball.setSize(1);
LivingEntity lv = (LivingEntity) ball;
lv.setCustomNameVisible(true);
lv.setCustomName(ChatColor.RED + "Basketball");
balls.add(ball);
shooter.remove(p);
}
}
}, 60L);
if (!(e.getCause() == DamageCause.ENTITY_ATTACK)) {
e.setCancelled(true);
e.setDamage(0);
}
}
}
@EventHandler
public void onEntityDeath(EntityDeathEvent e) {
if (balls.contains(e.getEntity())) {
e.getDrops().clear();
balls.remove(e.getEntity());
Entity ent = e.getEntity();
EntityDamageEvent ede = ent.getLastDamageCause();
DamageCause dc = ede.getCause();
if (dc.equals(DamageCause.FALL)) {
Location pos = e.getEntity().getLocation();
Slime ball = (Slime) w
.spawnEntity(pos, EntityType.SLIME);
ball.setRemoveWhenFarAway(false);
ball.setSize(1);
LivingEntity lv = (LivingEntity) ball;
lv.setCustomNameVisible(true);
lv.setCustomName(ChatColor.RED + "Basketball");
balls.add(ball);
}
}
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent e) {
Player p = e.getPlayer();
if (shooter.contains(p)) {
shooter.remove(p);
Location pos = p.getLocation();
Slime ball = (Slime) w
.spawnEntity(pos, EntityType.SLIME);
ball.setRemoveWhenFarAway(false);
ball.setSize(1);
LivingEntity lv = (LivingEntity) ball;
lv.setCustomNameVisible(true);
lv.setCustomName(ChatColor.RED + "Basketball");
balls.add(ball);
ball.setVelocity(p.getLocation().getDirection().normalize()
.multiply(2));
p.getInventory().remove(new ItemStack(Material.SLIME_BALL));
}
}
@EventHandler
public void onPlayerDeath(PlayerDeathEvent e) {
if (shooter.contains(e.getEntity())) {
shooter.remove(e.getEntity());
e.getDrops().clear();
e.getEntity().setLevel(0);
e.getEntity().setExp(0f);
}
}
@SuppressWarnings("deprecation")
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e) {
e.getPlayer().setScoreboard(cboard);
if (this.getServer().getOnlinePlayers().length >= 1) {
online.setScore(this.getServer().getOnlinePlayers().length);
startcountdown++;
if (startcountdown == 1) {
startcountdown++;
startgame++;
this.getServer().getScheduler()
.scheduleAsyncRepeatingTask(this, new Runnable() {
ItemStack i = new ItemStack(Material.LEATHER_HELMET, 1);
LeatherArmorMeta im = (LeatherArmorMeta) i.getItemMeta();
@Override
public void run() {
if (countdown > 0) {
countdown--;
c.setScore(countdown);
}
if (countdown == 0) {
countdown--;
game();
Slime ball = (Slime) w
.spawnEntity(pos, EntityType.SLIME);
ball.setRemoveWhenFarAway(false);
ball.setSize(1);
LivingEntity lv = (LivingEntity) ball;
lv.setCustomNameVisible(true);
lv.setCustomName(ChatColor.RED + "Basketball");
balls.add(ball);
for (Player p : Bukkit.getServer()
.getOnlinePlayers()) {
startcountdown = 1;
p.teleport(pos);
Random object = new Random();
p.setScoreboard(board);
int random;
for (int counter = 1; counter <= 1; counter++) {
random = 1 + object.nextInt(2);
if (random == 1) {
red.add(p);
im.setColor(Color.RED);
i.setItemMeta(im);
p.getInventory().setHelmet(i);
} else {
blue.add(p);
im.setColor(Color.BLUE);
i.setItemMeta(im);
p.getInventory().setHelmet(i);
}
}
}
}
}
}, 0L, 20L);
}
}
}
@SuppressWarnings("deprecation")
public void game() {
this.getServer().getScheduler()
.scheduleAsyncRepeatingTask(this, new Runnable() {
@Override
public void run() {
if (testint != -1) {
testint--;
test.setScore(testint);
} else {
for (Player p : Bukkit.getServer()
.getOnlinePlayers()) {
p.kickPlayer(ChatColor.GOLD + "GAME OVER");
p.getServer().reload();
}
}
}
}, 0L, 20L);
}
}
| c4ce5173f490e4a4dca08b3b8967ed53e0db6741 | [
"Markdown",
"Java"
] | 2 | Markdown | TheRealBuckshot/Basketball | 5c2ecac7850ee8586485babd22ede7ea5eb9c710 | 41e61b09805b91e4cd1f54eac5a40c0b80fff934 |
refs/heads/master | <repo_name>CallumGilly/race-time-keeper-version-2<file_sep>/sqlDesign.md
# Design for SQL database
## Tables
All the tables that will be used with the heading, type and example data
### RacerTbl
All the unique racers
RacerID :key: | First Name | Second Name | isMale | Birthday
-|-|-|-|-
autoNum | varChar(255) | varChar(255) | Boolean | Date
001 | John | Doe | True | 01/01/2000
### RaceTypeTbl
All the unique race types
RaceTypeID :key: | Race Name | Length(m) | isHome
-|-|-|-
autoNum | varChar(255) | Int | Boolean
001 | Henley 5k | 5000 | True
### EventTbl
All the unique events
EventID :key:| _RaceTypeID_ | Date
-|-|-
autoNum | Int | Date
001 | 001 | 01/01/2020
### RaceRecordsTbl
Records of races
RaceID :key: | _EventID_ | _RacerID_ | Time(s)
-|-|-|-
autoNum | Int | Int | Int
001 | 001 | 001 | 1800
<file_sep>/README.md
# Race time keeper
An app to keep track of times for a variety of races.
## Current development plans
- Hold race records for each racer who can:
- Access there data with just there `racerID` (no need for a password)
- Add times to there record with a length and time
- Get all of there times
- Get a list of all racer times
- Hold a variaty of lengths of races
- Hold multiple races for each user and length
- Be accesed with basic requests (JSON response)
## Running the code
The program can currently be ran with: `docker-compose -f docker-compose.dev.yml up --build` and tested with: `docker build -t race-time-keeper --target test .`
You can also test for youself when the program is build with curl statements along the lines of:'
- `curl --data '{"foo":"bar"}' --header 'content-type: application/json' localhost:3030/test`
- `curl localhost:3030/test`
## Credits
Made by [<NAME>](https://github.com/CallumGilly/)
<file_sep>/Dockerfile
# syntax=docker/dockerfile:1
FROM node:12.18.1 as base
WORKDIR /app
COPY package.json package.json
COPY package-lock.json package-lock.json
FROM base as test
RUN npm ci
COPY . .
RUN npm run test
FROM base as prod
RUN npm ci --production
COPY . .
CMD [ "npm", "start"]
<file_sep>/app/router.js
express = require(`express`);
router = express.Router();
//#region Code to test the JSON parsing mechanisms
//Should return the `User` value inside of testList
router.get(`/test`, (req, res) => {
testList = {
User: 'David'
};
res.json({
'error': false,
'user': testList.User
});
});
//Should return the data it was sent
router.post(`/test`, (req,res) => {
console.log(req.body);
res.json({
'error': false,
'data': req.body
});
});
//#endregion
module.exports = router; | 674efc372fe52286ac71727d0056010cf4b68934 | [
"Markdown",
"JavaScript",
"Dockerfile"
] | 4 | Markdown | CallumGilly/race-time-keeper-version-2 | 3917ccb85c5c049e3b4317a29800bcd103ed9cc4 | d301c89ebe426aced530c75a55fef3d4f8fe159e |
refs/heads/master | <repo_name>djtrueway/OC7<file_sep>/js/restaurant.js
class Restaurant {
constructor(data){
window[data.restaurantName] = this;
this.DOM = document.createElement('li');
this.DOMstar = document.createElement("stars");
this.DOMcomments = document.createElement("comments");
this.name = data.restaurantName;
this.lat = data.lat;
this.long = data.long;
this.comments = dataManager.getEvaluation(this.name);
if(dataManager.getEvaluation(this.name)){
let score = 0;
for (let index = 0; index < this.comments.length; index++) {
score += this.comments[index].stars;
console.log("--- avering "+ this.comments[index].stars)
}
this.avering = score / this.comments.length;
}else{
this.comments = [];
this.avering = data.ratings[0].stars
console.log('1 ___ data.rating '+ data.ratings[0].stars)
}
// give each restaurant a unique id
let method = data.restaurantName
method = method.split(' ').join('_')
method = method.split('&').join('_')
method = method.split("'").join('_')
method = method.split("-").join('_')
this.id = method
this.viewDetails = false;
this.addMarker();
this.initialRender();
SimpleStarRating(this.DOMstar);
this.DOMstar.addEventListener('rate', function (e) {
console.log(e);
if(this.userRating !== null) return;
console.log("wxcwcwxc", e.detail)
this.starClick(e)
//this.addComment(e)
this.DOMstar.innerHTML += this.renderAddComment();
}.bind(this));
this.userRating = null;
window[this.id] = this;
console.log(this.id)
}
// filter restaurant to diplay in the dom
initialRender(){
if(this.avering >= 4){
this.DOM.onclick = this.showHideRatings.bind(this);
this.DOM.className = 'list-group-item';
document.getElementsByTagName("ul")[0].appendChild(this.DOM);
this.DOM.innerHTML = this.name;
this.DOMstar.className="rating";
// this.DOMstar.setAttribute("data-stars", 15);
this.DOMstar.setAttribute("data-default-rating", this.avering);
this.DOMstar.onclick = this.starClick;
this.DOM.appendChild(this.DOMstar);
this.DOM.appendChild(this.DOMcomments);
console.log('___ data.rating '+this.avering)
}
}
starClick(e){
this.stars = e.detail
return
}
// make start with '*'
makeStars(qty){
let stars = "";
for (let i=0; i<qty; i++) stars +="*";
return stars;
}
renderComment() {
let content = "";
if (this.viewDetails ){
content +=`
<ul>${this.renderRatings()}</ul>
`;
}
this.DOMcomments.innerHTML = content;
}
// add comment for each restaurant
addComment(){
const stars = this.stars
const comment = document.querySelector(`#${this.id}Comment`).value;
if(comment === ''){
alert('SVP AJOUTE UN COMMENNTAIRE')
return
}
let rates = {
"stars": stars,
"comment": comment
}
console.log("----",this.comments);
this.comments.push(rates)
dataManager.addComment(this.name, rates);
this.renderComment()
document.querySelector(`#${this.id}Comment`).value = '';
this.stars = '';
return ;
}
// form for add comment
renderAddComment(){
return `
<div onclick="event.stopPropagation();">
<input name="commentaires" class='form-control form-control-sm' id='${this.id}Comment' placeholder="ajouter un commentaire">
</div>
<button class='btn btn-sm btn-primary mt-1' onclick="event.stopPropagation();window.${this.id}.addComment() ">ajoute un commentaire</button>
`;
}
renderRatings(){
let content = "";
for (let i=0; i< this.comments.length; i++){
content += `<li>${this.makeStars(this.comments[i].stars)} ${this.comments[i].comment}</li>`;
}
return content;
}
showHideRatings(){
this.updateState("viewDetails", !this.viewDetails);
}
updateState(key, value){
this[key] = value;
this.renderComment();
}
// add restaurant to the map
addMarker ( ){
var marker = L.marker([this.lat, this.long]).addTo(mymap).on('click', (e) =>{
// alert('make ajax request to the api')
window.addGoogleStreetView(this.lat, this.long)
});
let msg = '<b>'+ this.name + '<b>'+'<br><br>'
marker.bindPopup(msg);
}
} | d48481ea34e11030c6978150a4bcacdc3445e435 | [
"JavaScript"
] | 1 | JavaScript | djtrueway/OC7 | 92219ed6e7dfb016a42efcf3125eb16241f366dd | 588503ed54ae56948e40b3db2f8b9da4dc886836 |
refs/heads/master | <file_sep>import time
import mss
from PIL import Image
start = time.time()
monitor = {'top': 0, 'left': 0, 'width': 1920, 'height': 1080}
sct_img = mss.mss().grab(monitor)
img = Image.frombytes('RGB', sct_img.size, sct_img.rgb)
end = time.time()
print(end-start)
<file_sep>import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import mss
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
import cv2
sys.path.append("..")
from utils import label_map_util
from utils import visualization_utils as vis_util
MODEL_NAME = 'faster_inference_graph'
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('data', 'object-detection.pbtxt')
NUM_CLASSES = 3
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape(
(im_height, im_width, 3)).astype(np.uint8)
with detection_graph.as_default():
with tf.Session(graph=detection_graph) as sess:
while True:
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
monitor = {'top': 0, 'left': 0, 'width': 960, 'height': 540}
pix = mss.mss().grab(monitor)
image = Image.frombytes('RGB', pix.size, pix.rgb)
#image = Image.open(imagename)
image_np = load_image_into_numpy_array(image)
image_np_expanded = np.expand_dims(image_np, axis=0)
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
# Each box represents a part of the image where a particular object was detected.
boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represent how level of confidence for each of the objects.
# Score is shown on the result image, together with the class label.
scores = detection_graph.get_tensor_by_name('detection_scores:0')
classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')
# Actual detection.
(boxes, scores, classes, num_detections) = sess.run(
[boxes, scores, classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
width = 960
height = 540
ymin = boxes[0][0][0]*height
xmin = boxes[0][0][1]*width
ymax = boxes[0][0][2]*height
xmax = boxes[0][0][3]*width
print(ymin)
print(xmin)
print(ymax)
print(xmax)
objects = []
for index, value in enumerate(classes[0]):
object_dict = {}
if scores[0, index] > 0.5:
object_dict[(category_index.get(value)).get('name').encode('utf8')] = \
scores[0, index]
objects.append(object_dict)
print(objects)
# Visualization of the results of a detection.
#vis_util.visualize_boxes_and_labels_on_image_array(
# image_np,
# np.squeeze(boxes),
# np.squeeze(classes).astype(np.int32),
# np.squeeze(scores),
# category_index,
# use_normalized_coordinates=True,
# line_thickness=8)
# cv2.imshow('object detection', cv2.resize(image_np, (400,300)))
# if cv2.waitKey(25) & 0xFF == ord('q'):
# cv2.destroyAllWindows()
# break
| 17dd8b54183a102a8e0409db18defb4ab30ab763 | [
"Python"
] | 2 | Python | Possums/dinosaur | 233efc5e85347c40dd21dc2fc12ade2da1c006b6 | 64b3e6bf340d36aff187383c4c5eba56e1dccebc |
HEAD | <file_sep><?php
/**
* Part of the Auth Module
*
* @package FuelPHP-KickStart
* @version 1.0
* @author <NAME> <<EMAIL>>
* @license MIT License
* @copyright 2012 <NAME>
* @link http://danielberry,me
*/
/**
* Custom Routing for the Auth Module
*
* @package Auth
*/
return array(
'auth/login' => 'auth/login', // the default login page
'auth/logout' => 'auth/logout',
'auth/landing' => 'welcome/index',
'auth/activate' => 'auth/activate',
'auth/register' => 'auth/register',
'auth/password' => '<PASSWORD>',
'auth/password/confirm' => '/auth/password/confirm',
);
/** end of auth/config/routes.php **/
<file_sep><?php
/**
* Part of the Auth Module
*
* @package FuelPHP-KickStart
* @version 1.0
* @author <NAME> <<EMAIL>>
* @license MIT License
* @copyright 2012 <NAME>
* @link http://danielberry,me
*/
namespace Auth;
/**
* Module Controller for Auth Module
*
* @package Auth
*/
class Controller_Module extends \Controller_Kickstart_Common
{
/**
* @var string require_login
* always assume we need a valid login.
*/
public $require_login = false;
/**
* Setup the Controller
*/
public function before()
{
// load the user module language file
\Lang::load('auth', true);
// let's load user module config!
\Config::load('auth', true);
parent::before();
}
}<file_sep><?php
/**
* Part of the Auth Module
*
* @package FuelPHP-KickStart
* @version 1.0
* @author <NAME> <<EMAIL>>
* @license MIT License
* @copyright 2012 <NAME>
* @link http://danielberry,me
*/
/**
* EN Lang File for the Auth Module
*
* @package Auth
*/
return array(
'fields' => array(
'username_or_email' => 'Email Address',
'password' => '<PASSWORD>',
'retype_password' => 'Retype Password',
'first_name' => 'First Name',
'last_name' => 'Last Name',
'email' => 'Email Address',
'username' => 'Username',
'button_register' => 'Register',
'button_reset_password' => '<PASSWORD> Password'
),
'messages' => array(
'login_required' => '<h4 class="alert-header">Oops, Login Required!</h4> <p>Please login to view the requested page.</p>',
),
'login' => array(
'page_title' => 'Please Login',
'messages' => array(
'failed' => '<h4 class="alert-heading">Invalid Username and/or Password</h4> <p>Oops, the username and/or password you entered is invalid. Please try again.</p>',
)
),
'logout' => array(
'messages' => array(
'success' => '<h4 class="alert-heading">Successfully Logged Out</h4> <p>You can now close this page or login below.</p>',
)
),
'register' => array(
'page_title' => 'Create Your Account!',
'messages' => array(
'success' => '<h4 class="alert-heading">Account Created!</h4> <p>You have successfully registered your account. Please check your email for instructions on how to activate.</p>',
'failed' => 'Oops, an error occured while creating your account.'
)
),
'activate' => array(
'messages' => array(
'success' => '<h4 class="alert-heading">Email Address Verified!</h4> <p> Please login below.</p>',
'failed' => '<h4>Oops, Something Went Wrong</h4> <p>Please check your email address to make sure you followed the right activation url.</p>',
)
),
'reset_password' => array(
'page_title' => 'Reset Your Password',
'messages' => array(
'success' => '<h4 class="alert-heading">Confirmation Email Has Been Sent</h4> <p>Please check your email for instructions how how to confirm your new password.</p>',
'failed' => '<h4>Oops, Something Went Wrong</h4> <p>We were unable to confirm your account. </p>',
)
),
'confirm_reset_password' => array(
'messages' => array(
'success' => '<h4 class="alert-heading">Your Password Has Been Reset</h4> <p>We have successfully confirmed your account and reset your password. Please login below using your email address and new password.</p>',
'failed' => '<h4>Oops, Something Went Wrong</h4> <p>We were unable to confirm your account. </p>',
)
),
);<file_sep><div class="row">
<div class="span8 offset2">
<div class="page-header">
<h1>Forgot Your Password?</h1>
<p>Enter your email address and create a new password below. Once your email has been verified, we will send you an email with instructions on how to activate your new password.</p>
</div>
<!-- sysmessage if any. !-->
<?php echo Message::render(); ?>
<form name="form-reset-password" id="form-reset-password" method="post" class="form-horizontal" action="">
<div class="control-group <?php echo !empty($errors['email']) ? 'error' : ''; ?>">
<label class="control-label" for="email"><?php echo \Lang::get('auth.fields.email'); ?></label>
<div class="controls">
<input type="email" class="input-xlarge" id="email" name="email" value="<?php echo \Input::post('email', ''); ?>">
</div>
</div>
<div class="control-group <?php echo !empty($errors['password']) ? 'error' : ''; ?>">
<label class="control-label" for="password"><?php echo \Lang::get('auth.fields.password'); ?></label>
<div class="controls">
<input type="<PASSWORD>" class="input-xlarge" id="password" name="password" value="<?php echo \Input::post('password', ''); ?>">
</div>
</div>
<div class="control-group <?php echo !empty($errors['retype_password']) ? 'errors' : ''; ?> ">
<label class="control-label" for="retype_password"><?php echo \Lang::get('auth.fields.retype_password'); ?></label>
<div class="controls">
<input type="password" class="input-xlarge" id="retype_password" name="retype_password" value="<?php echo \Input::post('retype_password', ''); ?>">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-large gray"><?php echo \Lang::get('auth.fields.button_reset_password'); ?></button>
<span class="pull-right form-action-link-align">
<i class="icon-user"></i> Don't Have an Account? <a href="<?php echo Router::get('auth/register'); ?>">Sign Up!</a> <br />
<i class="icon-exclamation-sign"></i> Remembered Your Password? <a href="<?php echo \Router::get('auth/login'); ?>>Login!</a>
</span>
</div>
</form>
</div>
</div><file_sep><?php
/**
* Common Controller for the KickStart System
*
* @package FuelPHP-KickStart
* @version 1.0
* @author <NAME> <<EMAIL>>
* @license MIT License
* @copyright 2012 <NAME>
* @link http://danielberry,me
*/
class Controller_Kickstart_Common extends Controller_Template
{
protected $view = '';
protected $data = array();
/**
* @var string $require_login
* always assume we need a valid login.
*/
public $require_login = true;
/**
* @var string $template
*/
public $template = 'templates/default';
//-------------------------------------------------------------------------------------
/**
* Custom Constructor for Kickstart
* @param Request $request
* @param Response $response
*/
public function __construct(Request $request, Response $response)
{
parent::__construct($request, $response);
// let's rock-n-roll with Kickstart!
Kickstart::init();
}
//-------------------------------------------------------------------------------------
public function router($method, $args)
{
/**
* Check for Required Login
*
* redirect to login if login is required and no current user exists
*
* @todo add lang for login required message.
*/
if ($this->require_login === true and !Sentry::check()) {
/**
* Last Page Viewed
* we will use this to send the user back to this page once
* they have logged in.
*/
Session::set('last_viewed', Uri::create());
/**
* set a message letting the user know they must be logged in
*/
Message::warning(__('auth.messages.login_required'));
/**
* redirect the user to the login page
* uses Response & Router
*/
Response::redirect(Config::get('kickstart.uri.login_page'));
}
// call the called method
return call_user_func_array(array($this, 'action_' . $method), $args);
}
//-------------------------------------------------------------------------------------
/**
* @param null $response
* @return mixed
*/
public function after($response = null)
{
/*
* if no view has been assigned, let's create one!
* This takes the class name & method and assigns a view based on that.
*/
if (empty($this->view))
{
// create the view
if (empty($module))
{
$this->view = Kickstart::$current_controller.'/'.Kickstart::$current_action;
}
else
{
$this->view = Kickstart::$current_module.'/'.Kickstart::$current_controller.'/'.Kickstart::$current_action;
}
}
if (empty($this->template->content))
{
$this->template->content = View::forge($this->view, $this->data);
}
return parent::after($response);
}
}
/** end of app/classes/controller/kickstart/common.php **/<file_sep><?php
/**
* Custom Validations
*
* @package FuelPHP-KickStart
* @version 1.0
* @author <NAME> <<EMAIL>>
* @license MIT License
* @copyright 2012 <NAME>
* @link http://danielberry,me
*/
class Kickstart_Validation
{
/**
* Check to see if a value is unique
*
* @static
* @param $val
* @param $options
* @return bool
*/
public static function _validation_unique($val, $options)
{
list($table, $field) = explode('.', $options);
$result = DB::select("LOWER (\"$field\")")
->where($field, '=', Str::lower($val))
->from($table)->execute();
return ! ($result->count() > 0);
}
/**
* Valdiate Username
*
* used to verify that a username contains valid characters.
*
* @param $val
* @return bool
*/
public static function _validation_username($val)
{
if (preg_match('/^[a-z\d_]{5,20}$/i', $val))
{
return true;
}
return false;
}
/**
* Validate Password Format
*
* makes sure a user submitted password meets the requirements
*
* @param string $val user entered password to validate
* @param array $options minimum & maximum values
* @return bool returns true or false
*/
public static function _validation_password($val, $min_length = 8, $max_length = 18)
{
if (preg_match('/^[.a-zA-Z_0-9-!@#$%\^&*()]{'.$min_length.','.$min_length.'}$/', $val))
{
return true;
}
return false;
}
public static function _validation_name($val)
{
if (preg_match("#^[-A-Za-z' ]*$#", $val))
{
return true;
}
return false;
}
}
/* end of classes/kickstart/validation.php */
<file_sep><?php
/**
* Task to setup directory permissions
*
* @package FuelPHP-KickStart
* @version 1.0
* @author <NAME> <<EMAIL>>
* @license MIT License
* @copyright 2012 <NAME>
* @link http://danielberry,me
*/
namespace Fuel\Tasks;
class Writable
{
public function run()
{
chmod(APPPATH.'/logs', 0777);
chmod(APPPATH.'/cache', 0777);
chmod(APPPATH.'/config', 0777);
chmod(APPPATH.'/config/crypt.php', 0777);
}
}<file_sep><?php
return array(
'site' => array(
/**
* What is the name of your site?
*/
'name' => 'FuelPHP Kickstart',
// meta data information
'meta' => array(
'keywords' => '',
'description' => '',
),
),
'uri' => array(
'login_page' => 'auth/login',
),
);
<file_sep><?php
/**
* Part of the Profile Module
*
* @package FuelPHP-KickStart
* @version 1.0
* @author <NAME> <<EMAIL>>
* @license MIT License
* @copyright 2012 <NAME>
* @link http://danielberry,me
*/
namespace Profile;
/**
* User's Home Screen
*
* @package Profile
*/
class Controller_Home extends Controller_Module
{
public function action_index()
{
// set the page title
$this->template->set('page_title', __('profile.home.page_title'));
// set custom content since this is not in the standard module/controller/format
$this->template->content = \View::forge('profile/home')->set('user', \Kickstart::user());
}
}
/** end of modules/profile/classes/controller/home.php **/
<file_sep><p style="font-size: 18px; font-weight: bold;">
Hi <?php echo $first_name; ?>, <br/>
You need to activate your <?php echo \Config::get('kickstart.site.name'); ?> account before continuing. Please click on or paste the following URI to continue.
</p>
<p> <?php echo $activation_uri; ?></p>
<p style="font-size: 14px; font-weight: bold;">Login Details:</p>
<p>
<b>Login Url:</b><?php echo $login_uri; ?> <br/>
<b>Username:</b> <?php echo $username; ?> <br/>
</p>
<p>
Sincerely, <br />
The <?php echo \Config::get('kickstart.site.name'); ?> Team
</p><file_sep><?php
/**
* Part of the Auth Module
*
* @package FuelPHP-KickStart
* @version 1.0
* @author <NAME> <<EMAIL>>
* @license MIT License
* @copyright 2012 <NAME>
* @link http://danielberry,me
*/
/**
* Auth Module Config
*
* @package Auth
*/
return array(
/**
* Where to redirect the user on a successful login
*/
'default_landing' => 'welcome/index',
'register' => array(
'email_from_address' => '<EMAIL>',
'email_from_name' => \Config::get('site.title'),
'email_subject' => 'Your New '.\Config::get('site.title').' Account.',
),
'reset_password' => array(
'email_from_address' => '<EMAIL>',
'email_from_name' => \Config::get('site.title'),
'email_subject' => 'Reset Your '.\Config::get('site.title').' Passwrd.',
)
);<file_sep><?php
/**
* Part of the Auth Module
*
* @package FuelPHP-KickStart
* @version 1.0
* @author <NAME> <<EMAIL>>
* @license MIT License
* @copyright 2012 <NAME>
* @link http://danielberry,me
*/
namespace Auth;
/**
* Activate the User's Account
*
* @package Auth
*/
class Controller_Activate extends Controller_Module
{
/**
* Activate a User
*
* We are using the Sentry Auth package for FuelPHP. The user is sent
* an email containing a link that had the user hash in it. This user
* hash is validated against the db to verify the user's email address.
*
* No view is required. Fail & Success are both passed to back to the
* Login view with the appropriate message.
*
* @param $hash_login
* @param $hash_token
*/
public function action_index($hash_login, $hash_token)
{
// try to log a user in
try
{
// log the user in
$activate_user = \Sentry::activate_user($hash_login, $hash_token);
if ($activate_user)
{
// the user is now activated
\Message::success(__('auth.activate.messages.success'));
}
else
{
// the user is now activated
\Message::error(__('auth.activate.messages.failed'));
}
}
catch (\SentryAuthException $e)
{
// issue activating the user
// store/set and display caught exceptions such as a suspended user with limit attempts feature.
\Message::error($e->getMessage());
}
// redirect to the login page as this view doesn't exist.
\Response::redirect(\Router::get('auth/login'));
}
}<file_sep><div class="alert alert-block alert-error fade in <?php echo !empty($options['sticky']) ? $options['sticky'] : ''; ?>}">
<?php if (isset($options['closeable'])) { ?><a class="close" data-dismiss="alert" href="#">×</a> <?php } ?>
<?php echo $messages; ?>
</div><file_sep><?php
return array(
'home' => array(
'page_title' => 'Profile Home',
)
);<file_sep><?php
/**
* Part of the Auth Module
*
* @package FuelPHP-KickStart
* @version 1.0
* @author <NAME> <<EMAIL>>
* @license MIT License
* @copyright 2012 <NAME>
* @link http://danielberry,me
*/
namespace Auth;
/**
* Request password be reset
*
* @package Auth
*/
class Controller_Password extends Controller_Module
{
/**
* Reset the User's Password
*/
public function action_index()
{
if (\Input::method() === 'POST')
{
// setup some boring validation.
$val = \Validation::forge();
$val->add_callable('Kickstart_Validation');
$val->add('email', __('auth.fields.email'))
->add_rule('trim')
->add_rule('required')
->add_rule('valid_email');
$val->add('password', __('auth.fields.password'))
->add_rule('trim')
->add_rule('required')
->add_rule('min_length', 8)
->add_rule('max_length', 18);
$val->add('retype_password', __('auth.fields.retype_password'))
->add_rule('trim')
->add_rule('required')
->add_rule('match_field', 'password');
if ($val->run())
{
try
{
$reset = \Sentry::reset_password(\Input::post('email'), \Input::post('password'));
if ($reset)
{
// load the email package so we can use it.
\Package::load('email');
$view = \View::forge('auth/email/reset_password')
->set('email', $reset['email'])
->set('reset_uri', \Router::get('auth/password/confirm').'/'.$reset['link'], false);
$email = \Email::forge()
->from(\Config::get('auth.reset_password.email_from_address'), \Config::get('auth.reset_password.email_from_name'))
->to($reset['email'], $reset['email'])
->subject(\Config::get('auth.reset_password.email_subject'))
->html_body($view);
// try to send the new email
try
{
if ($email->send())
{
// yay, the email was successfully sent, so let's tell the user and redirect to login screen.
\Message::success(__('auth.reset_password.messages.success'));
\Response::redirect(\Router::get('auth/login'));
}
}
catch (\EmailValidationFailedException $e)
{
\Message::error($e->getMessage());
}
catch (\EmailSendingFailedException $e)
{
\Message::error($e->getMessage());
}
}
else
{
// mostly likely scenario is the email address was not registered.
\Message::error(__('auth.reset_password.messages.failed'));
}
}
catch (\SentryAuthException $e)
{
// issue resetting the password
// store/set and display caught exceptions such as a user not existing or user is disabled
\Message::error($e->getMessage());
}
}
else
{
// something went wrong - shouldn't really happen
\Message::error($val->show_errors());
$this->data['errors'] = $val->error();
}
}
// set the page title
$this->template->set('page_title', __('auth.reset_password.page_title'));
// set custom content since this is not in the standard module/controller/format
$this->template->content = \View::forge('auth/reset_password', $this->data);
}
/**
* Confirm Password Reset
*
* This takes the login hash that was sent to the user from the url and
* compares it against the database. If it matched, than the user's password
* is reset to the password they selected when they initiated the request.
*
* @param $hash_login
* @param $hash_token
*/
public function action_confirm($hash_login, $hash_token)
{
if (!empty($hash_login) and !empty($hash_token))
{
try
{
// confirm password reset
$confirm_reset = \Sentry::reset_password_confirm($hash_login, $hash_token, true);
if ($confirm_reset)
{
// user was confirmed, so set success message and redirect to login
\Message::success(__('auth.confirm_reset_password.messages.success'));
\Response::redirect(\Router::get('auth/login'));
}
else
{
// the user was not confirmed so set error and redirect to reset password page.
\Message::error(__('auth.confirm_reset_password.messages.failed'));
\Response::redirect(\Router::get('auth/reset_password'));
}
}
catch (\SentryAuthException $e)
{
// issue activating the user
// store/set and display caught exceptions such as a user not existing or user is disabled
\Message::error($e->getMessage());
}
}
// set the page title
$this->template->set('page_title', __('auth.reset_password.page_title'));
// set custom content since this is not in the standard module/controller/format
$this->template->content = \View::forge('auth/reset_password', $this->data);
}
}
/** end logout.php **/
<file_sep><?php
/**
* Extending the FuelPHP Response Class
*
* We need to be able to carry our flash messages over after a redirect. So we're
* going to slightly modify FuelPHP's standard Redirect to check for messages. If
* message(s) exist, that we will call Message::to_flash() to store the messages.
*
* @package FuelPHP-KickStart
* @version 1.0
* @author <NAME> <<EMAIL>>
* @license MIT License
* @copyright 2012 <NAME>
* @link http://danielberry,me
*/
class Response extends Fuel\Core\Response
{
/**
* @static
* @param string $url
* @param string $method
* @param int $code
* @return mixed
*/
public static function redirect($url = '', $method = 'location', $code = 302)
{
if (Message::count() >= 1)
{
// save outstanding messages to flash
Message::to_flash();
}
$response = new static;
$response->set_status($code);
if (strpos($url, '://') === false)
{
$url = $url !== '' ? \Uri::create($url) : \Uri::base();
}
if ($method == 'location')
{
$response->set_header('Location', $url);
}
elseif ($method == 'refresh')
{
$response->set_header('Refresh', '0;url='.$url);
}
else
{
return;
}
\Event::shutdown();
$response->send(true);
exit;
}
}
/** end of response.php **/
<file_sep><div class="row">
<div class="span8 offset2">
<div class="page-header">
<h1>Please Login</h1>
</div>
<!-- sysmessage if any. !-->
<?php echo Message::render(); ?>
<form name="form-register" id="form-register" method="post" class="form-horizontal" action="">
<div class="control-group <?php isset($errors['username_or_email']) ? 'error' : '' ?>">
<label class="control-label" for="username_or_email"><?php echo Lang::get('auth.fields.username_or_email'); ?></label>
<div class="controls">
<input type="text" class="input-xlarge" id="username_or_email" name="username_or_email" value="<?php echo Input::post('username_or_email', ''); ?>">
</div>
</div>
<div class="control-group <?php isset($errors['password']) ? 'error' : '' ?>">
<label class="control-label" for="password"><?php echo Lang::get('auth.fields.password'); ?></label>
<div class="controls">
<input type="<PASSWORD>" class="input-xlarge" id="password" name="<PASSWORD>">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" id="rememberme" value="true">
Remember me on this computer
</label>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-large gray">Login</button>
<span class="pull-right form-action-link-align">
<i class="icon-question-sign"></i> Don't Have an Account? <a href="<?php echo Router::get('auth/register'); ?>">Sign Up!</a><br />
<i class="icon-lock"></i> Forgot Your Password? <a href="<?php echo Router::get('auth/password'); ?>">Reset Your Password</a>
</span>
</div>
</form>
</div>
</div><file_sep><?php
/**
* Part of the Auth Module
*
* @package FuelPHP-KickStart
* @version 1.0
* @author <NAME> <<EMAIL>>
* @license MIT License
* @copyright 2012 <NAME>
* @link http://danielberry,me
*/
namespace Auth;
/**
* Register a New User's Account
*
* @package Auth
*/
class Controller_Register extends Controller_Module
{
/**
* Register a New User
*/
public function action_index()
{
if (\Input::method() === 'POST')
{
$val = \Validation::forge();
$val->add_callable('Kickstart_Validation');
$val->add('metadata.first_name', __('auth.fields.first_name'))
->add_rule('trim')
->add_rule('required')
->add_rule('name');
$val->add('metadata.last_name', __('auth.fields.last_name'))
->add_rule('trim')
->add_rule('required')
->add_rule('name');
$val->add('email', __('auth.fields.email'))
->add_rule('trim')
->add_rule('required')
->add_rule('valid_email')
->add_rule('unique', 'users.email');
$val->add('username', __('auth.fields.username'))
->add_rule('trim')
->add_rule('required')
->add_rule('min_length', 6)
->add_rule('unique', 'users.username')
->add_rule('username');
$val->add('password', __('auth.fields.password'))
->add_rule('trim')
->add_rule('required')
->add_rule('min_length', 8)
->add_rule('max_length', 18);
$val->add('password_retype', __('auth.fields.retype_password'))
->add_rule('trim')
->add_rule('required')
->add_rule('match_field', 'password');
if ($val->run())
{
try
{
// create the user - no activation required
$vars = array(
'username' => \Input::post('username'),
'email' => \Input::post('email'),
'password' => \Input::post('<PASSWORD>'),
'metadata' => array(
'first_name' => \Input::post('metadata.first_name'),
'last_name' => \Input::post('metadata.last_name'),
)
);
$user = \Sentry::user()->register($vars, false);
if ($user)
{
// the user was created - send email notifying user account was created
// email $link to $email
\Package::load('email');
$view = \View::forge('auth/email/activate')
->set('first_name', \Input::post('metadata.first_name'))
->set('username', \Input::post('username'))
->set('password', \Input::post('<PASSWORD>'))
->set('activation_uri', \Router::get('auth/activate').'/index/'.$user['hash'])
->set('login_uri', \Router::get('auth/login'));
$email = \Email::forge()
->from(\Config::get('auth.register.email_from_address'), \Config::get('auth.register.email_from_name'))
->to(\Input::post('email'), \Input::post('metadata.first_name').\Input::post('metadata.last_name'))
->subject(\Config::get('auth.register.email_subject'))
->html_body($view);
try
{
if ($email->send())
{
\Message::success(__('auth.register.messages.success'));
\Response::redirect(\Router::get('auth/login'));
}
}
catch (\EmailValidationFailedException $e)
{
\Message::error($e->getMessage());
}
catch (EmailSendingFailedException $e)
{
\Message::error($e->getMessage());
}
}
else
{
// something went wrong - shouldn't really happen
\Message::error(__('auth.register.failed'));
}
}
catch (\SentryUserException $e)
{
\Message::error($e->getMessage());
}
}
else
{
// something went wrong - shouldn't really happen
\Message::error($val->show_errors());
$this->data['errors'] = $val->error();
}
}
// set the page title
$this->template->set('page_title', __('auth.register.page_title'));
// set custom content since this is not in the standard module/controller/format
$this->template->content = \View::forge('auth/register', $this->data);
}
}<file_sep><?php
/**
* Task to setup directory permissions
*
* @package FuelPHP-KickStart
* @version 1.0
* @author <NAME> <<EMAIL>>
* @license MIT License
* @copyright 2012 <NAME>
* @link http://danielberry,me
*/
namespace Fuel\Tasks;
class Git
{
public function run()
{
// add files to assume unchanged in git
exec('git update-index --assume-unchanged '.APPPATH.'/config/development/db.php');
exec('git update-index --assume-unchanged '.APPPATH.'/config/migrations.php');
}
}<file_sep><?php
/**
* Part of the Auth Module
*
* @package FuelPHP-KickStart
* @version 1.0
* @author <NAME> <<EMAIL>>
* @license MIT License
* @copyright 2012 <NAME>
* @link http://danielberry,me
*/
namespace Auth;
/**
* Let's Get the User Logged In!
*
* @package Auth
*/
class Controller_Login extends Controller_Module
{
public function action_index()
{
if (\Input::method() === 'POST')
{
// add validation
$val = \Validation::forge();
//$val->set_message('valid_email', 'Enter a valid email address');
$val->add('username_or_email', __('auth.fields.username_or_email'))
->add_rule('trim')
->add_rule('required')
->add_rule('valid_email');
$val->add('password', __('auth.fields.password'))
->add_rule('trim')
->add_rule('required');
if ($val->run())
{
// try to log a user in
try
{
// log the user in
$valid_login = \Sentry::login(\Input::post('username_or_email'), \Input::post('password'), \Input::post('rememberme'));
if ($valid_login)
{
\Response::redirect(\Config::get('auth.default_landing'));
}
else
{
\Message::error(__('auth.login.messages.failed'));
}
}
catch (\SentryAuthException $e)
{
// issue logging in via Sentry - lets catch the sentry error thrown
// store/set and display caught exceptions such as a suspended user with limit attempts feature.
\Message::error($e->getMessage());
}
}
else
{
// let's show an error message
\Message::error($val->show_errors());
// send back the errors
$this->data['errors'] = $val->errors();
}
}
// set the page title
$this->template->set('page_title', __('auth.login.page_title'));
// set custom content since this is not in the standard module/controller/format
$this->template->content = \View::forge('auth/login', $this->data);
}
}
/** end of auth/classes,php **/
<file_sep><?php
/**
* Part of the Sentry package for FuelPHP.
*
* @package Sentry
* @version 2.0
* @author Cartalyst LLC
* @license MIT License
* @copyright 2011 - 2012 Cartalyst LLC
* @link http://cartalyst.com
*/
return array(
/**
* Database instance to use
* Leave this null to use the default 'active' db instance
* To use any other instance, set this to any instance that's defined in APPPATH/config/db.php
*/
'db_instance' => null,
/*
* Table Names
*/
'table' => array(
'users' => 'users',
'groups' => 'groups',
'users_groups' => 'users_groups',
'users_metadata' => 'users_metadata',
'users_suspended' => 'users_suspended',
),
/*
* Session keys
*/
'session' => array(
'user' => 'sentry_user',
'provider' => 'sentry_provider',
),
/*
* Default Authorization Column - username or email
*/
'login_column' => 'email',
/*
* Remember Me settings
*/
'remember_me' => array(
/**
* Cookie name credentials are stored in
*/
'cookie_name' => 'sentry_rm',
/**
* How long the cookie should last. (seconds)
*/
'expire' => 1209600, // 2 weeks
),
/**
* Limit Number of Failed Attempts
* Suspends a login/ip combo after a # of failed attempts for a set amount of time
*/
'limit' => array(
/**
* enable limit - true/false
*/
'enabled' => true,
/**
* number of attempts before suspensions
*/
'attempts' => 5,
/**
* suspension length - minutes
*/
'time' => 15,
),
/**
* Password Hashing
* Sets hashing strategies for passwords
* Note: you may have to adjust all password related fields in the database depending on the password hash length
*/
'hash' => array(
/**
* Strategy to use
* look into classes/sentry/hash/strategy for available strategies ( or make/import your own )
* Must be in strategies below
*/
'strategy' => 'BCrypt',
'convert' => array(
'enabled' => false,
'from' => '',
),
/**
* Available Strategies for your app
* This is used to set settings for conversion, like switching from SimpleAuth hashing to Sha256 or vice versa
*/
'strategies' => array(
/**
* config options needed for hashing
* example:
* 'Strategy' => array(); // additional options needed for password hashing in your driver like a configurable salt
*/
'Sentry' => array(),
'SimpleAuth' => array(
'salt' => '',
),
'BCrypt' => array(
'strength' => 4,
// if you want to use a bacrypt hash with an algorithm
'hashing_algorithm' => null,
),
),
),
'permissions' => array(
/**
* enable permissions - true or false
*/
'enabled' => true,
/**
* super user - string
* this will be used for the group and rules
* if you change this, you need to make sure you change the
*/
'superuser' => 'superuser',
/**
* setup rules for permissions
* These are resources that will require access permissions.
* Rules are assigned to groups or specific users in the
* format module_controller_method or controller_method
*/
'rules' => array(
/**
* config samples.
*
* // user module admin
* 'user_admin_create',
* 'user_admin_read',
* 'user_admin_update',
* 'user_admin_delete',
* 'user_permissions',
*
* // blog module admin
* 'blog_admin_create',
* 'blog_admin_read',
* 'blog_admin_update',
* 'blog_admin_delete',
*
* // product module admin
* 'product_admin_create',
* 'product_admin_read',
* 'product_admin_update',
* 'product_admin_delete',
*/
)
)
);
<file_sep><?php
/**
* A generic message handler
*
* use the message class to store single or an array of messages. These messages can be any type and are rendered using
* the templates in your custom theme. An $options array is available for you to specify any custom data that you might
* require for your custom theme.
*
* @author Weztec Limited/Berry Media Group
* @license TBD
* @copyright 2012 Weztec Limited/Berry Media Group
* @link http://www.weztec.com / http://www.berrymediagroup.com
* @email <EMAIL> / <EMAIL>
* @package PhoenixCMS
* @version 2.0
* @created 2/25/12 4:18 AM
*
*/
/**
* Custom Exceptions Exceptions
*/
class NoMessageTypeException extends FuelException {}
class NoMessageTextException extends FuelException {}
/**
* Phoenix CMS Message Class
*/
class Message
{
/**
* @var array store the messages
*/
protected static $_messages = array();
/**
* generic function to add a message or an array of messages to the stack
*
* <code>
* Message::add('generic', 'The action was successful', array('closeable' => true, 'notification' => 'classname', 'custom' => 'option');
* Message::add('form_error', $val->show_errors(), array('closeable' => true, 'notification' => 'classname', 'custom' => 'option');
* </code>
*
* @static
* @param null $type
* @param null $body
* @param array $options
* @throws NoMessageTextException|NoMessageTypeException
*/
public static function add($type, $body, $options = array())
{
if (empty($type))
{
throw new NoMessageTypeException('No message type was specified.');
}
elseif (empty($body))
{
throw new NoMessageTextException('No message text was specified.');
}
if (!is_array($body))
{
array_push(static::$_messages, array(
'type' => $type,
'body' => trim($body),
'options' => $options
));
}
else
{
foreach($body as $msg)
{
array_push(static::$_messages, array(
'type' => $type,
'body' => trim($msg),
'options' => $options
));
}
}
}
/**
* Check to see if any messages have been added.
*
* @static
* @param null $type
* @return int
*/
public static function count($type = null)
{
if (empty($type))
{
return (bool) count(static::$_messages);
}
else
{
$count = 0;
foreach (static::$_messages as $msg)
{
if ($msg['type'])
{
$count++;
}
}
return $count;
}
}
/**
* Get the Messages
*
* Get the stored messages. You can include or exclude the message types you want to display.
*
* <code>
* // include only the info messages
* <?php echo Message::render(array('info'));?>
*
* // display all but the info messages.
* <?php echo Message::render(array(), array('info'));?>
* </code>
*
* @static
* @param array $included
* @param array $excluded
* @return array|bool
*/
public static function get($included = array(), $excluded = array())
{
if (empty(static::$_messages))
{
static::$_messages = Session::get_flash('messages');
}
if (static::count())
{
$messages = array();
if (!empty($included))
{
foreach(static::$_messages as $msg)
{
if (in_array($msg['type'], $included))
{
$messages[] = $msg;
}
}
}
else
{
foreach(static::$_messages as $msg)
{
if (!in_array($msg['type'], $excluded))
{
$messages[] = $msg;
}
}
}
return $messages;
}
// nothing to do
return false;
}
/**
* render messages using views
*
* this method will render the message or message array using the theme in your theme/yourtheme/templates/messages
* directory. The theme to use is determined by the message type or in the case of notifications by the template
* set in the options. The options are optional and can be used to specify any additional information that you might
* need for your custom message templates.
*
* <code>
* echo Message::render('success');
* </code>
*
* @static
* @param array $included
* @param array $excluded
* @return bool
*/
public static function render($included = array(), $excluded = array())
{
$messages = static::get($included, $excluded);
if (!empty($messages))
{
foreach($messages as $msg)
{
$data['messages'] = $msg['body'];
$data['options'] = $msg['options'];
if ($msg['type'] === 'notification' and $msg['options']['locked'] === '')
{
echo View::forge('templates/messages/'.$msg['options']['template'], $data, false);
}
else
{
echo View::forge('templates/messages/'.$msg['type'], $data, false);
}
}
}
// there is nothing for us to render
return false;
}
/**
* clear all stored messages
*
* @static
*/
static public function clear()
{
static::$_messages = array();
}
/**
* add a success message
*
* This is an alias for Message::add('success', 'message here');
*
* <code>
* Message::success('Your Update was successful', array('custom' => 'option');
* </code>
*
* @static
* @param null $message
* @param array $options
*/
public static function success($message = null, $options = array())
{
static::add('success', $message, $options);
}
/**
* add an error message
*
* This is an alias for Message::add('error', 'message here');
*
* <code>
* Message::error('Your Update was successful', array('custom' => 'option');
* </code>
*
* @static
* @param null $message
* @param array $options
*/
public static function error($message = null, $options = array())
{
static::add('error', $message, $options);
}
/**
* add an info message
*
* This is an alias for Message::add('info', 'message here');
*
* <code>
* Message::info('Your Update was successful', array('custom' => 'option');
* </code>
*
* @static
* @param null $message
* @param array $options
*/
public static function info($message = null, $options = array())
{
static::add('info', $message, $options);
}
/**
* add a warning message
*
* This is an alias for Message::add('warning', 'message here');
*
* <code>
* Message::warning('Your Update was successful', array('custom' => 'option');
* </code>
*
* @static
* @param null $message
* @param array $options
*/
public static function warning($message = null, $options = array())
{
static::add('warning', $message, $options);
}
/**
* add a notification message
*
* <code>
* Message::notification('Your Update was successful', array('sticky' => 'classname', 'closeable' => true);
* </code>
*
* Notifications can be used to add a sticky message to your page. See the example in the default template
* for more information.
*
* Required Options:
* 'template' => the message template you want to use for the notification.
*
* This is an alias for Message::add('notification', 'message here', array('template' => 'success'));
*
* @static
* @param null $message
* @param array $options
* @example themes/phoenix/templates/messages/notification/
*/
public static function notification($message = null, $options = array())
{
static::add('notification', $message, $options);
}
/**
* saves all pending messages to session flash
*
* @param void
* @param string
* @return void
*/
public static function to_flash()
{
// save any messages in flash
Session::set_flash('messages', static::$_messages);
}
public static function check_messages()
{
// do we have any messages in flash?
$messages = Session::get_flash('messages');
// if there were any stored, add them to the messages array
if ( is_array($messages) )
{
// restore the messages
foreach($messages as $message)
{
static::add($message['type'], $message['body'], $message['options']);
}
}
}
}
/** end of messages.php **/<file_sep><p>
Hello, <br/>
Did you forget your password? We can help you with that! Please visit the following link to confirm your email address and to activate your new password.
</p>
<p><?php echo $reset_uri; ?></p>
<p>
If you did not initiate this process, please feel free to ignore this message.
</p>
<p>
Sincerely, <br />
The <?php echo \Config::get('kickstart.site.name'); ?> Team
</p><file_sep><?php
/**
* Part of the Auth Module
*
* @package FuelPHP-KickStart
* @version 1.0
* @author <NAME> <<EMAIL>>
* @license MIT License
* @copyright 2012 <NAME>
* @link http://danielberry,me
*/
namespace Auth;
/**
* Let's Log the User Out
*
* @package Auth
*/
class Controller_Logout extends Controller_Module
{
public function action_index()
{
if (\Sentry::check())
{
\Sentry::logout();
}
// set message to the user
\Message::info(__('auth.logout.messages.success'));
\Response::redirect(\Router::get('auth/login'));
}
}
/** end logout.php **/
<file_sep><?php
return array(
'required' => ':label is required and must contain a value.',
'min_length' => ':label has to contain at least :param:1 characters.',
'max_length' => ':label may not contain more than :param:1 characters.',
'exact_length' => ':label must contain exactly :param:1 characters.',
'match_value' => ':label must contain the value :param:1.',
'match_pattern' => ':label must match the pattern :param:1.',
'match_field' => ':label must match the field :param:1.',
'valid_email' => ':label must contain a valid email address.',
'valid_emails' => ':label must contain a list of valid email addresses.',
'valid_url' => ':label must contain a valid URL.',
'valid_ip' => ':label must contain a valid IP address.',
'numeric_min' => 'The minimum numeric value of :label must be :param:1',
'numeric_max' => 'The maximum numeric value of :label must be :param:1',
'valid_string' => 'The valid string rule :rule failed for field :label',
/**
* Start of custom fields
*/
'unique' => ':label is already in use.',
'password' => 'Your password must contain letters, numbers and special characters and be between :param:1 and :param:2 characters in length.'
);
<file_sep><?php
/**
* Kick-starts, Kickstart!!!
*
* The Kickstart Class contains var, methods and wrappers that are used throughout the Kickstart Core system.
* Common uses are variables that will be used in several different locations, wrappers to provide a common
* call in case the package changes in the future.
*
*
* @package FuelPHP-KickStart
* @version 1.0
* @author <NAME> <<EMAIL>>
* @license MIT License
* @copyright 2012 <NAME>
* @link http://danielberry,me
*/
class Kickstart
{
/**
* contains the current module in Request::active()->module
* @var string $current_module contains the current module
*/
public static $current_module = '';
/**
* Denamespaced Controller
* @var string $current_module contains the current controller
*/
public static $current_controller = '';
/**
* contains the current action (method)
* @var string $current_module contains the current action
*/
public static $current_action = '';
//-------------------------------------------------------------------------------
/**
* Initialize the Kickstart Class. Everything happens here first.
* * Get the Current Module, Controller and Action
*
* @return void
*/
public static function init()
{
// current module, controller, action
static::get_current_mca();
// get messages
Message::check_messages();
// let's load the kickstart config
Config::load('kickstart', true);
}
//-------------------------------------------------------------------------------
/**
* Wrapper method for the Sentry User Class
*
* This will return the current user object, will return null if there is no current user.
*
* Example Usage:
* <code>
* Kickstart::user()->get('username');
* </code>
*
* @return object the current user object
*/
public static function user()
{
return Sentry::user();
}
//-------------------------------------------------------------------------------
/**
* get the current module/controller/action
*/
/**
* Ge the Current Module, Controller and Action
*
* This uses the Request::active() method provided by FuelPHP to give us the current module, denamespaced controller and action.
*
* * Phoneix::$current_module
* * Phoneix::$current_controller
* * Kickstart::$current_action
*
* @return null
*/
public static function get_current_mca()
{
static::$current_module = Request::active()->module;
static::$current_controller = Str::lower(preg_replace(array('/^Controller_/', '/_/'), array('', '/'), Inflector::denamespace(Request::active()->controller)));
static::$current_action = Request::active()->action;
}
}
/** end of app/classes/kickstart.php **/
<file_sep>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo $page_title; ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<?php echo Asset::css('common.css'); ?>
<style type="text/css">
body {
padding-top:60px;
}
</style>
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">FuelPHP Kickstart</a>
<div class="nav-collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<?php echo $content; ?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<?php
Asset::js(array(
'bootstrap/bootstrap-transition.js',
'bootstrap/bootstrap-alert.js',
'bootstrap/bootstrap-modal.js',
'bootstrap/bootstrap-dropdown.js',
'bootstrap/bootstrap-dropdown.js',
'bootstrap/bootstrap-scrollspy.js',
'bootstrap/bootstrap-tab.js',
'bootstrap/bootstrap-tooltip.js',
'bootstrap/bootstrap-popover.js',
'bootstrap/bootstrap-button.js',
'bootstrap/bootstrap-collapse.js',
'bootstrap/bootstrap-carousel.js',
'bootstrap/bootstrap-typeahead.js',
)
);
?>
</body>
</html>
<file_sep>FuelPHP Bootstrap
-----------------
Preface this by saying that this is not an official FuelPHP application. FuelPHP Bootstrap is a maintained by me and used as a bootstrap for applications that I develop. I also use this as a
learning tool to try out new ideas that pop into my head from time to time.
Hopefully someone else will find this useful. Please do send me any feedback that you have. If you're curious as to why I've done something a certain way or if you have a better way of doing it,
please take a second to create an issue/pull request.
<hr />
What's Included?
================
Initially this will be just a real simple bootstrap. We'll have migrations to get you up and running a complete system with sessions management (mysql backed), authentication using sentry,
a common controller that you can extend to your other controllers, and a few other goodies.
I've chosen to include Twitter Bootstrap for design and assets simply because it is quick and simple. Once installed you can change that to anything you like!
<hr />
Getting Things Going
====================
As of right now this is a manual install. Once the features are better in place, an installer and migrations will be added to automate the install process.
###Clone the KickStart Repo
The first step is to clone the fuelphp-kickstart repo! We have a lot of submodules in here, so we need to make sure we recursively clone those. So from your command line run:
git clone --recursive git://github.com/dberry37388/FuelPHP-Kickstart.git kickstart
What this does is tell git to clone the fuelphp-kickstart repo, and go through all of the submodules and clone them as well and put all of that into a folder named "kickstart".
You can rename the "kickstart" folder to whatever you want that folder to be called.
###Setup Your Database
Sessions, user information and other items will be stored in your database. So before we can setup these tables, we need to add our access information to the database config.
- Open up app/config/development/db.php
- Add your database name, database user and database password. You will see where these items go.
- Save this file and upload if not working on a local server.
###Session Table Task
Now that we've got the database configured and ready to rock, let's use the session table provided by FuelPHP to setup our session table. From the command line run:
php oil r session
You will be presented with a couple of choices. Select "create". Once the table has been created, a success message will appear. If you get database errors, please make sure
your database permissions are set correctly.
###Installing Sentry Table
Sentry comes with some really nifty migrations that will get you up and running quickly. From your command line run:
php oil r migrate --packages=sentry
This will run and update you to the latest version 2.0 of the Sentry Auth Package.
Sentry is an awesome authentication package developed by the fellas at Cartalyst. For more information on Sentry please refer to the Sentry Website at http://sentry.cartalyst.com/
At the time of this writing the 2.0 docs are not available on the Sentry website. New feature usage is provided in the Sentry README.md
<hr />
Available Tasks:
================
I've included the following tasks to make your life a little easier. You may or may not need to run any or all of these tasks. If you are using git, I do recommend running the "git" task
just to make sure certain files are ignored.
###Writable
use this if you are having issues with write permissions on your log, cache or config directories. This will set their permissions to 777.
php oil r writable
###Git
This will do a simple "git update-index --assume-unchanged. This way you can upload to the repo with out these files being added, causing problems down the road and so you don't have
your DB password just hanging around in the web somewhere.
php oil r git
<hr /><file_sep><?php
/**
* The Welcome Controller.
*
* A basic controller example. Has examples of how to set the
* response body and status.
*
* @package app
* @extends Controller
*/
class Controller_Welcome extends Controller_Kickstart_Common
{
var $require_login = false;
/**
* The basic welcome message
*
* @access public
* @return Response
*/
public function action_index()
{
// set a page title
$this->template->set('page_title', 'Welcome to Kickstart!');
$this->template->content = View::forge('welcome/index');
}
/**
* The 404 action for the application.
*
* @access public
* @return Response
*/
public function action_404()
{
return Response::forge(ViewModel::forge('welcome/404'), 404);
}
}
<file_sep><div class="row">
<div class="span8 offset2">
<div class="page-header">
<h1>Let's Get Started <small>Create your <?php echo Config::get('site.title'); ?> Account!</small></h1>
</div>
<!-- sysmessage if any. !-->
<?php echo Message::render(); ?>
<form name="form-create" id="form-create" method="post" class="form-horizontal" action="">
<fieldset>
<legend>Profile Details</legend>
<div class="control-group <?php echo !empty($errors['metadata.first_name']) ? 'error' : ''; ?>">
<label class="control-label" for="first_name"><?php echo Lang::get('auth.fields.first_name'); ?></label>
<div class="controls">
<input type="text" class="input-xlarge" id="first_name" name="metadata[first_name]" value="<?php echo Input::post('metadata.first_name', ''); ?>">
<p class="help-block"><?php echo !empty($errors['metadata.first_name']) ? $errors['metadata.first_name'] : '' ; ?></p>
</div>
</div>
<div class="control-group <?php echo !empty($errors['metadata.last_name']) ? 'error' : ''; ?>">
<label class="control-label" for="last_name"><?php echo Lang::get('auth.fields.last_name'); ?></label>
<div class="controls">
<input type="text" class="input-xlarge" id="last_name" name="metadata[last_name]" value="<?php echo Input::post('metadata.last_name', ''); ?>">
<p class="help-block"><?php echo !empty($errors['metadata.last_name']) ? $errors['metadata.last_name'] : '' ; ?></p>
</div>
</div>
<div class="control-group <?php echo !empty($errors['email']) ? 'error' : ''; ?>">
<label class="control-label" for="email"><?php echo Lang::get('auth.fields.email'); ?></label>
<div class="controls">
<input type="text" class="input-xlarge" id="email" name="email" value="<?php echo Input::post('email', ''); ?>">
<p class="help-block"><?php echo !empty($errors['email']) ? $errors['email'] : '' ; ?></p>
</div>
</div>
</fieldset>
<fieldset>
<legend>Your Login</legend>
<div class="control-group <?php echo !empty($errors['username']) ? 'error' : ''; ?>">
<label class="control-label" for="username"><?php echo Lang::get('auth.fields.username'); ?></label>
<div class="controls">
<input type="text" class="input-xlarge" id="username" name="username" value="<?php echo Input::post('username', ''); ?>">
<p class="help-block"><?php echo !empty($errors['username']) ? $errors['username'] : 'min. 6 characters, no spaces or special characters. Underscores (_) are allowed.' ; ?></p>
</div>
</div>
<div class="control-group <?php echo !empty($errors['password']) ? 'error' : ''; ?>">
<label class="control-label" for="password"><?php echo Lang::get('auth.fields.password'); ?></label>
<div class="controls">
<input type="<PASSWORD>" class="input-xlarge" id="password" name="password" value="<?php echo Input::post('password', ''); ?>">
<p class="help-block"><?php echo !empty($errors['password']) ? $errors['password'] : 'min 8 characters, no spaces, must contain upper and lowercase.' ; ?></p>
</div>
</div>
<div class="control-group <?php echo !empty($errors['password_retype']) ? 'error' : ''; ?>">
<label class="control-label" for="password_retype"><?php echo Lang::get('auth.fields.retype_password'); ?></label>
<div class="controls">
<input type="password" class="input-xlarge" id="password_retype" name="password_retype" value="<?php echo Input::post('password_retype', ''); ?>">
<p class="help-block"><?php echo !empty($errors['password_retype']) ? $errors['password_retype'] : 'Retype the password you entered above.' ; ?></p>
</div>
</div>
</fieldset>
<div class="form-actions">
<button type="submit" class="btn btn-large gray"><?php echo Lang::get('auth.fields.button_register'); ?></button>
<span class="pull-right form-action-link-align">
<i class="icon-info-sign"></i> Already have an account? <a href="<?php echo Uri::create('auth/login'); ?>">Log In</a> <br/>
<i class="icon-lock"></i> Forgot Your Password? <a href="<?php echo Uri::create('auth/password'); ?>">Reset Your Password</a>
</span>
</div>
</form>
</div>
</div>
<file_sep>Welcome Back <?php echo $user->get('metadata.first_name'); | 0260061ff1184df7d1357bb5e345f0953ee83c86 | [
"Markdown",
"PHP"
] | 31 | PHP | huglester/FuelPHP-Kickstart | b0a06556e013e0690590e1f5e415ab55e614e17d | 5e5a427727ee310454b2961f56015bd61d81cef0 |
refs/heads/master | <repo_name>manasdas17/PyArduino<file_sep>/Examples/energy-meter/11.3energy_meter_power.py
#!/usr/bin/python
import serial,time
import struct
import sys
if serial.Serial('COM2',9600).isOpen():
serial.Serial('COM2',9600).close()
s= serial.Serial('COM2',9600)
#s.write("A")
s.flushOutput()
s.flushInput()
time.sleep(2)
a = '00000001'
b = '00000011'
c = '00001111'
d = '01001110'
e = '00000000'
f = '00000010'
g = '10100111'
h = '00001000'
aa = str(chr(int(a,2)))
bb = str(chr(int(b,2)))
cc = str(chr(int(c,2)))
dd = str(chr(int(d,2)))
ee = str(chr(int(e,2)))
ff = str(chr(int(f,2)))
gg = str(chr(int(g,2)))
hh = str(chr(int(h,2)))
fin = aa + bb + cc + dd + ee + ff + gg + hh
#s.flushOutput()
finaly = s.write(fin)
time.sleep(0.5)
i = 0
ll = []
while True:
time.sleep(0.001)
if s.inWaiting() != 0:
#s.flushInput()
ll.append(s.read())
#print ll
if len(ll) == 9:
temp = str(ll[5].encode('hex')) + str(ll[6].encode('hex')) + str(ll[3].encode('hex')) + str(ll[4].encode('hex'))
#print temp
ans = struct.unpack('!f', temp.decode('hex'))[0]
temp = str(ans).split("e")
print ('Value of active power on energy meter is %s' %(ans))
break
s.close()
time.sleep(1)
<file_sep>/Digital Circuits/Registers/Using_IC/SIPO_2.py
import os
import sys
cwd=os.getcwd()
(setpath__,Using_IC)=os.path.split(cwd)
print setpath__
(setpath_,Using_IC)=os.path.split(setpath__)
print setpath_
(setpath,Codes)=os.path.split(setpath_)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class SIPO_IC:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
dataPin=11
clockPin=9
latchPin=10
inPin=5
for _ in range(0,100):
self.obj_arduino.cmd_digital_out(1,latchPin,0) #So that the data is stored and not passed on to the output LEDs
self.obj_arduino.cmd_shift_out_(dataPin,clockPin,inPin)
self.obj_arduino.cmd_digital_out(1,latchPin,1) #So that the stored data is now passed on to the output LEDs
#and the output is obtained
sleep(0.5)
def exit(self):
self.obj_arduino.close_serial()
def main():
sipo=SIPO_IC(115200)
if __name__=='__main__':
main()
<file_sep>/Digital Circuits/Registers/Using_IC/SIPO_n_bits.py
import os
import sys
cwd=os.getcwd()
(setpath__,Using_IC)=os.path.split(cwd)
print setpath__
(setpath_,Using_IC)=os.path.split(setpath__)
print setpath_
(setpath,Codes)=os.path.split(setpath_)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class SIPO_IC:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
pinstate=0
n=int(raw_input("Enter no. of bits: "))
data=[0 for _ in range(0,n)] #an 8-elements list representing an 8 bit binary number
dataPin=11
clockPin=9
latchPin=10
inPin=5
for _ in range(0,50):
pinstate=self.obj_arduino.cmd_digital_in(1,inPin)
if pinstate=='1':
data[0]=1
#the msb becomes 1 when input is given
#high which is henceforth shifted
else:
data[0]=0
print data
self.obj_arduino.cmd_digital_out(1,latchPin,0)
self.obj_arduino.cmd_shift_out_n(dataPin,clockPin,'LSBFIRST',data,n)
self.obj_arduino.cmd_digital_out(1,latchPin,1)
sleep(0.5)
for k in range(0,(n-1)):
data[(n-1)-k]=data[(n-2)-k]
data[0]=0
#every element of the matrix is
#shifted one place to the right
#so effectively the 8 bit
#binary number is divided by 2
def exit(self):
self.obj_arduino.close_serial()
def main():
sipo=SIPO_IC(115200)
if __name__=='__main__':
main()
<file_sep>/Digital Circuits/Demux 1-4.py
import os
import sys
cwd=os.getcwd()
(setpath,Codes)=os.path.split(cwd)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class DEMUX:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
self.inPin=5 #Input
#select lines
self.aPin=6 #input A (MSB)
self.bPin=7 #input B (LSB)
#outputs
self.ledPin4=11 #output 4 (MSB)
self.ledPin3=10 #output 3
self.ledPin2=9 #output 2
self.ledPin1=8 #output 1 (LSB)
for _ in range(0,500):
i=self.obj_arduino.cmd_digital_in(1,self.inPin) #input
A=self.obj_arduino.cmd_digital_in(1,self.aPin) #MSB select line input
B=self.obj_arduino.cmd_digital_in(1,self.bPin) #LSB select line input
print ("A= "+A+", B= "+B+", i= "+i)
if i=='0': #all outputs will be zero irrespective of which one is selected
self.obj_arduino.cmd_digital_out(1,self.ledPin1,0)
self.obj_arduino.cmd_digital_out(1,self.ledPin2,0)
self.obj_arduino.cmd_digital_out(1,self.ledPin3,0)
self.obj_arduino.cmd_digital_out(1,self.ledPin4,0)
sleep(0.1)
elif i=='1':
if A=='0' and B=='0': #input i is seen at first output pin (LSB)
self.obj_arduino.cmd_digital_out(1,self.ledPin1,1)
self.obj_arduino.cmd_digital_out(1,self.ledPin2,0)
self.obj_arduino.cmd_digital_out(1,self.ledPin3,0)
self.obj_arduino.cmd_digital_out(1,self.ledPin4,0)
sleep(0.1)
elif A=='0' and B=='1': #input i is seen at second output pin
self.obj_arduino.cmd_digital_out(1,self.ledPin2,1)
self.obj_arduino.cmd_digital_out(1,self.ledPin1,0)
self.obj_arduino.cmd_digital_out(1,self.ledPin3,0)
self.obj_arduino.cmd_digital_out(1,self.ledPin4,0)
sleep(0.1)
elif A=='1' and B=='0': #input i is seen at third output pin
self.obj_arduino.cmd_digital_out(1,self.ledPin3,1)
self.obj_arduino.cmd_digital_out(1,self.ledPin1,0)
self.obj_arduino.cmd_digital_out(1,self.ledPin2,0)
self.obj_arduino.cmd_digital_out(1,self.ledPin4,0)
sleep(0.1)
elif A=='1' and B=='1': #input i is seen at fourth output pin (MSB)
self.obj_arduino.cmd_digital_out(1,self.ledPin4,1)
self.obj_arduino.cmd_digital_out(1,self.ledPin1,0)
self.obj_arduino.cmd_digital_out(1,self.ledPin2,0)
self.obj_arduino.cmd_digital_out(1,self.ledPin3,0)
sleep(0.1)
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_demux=DEMUX(115200)
if __name__=='__main__':
main()
<file_sep>/Examples/4.3LED.py
import os
import sys
cwd=os.getcwd()
(setpath,Examples)=os.path.split(cwd)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class LED_ON_OFF_MULTICOLOR:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
self.blue=9
self.green=10
self.red=11
self.obj_arduino.cmd_digital_out(1,self.blue,self.baudrate)
self.obj_arduino.cmd_digital_out(1,self.red,self.baudrate)
sleep(5)
self.obj_arduino.cmd_digital_out(1,self.blue,0)
sleep(3)
self.obj_arduino.cmd_digital_out(1,self.red,0)
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_led=LED_ON_OFF_MULTICOLOR(115200);
if __name__=='__main__':
main()
<file_sep>/Digital Circuits/Registers/Using_IC/PISO.py
import os
import sys
cwd=os.getcwd()
(setpath__,Using_IC)=os.path.split(cwd)
print setpath__
(setpath_,Registers)=os.path.split(setpath__)
print setpath_
(setpath,Codes)=os.path.split(setpath_)
print setpath
sys.path.append(setpath)
from Arduino._Arduino_ import _Arduino_
#from Arduino.IC_methods import IC_methods
from time import sleep
class Trial:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=_Arduino_()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
#self.obj_icm=IC_methods(self.baudrate,self.port)
def run(self):
dataPin=9
clockPin=10
latchPin=11
ledPin=5 #LED that shows serial output
clockLed=6 #LED that shows clock pulses
self.obj_arduino.cmd_digital_out(1,latchPin,1) #parallel load mode
for _ in range(0,50):
print ("Give input, Parallel load mode:")
sleep(2)
self.obj_arduino.cmd_digital_out(1,clockPin,1) #positive edge occurs
#parallel load is stored
print("Inputs stored, Serial shift mode:")
sleep(0.5)
self.obj_arduino.cmd_digital_out(1,clockPin,0)
self.obj_arduino.cmd_digital_out(1,latchPin,0) #serial out mode
self.obj_arduino.cmd_shift_in(dataPin,clockPin,ledPin,clockLed)
self.obj_arduino.cmd_digital_out(1,latchPin,1)
self.obj_arduino.cmd_digital_out(1,ledPin,0)
def main():
piso=Trial(115200)
if __name__=='__main__':
main()
<file_sep>/Digital Circuits/Trials/shift out hello world.py
import os
import sys
cwd=os.getcwd()
(setpath_,Using_IC)=os.path.split(cwd)
print setpath_
(setpath,Codes)=os.path.split(setpath_)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class SIPO_IC:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
# self.obj_icm=IC_methods(self.baudrate)
def run(self):
dataPin=11
clockPin=9
latchPin=10
#inPin=5
for x in range(0,256):
self.obj_arduino.cmd_digital_out(1,latchPin,0) #So that the data is stored and not passed on to the output LEDs
self.obj_arduino.cmd_shift_out(dataPin,clockPin,'MSBFIRST',x)
self.obj_arduino.cmd_digital_out(1,latchPin,1) #So that the stored data is now passed on to the output LEDs
#and the output is obtained
sleep(0.5)
def exit(self):
self.obj_arduino.close_serial()
def main():
sipo=SIPO_IC(115200)
if __name__=='__main__':
main()
<file_sep>/Digital Circuits/Full Subtracter.py
import os
import sys
cwd=os.getcwd()
(setpath,Codes)=os.path.split(cwd)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class SUBTRACTER:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
self.diffPin=9 #Difference
self.boutPin=10 #Borrow out
self.aPin=5 #input A
self.bPin=6 #input B
self.binPin=3 #input Bin (Borrow in)
for _ in range(0,100):
vala=self.obj_arduino.cmd_digital_in(1,self.aPin)
print "A= "+vala
valb=self.obj_arduino.cmd_digital_in(1,self.bPin)
print "B= "+valb
valbin=self.obj_arduino.cmd_digital_in(1,self.binPin)
print "Bin= "+valbin
#As acoording to the logic circuit of full subtracter
#First half subtracter
#Difference
#A XOR B
if vala=='0' and valb=='0':
fsdiff='0'
elif vala=='1' and valb=='1':
fsdiff='0'
else:
fsdiff='1'
#borrow out
#A NOT
if vala=='1':
fsnot='0'
else:
fsnot='1'
#B AND fsnot
if valb=='1' and fsnot=='1':
fsb='1'
else:
fsb='0'
#second half subtacter
#difference
#fsdiff XOR Bin
if fsdiff=='0' and valbin=='0':
self.obj_arduino.cmd_digital_out(1,self.diffPin,0)
sleep(0.1)
elif fsdiff=='1' and valbin=='1':
self.obj_arduino.cmd_digital_out(1,self.diffPin,0)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,self.diffPin,1)
sleep(0.1)
#borrow out
#fsdiff NOT
if fsdiff=='1':
ssnot='0'
else:
ssnot='1'
#Bin and ssnot
if valbin=='1' and ssnot=='1':
ssand='1'
else:
ssand='0'
#ssand OR fsb
if ssand=='0' and fsb=='0':
self.obj_arduino.cmd_digital_out(1,self.boutPin,0)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,self.boutPin,1)
sleep(0.1)
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_subtracter=SUBTRACTER(115200)
if __name__=='__main__':
main()
<file_sep>/Digital Circuits/Flip_Flops/JK_FF/JK FF edge.py
import os
import sys
cwd=os.getcwd()
(setpath__,JK_FF)=os.path.split(cwd)
print setpath__
(setpath_,Flip_Flops)=os.path.split(setpath__)
print setpath_
(setpath,Codes)=os.path.split(setpath_)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class JK_FF_edge:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
self.J='0'
self.K='0'
self.S='0'
self.R='1'
self.jPin=5
self.kPin=6
self.prePin=3
self.clrPin=4
#assuming initial state:
self.Q='0'
self.Qbar='1'
self.qPin=9
self.qbarPin=10
self.clockPin=2 #external clock
self.pinstate='0'
self.lastpinstate='0'
for _ in range(0,500):
if self.Q=='0':
self.obj_arduino.cmd_digital_out(1,self.qPin,0) #Gives low output at Q
self.obj_arduino.cmd_digital_out(1,self.qbarPin,1) #Gives high output at Qbar
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,self.qPin,1) #Gives high output at Q
self.obj_arduino.cmd_digital_out(1,self.qbarPin,0) #Gives low output at Qbar
sleep(0.1)
self.pre=self.obj_arduino.cmd_digital_in(1,self.prePin) #Reads preset input
self.clr=self.obj_arduino.cmd_digital_in(1,self.clrPin) #Reads clear input
if self.pre=='0' and self.clr=='1':
self.S='1'
self.R='0'
self.Q='1'
elif self.pre=='1' and self.clr=='0':
self.S='0'
self.R='1'
self.Q='0'
#Normal functioning when both are HIGH
elif self.pre=='1' and self.clr=='1':
self.pinstate=self.obj_arduino.cmd_digital_in(1,self.clockPin) #Reads clock input
if self.pinstate!=self.lastpinstate: #edge detection
if self.pinstate=='1': #Positive edge
#MASTER
#JK FF Code
self.J=self.obj_arduino.cmd_digital_in(1,self.jPin)
self.K=self.obj_arduino.cmd_digital_in(1,self.kPin)
if self.J=='0' and self.K=='1':
self.S='0'
self.R='1'
elif self.J=='1' and self.K=='0':
self.S='1'
self.R='0'
elif self.J=='1' and self.K=='1':
temp=self.S
self.S=self.R
self.R=temp
else:
pass
else:
pass
if self.pinstate=='0':
#SLAVE
#JK FF code only for state 01 and 10
if self.S=='0' and self.R=='1':
self.Q='0'
elif self.S=='1' and self.R=='0':
self.Q='1'
else:
pass
else:
pass
sleep(0.05)
self.lastpinstate=self.pinstate
else:
pass
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_jkffe=JK_FF_edge(115200)
if __name__=='__main__':
main()
<file_sep>/Digital Circuits/Decimal to binary priority encoder.py
import os
import sys
cwd=os.getcwd()
(setpath,Codes)=os.path.split(cwd)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class D2B:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
#binary Outputs
self.led1=10 #LSB
self.led2=11 #middle bit
self.led3=12 #MSB
#decimal inputs
self.Pin1=2 #decimal input 1 (LSB)
self.Pin2=3 #decimal input 2
self.Pin3=4 #decimal input 3
self.Pin4=5 #decimal input 4
self.Pin5=6 #decimal input 5
self.Pin6=7 #decimal input 6
self.Pin7=8 #decimal input 7 (MSB)
for _ in range(0,500):
d1=self.obj_arduino.cmd_digital_in(1,self.Pin1)
d2=self.obj_arduino.cmd_digital_in(1,self.Pin2)
d3=self.obj_arduino.cmd_digital_in(1,self.Pin3)
d4=self.obj_arduino.cmd_digital_in(1,self.Pin4)
d5=self.obj_arduino.cmd_digital_in(1,self.Pin5)
d6=self.obj_arduino.cmd_digital_in(1,self.Pin6)
d7=self.obj_arduino.cmd_digital_in(1,self.Pin7)
print (d1+" "+d2+" "+d3+" "+d4+" "+d5+" "+d6+" "+d7)
#decimal input 0, binary output 000
if d1=='0' and d2=='0' and d3=='0' and d4=='0' and d5=='0' and d6=='0' and d7=='0':
self.obj_arduino.cmd_digital_out(1,self.led1,0)
self.obj_arduino.cmd_digital_out(1,self.led2,0)
self.obj_arduino.cmd_digital_out(1,self.led3,0)
sleep(0.1)
#decimal input 1, binary output 001
elif d1=='1' and d2=='0' and d3=='0' and d4=='0' and d5=='0' and d6=='0' and d7=='0':
self.obj_arduino.cmd_digital_out(1,self.led1,1)
self.obj_arduino.cmd_digital_out(1,self.led2,0)
self.obj_arduino.cmd_digital_out(1,self.led3,0)
sleep(0.1)
#decimal input 2, binary output 010
elif d2=='1' and d3=='0' and d4=='0' and d5=='0' and d6=='0' and d7=='0':
self.obj_arduino.cmd_digital_out(1,self.led1,0)
self.obj_arduino.cmd_digital_out(1,self.led2,1)
self.obj_arduino.cmd_digital_out(1,self.led3,0)
sleep(0.1)
#decimal input 3, binary output 011
elif d3=='1' and d4=='0' and d5=='0' and d6=='0' and d7=='0':
self.obj_arduino.cmd_digital_out(1,self.led1,1)
self.obj_arduino.cmd_digital_out(1,self.led2,1)
self.obj_arduino.cmd_digital_out(1,self.led3,0)
sleep(0.1)
#decimal input 4, binary output 100
elif d4=='1' and d5=='0' and d6=='0' and d7=='0':
self.obj_arduino.cmd_digital_out(1,self.led1,0)
self.obj_arduino.cmd_digital_out(1,self.led2,0)
self.obj_arduino.cmd_digital_out(1,self.led3,1)
sleep(0.1)
#decimal input 5, binary output 101
elif d5=='1' and d6=='0' and d7=='0':
self.obj_arduino.cmd_digital_out(1,self.led1,1)
self.obj_arduino.cmd_digital_out(1,self.led2,0)
self.obj_arduino.cmd_digital_out(1,self.led3,1)
sleep(0.1)
#decimal input 6, binary output 110
elif d6=='1' and d7=='0':
self.obj_arduino.cmd_digital_out(1,self.led1,0)
self.obj_arduino.cmd_digital_out(1,self.led2,1)
self.obj_arduino.cmd_digital_out(1,self.led3,1)
sleep(0.1)
#decimal input 7, binary output 111
elif d7=='1':
self.obj_arduino.cmd_digital_out(1,self.led1,1)
self.obj_arduino.cmd_digital_out(1,self.led2,1)
self.obj_arduino.cmd_digital_out(1,self.led3,1)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,self.led1,0)
self.obj_arduino.cmd_digital_out(1,self.led2,0)
self.obj_arduino.cmd_digital_out(1,self.led3,0)
sleep(0.1)
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_d2b=D2B(115200)
if __name__=='__main__':
main()
<file_sep>/Digital Circuits/Counter/Counter edge.py
import os
import sys
cwd=os.getcwd()
(setpath_,Counter)=os.path.split(cwd)
print setpath_
(setpath,Codes)=os.path.split(setpath_)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class COUNTER:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
self.pinstate0='0' #input, clock pulse to FF1
self.lastpinstate0='0'
self.pinstate1='0' #output of FF1 (LSB), clock pulse to FF2
self.lastpinstate1='0'
self.pinstate2='0' #output of FF2 (middle bit)), clock pulse to FF3
self.lastpinstate2='0'
self.pinstate3='0' #output of FF3 (MSB)
self.lastpinstate3='0'
#outputs
self.Pin1=9 #LSB
self.Pin2=10 #middle bit
self.Pin3=11 #MSB
#external clock
self.clockPin=5
for _ in range(0,500):
#LSB
if self.pinstate1=='0':
self.obj_arduino.cmd_digital_out(1,self.Pin1,0)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,self.Pin1,1)
sleep(0.1)
#middle bit
if self.pinstate2=='0':
self.obj_arduino.cmd_digital_out(1,self.Pin2,0)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,self.Pin2,1)
sleep(0.1)
#MSB
if self.pinstate3=='0':
self.obj_arduino.cmd_digital_out(1,self.Pin3,0)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,self.Pin3,1)
sleep(0.1)
self.pinstate0=self.obj_arduino.cmd_digital_in(1,self.clockPin)
#negative edge of clock pulse to FF1
if self.pinstate0!=self.lastpinstate0:
if self.pinstate0=='0':
#toggle i.e if output is 0, change it to 1
if self.pinstate1=='0':
self.pinstate1='1'
else:
self.pinstate1='0'
else:
pass
sleep(0.05)
self.lastpinstate0=self.pinstate0
#negative edge of clock pulse to FF2
if self.pinstate1!=self.lastpinstate1:
if self.pinstate1=='0':
#toggle i.e if output is 0, change it to 1
if self.pinstate2=='0':
self.pinstate2='1'
else:
self.pinstate2='0'
else:
pass
sleep(0.05)
self.lastpinstate1=self.pinstate1
#negative edge of clock pulse to FF1
if self.pinstate2!=self.lastpinstate2:
if self.pinstate2=='0':
#toggle i.e if output is 0, change it to 1
if self.pinstate3=='0':
self.pinstate3='1'
else:
self.pinstate3='0'
else:
pass
sleep(0.05)
self.lastpinstate2=self.pinstate2
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_count=COUNTER(115200)
if __name__=='__main__':
main()
<file_sep>/Digital Circuits/Counter/Counter without ff.py
import os
import sys
cwd=os.getcwd()
(setpath_,Counter)=os.path.split(cwd)
print setpath_
(setpath,Codes)=os.path.split(setpath_)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class COUNTER_wo_ff:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
pinstate='0'
lastpinstate='0'
clockPin=5 # Pulse to be counted
#outputs
Pin1=9 #LSB
Pin2=10 #middle bit
Pin3=11 #MSB
i=0
a=0
b=0
c=0
for _ in range(0,500):
pinstate=self.obj_arduino.cmd_digital_in(1,clockPin)
#negative edge of clock pulse to FF1
if pinstate!=lastpinstate:
if pinstate=='0':
i+=1
else:
pass
sleep(0.05)
else:
pass
lastpinstate=pinstate
a=i%2
b=(i/2)%2
c=(i/4)%2
self.obj_arduino.cmd_digital_out(1,Pin1,a) #LSB
self.obj_arduino.cmd_digital_out(1,Pin2,b) #middle bit
self.obj_arduino.cmd_digital_out(1,Pin3,c) #MSB
sleep(0.1)
if i>7:
i=0
else:
pass
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_count_wo_ff=COUNTER_wo_ff(115200)
if __name__=='__main__':
main()
<file_sep>/Examples/7.2DCMOTOR.py
import os
import sys
cwd=os.getcwd()
(setpath,Examples)=os.path.split(cwd)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class DCMOTOR_ROTATION:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
self.pin1=9
self.pin2=10
self.obj_arduino.cmd_dcmotor_setup(1,3,1,self.pin1,self.pin2)
self.obj_arduino.cmd_dcmotor_run(1,1,100)
sleep(3)
self.obj_arduino.cmd_dcmotor_run(1,1,-100)
sleep(3)
self.obj_arduino.cmd_dcmotor_release(1,1)
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_dcmotor=DCMOTOR_ROTATION(115200)
if __name__=='__main__':
main()
<file_sep>/Digital Circuits/Registers/PIPO.py
import os
import sys
cwd=os.getcwd()
(setpath_,Registers)=os.path.split(cwd)
print setpath_
(setpath,Codes)=os.path.split(setpath_)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class PIPO:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
pinstate='0'
lastpinstate='0'
D2='0' #MSB input
D1='0' #middle bit input=MSB output
D0='0' #LSB input=middle bit output
Q='0' #LSB output
#Parallel inputs
inPin1=5 #LSB input
inPin2=6 #middle bit
inPin3=7 #MSB
#Parallel output
outPin1=9 #LSB = Q
outPin2=10 #middle bit = D0
outPin3=11 #MSB = D1
#external clock pulse
clockPin=2
for _ in range(0,100):
#pin 9=Q=LSB output
if Q=='0':
self.obj_arduino.cmd_digital_out(1,outPin1,0)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,outPin1,1)
sleep(0.1)
#pin 10=Q1=D0=middle bit output
if D0=='0':
self.obj_arduino.cmd_digital_out(1,outPin2,0)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,outPin2,1)
sleep(0.1)
#pin 11=Q2=D1=MSB output
if D1=='0':
self.obj_arduino.cmd_digital_out(1,outPin3,0)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,outPin3,1)
sleep(0.1)
#reads the state of clock
pinstate=self.obj_arduino.cmd_digital_in(1,clockPin)
#clock is common for all FFs
#thus only 1 if statement for detecting positive edge of clock
if pinstate!=lastpinstate:
if pinstate=='1':
#order of FFs: serial input-FF2-FF1-FF0
D0=self.obj_arduino.cmd_digital_in(1,inPin1)
D1=self.obj_arduino.cmd_digital_in(1,inPin2)
D2=self.obj_arduino.cmd_digital_in(1,inPin3)
#FF0 (LSB FF, i.e. third FF)
if D0=='0':
Q='0'
else:
Q='1'
#FF1 (middle bit FF i.e. second FF)
if D1=='0':
D0='0'
else:
D0='1'
#FF2 (MSB FF i.e first FF)
if D2=='0':
D1='0'
else:
D1='1'
sleep(0.05)
lastpinstate=pinstate
def exit(self):
self.obj_arduino.close_serial()
def main():
pipo=PIPO(115200)
if __name__=='__main__':
main()
<file_sep>/Digital Circuits/Mux 4-1.py
import os
import sys
cwd=os.getcwd()
(setpath,Codes)=os.path.split(cwd)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class MUX:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
self.ledPin=9 #Output
#select lines
self.aPin=6 #input A (MSB)
self.bPin=7 #input B (LSB)
#inputs
self.Pin4=5 #input 4 (MSB)
self.Pin3=4 #input 3
self.Pin2=3 #input 2
self.Pin1=2 #input 1 (LSB)
for _ in range(0,200):
i4=self.obj_arduino.cmd_digital_in(1,self.Pin4) #MSB input
i3=self.obj_arduino.cmd_digital_in(1,self.Pin3)
i2=self.obj_arduino.cmd_digital_in(1,self.Pin2)
i1=self.obj_arduino.cmd_digital_in(1,self.Pin1) #LSB input
A=self.obj_arduino.cmd_digital_in(1,self.aPin) #MSB select line input
B=self.obj_arduino.cmd_digital_in(1,self.bPin) #LSB select line input
if A=='0' and B=='0':
#input i1 is selected, output is same as i1
if i1=='0':
self.obj_arduino.cmd_digital_out(1,self.ledPin,0)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,self.ledPin,1)
sleep(0.1)
elif A=='0' and B=='1':
#input i2 is selected, output is same as i2
if i2=='0':
self.obj_arduino.cmd_digital_out(1,self.ledPin,0)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,self.ledPin,1)
sleep(0.1)
elif A=='1' and B=='0':
#input i3 is selected, output is same as i3
if i3=='0':
self.obj_arduino.cmd_digital_out(1,self.ledPin,0)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,self.ledPin,1)
sleep(0.1)
elif A=='1' and B=='1':
#input i4 is selected, output is same as i4
if i4=='0':
self.obj_arduino.cmd_digital_out(1,self.ledPin,0)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,self.ledPin,1)
sleep(0.1)
else:
print ("Invalid input!")
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_mux=MUX(115200)
if __name__=='__main__':
main()
<file_sep>/Digital Circuits/Flip_Flops/SR_FF/SR FF edge.py
import os
import sys
cwd=os.getcwd()
(setpath__,SR_FF)=os.path.split(cwd)
print setpath__
(setpath_,Codes)=os.path.split(setpath__)
print setpath_
(setpath,Codes)=os.path.split(setpath_)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class SR_FF_edge:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
self.S='0'
self.R='0'
self.sPin=5 #Input S is given to Pin 5
self.rPin=6 #Input R is given to Pin 6
#assuming initial state:
self.Q='0'
self.Qbar='1'
self.qPin=9
self.qbarPin=10
self.clockPin=2 #external clock
self.pinstate='0'
self.lastpinstate='0'
for _ in range(0,500): #Runs the program 500 times in a loop
if self.Q=='0':
self.obj_arduino.cmd_digital_out(1,self.qPin,0) #Gives low output at Q
elif self.Q=='1':
self.obj_arduino.cmd_digital_out(1,self.qPin,1) #Gives high output at Q
sleep(0.1)
else:
pass
if self.Qbar=='0':
self.obj_arduino.cmd_digital_out(1,self.qbarPin,0) #Gives low output at Qbar
elif self.Qbar=='1':
self.obj_arduino.cmd_digital_out(1,self.qbarPin,1) #Gives high output at Qbar
sleep(0.1)
else:
pass
self.pinstate=self.obj_arduino.cmd_digital_in(1,self.clockPin)
if self.pinstate!=self.lastpinstate: #edge detection
if(self.pinstate=='0'): #negative edge
self.S=self.obj_arduino.cmd_digital_in(1,self.sPin) #Reads the input S
self.R=self.obj_arduino.cmd_digital_in(1,self.rPin) #Reads the input R
if self.S=='0' and self.R=='1':
self.Q='0'
self.Qbar='1'
elif self.S=='1' and self.R=='0':
self.Q='1'
self.Qbar='0'
elif self.S=='1' and self.R=='1': #we assume this case doesn't occur
self.Q='0'
self.Qbar='0'
else:
pass
sleep(0.05)
self.lastpinstate=self.pinstate
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_srffe=SR_FF_edge(115200)
if __name__=='__main__':
main()
<file_sep>/Digital Circuits/Flip_Flops/T_FF/T ff edge.py
import os
import sys
cwd=os.getcwd()
(setpath__,T_FF)=os.path.split(cwd)
print setpath__
(setpath_,Codes)=os.path.split(setpath__)
print setpath_
(setpath,Codes)=os.path.split(setpath_)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class T_FF_edge:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
self.T='0'
self.tPin=5
#assuming initial state:
self.Q='0'
self.Qbar='1'
self.qPin=9
self.qbarPin=10
self.clockPin=2 #external clock
self.pinstate='0'
self.lastpinstate='0'
for _ in range(0,500):
if self.Q=='0':
self.obj_arduino.cmd_digital_out(1,self.qPin,0)
self.obj_arduino.cmd_digital_out(1,self.qbarPin,1)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,self.qPin,1)
self.obj_arduino.cmd_digital_out(1,self.qbarPin,0)
sleep(0.1)
self.pinstate=self.obj_arduino.cmd_digital_in(1,self.clockPin) #Reads clock
if self.pinstate!=self.lastpinstate: #Edge detection
if(self.pinstate=='0'): #negative edge
self.T=self.obj_arduino.cmd_digital_in(1,self.tPin) #Reads input T
if self.T=='1':
temp=self.Q
self.Q=self.Qbar
self.Qbar=temp
else:
pass
sleep(0.05)
self.lastpinstate=self.pinstate
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_tffe=T_FF_edge(115200)
if __name__=='__main__':
main()
<file_sep>/Digital Circuits/Flip_Flops/JK_FF/JK FF level.py
import os
import sys
cwd=os.getcwd()
(setpath__,JK_FF)=os.path.split(cwd)
print setpath__
(setpath_,Flip_Flops)=os.path.split(setpath__)
print setpath_
(setpath,Codes)=os.path.split(setpath_)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class JK_FF:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
self.J='0'
self.K='0'
self.jPin=5
self.kPin=6
self.prePin=3
self.clrPin=4
#assuming initial state:
self.Q='0'
self.Qbar='1'
self.qPin=9
self.qbarPin=10
self.clockPin=2 #external clock
for _ in range(0,500):
if self.Q=='0':
self.obj_arduino.cmd_digital_out(1,self.qPin,0) #Gives low output at Q
sleep(0.05)
elif self.Q=='1':
self.obj_arduino.cmd_digital_out(1,self.qPin,1) #Gives high output at Q
sleep(0.05)
else:
pass
if self.Qbar=='0':
self.obj_arduino.cmd_digital_out(1,self.qbarPin,0) #Gives low output at Qbar
sleep(0.05)
elif self.Qbar=='1':
self.obj_arduino.cmd_digital_out(1,self.qbarPin,1) #Gives high output at Qbar
sleep(0.05)
else:
pass
self.J=self.obj_arduino.cmd_digital_in(1,self.jPin) #Reads the input J
self.K=self.obj_arduino.cmd_digital_in(1,self.kPin) #Reads the input K
self.pre=self.obj_arduino.cmd_digital_in(1,self.prePin) #Reads the input Preset
self.clr=self.obj_arduino.cmd_digital_in(1,self.clrPin) #Reads the input Clear
if self.pre=='0' and self.clr=='1':
self.Q='1'
self.Qbar='0'
elif self.pre=='1' and self.clr=='0':
self.Q='0'
self.Qbar='1'
#Preset and clear are active low inputs, thus normal functioning of flip flop happens when both are HIGH
elif self.pre=='1' and self.clr=='1':
if self.obj_arduino.cmd_digital_in(1,self.clockPin)=='1':
if self.J=='0' and self.K=='1':
self.Q='0'
self.Qbar='1'
elif self.J=='1' and self.K=='0':
self.Q='1'
self.Qbar='0'
elif self.J=='1' and self.K=='1': #toggle state
temp=self.Q
self.Q=self.Qbar
self.Qbar=temp
else:
pass
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_jkff=JK_FF(115200)
if __name__=='__main__':
main()
<file_sep>/README.md
# PyArduino
Python-Arduino Interface
Python 2.7 and pyserial
<file_sep>/Digital Circuits/Logic_Gates/XOR.py
import os
import sys
cwd=os.getcwd()
(setpath_,Logic_Gates)=os.path.split(cwd)
print setpath_
(setpath,Codes)=os.path.split(setpath_)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class XOR_GATE:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
self.ledPin=9
self.aPin=5
self.bPin=6
for _ in range(0,100):
vala=self.obj_arduino.cmd_digital_in(1,self.aPin) #Reads state of aPin and stores it in vala
print "A= "+vala
#print type(vala)
#sleep(0.1)
valb=self.obj_arduino.cmd_digital_in(1,self.bPin) #Reads state of bPin and stores it in valb
print "B= "+valb
#print type(valb)
#sleep(0.1)
if vala=='0' and valb=='0':
self.obj_arduino.cmd_digital_out(1,self.ledPin,0) #sets state of output pin as LOW
sleep(0.1)
elif vala=='1' and valb=='1':
self.obj_arduino.cmd_digital_out(1,self.ledPin,0)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,self.ledPin,1) #sets state of output pin as HIGH
sleep(0.1)
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_gate=XOR_GATE(115200)
if __name__=='__main__':
main()
<file_sep>/Examples/5.1pushbutton.py
import os
import sys
cwd=os.getcwd()
(setpath,Examples)=os.path.split(cwd)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class PUSHBUTTON:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
self.pushbutton=12
for i in range(10):
val=self.obj_arduino.cmd_digital_in(1,self.pushbutton)
sleep(1)
print val
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_pushbutton=PUSHBUTTON(115200)
if __name__=='__main__':
main()
<file_sep>/Digital Circuits/Registers/SISO.py
#3 bit SISO shift register
#in a SISO shift register, input is given to the MSB
#it shifts rightwards with positive clock pulses and output is seen at LSB
import os
import sys
cwd=os.getcwd()
(setpath_,Registers)=os.path.split(cwd)
print setpath_
(setpath,Codes)=os.path.split(setpath_)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class SISO:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
pinstate='0'
lastpinstate='0'
D2='0' #serial data input to FF2 (MSB FF)
D1='0' #D1=Q2, output of FF2=input of FF1 (middle bit FF)
D0='0' #D0=Q1, output of FF1=input of FF0 (LSB FF)
Q='0' #serial data out, output of FF0
#Serial input
inPin=5
#Serial output
outPin=9
#external clock pulse
clockPin=2
for _ in range(0,500):
if D0=='0':
self.obj_arduino.cmd_digital_out(1,outPin,0)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,outPin,1)
sleep(0.1)
pinstate=self.obj_arduino.cmd_digital_in(1,clockPin) #reads the state of clock
#clock is common for all FFs
#thus only 1 if statement for detecting positive edge of clock
if pinstate!=lastpinstate:
if pinstate=='1':
#order of FFs: FF2-FF1-FF0-serial output
#FF0 (LSB FF, i.e. third FF)
if D0=='0':
Q='0'
else:
Q='1'
#FF1 (middle bit FF i.e. second FF)
if D1=='0':
D0='0'
else:
D0='1'
#FF2 (MSB FF i.e first FF)
if D2=='0':
D1='0'
else:
D1='1'
D2=self.obj_arduino.cmd_digital_in(1,inPin) #input is given to D of FF2 (MSB FF)
sleep(0.05)
lastpinstate=pinstate
def exit(self):
self.obj_arduino.close_serial()
def main():
siso=SISO(115200)
if __name__=='__main__':
main()
<file_sep>/Digital Circuits/Full Adder.py
import os
import sys
cwd=os.getcwd()
(setpath,Codes)=os.path.split(cwd)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class ADDER:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
self.sumPin=9 #Sum
self.coutPin=10 #Carry out
self.aPin=5 #input A
self.bPin=6 #input B
self.cPin=3 #input Cin (Caryy in)
for _ in range(0,100):
vala=self.obj_arduino.cmd_digital_in(1,self.aPin)
print "A= "+vala
valb=self.obj_arduino.cmd_digital_in(1,self.bPin)
print "B= "+valb
valc=self.obj_arduino.cmd_digital_in(1,self.cPin)
print "Cin= "+valc
#As acoording to the logic circuit of full adder
#to get Pi: A XOR B
if vala=='0' and valb=='0':
P='0'
elif vala=='1' and valb=='1':
P='0'
else:
P='1'
#to get Gi: A AND B
if vala=='1' and valb=='1':
G='1'
else:
G='0'
#to get Sum: Pi XOR Cin
if P=='0' and valc=='0':
self.obj_arduino.cmd_digital_out(1,self.sumPin,0)
sleep(0.1)
elif P=='1' and valc=='1':
self.obj_arduino.cmd_digital_out(1,self.sumPin,0)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,self.sumPin,1)
sleep(0.1)
#To get Carry out
#Pi AND Cin
if P=='1' and valc=='1':
temp='1'
else:
temp='0'
# Gi OR temp
if G=='0' and temp=='0':
self.obj_arduino.cmd_digital_out(1,self.coutPin,0)
sleep(0.1)
else:
self.obj_arduino.cmd_digital_out(1,self.coutPin,1)
sleep(0.1)
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_adder=ADDER(115200)
if __name__=='__main__':
main()
<file_sep>/Examples/therm-buzzer.py
import os
import sys
cwd=os.getcwd()
(setpath,Examples)=os.path.split(cwd)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class POT:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino=Arduino()
self.port=self.obj_arduino.locateport()
self.obj_arduino.open_serial(1,self.port,self.baudrate)
def run(self):
self.therm=4
self.buzzer=3
for i in range(20):
val=self.obj_arduino.cmd_analog_in(1,self.therm)
print val
if (int(val) > 550):
self.obj_arduino.cmd_digital_out(1,self.buzzer,1)
else:
self.obj_arduino.cmd_digital_out(1,self.buzzer,0)
sleep(2)
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_pot=POT(115200)
if __name__=='__main__':
main()
<file_sep>/Examples/4.1LED.py
import os
import sys
cwd=os.getcwd()
(setpath,Examples)=os.path.split(cwd)
print setpath
sys.path.append(setpath)
from Arduino.Arduino import Arduino
from time import sleep
class LED_ON_OFF:
def __init__(self,baudrate):
self.baudrate=baudrate
self.setup()
self.run()
self.exit()
def setup(self):
self.obj_arduino = Arduino()
self.port = self.obj_arduino.locateport()
self.obj_arduino.open_serial(1, self.port,self.baudrate)
def run(self):
self.blue=9
self.obj_arduino.cmd_digital_out(1,self.blue,1)
def exit(self):
self.obj_arduino.close_serial()
def main():
obj_led=LED_ON_OFF(115200)
if __name__== '__main__':
main()
<file_sep>/Arduino/Arduino.py
import sys
import serial
from serial import Serial
from serial.tools.list_ports import comports
from time import sleep
p1=0 #Initial Position of servo motor
p2=0 #Final Position of servo motor
a=["0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","A","B","C","D"]
class Initialization:
def __init__(self):
pass
def locateport(self):
if sys.platform.startswith('win'):
port =''
ports = list(comports())
for i in ports:
for j in i:
if 'Arduino' in j:
port = i[0]
elif sys.platform.startswith('linux'):
b=[]
port =''
ports = list(comports())
for i in range(len(ports)):
for x in range(7):
portname="/dev/ttyACM"+str(x)
if ports[i][0]==portname:
b.append(ports[i][0])
port=b[0]
return port
def open_serial(self,ard_no, PortNo,baudrate):
#global ser
if PortNo =='':
sys.exit("aa..error..! arduino not found")
else:
self.ser = Serial(PortNo,baudrate)
sleep(2)
self.checkfirmware()
def close_serial(self):
#global ser
self.ser.close()
def checkfirmware(self):
print "Check Firm Ware"
#global ser
self.ser.write(chr(118))
try:
x=self.ser.read()
if x=='o':
try:
x=self.ser.read()
except:
sys.exit("aa..! error..! it seems correct firmware not loaded")
else:
sys.exit("aa..! error..! it seems correct firmware not loaded")
except:
sys.exit("aa..! error..! it seems correct firmware not loaded")
class Arduino(Initialization):
def __init__(self):
print "Init Arduino"
#self.baudrate=0
#self.ard_no=1
#self.PortNo=0
#self.pin=0
#self.val=0
#self.mode=0
#self.mno=0
#self.pin1=0
#self.pin2=0
#self.servo=0
def cmd_digital_out(self,ard_no,pin,val):
cmd=""
a=["0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","A","B","C","D"]
cmd="D"+"a"+a[pin]+"1"
self.ser.write(cmd)
cmd=""
cmd="D"+"w"+a[pin]+str(val)
self.ser.write(cmd)
def cmd_digital_in(self,ard_no,pin):
b=[]
cmd=""
a=["0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","A","B","C","D"]
cmd="D"+"a"+a[pin]+"0"
self.ser.write(cmd)
cmd=""
cmd="D"+"r"+a[pin]
self.ser.write(cmd)
a=self.ser.read()
return(a)
def cmd_analog_in(self,ard_no,pin):
cmd=""
a=["0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","A","B","C","D"]
cmd="A"+a[pin]
self.ser.write(cmd)
analog_times=[];
b1=ord(self.ser.read(1))
b2=ord(self.ser.read(1))
a=b1+b2*256
#a=ser.read()
return(a)
#return(int((1023-0)*int(ord(a))/(255-0)))
def cmd_analog_out(self,ard_no, pin, val):
a=["0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","A","B","C","D"]
cmd = "W" + a[pin] + chr(val)
self.ser.write(cmd)
def cmd_dcmotor_setup(self,ard_no,mode,mno,pin1,pin2):
cmd=""
a=["0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","A","B","C","D"]
cmd="C"+a[mno]+a[pin1]+a[pin2]+a[mode]
self.ser.write(cmd)
def cmd_dcmotor_run(self,ard_no,mno,val):
cmd=""
if(val <0):
dirc=0
else:
dirc=1
a=["0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","A","B","C","D"]
cmd="M"+a[mno]+a[dirc]+chr(abs(val))
self.ser.write(cmd)
def cmd_dcmotor_release(self,ard_no,mno):
cmd=""
a=["0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","A","B","C","D"]
cmd="M"+a[mno]+"r"
self.ser.write(cmd)
def cmd_servo_attach(self,ard_no,servo): #1->pin=9 #2->pin=10
cmd=""
a=["0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","A","B","C","D"]
cmd="S"+"a"+a[servo]
self.ser.write(cmd)
def cmd_servo_detach(self,ard_no,servo): #1->pin=9 #2->pin=10
cmd=""
a=["0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","A","B","C","D"]
cmd="S"+"d"+a[servo]
self.ser.write(cmd)
def cmd_servo_move(self,ard_no,servo,angle): #1->pin=9 #2->pin=10
cmd=""
a=["0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","A","B","C","D"]
cmd="S"+"w"+a[servo]+chr(angle)
self.ser.write(cmd)
#For PISO shift register
def cmd_shift_in(self,dataPin,clockPin,ledPin,clockLed):
value=[0 for _ in range(0,8)]
#print value
value2=[value for _ in range(0,8)]
#print value2
for i in range(0,8):
so= self.cmd_digital_in(1,dataPin) #Reads serial out of IC
print so
if so=='1':
self.cmd_digital_out(1,ledPin,1)
sleep(0.1)
else:
self.cmd_digital_out(1,ledPin,0)
sleep(0.1)
value2[i][i]=int(so)
#performs value=value|value2[i]
for j in range(0,8):
if value[j]==1 or value2[i][j]==1:
value[j]=1
else:
value[j]=0
self.cmd_digital_out(1,clockPin,1)
self.cmd_digital_out(1,clockLed,1)
sleep(0.5)
self.cmd_digital_out(1,clockPin,0)
self.cmd_digital_out(1,clockLed,0) #clockLED: Led indicating clock pulses
sleep(0.4)
#after every clock pulse, 1 right shift occurs for every bit
#thus after 8 clock pulses, the entire parallel input is shifted out,
#and obtained at the dataPin, one bit per clock pulse
#Thus we get the bit by bit serial output of the Parallel Load
print value
#For PISO shift register
#shift in for n bits
def cmd_shift_in_n(self,dataPin,clockPin,ledPin,clockLed,numBits):
n=numBits #no. of bits
value=[0 for _ in range(0,n)] #a list of n elements, all 0s, to store the n bits of the inputs together
value2=[value for _ in range(0,n)] #a list of lists, analogous to nxn array of all 0s
for i in range(0,n): #n iterations since n bit input is given
so=self.cmd_digital_in(1,dataPin)
if so=='1':
self.cmd_digital_out(1,ledPin,1)
sleep(0.1)
else:
self.cmd_digital_out(1,ledPin,0)
sleep(0.1)
value2[i][i]=int(so)
#performs value=value|value2[i]
for j in range(0,n):
if value[j]==1 or value2[i][j]==1:
value[j]=1
else:
value[j]=0
self.cmd_digital_out(1,clockPin,1)
self.cmd_digital_out(1,clockLed,1)
sleep(0.5)
self.cmd_digital_out(1,clockPin,0)
self.cmd_digital_out(1,clockLed,0) #clockLED: Led indicating clock pulses
sleep(0.4)
print value
#For SIPO shift register
def cmd_shift_out(self,dataPin,clockPin,bitOrder,val):
val2=0
mat=[]
if bitOrder=='MSBFIRST':
#to create identity matrix
for i in range(0,8):
matsub=[0 for _ in range(0,8)]
matsub[i]=1
mat.append(matsub)
else:
#to create horizontally flipped identity matrix
for i in range(0,8):
matsub=[0 for _ in range(0,8)]
matsub[7-i]=1
mat.append(matsub)
for i in range(0,8):
#performs & operation on corresponding elements of list
for x,y in zip(val,mat[i]):
if x==1 and y==1:
val2=1
break
else:
val2=0
self.cmd_digital_out(1,dataPin,val2)
self.cmd_digital_out(1,clockPin,1)
self.cmd_digital_out(1,clockPin,0)
#For SIPO shift register
def cmd_shift_out_(self,dataPin,clockPin,inPin):
print ("Give serial input: ")
sleep(0.25)
self.cmd_digital_out(1,dataPin,self.cmd_digital_in(1,inPin)) #if inPin is HIGH,
#i.e. if input is given, write HIGH on Serial In Pin of IC
print("Serial input stored: ")
self.cmd_digital_out(1,clockPin,1)
self.cmd_digital_out(1,clockPin,0) #One clock pulse
sleep(0.15)
#For SIPO shift register
#shift out for n bits
def cmd_shift_out_n(self,dataPin,clockPin,bitOrder,val,numBits):
n=int(numBits) #number of bits
if (n%8)==0:
p=n
else:
p=(8*(n/8))+8
val1=[0 for _ in range(0,n)] #output matrix.
#If all elements of the matrix are 0,
#output pinstate will be 0 (i.e LOW).
#If 1 or more elements of the matrix is 1,
#output pinstate will be 1 (i.e HIGH)
val2=0
mat=[]
if bitOrder=='MSBFIRST':
for i in range(0,n):
matsub=[0 for _ in range(0,n)]
matsub[i]=1
mat.append(matsub)
else:
for i in range(0,n):
matsub=[0 for _ in range(0,n)]
matsub[(n-1)-i]=1
mat.append(matsub)
for j in range(0,(p-n)): #do nothing for the first (p-n) clock pulses
self.cmd_digital_out(1,dataPin,0)
self.cmd_digital_out(1,clockPin,1)
self.cmd_digital_out(1,clockPin,0)
for i in range(0,n): #shift for last n clock pulses
#to perform val & mat[i]
for x,y in zip(val,mat[i]):
if x==1 and y==1:
val2=1
break
else:
val2=0
print val2,
self.cmd_digital_out(1,dataPin,val2)
self.cmd_digital_out(1,clockPin,1)
self.cmd_digital_out(1,clockPin,0)
| 841e322be80488d9b675b4edb77da7112a42fef2 | [
"Markdown",
"Python"
] | 26 | Python | manasdas17/PyArduino | 3e00eea7ac1a12ed26a2a6191b75d9b2c1c7de13 | 1cb389c50f5e00966ca9ce7233fe58f3bdc9673c |
refs/heads/master | <repo_name>KristianOellegaard/puppet-github<file_sep>/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant::Config.run do |config|
config.vm.box = "ubuntu-11.10"
config.vm.box_url = "https://github.com/downloads/KristianOellegaard/vagrant-base-boxes/ubuntu-11.10-64bit.box"
config.vm.provision :puppet do |puppet|
puppet.manifests_path = "./"
puppet.manifest_file = "vagrant.pp"
puppet.module_path = "../"
end
end
<file_sep>/README.rst
puppet-github
-------------
A very simple report for puppet that creates a github issue if a run fails. It should probably be optimized, so that it doesn't post the same issue twice, if it occurs twice.
Heavily inspired by the different reports made by <NAME> (@jamtur01).
Requirements
------------
ruby-json
puppet
Install
-------
Add to ``modules`` folder and add ``reports=github`` to your puppet configuration, then add your github username/password using the bundled class. Check vagrant.pp
Testing
-------
There is a bundled Vagrantfile that will make an error. You can add your username/password in vagrant.pp and test it.
<file_sep>/lib/puppet/reports/github.rb
require 'puppet'
require 'json'
require 'yaml'
Puppet::Reports.register_report(:github) do
config_file = File.join(File.dirname(Puppet.settings[:config]), "github.yaml")
raise(Puppet::ParseError, "Github report config file #{config_file} not readable") unless File.exist?(config_file)
config = YAML.load_file(config_file)
GITHUB_USER = config[:github_user]
GITHUB_REPO = config[:github_repo]
GITHUB_PASS = config[:github_pass]
def process
Puppet.debug "Parsed with Github Issues report. Status of this run is #{self.status}"
if self.status == "failed"
Puppet.debug "Sending status for #{self.host} to Github issues."
details = Array.new
self.logs.each do |log|
details << log
end
begin
timeout(8) do
Puppet.debug 'Creating request to github'
uri = URI.parse(URI.encode("https://api.github.com/repos/#{GITHUB_REPO}/issues"))
req = Net::HTTP::Post.new(uri.request_uri)
req.basic_auth GITHUB_USER, GITHUB_PASS
req.body = {
"title" => "Puppet run failed on #{host} at #{Time.now.asctime}",
"body" => details,
}.to_json
Puppet.debug "Sending request to github (#{uri})"
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
res = http.start {|http| http.request(req) }
Puppet.debug "Received response (#{res.code}) from github"
end
rescue Timeout::Error
Puppet.error "Timed out while attempting to create a GitHub issue, retrying ..."
max_attempts -= 1
retry if max_attempts > 0
end
end
end
end | 80e664d9437329dd32090e966a19928286290bb8 | [
"Ruby",
"reStructuredText"
] | 3 | Ruby | KristianOellegaard/puppet-github | ab2f515465bc527b2fc56296aefcde0603908875 | e4e694011667b5f965897ffd38b234878b14e9df |
refs/heads/master | <file_sep><?php namespace F16;
use Illuminate\Support\Facades\File;
Class Converter
{
public static function sourceToarray($file, $ext)
{
$dArr = null;
$content = file($file);
switch ($ext) {
case 'json':
for ($i = 0; $i < count($content); $i++) self::jta($i, $dArr, $content);
break;
case 'csv':
$j = 0;
for ($i = 0; $i < count($content); $i++) self::cta($i, $dArr, $content, $j);
break;
case 'xml':
for ($i = 0; $i < count($content); $i++) self::xta($i, $dArr, $content);
break;
case 'yml':
for ($i = 0; $i < count($content); $i++) self::yta($i, $dArr, $content);
break;
default:
return false;
}
return $dArr;
}
public static function jta(&$i, &$dA3, &$content)
{
$line = trim($content[$i]);
if (preg_match('/^".*":.*,\z/', $line)) {
$s = explode(":", rtrim($line, ','));
$key = substr($s[0], 1, -1);
$value = trim($s[1], '\"');
$dA3 [$key] = $value;
return true;
}
if (preg_match('/".*":\z/', $line)) {
$s = explode(":", $line);
$key = substr($s[0], 1, -1);
$dAr = array();
while ($i < count($content) - 1) {
$i++;
if (trim($content[$i]) == '}') break;
self::jta($i, $dAr, $content);
}
$dA3[$key] = $dAr;
return true;
}
return false;
}
public static function cta(&$i, &$dA3, &$content, &$j)
{
$line = trim($content[$i]);
$line = explode(";", $line);
if ($j >= 0 && strlen($line[$j]) > 0 && (strlen($line[$j + 1]) > 0 || substr($line[$j], -1) == "/")) {
$key = $line[$j];
$value = $line[$j + 1];
$dA3[$key] = $value;
return true;
}
if ($j >= 0 && strlen($line[$j]) > 0 && strlen($line[$j + 1]) == 0) {
$key = $line[$j];
$dAr = array();
$j++;
while ($i < count($content) - 1) {
$len = trim($content[$i + 1]);
if (strlen($len) > 0) {
$len = explode(';', $len);
if (count($len) > $j && strlen($len[$j]) == 0 || strlen($len[$j - 1]) !== 0) break;
$i++;
self::cta($i, $dAr, $content, $j);
}
}
$dA3[$key] = $dAr;
$j--;
return true;
}
if ($j > 0 && strlen($line[$j]) == 0 && strlen($line[$j + 1]) == 0) {
$j--;
return true;
}
return false;
}
public static function xta(&$i, &$dA3, &$content)
{
$line = trim($content[$i]);
if (preg_match('/^\<root\>/', $line)) {
$dA5 = array();
while ($i < count($content) && !preg_match('/^\<\/root\>/', trim($content[$i]))) {
$i++;
self::xta($i, $dA5, $content);
}
$dA3['root'] = $dA5;
return true;
}
if (preg_match('/^<.*>.*<.*>\z/', $line)) {
$s = explode(">", $line);
$key = trim($s[0], '<');
$v = explode("<", $s[1]);
$value = $v[0];
$dA3[$key] = $value;
return true;
}
if (preg_match('!^<.*\/>\z!', $line)) {
$key = trim($line, "<>");
$dA3[$key] = "";
return true;
}
if (preg_match('/^<[^\/].*>\z/', $line)) {
$key = ltrim(rtrim($line, ">"), "<");
$dA4 = array();
while ($i < count($content) - 1) {
$i++;
if (preg_match('`^</' . $key . '>\z`', trim($content[$i]))) break;
self::xta($i, $dA4, $content);
}
$dA3[$key] = $dA4;
return true;
}
return false;
}
public static function yta(&$i, &$dA3, &$content)
{
$line = trim($content[$i]);
if (preg_match('/^\<yml_catalog.*\>/', $line)) {
$key = ltrim(rtrim($line, ">"), "<");
$dA5 = array();
while ($i < count($content) && !preg_match('/^\<\/yml_catalog\>/', trim($content[$i]))) {
$i++;
self::yta($i, $dA5, $content);
}
$dA3[$key] = $dA5;
return true;
}
if (preg_match('/^<.*>.*<.*>\z/', $line)) {
$s = explode(">", $line);
$key = trim($s[0], '<');
$v = explode("<", $s[1]);
$value = $v[0];
$dA3[$key] = $value;
return true;
}
if (preg_match('/^<[^\/].*[^\/]>\z/', $line)) {
$key = ltrim(rtrim($line, ">"), "<");
$dA4 = array();
while ($i < count($content) - 1) {
if (preg_match('`^</' . $key . '>\z`', trim($content[$i + 1]))) break;
$i++;
self::yta($i, $dA4, $content);
}
$dA3[$key] = $dA4;
return true;
}
if (preg_match('/^<.*\/>\z/', $line)) {
$key = ltrim(rtrim($line, ">"), "<");
$dA3[$key] = '';
return true;
}
if (preg_match('/CDATA/', $line)) {
$key = 'CDATA';
$dA7 = array();
while ($i < count($content) - 1) {
$n = 0x5b;
if (trim($content[$i + 1]) == ']]>') break;
$i++;
self::yta($i, $dA7, $content);
}
$dA3[$key] = $dA7;
}
return false;
}
public static function arrayToFile($source, $cExt, $fileName)
{
$uploadPath = 'uploads/';
switch ($cExt) {
case 'json':
$data = self::arrayTojson($source, $fileName, $uploadPath, $cExt);
break;
case 'xml':
$data = self::arrayToxml($source, $fileName, $uploadPath, $cExt);
break;
case 'csv':
$data = self::arrayTocsv($source, $fileName, $uploadPath, $cExt);
break;
case 'yml':
$data = self::arrayToyml($source, $fileName, $uploadPath, $cExt);
break;
default:
return false;
}
return $data;
}
private static function arrayTojson($source, $fileName, $uploadPath, $cExt)
{
$filePath = $uploadPath . $fileName . '.' . $cExt;
function putTojson(&$source, &$data, &$tab)
{
foreach ($source as $key => $elem) {
if (is_array($elem)) {
$data .= $tab;
$tab .= "\t";
$data .= '"' . $key . '":' . "\n" . $tab . "{\n";
putTojson($elem, $data, $tab);
$data .= $tab . "}\n";
$tab = substr($tab, 0, -1);
} else {
$data .= $tab . '"' . $key . '":"' . $elem . '",' . "\n";
}
}
}
$tab = '';
$data = '';
putTojson($source, $data, $tab);
File::put(public_path($filePath), $data);
return $filePath;
}
private static function arrayToxml($source, $fileName, $uploadPath, $cExt)
{
$filePath = $uploadPath . $fileName . '.' . $cExt;
function putToxml(&$source, &$data, &$tab)
{
foreach ($source as $key => $elem) {
if (is_array($elem)) {
$data .= $tab;
$tab .= "\t";
if ($key !== 'CDATA') $data .= '<' . $key . '>' . "\n";
else $data .= '<![' . $key . '[' . "\n";
putToxml($elem, $data, $tab);
$k = explode(" ", $key);
if (count($k) > 1) $key = $k[0];
$tab = substr($tab, 0, -1);
if (!preg_match("/^.xml.*/i", $key)/*$key !== "?xml"*/) if ($key !== 'CDATA') $data .= $tab . "</" . $key . ">\n"; else $data .= $tab . "]]>\n";
} else {
if (!preg_match('!.*\/\z!', $key)/*$elem !== '+++'*/) {
$data .= $tab . '<' . $key . '>' . $elem . '</';
$k = explode(" ", $key);
if (count($k) > 1) $key = $k[0];
$data .= $key . '>' . "\n";
} else $data .= $tab . '<' . $key . '>' . "\n";
}
}
}
$tab = '';
foreach ($source as $key => $elem) {
if (preg_match("/^.xml version=.*/i", $key)) $data = "";
else $data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
break;
}
putToxml($source, $data, $tab);
File::put(public_path($filePath), $data);
return $filePath;
}
private static function arrayTocsv($source, $fileName, $uploadPath, $cExt)
{
$filePath = $uploadPath . $fileName . '.' . $cExt;
function putTocsv(&$source, &$data, &$tab)
{
foreach ($source as $key => $elem) {
if (is_array($elem)) {
$data .= $tab;
$tab .= ";";
$data .= '' . $key . ';;' . "\n";
putTocsv($elem, $data, $tab);
$tab = substr($tab, 0, -1);
} else $data .= $tab . $key . ';' . $elem . ";\n";
}
}
$tab = '';
$data = "";
putTocsv($source, $data, $tab);
File::put(public_path($filePath), $data);
return $filePath;
}
private static function arrayToyml($source, $fileName, $uploadPath, $cExt)
{
$filePath = $uploadPath . $fileName . '.' . $cExt;
function putToyml(&$source, &$data, &$tab)
{
foreach ($source as $key => $elem) {
if (is_array($elem)) {
$data .= $tab;
$tab .= "\t";
if ($key !== 'CDATA') $data .= '<' . $key . '>' . "\n";
else $data .= '<![' . $key . '[' . "\n";
putToyml($elem, $data, $tab);
$k = explode(" ", $key);
if (count($k) > 1) $key = $k[0];
$tab = substr($tab, 0, -1);
if (!preg_match("/^.xml.*/i", $key)) if ($key !== 'CDATA') $data .= $tab . "</" . $key . ">\n"; else $data .= $tab . "]]>\n";
} else {
if (!preg_match('!.*\/\z!', $key)) {
$data .= $tab . '<' . $key . '>' . $elem . '</';
$k = explode(" ", $key);
if (count($k) > 1) $key = $k[0];
$data .= $key . '>' . "\n";
} else $data .= $tab . '<' . $key . '>' . "\n";
}
}
}
$tab = '';
foreach ($source as $key => $elem) {
if (preg_match("/^.xml version=.*/i", $key)) $data = "";
else $data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
break;
}
putToyml($source, $data, $tab);
File::put(public_path($filePath), $data);
return $filePath;
}
}<file_sep><?php
namespace Tests\Feature;
use Tests\TestCase;
use F16\Converter;
class BasicTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testExample()
{
$this->assertTrue(true);
}
public function testCSVjson()
{
$testFile = public_path('uploads/5.csv');
$str = Converter::sourceToarray($testFile, 'csv');
$this->assertNotNull($str);
Converter::arrayToFile($str, 'json', 'testfile');
$testFile = public_path('uploads/testfile.json');
$str = is_file($testFile);
$this->assertTrue($str);
$testFile = public_path('uploads/5.json');
$str = Converter::sourceToarray($testFile,'json');
$this->assertNotNull($str);
Converter::arrayToFile($str,'xml','testfile');
$testFile = public_path('uploads/testfile.xml');
$str = is_file($testFile);
$this->assertTrue($str);
$testFile = public_path('uploads/5.xml');
$str = Converter::sourceToarray($testFile,'xml');
$this->assertNotNull($str);
Converter::arrayToFile($str,'yml','testfile');
$testFile = public_path('uploads/testfile.yml');
$str = is_file($testFile);
$this->assertTrue($str);
$testFile = public_path('uploads/5.yml');
$str = Converter::sourceToarray($testFile,'yml');
$this->assertNotNull($str);
Converter::arrayToFile($str,'csv','testfile');
$testFile = public_path('uploads/testfile.csv');
$str = is_file($testFile);
$this->assertTrue($str);
}
}
<file_sep><?php
namespace F16\Http\Controllers;
use Illuminate\Http\Request;
use F16\Converter;
//require_once('app/Converter.php');
class ConverterController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('converter');
}
public function convert(Request $request)
{
if($request->hasFile('source'))
{
$file = $request->file('source');
$source = Converter::sourceToarray($file->path(),$file->getClientOriginalExtension());
if(!is_array($source))return response()->json(array('result'=>'!','errorStatus'=>true,'error'=>'File incorrect.'), 200);
$cExt = strtolower($request->get('extention'));
$fileName = explode('.',$file->getClientOriginalName());
$data = Converter::arrayToFile($source, $cExt, $fileName[0]);
if(is_string($data) && preg_match('/.*(json|xml|csv|yml)\z/', $data))return response()->json(array('result'=>$data,'errorStatus'=>false), 200);
else return response()->json(array('result'=>'!','errorStatus'=>true,'error'=>'File d\'not converted.'), 200);
}
else return response()->json(array('result'=>'!','errorStatus'=>true,'error'=>'File d\'not recieved.'), 200);
}
}
| b7f9c4e55108dbfd1ba9a0141a0b33af5bc2f08d | [
"PHP"
] | 3 | PHP | gitMykola/test | 8248596634c7c1fd8a14709e6dc4119ea773bb57 | 27ed8f398b32209fa9396de6e862497d83c5553f |
refs/heads/master | <repo_name>massimo-me/SimpleCMS<file_sep>/src/CMS/CoreBundle/Document/User.php
<?php
namespace CMS\CoreBundle\Document;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* @MongoDB\Document
*/
class User extends BaseUser
{
/**
* @MongoDB\Id(strategy="auto")
*/
protected $id;
/**
* @MongoDB\String
*/
protected $name;
/**
* @MongoDB\String
*/
protected $phone;
public function __construct()
{
parent::__construct();
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
* @return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @return mixed
*/
public function getPhone()
{
return $this->phone;
}
/**
* @param mixed $phone
* @return $this
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
}
<file_sep>/src/CMS/CoreBundle/Document/SeoMetaData.php
<?php
namespace CMS\CoreBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* @MongoDB\Document()
*/
class SeoMetaData
{
/**
* @MongoDB\Id(strategy="auto")
*/
protected $id;
/**
* @MongoDB\String()
*/
protected $title;
/**
* @MongoDB\String()
*/
protected $description;
/**
* @MongoDB\String()
*/
protected $keywords;
/**
* @MongoDB\String()
*/
protected $robots;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* @return mixed
*/
public function getDescription()
{
return $this->description;
}
/**
* @return mixed
*/
public function getKeywords()
{
return $this->keywords;
}
/**
* @return mixed
*/
public function getRobots()
{
return $this->robots;
}
/**
* @param mixed $title
* @return $this
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* @param mixed $description
* @return $this
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* @param mixed $keywords
* @return $this
*/
public function setKeywords($keywords)
{
$this->keywords = $keywords;
return $this;
}
/**
* @param mixed $robots
* @return $this
*/
public function setRobots($robots)
{
$this->robots = $robots;
return $this;
}
public function __toString()
{
if (!$this->id) {
return 'New Seo Meta';
}
return $this->id;
}
}
<file_sep>/src/CMS/CoreBundle/Document/Page.php
<?php
namespace CMS\CoreBundle\Document;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* @MongoDB\Document()
*/
class Page
{
/**
* @MongoDB\Id(strategy="auto")
*/
protected $id;
/**
* @MongoDB\String()
*/
protected $title;
/**
* @MongoDB\String()
*/
protected $content;
/**
* @Gedmo\Timestampable(on="create")
* @MongoDB\Date()
*/
protected $created;
/**
*
* @Gedmo\Timestampable(on="update")
* @MongoDB\Date()
*/
protected $updated;
/**
* @MongoDB\String @MongoDB\Index(unique=true)
* @Gedmo\Slug(fields={"title"}, updatable=false)
*/
protected $slug;
/**
* @MongoDB\ReferenceOne(targetDocument="SeoMetaData", cascade="all", nullable=true)
*/
protected $seoMetaData;
/**
* @return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* @param mixed $title
* @return $this
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* @return mixed
*/
public function getContent()
{
return $this->content;
}
/**
* @param mixed $content
* @return $this
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* @return mixed
*/
public function getCreated()
{
return $this->created;
}
/**
* @param mixed $created
* @return $this
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* @return mixed
*/
public function getUpdated()
{
return $this->updated;
}
/**
* @param mixed $updated
* @return $this
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* @return mixed
*/
public function getSlug()
{
return $this->slug;
}
/**
* @param mixed $slug
* @return $this
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* @return mixed
*/
public function getSeoMetaData()
{
return $this->seoMetaData;
}
/**
* @param mixed $seoMetaData
* @return $this
*/
public function setSeoMetaData($seoMetaData)
{
$this->seoMetaData = $seoMetaData;
return $this;
}
public function __toString()
{
if ($this->title) {
return $this->title;
}
return 'New page';
}
public function getFirstImage()
{
preg_match("/\<img src=\"(.*?)\"(.*)\>/i", $this->getContent(), $matches);
if (array_key_exists(1, $matches)) {
return $matches[1];
}
return null;
}
}
<file_sep>/src/CMS/CoreBundle/Admin/SeoMetaData.php
<?php
namespace CMS\CoreBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
class SeoMetaData extends Admin
{
protected function configureFormFields(FormMapper $form)
{
$form
->add('title', null, [
'required' => false
])
->add('description', null, [
'required' => false
])
->add('keywords', null, [
'required' => false
])
->add('robots', null, [
'required' => false
])
;
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('title')
->add('description')
->add('keywords')
->add('robots')
->add('_action', 'actions', [
'actions' => [
'edit' => []
]
])
;
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('title')
->add('description')
->add('keywords')
->add('robots')
;
}
}
<file_sep>/src/CMS/CoreBundle/Controller/HomeController.php
<?php
namespace CMS\CoreBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class HomeController extends Controller
{
/**
* @Route("/", name="cms_core.home.show")
* @Template("CMSCoreBundle:Home:show.html.twig")
* @return array
*/
public function showAction()
{
return [
'base_dir' => $this->container->get('kernel')->getRootDir()
];
}
}
<file_sep>/README.md
SimpleCMS
=======================
##Install
git clone https://github.com/ChiarilloMassimo/SimpleCMS.git
composer install
app/console fos:user:create
app/console fos:user:promote
app/console server:run
##Route
- Home [http://127.0.0.1:8000/](http://127.0.0.1:8000/)
- Admin [http://127.0.0.1:8000/admin](http://127.0.0.1:8000/admin)
- SimplePage [http://127.0.0.1:8000/{slug}](http://127.0.0.1:8000/{slug})
##Already configured
- "symfony/symfony": "2.8.*"
- "symfony/assetic-bundle": "~2.3",
- "symfony/swiftmailer-bundle": "~2.3",
- "symfony/monolog-bundle": "~2.4",
- "sensio/distribution-bundle": "~4.0",
- "sensio/framework-extra-bundle": "^3.0.2",
- "incenteev/composer-parameter-handler": "~2.0",
- "doctrine/mongodb-odm": "1.0.*@dev",
- "doctrine/mongodb-odm-bundle": "3.0.*@dev",
- "friendsofsymfony/user-bundle": "~2.0@dev",
- "sonata-project/admin-bundle": "~2.3",
- "sonata-project/doctrine-mongodb-admin-bundle": "~2.3",
- "knplabs/knp-paginator-bundle": "~2.5",
- "stof/doctrine-extensions-bundle": "~1.2",
- "egeloen/ckeditor-bundle": "~3.0"
##Document
- Page
- SeoMetaData
- User
##Controller
- HomeController
- PageController
<file_sep>/src/CMS/CoreBundle/Admin/User.php
<?php
namespace CMS\CoreBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
class User extends Admin
{
protected function configureFormFields(FormMapper $form)
{
$form
->add('name')
->add('email')
->add('phone', null, [
'required' => false
])
->add('plainPassword', 'text', [
'label' => 'Password',
'required' => false
])
->setHelps([
'plainPassword' => '<PASSWORD>, enter a <PASSWORD>'
])
;
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('name')
->add('email')
->add('phone')
->add('_action', 'actions', [
'actions' => [
'edit' => []
]
])
;
}
public function preUpdate($object)
{
if (!$object->getPlainPassword()) {
return ;
}
$manipulator = $this->getConfigurationPool()->getContainer()->get('fos_user.util.user_manipulator');
$manipulator->changePassword($object->getUsername(), $object->getPlainPassword());
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('name')
->add('email')
->add('phone')
;
}
}<file_sep>/src/CMS/CoreBundle/Controller/PageController.php
<?php
namespace CMS\CoreBundle\Controller;
use CMS\CoreBundle\Document\Page;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
class PageController extends Controller
{
/**
* @Route("/{slug}", name="cms_core.page.show")
* @Template("CMSCoreBundle:Page:show.html.twig")
* @ParamConverter("page", class="CMSCoreBundle:Page", options={"mapping": {"slug" = "slug"}})
* @param Page $page
* @return array
*/
public function showAction(Page $page)
{
return [
'page' => $page
];
}
}
<file_sep>/src/CMS/CoreBundle/Admin/Page.php
<?php
namespace CMS\CoreBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
class Page extends Admin
{
protected $datagridValues = [
'_sort_order' => 'DESC',
'_sort_by' => 'created'
];
protected function configureFormFields(FormMapper $form)
{
$form
->with('Page')
->add('title')
->add('content', 'ckeditor', [
'config_name' => 'page'
])
->end()
;
if ($this->getSubject()) {
$form
->with('Route')
->add('slug', null, [
'required' => false
])
->end()
;
}
$form
->with('SEO')
->add('seoMetaData', 'sonata_type_model_list', [
'required' => false
])
->end()
;
$form->setHelps([
'slug' => "If you leave empty it will be automatically created from the page title.<br/><br/> <b>Example:</b> <br/> <b>Title</b>: This article <br/> <b>Slug</b>: this-article"
]);
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('title')
->add('slug')
->add('_action', 'actions', [
'actions' => [
'edit' => []
]
])
;
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('title')
->add('slug')
;
}
} | 6ff80b8f3c7dad7624dad2c44214ba1be5fda7ed | [
"Markdown",
"PHP"
] | 9 | PHP | massimo-me/SimpleCMS | fbe9392433f108379f9c3d52f93bf027ea51349b | b8bb45955fd5ee4095eca950d8a1645b9d855dec |
refs/heads/master | <file_sep>/* Instructions:
Add javadoc comments to all the fields and methods in Employee. Don't worry about making
them completely descriptive, but do document parameters and return values for the methods.
Note that judicious use of copy and paste can speed up the process.
Run javadoc and view index.html in a browser.
*/
package employees;
public class Employee {
/**
<code>nextID</code> holds the id of the next employee instance
*/
private static int nextID = 1;
/**
Stores the current next id value in this insance and increments <code>nextID</code>
*/
private int employeeID = nextID++;
/**
Stores the first name
*/
private String firstName;
/**
Stroes the last name
*/
private String lastName;
/**
Stores the department number
*/
private int dept;
/**
Stores the pay rate
*/
private double payRate;
/**
Constructs an empty employee
*/
public Employee() {}
/**
Constructs an Employee with first and last names
@param firstName the first name
@param lastName the last name
*/
public Employee(String firstName, String lastName) {
setFirstName(firstName);
setLastName(lastName);
}
/**
Constructs an Employee with first and last names, and department number
@param firstName the first name
@param lastName the last name
@param dept the department number
*/
public Employee(String firstName,String lastName, int dept) {
this(firstName, lastName);
setDept(dept);
}
/**
Constructs an Employee with first and last names, department number,
and pay rate
@param firstName the first name
@param lastName the last name
@param payRate the pay rate
*/
public Employee(String firstName, String lastName, double payRate) {
this(firstName, lastName);
setPay(payRate);
}
/**
Constructs an Employee with first and lsst names, department number,
and pay rate
@param firstName the first name
@param lastName the last name
@param dept the department number
@param payRate the pay rate
*/
public Employee(String firstName, String lastName,
int dept, double payRate) {
this(firstName, lastName, dept);
setPay(payRate);
}
/**
Retrieves the id
@return the id
*/
public int getID() {
return employeeID;
}
/**
Retrieves the first name
@return the first name
*/
public String getFirstName() {
return firstName;
}
/**
Retrieves the last name
@return the last name
*/
public String getLastName() {
return lastName;
}
/**
Retrieves the department
@return the department
*/
public int getDept() {
return dept;
}
/**
Retrieves the pay rate
@return the pay rate
*/
public double getPayRate() {
return payRate;
}
/**
Retrieves a pay information string
@return a String with the pay information
*/
public String getPayInfo() {
return (getFullName() + " " + employeeID + " " + dept + " " + payRate);
}
/**
Retrieves the full name as first name and last name separated by a space
@return the full name
*/
public String getFullName() {
return (firstName + " " + lastName);
}
/**
Sets the first name
@param firstName the first name
*/
public void setFirstName(String fn) {
firstName = fn;
}
/**
Sets the last name
@param lastName the last name
*/
public void setLastName(String ln) {
lastName = ln;
}
/**
Sets the department
@param dept the department
*/
public void setDept(int x) {
if(0 < x) dept = x;
}
/**
Sets the pay rate
@param payRate the pay rate
*/
public void setPay(double p) {
if(0 <= p) payRate = p;
}
/**
Retrieves the next id
@return the nextId value
*/
public static int getNextId() {
return nextID;
}
/**
Retrieves the next id
@return the nextId value
*/
public static void setNextId(int nextId) {
Employee.nextID = nextId;
}
}<file_sep>/* Instructions:
Modify your Employee class to use a constructor that accepts parameters for the first and last names, department, and pay rate.
Also add a constructor that takes no parameters and does nothing (as we discussed above).
public Employee() { }
In Payroll, modify main to add another Employee variable that receives an instance created using this constructor, then print their pay info.
*/
public class Employee {
// fields
private int employeeID = 0;
private String firstName;
private String lastName;
private int dept;
private double payRate;
// Constructor
public Employee() {}
public Employee(String n1, String n2, int dpt, double pr) {
firstName = n1;
lastName = n2;
dept = dpt;
payRate = pr;
}
// return ID
public int getID() {
return employeeID;
}
// return employee first name
public String getFirstName() {
return firstName;
}
// return employee last name
public String getLastName() {
return lastName;
}
// return department number
public int getDept() {
return dept;
}
//return pay rate
public double getPayRate() {
return payRate;
}
// return a sentence with the employee's name, id, department, and pay amount
public String getPayInfo() {
return (firstName + " " + lastName + " " + " " + employeeID + " " + dept + " " + payRate);
}
// return the first and last names separated by a space
public String getFullName() {
return (firstName + " " + lastName);
}
// set first name
public void setFirstName(String fn) {
firstName = fn;
}
// set last name
public void setLastName(String ln) {
lastName = ln;
}
// set department number
public void setDept(int x) {
dept = x;
}
// set pay rate
public void setPay(double p) {
payRate = p;
}
}<file_sep>/*
Instructions:
Revise the number guessing program to force the user to guess
until they are correct (loop-wise, to keep guessing as long as they are incorrect).
Then add more logic to ask if they want to play again, read a Y or N
as their answer, and loop as long as they enter a Y.
*/
import util.*;
import java.util.*;
public class Game {
private Random r = new Random();
private int answer = r.nextInt(100) + 1;
private int range = 10;
public Game(){
this('I');
}
public Game(char level){
switch(level){
default:
System.out.println("Invalid option: " + level +
", using beginner.");
case 'b':
case 'B':
range = 10;
break;
case 'i':
case 'I':
range = 100;
case 'a':
case 'A':
range = 1000;
break;
}
Random r = new Random();
int answer = r.nextInt(range) + 1;
}
public void play() {
int guess;
do {
guess = KeyboardReader.getPromptedInt("Enter a number 1 - " + range + ": ");
if (guess < answer) System.out.println("Too low");
else if (guess > answer) System.out.println("Too high");
} while(guess != answer);
System.out.println("Correct!");
}
public static void main(String[] args){
char playAgain = 'Y';
do {
char level = KeyboardReader.getPromptedChar("What level (B, I, A)? ");
new Game(level).play();
playAgain = KeyboardReader.getPromptedChar("Play again (Y/N)? ");
} while(playAgain == 'Y' || playAgain == 'y');
}
}<file_sep>package employees;
public class ExemptEmployee extends Employee {
/**
Constructs an empty ExemptEmployee
*/
public ExemptEmployee() {}
/**
Constructs an ExemptEmployee with first and last names
@param firstName the first name
@param lastName the last name
*/
public ExemptEmployee(String firstName, String lastName) {
super(firstName, lastName);
}
/**
Constructs an ExemptEmployee with first and last names, and department number
@param firstName the first name
@param lastName the last name
@param dept the department number
*/
public ExemptEmployee(String firstName,String lastName, int dept) {
super(firstName, lastName, dept);
}
/**
Constructs an ExemptEmployee with first and last names, department number,
and pay rate
@param firstName the first name
@param lastName the last name
@param payRate the pay rate
*/
public ExemptEmployee(String firstName, String lastName, double payRate) {
super(firstName, lastName, payRate);
}
/**
Constructs an ExemptEmployee with first and lsst names, department number,
and pay rate
@param firstName the first name
@param lastName the last name
@param dept the department number
@param payRate the pay rate
*/
public ExemptEmployee(String firstName, String lastName,
int dept, double payRate) {
super(firstName, lastName, dept, payRate);
}
/**
Retrieves a pay information string
@return a String with the pay information
*/
public String getPayInfo() {
return (getFullName() + " " + getID() + " " + getDept() + " " + getPayRate());
}
}<file_sep>/* Instructions:
Create a package called employees; put the Employee.java file into this package (leave Payroll where it is).
This will require not only creating the directory and moving the file, but also adding an import statement to
Payroll and a package statement to Employee.
Also, if Employee.class still exists in the original directory, it's presence may cause compilation problems -
delete Employee.class (the IDE's call this doing a clean) .
To compile, start in the project root directory (the directory containing Payroll).
If you compile Payroll as usual, it will also find and compile Employee.
To compile just Employee, you would still work in the project root directory, but execute.
javac employees\Employee.java
Run Payroll in the usual fashion.
*/
package employees;
public class Employee {
// fields
private static int nextID = 1;
private int employeeID = nextID++;
private String firstName;
private String lastName;
private int dept;
private double payRate;
// Constructor
public Employee() {}
public Employee(String firstName, String lastName) {
setFirstName(firstName);
setLastName(lastName);
}
public Employee(String firstName,String lastName, int dept) {
this(firstName, lastName);
setDept(dept);
}
public Employee(String firstName, String lastName, double payRate) {
this(firstName, lastName);
setPay(payRate);
}
public Employee(String firstName, String lastName,
int dept, double payRate) {
this(firstName, lastName, dept);
setPay(payRate);
}
// return ID
public int getID() {
return employeeID;
}
// return employee first name
public String getFirstName() {
return firstName;
}
// return employee last name
public String getLastName() {
return lastName;
}
// return department number
public int getDept() {
return dept;
}
//return pay rate
public double getPayRate() {
return payRate;
}
// return a sentence with the employee's name, id, department, and pay amount
public String getPayInfo() {
return (getFullName() + " " + employeeID + " " + dept + " " + payRate);
}
// return the first and last names separated by a space
public String getFullName() {
return (firstName + " " + lastName);
}
// set first name
public void setFirstName(String fn) {
firstName = fn;
}
// set last name
public void setLastName(String ln) {
lastName = ln;
}
// set department number
public void setDept(int x) {
dept = x;
}
// set pay rate
public void setPay(double p) {
payRate = p;
}
public static int getNextId() {
return nextID;
}
public static void setNextId(int nextId) {
Employee.nextID = nextId;
}
}<file_sep>public class Hello {
public static void main(String[] args) {
for(int i = 0; i < args.length; i++){
System.out.println(args[i]);
}
//for each option
for(String a : args) {
System.out.println(a);
}
}
}<file_sep>public class Calculator{
public static double add(double x, double y){
return x + y;
}
public static double subtract(double x, double y){
return x - y;
}
public static double multiply(double x, double y){
return x * y;
}
public static double divide(double x, double y){
return x / y;
}
public static void main(String[] args){
double a = 7, b = 2, c;
c = add(a, b);
System.out.println(a + " + " + b + " = " + c);
c = subtract(a, b);
System.out.println(a + " - " + b + " = " + c);
c = multiply(a, b);
System.out.println(a + " * " + b + " = " + c);
c = divide(a, b);
System.out.println(a + " / " + b + " = " + c);
}
}<file_sep>import employees.*;
import util.*;
/**
* Tests the {@link Employee} class.
*/
public class Payroll {
public static void main(String[] args) {
Employee e1 = new Employee();
e1.setFirstName("John");
e1.setLastName("Doe");
e1.setDept(23);
e1.setPay(21.78);
Employee e2 = new Employee("Jane", "Smith", 3, 33.22);
Employee e3 = new Employee("Joe", "Dirt", 55);
Employee e4 = new Employee("Mary", "Sue", 13.43);
String fn = KeyboardReader.getPromptedString("Please enter first name: ");
String ln = KeyboardReader.getPromptedString("Please enter last name: ");
double pay = KeyboardReader.getPromptedDouble("Please enter pay rate: ");
int dept = KeyboardReader.getPromptedInt("Please enter department number: ");
Employee e5 = new Employee(fn, ln, dept, pay);
System.out.println(e1.getPayInfo());
System.out.println(e2.getPayInfo());
System.out.println(e3.getPayInfo());
System.out.println(e4.getPayInfo());
System.out.println(e5.getPayInfo());
}
} <file_sep>/* Instructions:
Add more Employee constructors:
One that takes values for first and last names only.
One that takes values for first name, last name, and department.
One that takes values for first name, last name, and pay rate.
Note that, in practice, you can use the parameter lists for constructors to help enforce what you would consider valid combinations of properties - for example, if you would not want an employee to exist in a state where they had name and department information, but no pay rate, then the absence of that particular constructor would help ensure that
judicious use of copy-paste-edit can speed up this process, but be careful to make every necessary edit if you do this!
You will find yourself writing somewhat repetitive code, setting the same values the same way in several different constructors - we will address this in a few pages.
In Payroll, create and pay additional instances using these constructors.
*/
public class Employee {
// fields
private int employeeID = 0;
private String firstName;
private String lastName;
private int dept;
private double payRate;
// Constructor
public Employee() {}
public Employee(String n1, String n2, int dpt, double pr) {
firstName = n1;
lastName = n2;
dept = dpt;
payRate = pr;
}
public Employee(String first, String last) {
firstName = first;
lastName = last;
}
public Employee(String first, String last, int d) {
firstName = first;
lastName = last;
dept = d;
}
public Employee(String first, String last, double pay) {
firstName = first;
lastName = last;
payRate = pay;
}
// return ID
public int getID() {
return employeeID;
}
// return employee first name
public String getFirstName() {
return firstName;
}
// return employee last name
public String getLastName() {
return lastName;
}
// return department number
public int getDept() {
return dept;
}
//return pay rate
public double getPayRate() {
return payRate;
}
// return a sentence with the employee's name, id, department, and pay amount
public String getPayInfo() {
return (firstName + " " + lastName + " " + " " + employeeID + " " + dept + " " + payRate);
}
// return the first and last names separated by a space
public String getFullName() {
return (firstName + " " + lastName);
}
// set first name
public void setFirstName(String fn) {
firstName = fn;
}
// set last name
public void setLastName(String ln) {
lastName = ln;
}
// set department number
public void setDept(int x) {
dept = x;
}
// set pay rate
public void setPay(double p) {
payRate = p;
}
}<file_sep>/*
Instructions:
Revise your payroll program to use only one Employee variable.
Use a loop to repeatedly create a new instance to store in it,
populate it from the keyboard, and display it on the screen
(you can ask after each one if the user wants to enter another, or
just use a loop that has a fixed number of iterations).
Also, change the logic for reading the pay rate and department values
from the keyboard to use do . . . while loops that will continue to loop
as long as the user enters invalid values (note that you will need to
separate declaring the variables from populating them - declare each of them
before their loop starts, in order for the variable to be available to the test
at the end of the loop).
*/
import employees.*;
import util.*;
/**
* Tests the {@link Employee} class.
*/
public class Payroll {
public static void main(String[] args) {
Employee e = null;
String fn;
String ln;
int dept;
double pay;
for(int i = 0; i < 3; i++){
fn = KeyboardReader.getPromptedString("Enter first name: ");
ln = KeyboardReader.getPromptedString("Enter last name: ");
do {
pay = KeyboardReader.getPromptedDouble("Enter pay rate: ");
if(pay < 0.0) System.out.println("Pay rate must be greater than or equal to 0.0");
} while(pay < 0.0);
do {
dept = KeyboardReader.getPromptedInt("Please enter department number: ");
if(dept <= 0) System.out.println("Department must be greater than 0");
}while(dept <= 0);
e = new Employee(fn, ln, dept, pay);
System.out.println(e.getPayInfo());
}
}
} | 84a85d01e52ce670488d5e8b7bc4ff31e8f6f43e | [
"Java"
] | 10 | Java | CSchrisD/Java-Practice | 655863f818642056b98a151ba7d1ad605925ab5a | 99d02a6b5652f8d93e7c6a6d85e557be76d85c62 |
refs/heads/master | <file_sep>spring.application.name=carshare-usersservice<file_sep>package be.harm.carshare.users.security.authentication.token;
import be.harm.carshare.users.security.authentication.AuthenticatedUser;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Calendar;
import java.util.Date;
import java.util.Optional;
@Service
public final class JwtTokenService implements TokenService {
@Value("${carshare.users.jwt.secret}")
private String tokenSecret;
@Override
public String createToken(AuthenticatedUser user) {
Algorithm tokenEncryptionAlgorithm = Algorithm.HMAC256(tokenSecret);
final Date now = new Date();
return JWT.create()
.withSubject(user.getUsername())
.withIssuedAt(now)
.withExpiresAt(getExpirationDate(now))
.sign(tokenEncryptionAlgorithm);
}
/**
* @return the name of the verified user
*/
@Override
public Optional<String> verify(String token) {
Algorithm tokenEncryptionAlgorithm = Algorithm.HMAC256(tokenSecret);
JWTVerifier verifier = JWT.require(tokenEncryptionAlgorithm).build();
try {
DecodedJWT decodedToken = verifier.verify(token);
return Optional.of(decodedToken.getSubject());
} catch (JWTVerificationException verificationException) {
return Optional.empty();
}
}
private Date getExpirationDate(Date start) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(start);
calendar.add(Calendar.DATE, 1);
return calendar.getTime();
}
}
<file_sep>package be.harm.carshare.users.user;
import be.harm.carshare.users.security.authentication.AuthenticatedUser;
import be.harm.carshare.users.security.authentication.token.TokenService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Set;
import static org.springframework.http.ResponseEntity.created;
import static org.springframework.http.ResponseEntity.ok;
@RestController
@RequestMapping("users")
public class UserRestController {
private final UserService userService;
private final TokenService tokenService;
public UserRestController(UserService userService, TokenService tokenService) {
this.userService = userService;
this.tokenService = tokenService;
}
@GetMapping("")
public ResponseEntity<Set<User>> getUsers() {
return ok(userService.findAll());
}
@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
return ok(userService.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)));
}
@PutMapping("/{id}")
@PreAuthorize("#user.getId() == #id")
public ResponseEntity<String> updateUser(
@AuthenticationPrincipal AuthenticatedUser user,
@PathVariable Long id,
@RequestBody User updatedUser,
BindingResult bindingResult,
HttpServletRequest request
) {
var savedUser = userService.updateUser(updatedUser);
return ok(ServletUriComponentsBuilder
.fromContextPath(request)
.path("users/{id}")
.buildAndExpand(savedUser.getId().toString())
.toUri().toString());
}
@PostMapping("")
public ResponseEntity<String> registerUser(
@Valid @RequestBody User user,
BindingResult bindingResult,
HttpServletRequest request
) {
if (bindingResult.hasErrors()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
} else {
var savedUser = userService.saveUser(user);
return created(ServletUriComponentsBuilder
.fromContextPath(request)
.path("users/{id}")
.buildAndExpand(savedUser.getId().toString())
.toUri())
.build();
}
}
@RequestMapping("/verify")
/*
* Checks if the given [token] is currently valid.
*/
public ResponseEntity<?> verify(@RequestParam String token) {
if (tokenService.verify(token).isPresent()) {
return ResponseEntity.status(HttpStatus.OK).build();
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
}
<file_sep># Car Share
Application for a car-sharing platform.
## Functionalities
* Users can register
* Users can update their information
* Users can login, logout
* Users can send an application to add a new car to the system.
* Users can make a reservation for a car
* Users can cancel a reservation for a car
* Users can shorten a reservation for a car
* Users can register a finished reservation (number of km ridden + optional fuel fill-up registration)
* Admins can approve an application for a new car.
* The platform can send an quarterly invoice for all the reservations in that quarter.
## Domain model / rules
* A user can have 0 or more cars registered in the system
* A car is tied to 1 user.
* A reservation is always for 1 car
* Reservations cannot overlap
* Cost of a reservation: 30c/km for the first 100 km, 25c/km for all kilometers after the first 100.
* User can only make a reservation if their profile is complete
<file_sep>package be.harm.carshare.users.user;
import java.util.Optional;
import java.util.Set;
public interface UserService {
Set<User> findAll();
Optional<User> findById(Long id);
User saveUser(User user);
User saveAdmin(User user);
User updateUser(User user);
}
<file_sep>spring.cloud.config.username=configUser
spring.cloud.config.password=<PASSWORD>
spring.cloud.config.fail-fast=true
spring.cloud.config.discovery.service-id=carshare-configserver
<file_sep>package be.harm.carshare.users.testutil;
import org.springframework.security.test.context.support.WithSecurityContext;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class)
public @interface WithMockCustomUser {
String username() default "Xander";
String password() default "<PASSWORD>";
long id();
}
<file_sep>package be.harm.carshare.users.user;
import be.harm.carshare.users.user.security.ApplicationRole;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.security.crypto.password.PasswordEncoder;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
class UserJPAServiceTest {
@Mock
private PasswordEncoder passwordEncoder;
@Mock
private UserRepository userRepository;
@InjectMocks
private UserJPAService userJPAService;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
// Thoughts: change to dummy implementations?
when(passwordEncoder.encode(anyString())).then(returnsFirstArg());
when(userRepository.save(any(User.class))).then(returnsFirstArg());
}
@Test
void shouldGiveNewAdminAdminRights() {
// Given
User user = new User("Username", "Wachtwoord1");
// When
User resultingUser = userJPAService.saveAdmin(user);
// Then
assertEquals(1, resultingUser.getRoles().size());
assertTrue(resultingUser.getRoles().stream()
.anyMatch((role -> role == ApplicationRole.ADMIN)));
}
@Test
void shouldGiveNewUserOnlyPlayerRights() {
// Given
User user = new User("Username", "Wachtwoord1");
// When
User resultingUser = userJPAService.saveUser(user);
// Then
assertEquals(1, resultingUser.getRoles().size());
assertTrue(resultingUser.getRoles().stream()
.anyMatch((role -> role == ApplicationRole.USER)));
}
}<file_sep>package be.harm.carshare.users;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CarshareUsersApplication {
public static void main(String[] args) {
SpringApplication.run(CarshareUsersApplication.class, args);
}
}
<file_sep>package be.harm.carshare.users;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
@SpringBootTest
@ActiveProfiles("local")
@TestPropertySource(properties = {"carshare.users.jwt.secret=secret"})
class CarshareUsersApplicationTests {
@Test
void contextLoads() {
}
}
<file_sep>spring.datasource.url=jdbc:h2:mem:testdb
server.port=18081
application.adminUserName=AdminUser
application.adminUserPassword=<PASSWORD>
carshare.users.jwt.secret=localtestingsecret
logging.level.org.springframework.security=DEBUG<file_sep>spring.cloud.config.discovery.enabled=true
spring.cloud.config.enabled=true
eureka.client.service-url.defaultZone=http://eurekaUser:eurekaUserPassword@eureka:8761/eureka | 54c3c419e7214328db7194749411e2163ad44d4d | [
"Markdown",
"Java",
"INI"
] | 12 | INI | hdeweirdt/carshare-users | 07284574877191134e4e2bda3c3d66e590c7bdc5 | 5151e4308fc4912c956c13ec0506cccc9aff0447 |
refs/heads/master | <repo_name>buggithubs/tidb-inspect-tools<file_sep>/metrics/snapshot-collector/util.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/juju/errors"
"github.com/ngaut/log"
"io"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"runtime"
"strings"
"time"
)
const (
//LoginPath grafana login path
LoginPath = "/login"
//DashboardAPI grafana dashboards
DashboardAPI = "/api/search?query="
//DashboardAPIPrefix grafana dashboard detail
DashboardAPIPrefix = "/api/dashboards/"
//DashboardDatasource grafana datasource
DashboardDatasource = "/api/datasources"
//DatasourceProxy grafana request prometheus proxy
DatasourceProxy = "/api/datasources/proxy/"
//PrometheusMatchAPI prometheus match api
PrometheusMatchAPI = "/api/v1/series?match[]="
//CreateHTTPClientTimeout http timeout
CreateHTTPClientTimeout = 15
//TemplateVar panel templating variables
TemplateVar = "Host"
//PanelsAllInOnePicturePoint delimit one picture informations
PanelsAllInOnePicturePoint = 30
//PngDir save images directory
PngDir = "PngDir"
//TimeFormat time format
TimeFormat = "2006-01-02 15:04:05"
)
//Dashboard informations
type Dashboard struct {
TemplateVar string
Host []string
URI string
title string
ID int64
DataSourceID int64
DataSourceType string
Panels []Panel
}
//Panel informations
type Panel struct {
Title string
ID int64
URL string
}
//URL redner images struct
type URL struct {
Title string
URL string
}
//InitDashboard init struct
func InitDashboard() *Dashboard {
return &Dashboard{
DataSourceType: "prometheus",
DataSourceID: 1,
}
}
//NewSession crate http client
func NewSession() (*http.Client, error) {
jar, err := cookiejar.New(nil)
if err != nil {
return nil, err
}
return &http.Client{
Jar: jar,
Timeout: time.Second * CreateHTTPClientTimeout,
}, nil
}
//LoginGrafana login granfana
func (r *Run) LoginGrafana() (err error) {
jsonData, jerr := json.Marshal(r)
if jerr != nil {
return jerr
}
_, err = r.XHttp("POST", fmt.Sprintf("%s%s", r.url, LoginPath), bytes.NewBuffer(jsonData))
return err
}
//XHttp http
func (r *Run) XHttp(method string, url string, body io.Reader) ([]byte, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
for i := 0; i < 3; i++ {
resp, err := r.client.Do(req)
if err != nil && i == 2 {
return nil, err
}
if err == nil && resp.StatusCode == 200 {
return ioutil.ReadAll(resp.Body)
}
}
return nil, errors.Errorf("can not request url %s", url)
}
//Xget http get
func (r *Run) Xget(url string) (interface{}, error) {
d, err := r.XHttp("GET", url, nil)
if err != nil {
return nil, err
}
var iface interface{}
errJ := json.Unmarshal(d, &iface)
return iface, errJ
}
//HandlerRequestURL handler offer URL to render
func (r *Run) HandlerRequestURL() error {
u, err := url.Parse(r.requestRenderURL)
if err != nil {
return err
}
r.url = fmt.Sprintf("%s://%s", u.Scheme, u.Host)
uPath := strings.Split(u.Path, "/")
u.Path = fmt.Sprintf("/render%s", u.Path)
return r.AddImageURL(fmt.Sprintf("%s_%d", uPath[len(uPath)-1], time.Now().UnixNano()), u.String())
}
//GetDashboards http get dashboards
func (r *Run) GetDashboards() error {
// http://192.168.2.188:3000/api/search?query=
iface, err := r.Xget(fmt.Sprintf("%s%s", r.url, DashboardAPI))
if err != nil {
return err
}
r.JSONData(iface, InitDashboard())
return nil
}
//JSONData handle http json data
func (r *Run) JSONData(iface interface{}, dash *Dashboard) {
// dashboard, rows, panels handle dashboard json
// templating, list handle template variables
// data options from [templating, list]
loopKey := []string{"dashboard", "rows", "panels", "templating", "list", "data"}
switch s := iface.(type) {
case map[string]interface{}:
// handler dashboards
if _, ok := s["uri"]; ok && dash.URI == "" {
d := InitDashboard()
d.URI = s["uri"].(string)
d.ID = int64(s["id"].(float64))
d.title = stringReplacer.Replace(s["title"].(string))
r.dashboards = append(r.dashboards, d)
}
for _, key := range loopKey {
if _, ok := s[key]; ok {
r.JSONData(s[key], dash)
}
}
//handler templating map, get label query info
label, okLabel := s["label"]
query, okQuery := s["query"]
if okLabel && okQuery && reflect.ValueOf(label) != reflect.ValueOf(nil) && label.(string) == TemplateVar {
//such like label_values(node_disk_reads_completed, instance)
dash.TemplateVar = regexp.MustCompile("[(,]").Split(query.(string), -1)[1]
}
//handler panels map, get panel info
title, okTitle := s["title"]
id, okID := s["id"]
if (okTitle && okID && title.(string) != "") &&
(r.name == "" || stringReplacer.Replace(r.name) == stringReplacer.Replace(title.(string))) {
dash.Panels = append(dash.Panels, Panel{
Title: stringReplacer.Replace(title.(string)),
ID: int64(id.(float64)),
})
}
//handler option variables, get host list
if _, okInstance := s["instance"]; okInstance {
h := s["instance"].(string)
if len(dash.Host) == 0 {
dash.Host = append(dash.Host, h)
}
for i, host := range dash.Host {
if host == h {
break
}
if i == len(dash.Host)-1 {
dash.Host = append(dash.Host, h)
}
}
}
case []interface{}:
for _, sub := range s {
r.JSONData(sub, dash)
}
}
}
//GetDashboardPanels http panels
func (r *Run) GetDashboardPanels() error {
for _, dash := range r.dashboards {
if r.requestDashboard != "" && r.requestDashboard != dash.title {
continue
}
// http://192.168.2.188:3000/api/dashboards/db/test-cluster-disk-performance
iface, err := r.Xget(fmt.Sprintf("%s%s%s", r.url, DashboardAPIPrefix, dash.URI))
if err != nil {
return err
}
r.JSONData(iface, dash)
if dash.TemplateVar != "" {
// http://192.168.2.188:3000/api/datasources/proxy/1/api/v1/series?match[]=node_disk_reads_completed&start=1511935611&end=1511939211
ifaceHost, errHost := r.Xget(fmt.Sprintf("%s%s%d%s%s&start=%d&end=%d",
r.url, DatasourceProxy, dash.DataSourceID, PrometheusMatchAPI, dash.TemplateVar, r.from, r.to))
if errHost != nil {
return errHost
}
r.JSONData(ifaceHost, dash)
}
}
return nil
}
//PrefixWork prefixWork
func (r *Run) PrefixWork() error {
workDir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return err
}
r.pngDir = filepath.Join(workDir, PngDir)
if _, err := os.Stat(r.pngDir); os.IsNotExist(err) {
return os.Mkdir(r.pngDir, 0774)
}
return nil
}
//GenerateURL generate image url
func (r *Run) GenerateURL() error {
for _, d := range r.dashboards {
baseURL := fmt.Sprintf("%s/render/dashboard/%s?from=%d&to=%d&width=%d&height=%d&timeout=%d&tz=%s",
r.url, d.URI, r.from, r.to, r.width, r.height, r.timeout, r.tz)
// all of panels less than PanelsAllInOnePicturePoint, generate one picture
if len(d.Panels) < PanelsAllInOnePicturePoint && len(d.Host) > 1 {
for _, h := range d.Host {
r.AddImageURL(fmt.Sprintf("%s_%s", d.title, h), fmt.Sprintf("%s&var-host=%s", baseURL, h))
}
} else if len(d.Panels) < PanelsAllInOnePicturePoint {
r.AddImageURL(d.title, baseURL)
} else {
for _, p := range d.Panels {
r.AddImageURL(fmt.Sprintf("%s_%s", d.title, p.Title), fmt.Sprintf("%s&panelId=%d&fullscreen", baseURL, p.ID))
}
}
}
return nil
}
//AddImageURL add url
func (r *Run) AddImageURL(title string, url string) error {
r.imageURLs <- URL{
Title: title,
URL: url,
}
return nil
}
//GetRenderImages get redner images
func (r *Run) GetRenderImages() {
for p := range r.imageURLs {
log.Infof("remain image %d, get %s render image...", len(r.imageURLs), p.Title)
data, err := r.XHttp("GET", p.URL, nil)
if err != nil {
log.Errorf("http get url %s render image error %v", p.URL, err)
continue
}
if err := r.SaveImage(p.Title, data); err != nil {
log.Errorf("write image file error %v", err)
}
}
}
//SaveImage save image
func (r *Run) SaveImage(title string, data []byte) error {
dstImage := filepath.Join(r.pngDir, fmt.Sprintf("%s.png", title))
return ioutil.WriteFile(dstImage, data, 0666)
}
//GetCPUNum get cpu number
func GetCPUNum() int {
return runtime.NumCPU()
}
<file_sep>/metrics/snapshot-collector/README.md
metrics-snapshot-collector
------
**This tool is used to capture screenshots of grafana**
### Preparation
- **Make sure grafana server has shared object file `libfontconfig.so.1`**
- debian/ubuntu:
- `apt-get install -y libfontconfig freetype-devel fontconfig-devel fontconfig`
- centos:
- `yum install -y fontconfig freetype freetype-devel fontconfig-devel libstdc++`
- **Make sure grafana server has fonts installed for English**
- to list the fonts support English:
- `fc-list :lang=en`
- if the output is empty, you will need to install at least one font that supports English, here is an example of install Google Fonts on Linux servers:
- `cd`
- `wget -O Open_Sans.zip https://fonts.google.com/download?family=Open%20Sans`
- `unzip -d Open_Sans Open_Sans.zip`
- `sudo cp -rvf Open_Sans /usr/share/fonts`
- `sudo fc-cache -fv`
- centos:
- `sudo yum install -y open-sans-fonts`
### Build
- install Golang(1.8.3+)
- `make`
**The target executable binary file is bin/metrics-snapshot-collector**
### Usages
```
Usage of ./bin/metrics-snapshot-collector:
-address string
grafana address (default "http://192.168.2.188:3000")
-dashboard string
dashboard name
-end string
end time,default is now (default "2017-12-04 10:20:34")
-name string
panel name
-password string
grafana password (default "<PASSWORD>")
-renderurl string
render url
-start string
start time, default is 3 days ago (default "2017-12-01 10:20:34")
-timeout int
execute query timeout[second] (default 60)
-user string
grafana user (default "admin")
```
### Examples:
- collect all panels
- `./metrics-snapshot-collector -address "http://192.168.2.188:3000" -user "admin" -password="<PASSWORD>" -start "2017-12-01 10:20:34" -end "2017-12-04 10:20:34"`
- collect all panels of the `Test-Cluster-TiKV` dashboard
- `./snapshot-collector -address "http://192.168.2.188:3000" -user "admin" -password="<PASSWORD>" -dashboard "Test-Cluster-TiKV"`
- collect one panel by URL
- `./metrics-snapshot-collector -user "admin" -password="<PASSWORD>" -renderurl "http://192.168.2.188:3000/dashboard/db/test-cluster-disk-performance?panelId=11&fullscreen&orgId=1"`
- collect one panel by name
- `./metrics-snapshot-collector -address "http://192.168.2.188:3000" -user "admin" -password="<PASSWORD>" -name "Disk Latency"`
<file_sep>/metrics/snapshot-collector/snapshot-collector.go
package main
import (
"github.com/ngaut/log"
"sync"
)
func main() {
r, err := InitRun()
if err != nil {
log.Errorf("can not init,error %v", err)
return
}
if err := r.PreData(); err != nil {
log.Errorf("get error %v", err)
return
}
var wg sync.WaitGroup
for i := 0; i < GetCPUNum(); i++ {
wg.Add(1)
go func() {
r.GetRenderImages()
wg.Done()
}()
}
wg.Wait()
}
<file_sep>/metrics/snapshot-collector/Makefile
GO=GO15VENDOREXPERIMENT="1" CGO_ENABLED=0 go
GOTEST=GO15VENDOREXPERIMENT="1" CGO_ENABLED=1 go test # go race detector requires cgo
PACKAGES := $$(go list ./...| grep -vE 'vendor')
GOFILTER := grep -vE 'vendor|render.Delims|bindata_assetfs|testutil'
GOCHECKER := $(GOFILTER) | awk '{ print } END { if (NR > 0) { exit 1 } }'
LDFLAGS += -X "github.com/pingcap/tidb-inspector-tools/util.BuildTS=$(shell date -u '+%Y-%m-%d %I:%M:%S')"
LDFLAGS += -X "github.com/pingcap/tidb-inspector-tools/util.GitHash=$(shell git rev-parse HEAD)"
GOBUILD=$(GO) build -ldflags '$(LDFLAGS)'
default: metrics-snapshot-collector
all: check test metrics-snapshot-collector
metrics-snapshot-collector:
$(GOBUILD) -o bin/metrics-snapshot-collector *.go
test:
$(GOTEST) --race $(PACKAGES)
check:
go get github.com/golang/lint/golint
@echo "vet"
@ go tool vet . 2>&1 | $(GOCHECKER)
@ go tool vet --shadow . 2>&1 | $(GOCHECKER)
@echo "golint"
@ golint ./... 2>&1 | $(GOCHECKER)
@echo "gofmt"
@ gofmt -s -l . 2>&1 | $(GOCHECKER)
clean:
@rm -rf bin/*
.PHONY: all test clean metrics-snapshot-collector
<file_sep>/metrics/snapshot-collector/grafanarender.go
package main
import (
"flag"
"github.com/araddon/dateparse"
"github.com/juju/errors"
"github.com/ngaut/log"
"net/http"
"strings"
"time"
)
//Run base struct
type Run struct {
client *http.Client
dashboards []*Dashboard
imageURLs chan URL
User string `json:"user"`
Password string `json:"<PASSWORD>"`
url string
from int64
to int64
tz string
width int64
height int64
timeout int64
name string
pngDir string
requestDashboard string
requestRenderURL string
}
var (
addr = flag.String("address", "http://192.168.2.188:3000", "input grafana address")
from = flag.String("start", time.Now().AddDate(0, 0, -3).Format(TimeFormat), "input start time, default is 3 days ago")
to = flag.String("end", time.Now().Format(TimeFormat), "input end time,default is now")
name = flag.String("name", "", "input panel name")
timeout = flag.Int64("timeout", 60, "input execute query timeout")
user = flag.String("user", "admin", "input granfana user")
password = flag.String("password", "<PASSWORD>", "input granfana password")
dashboard = flag.String("dashboard", "", "input dashboard name")
renderURL = flag.String("renderurl", "", "input render url")
stringReplacer = strings.NewReplacer(" ", "_", "/", "_", "\\", "_")
)
//InitRun init struct
func InitRun() (*Run, error) {
flag.Parse()
log.Infof("init..")
c, err := NewSession()
if err != nil {
return nil, errors.Errorf("create http client with error %v", err)
}
ft, err := dateparse.ParseAny(*from)
if err != nil {
return nil, errors.Errorf("start time is error %v", err)
}
et, err := dateparse.ParseAny(*to)
if err != nil {
return nil, errors.Errorf("end time is error %v", err)
}
tz, _ := time.Now().Zone()
return &Run{
client: c,
imageURLs: make(chan URL, 10000),
width: 1980,
height: 1080,
timeout: *timeout,
from: ft.UnixNano() / 1000000,
to: et.UnixNano() / 1000000,
tz: tz,
name: stringReplacer.Replace(*name),
User: *user,
Password: <PASSWORD>,
url: *addr,
requestDashboard: stringReplacer.Replace(*dashboard),
requestRenderURL: *renderURL,
}, nil
}
//PreData prepare data
func (r *Run) PreData() error {
log.Infof("prepare data start...")
if err := r.PrefixWork(); err != nil {
return err
}
if r.requestRenderURL != "" {
log.Infof("handler render url...")
if err := r.HandlerRequestURL(); err != nil {
return err
}
}
log.Infof("login grafana...")
if err := r.LoginGrafana(); err != nil || len(r.imageURLs) > 0 {
close(r.imageURLs)
return err
}
log.Infof("get dashboards...")
if err := r.GetDashboards(); err != nil {
return err
}
log.Infof("get panels...")
if err := r.GetDashboardPanels(); err != nil {
return err
}
log.Infof("generate image url...")
if err := r.GenerateURL(); err != nil {
return err
}
close(r.imageURLs)
log.Infof("prepare data finished...")
return nil
}
| 2645c986e5d2f83683768d850c397c79c6ac0465 | [
"Markdown",
"Go",
"Makefile"
] | 5 | Go | buggithubs/tidb-inspect-tools | fe171e4a50a3a68657506180845bd15b7b3591f6 | 7f75841eb61b465d28626322bbdbbf9b73721c7e |
refs/heads/main | <file_sep>import firebase from 'firebase'
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "disneyplus-clone-5efb1.firebaseapp.com",
projectId: "disneyplus-clone-5efb1",
storageBucket: "disneyplus-clone-5efb1.appspot.com",
messagingSenderId: "264142125974",
appId: "1:264142125974:web:81c95be2761801344cbbb7"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const auth = firebase.auth();
const provider = new firebase.auth.GoogleAuthProvider();
const storage = firebase.storage();
export { auth, provider, storage };
export default db; | 8f5c2b0dc343967c97cb2a0ab1bd40e6c0486d0a | [
"JavaScript"
] | 1 | JavaScript | tugane/Tugane-disneyplus-clone | a4060d79ac545e1329565e9d3cefd4780f60f1d0 | 38080ea3871dbdd47b93dc1828f106195d9a8a90 |
refs/heads/master | <repo_name>AswinKalaivanan/UrbanLadder<file_sep>/src/test/java/com/quinbay/urbanladder/Steps/UrbanladderSteps.java
package com.quinbay.urbanladder.Steps;
import Action.ActionClass;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class UrbanladderSteps {
WebDriver driver;
ActionClass actionClass;
@Given("I am on Urbanladder Home page")
public void iAmOnUrbanladderHomePage()
{
System.setProperty("webdriver.chrome.driver","/Users/apaswinkalaivanan/IdeaProjects/UrbanLadder/src/main/resources/chromedriver");
System.setProperty("webdriver.chrome.driver", "/Users/apaswinkalaivanan/IdeaProjects/BliBliAddToCart/src/main/resources/chromedriver");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.urbanladder.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
actionClass = new ActionClass(driver);
}
@When("I hover Kids room")
public void iHoverKidsRoom() {
actionClass.hoverKidsRoom();
}
@Then("Check Kids Storage Cabinets")
public void checkKidsStorageCabinets() {
actionClass.assertStorageCabinet();
}
@And("I click kids bunk beds")
public void iClickKidsBunkBeds() {
actionClass.clickBunkBeds();
}
@Then("Check the current page as Kids Bunk Beds")
public void checkTheCurrentPageAsKidsBunkBeds() {
actionClass.assertBunkBeds();
}
@And("I click on exclude out of stock")
public void iClickOnExcludeOutOfStock() {
actionClass.clickOutofStock();
}
@Then("Check checkbox clicked")
public void checkCheckboxClicked() {
actionClass.assertStock();
}
@And("I click sort")
public void iClickSort() {
actionClass.clickSort();
}
@Then("Assert whether price:High to Low applied")
public void assertWhetherPriceHighToLowApplied() throws InterruptedException {
actionClass.assertPrice();
}
@And("I click price filter")
public void iClickPriceFilter() throws InterruptedException {
actionClass.clickFilterPrice();
}
@And("Close Driver")
public void closeDriver() {
driver.close();
}
@Then("Assert Radio buttons")
public void assertRadioButtons() {
actionClass.assertRadioButtons();
}
@And("I click on price range")
public void iClickOnPriceRange() {
actionClass.clickRadio4();
}
@Then("Assert Final Price")
public void assertFinalPrice() {
actionClass.assertFinalPrice();
}
//new branch
}
<file_sep>/src/main/java/Action/ActionClass.java
package Action;
import Pages.HomePage;
import Pages.KidsBunkBeds;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
public class ActionClass {
HomePage homePage;
KidsBunkBeds kidsBunkBeds;
WebDriver driver;
public ActionClass(WebDriver driver)
{
this.driver=driver;
homePage= PageFactory.initElements(driver,HomePage.class);
kidsBunkBeds=PageFactory.initElements(driver,KidsBunkBeds.class);
}
public void hoverKidsRoom()
{
homePage.hoverKidsRoom(driver);
}
public void assertStorageCabinet()
{
homePage.assertStorageCabinet();
}
public void clickBunkBeds()
{
homePage.clickBunkBeds();
}
public void assertBunkBeds()
{
homePage.assertBunkBeds();
}
public void clickOutofStock()
{
kidsBunkBeds.clickOutofStock();
}
public void assertStock()
{
kidsBunkBeds.assertStock();
}
public void clickSort()
{
kidsBunkBeds.clickSort();
}
public void assertPrice() throws InterruptedException {
kidsBunkBeds.assertPrice();
}
public void clickFilterPrice() throws InterruptedException {
kidsBunkBeds.clickFilterPrice(driver);
}
public void assertRadioButtons()
{
kidsBunkBeds.assertRadioButtons();
}
public void clickRadio4()
{
kidsBunkBeds.clickRadio4(driver);
}
public void assertFinalPrice()
{
kidsBunkBeds.assertFinalPrice();
}
}
| 2c69b8615a32e22591b59170feec31dd1b6946dd | [
"Java"
] | 2 | Java | AswinKalaivanan/UrbanLadder | 8bc951f165265651eaf477ebafa722551b6346ec | 9c4ade4206f6cdac7f10d026c213b9fea8c1fd94 |
refs/heads/master | <file_sep>var SkillSet = function()
{
var self = this;
this.$set;
this.MASK = 1;
this.DESTROYTREE = 2;
this.skills = {
1: new Skills.Mask(),
2: null,
3: null
}
this._inUse = {};
this.init = function()
{
$("body").append('<div id="skillset" class="hasInfo" data-info="Skills" />');
this.$set = $("#skillset");
this.fill();
this.$set.css('left', ($(window).width() - this.$set.width()) / 2);
}
this.fill = function(){
this.$set.children().remove();
for(id in this.skills) {
var skill = this.skills[id];
var info, usage;
if(skill !== null) {
usage = skill.levels[skill.level].usage;
info = 'data-info="' + usage.description + '<br><span style=\'color:#ff0000\'>Cost: ' + usage.cost + '</span><br><span style=\'color:#0000ff\'>Duration: ' + skill.getDuration() + '</span>"';
} else {
usage = null;
info = null;
}
this.$set.append('<div class="skill ' + (info ? 'hasInfo hide top small' : '') + '" id="skill-' + id + '" ' + (info ? info : '') + ' />');
var $elm = this.$set.children("#skill-" + id);
$elm.data('id', id);
if(skill !== null) {
$elm.css("background-image", "url(" + skill.icon + ")");
}
$elm.bind('click', function(){
skillSet.use($(this).data("id"));
}).bind('mouseenter', function(){
if($(this).data('info-elm')) {
$(this).data('info-elm').show();
}
}).bind('mouseleave', function(){
if($(this).data('info-elm')) {
$(this).data('info-elm').hide();
}
});
}
if(assetsLoaded) {
Info.build();
}
}
this.activate = function(n)
{
console.log('SkillSet: activate');
this.skills[n].activate();
}
this.deactivate = function(n)
{
console.log('SkillSet: deactivate');
this.skills[n].deactivate();
}
this.use = function(n)
{
this._inUse[n] = true;
this.skills[n].use();
}
this.unUse = function(n)
{
this._inUse[n] = false;
this.skills[n].unUse();
}
this.inUse = function(n)
{
return this._inUse[n];
}
}
<file_sep>// set the scene size
var WIDTH,
HEIGHT;
// set some camera attributes
var VIEW_ANGLE = 45,
ASPECT,
NEAR = 0.1,
FAR = 10000;
var $container;
var controls;
var renderer, camera, scene;
var planet, tree;
var humans = [],
clouds = [],
fears = [],
trees = [],
houses = [],
whiteHouse,
president;
var EXPLORE = 1,
SKILL = 2;
var state = EXPLORE;
var skillSet = new SkillSet();
skillSet.activate(skillSet.MASK);
var assetsLoaded = false;
var shop = new Shop();
var fearScore = new FearScore();
var planetFear = new PlanetFear();
var backgroundMusic;
function init()
{
backgroundMusic = new Audio('sound/background.wav');
// backgroundMusic.play();
backgroundMusic.volume = 0.4;
backgroundMusic.loop = true;
WIDTH = $(window).width();
HEIGHT = $(window).height();
ASPECT = WIDTH / HEIGHT;
// get the DOM element to attach to
// - assume we've got jQuery to hand
$container = $('#container');
// create a WebGL renderer, camera
// and a scene
renderer = new THREE.WebGLRenderer({maxLights: 8});
camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
scene = new THREE.Scene();
// add the camera to the scene
scene.add(camera);
camera.position.z = 100;
// THREEx stuff
THREE.Object3D._threexDomEvent.camera(camera);
// start the renderer
renderer.setSize(WIDTH, HEIGHT);
$container.append(renderer.domElement);
skillSet.init();
shop.init();
fearScore.init();
planetFear.init();
// Create planet
planet = new Planet(function(model){
scene.add(model);
model.children[1].on('click', function(){
console.log("Planet: click");
});
// Create trees
for(var i = 0; i < 3; i++) {
planet.spawnTree();
}
// Create clouds
for(var i = 0; i < 5; i++) {
clouds.push(new Cloud(function(model){
scene.add(model);
model.position.x = planet.radius + 20;
model.lookAt(planet.model.position);
}));
}
// Create humans
for(var i = 0; i < 5; i++) {
planet.spawnHuman();
}
});
controls = new THREE.TrackballControls( camera );
realWindow = window.parent || window;
realWindow.addEventListener( 'keydown', keys.event.down, false );
realWindow.addEventListener( 'keyup', keys.event.up, false );
$('body').bind('mousewheel', function(e){
var factor;
if(e.originalEvent.wheelDelta > 0) {
factor = 0.9;
} else {
factor = 1.1;
}
camera.position.multiplyScalar(factor);
});
animate();
}
$(window).load(function(){
assetsLoaded = true;
Info.build();
});
var keys = {
code: {
SPACE: 32,
W: 87,
S: 83,
A: 65,
D: 68
},
down: {},
update: function() {
if(skillSet.inUse(skillSet.MASK)) {
skillSet.skills[skillSet.MASK].keys();
}
},
event: {
down: function(e) { keys.down[e.keyCode] = true; },
up: function(e) { keys.down[e.keyCode] = false }
}
}
function animate()
{
requestAnimationFrame( animate );
render();
update();
}
function update()
{
controls.update();
keys.update();
if(clouds.length > 0) {
_.each(clouds, function(cloud) {
cloud.update();
});
}
if(skillSet.inUse(skillSet.MASK)) {
skillSet.skills[skillSet.MASK].update();
}
if(humans.length > 0) {
_.each(humans, function(human) {
human.update();
});
}
if(fears.length > 0) {
_.each(fears, function(fear) {
fear.update();
});
}
if(president && president.model && president.model.position) {
president.update();
}
if(whiteHouse && whiteHouse.model && whiteHouse.model.position && cameraOnWhiteHouse) {
camera.position = whiteHouse.model.position.clone().multiplyScalar(15);
camera.lookAt(whiteHouse.model.position);
}
TWEEN.update();
}
/**
* Grow planet every 5 seconds
*/
setInterval(function(){
if(planet.model.position) {
planet.grow();
}
}, 5000);
function render()
{
renderer.render( scene, camera );
}
function changeState(_state) {
state = _state;
}
var toRadian = function(degrees)
{
return degrees * Math.PI / 180;
}
var toDegrees = function(radian)
{
return radian * 180 / Math.PI;
}
var Info = {
build: function() {
$(".hasInfo").each(function(){
// This info box is already created, stop
if($(this).data('info-elm')) {
return;
}
// Create the container if in need
if($("#info-container").length == 0)
$("body").append('<div id="info-container" />')
// The information to display in the info box
var data = $(this).data("info");
// Create the info box
console.log(data);
var $elm = $('<div class="info">' + data + '<div class="arrow" /></div>');
$("#info-container").append($elm);
if($(this).hasClass('small')) {
$elm.addClass('small');
}
// Position the info box on right position
var offset = $(this).offset();
var top;
var left;
if($(this).hasClass("right")) {
$elm.addClass("right");
top = offset.top + (($(this).height() - $elm.height()) / 2);
left = offset.left + $(this).outerWidth() + 20;
} else if ($(this).hasClass("top")) {
$elm.addClass("top");
var arrow = $elm.children(".arrow");
arrow.css("left", ($elm.outerWidth() - arrow.width()) / 2);
top = offset.top - $elm.outerHeight() - 20;
left = offset.left + (($(this).outerWidth() - $elm.outerWidth()) / 2);
} else {
top = offset.top + (($(this).height() - $elm.height()) / 2);
left = offset.left - $elm.outerWidth() - 20;
}
$elm.css({
left: left,
top: top
});
if($(this).hasClass('hide')) {
$elm.hide();
}
$(this).data('info-elm', $elm);
});
}
}
<file_sep>var Mask = function(loaded)
{
this.model;
this.loaded = loaded;
this.model = 'models/mask.obj';
this.texture = 'models/textures/mask-uv.png';
this.turnX = 0;
this.turnY = 0;
this.mayMove = true;
this.init();
}
Mask.prototype = new Dystopia.Object3D();
Mask.prototype.init = function() {
this.load();
}
Mask.prototype.update = function() {
if(this.speed > 0) {
this.model.position.x += this.speed;
this.speed -= 1;
}
}
Mask.prototype.moveForward = function() {
if(!this.mayMove) {
return;
}
// Move the bloody thing forward
this.move(new THREE.Vector3(toRadian(this.turnX), toRadian(this.turnY), toRadian(1)));
// Reset
this.turnX = 0;
this.turnY = 0;
}
Mask.prototype.moveBackward = function() {
if(!this.mayMove) {
return;
}
this.move(new THREE.Vector3(toRadian(this.turnX), toRadian(this.turnY), toRadian(-1)));
}
Mask.prototype.turnRight = function() {
this.turnX = 1;
}
Mask.prototype.turnLeft = function() {
this.turnY = 1;
}<file_sep>Dystopia
========
This is a WebGL game I made during lessons in Game Design. For an assignment you had to add certain dynamics. Also see http://arcomul.nl/games/dytopia/info for more information. Or play the game at http://arcomul.nl/games/dystopia
Feel free to check/use/change the code and the models.
(Actually this is just an easy way to host my code, since it should be downloadable :-D)
<file_sep>var Guard = function(loaded)
{
this.model;
this.loaded = loaded;
this.model = 'models/human.obj';
this.texture = 'models/textures/human-uv.png';
this.startPosition = false;
this.isScared = false;
this.init();
}
Guard.prototype = new Dystopia.Object3D();
Guard.prototype.init = function()
{
this.load();
}
Guard.prototype._loaded = function(model)
{
// The blue material
var mat = new THREE.MeshBasicMaterial({color: 0x222222});
// Give all its meshes the right materail / color
for(var i = 0; i < model.children.length; i++) {
model.children[i].material = mat;
}
this.loaded(model);
}
Guard.prototype.update = function()
{
}<file_sep>var Planet = function(loaded)
{
var self = this;
this.model;
this.loaded = loaded;
this.model = 'models/planet.obj';
this.texture = 'models/textures/planet-uv.png';
this.skyColors = {
0: ["#DAFAFF", "#59E4FF"],
1: ["#CFF3F8", "#4EECE0"],
2: ["#CFF8DF", "#38D3B4"],
3: ["#BDF1D2", "#2DBE90"],
4: ["#A4DFBB", "#1D965C"]
};
this.housesActivated = false;
this.whiteHouseActivated = false;
this.radius;
this.size = 1;
var texture = new THREE.Texture();
var loader = new THREE.ImageLoader();
loader.addEventListener( 'load', function ( event ) {
texture.image = event.content;
texture.needsUpdate = true;
});
loader.load( this.texture );
var loader = new THREE.OBJLoader();
loader.addEventListener( 'load', function ( event ) {
self.model = event.content;
for ( var i = 0, l = self.model.children.length; i < l; i ++ ) {
self.model.children[ i ].material.map = texture;
}
self.setRadius();
self.loaded(self.model);
});
loader.load( this.model );
}
Planet.prototype.updateFear = function()
{
var fearFactor = Math.round(planetFear.percentage / 10);
console.log("Planet set skycolor:", fearFactor);
$("body").css("background", "-webkit-radial-gradient(center, ellipse cover, " + this.skyColors[fearFactor][0] + " 0%," + this.skyColors[fearFactor][1] + " 100%)");
}
Planet.prototype.grow = function()
{
var self = this;
var scaleFactor = 1.1 - (this.size * 0.005);
if(scaleFactor <= 1 && $('#end-of-game').length == 0) {
$("body").append("<img src='img/explosion.gif' id='explosion' />");
$("body").append("<div id='end-of-game'>End of game!</div>");
backgroundMusic.pause();
var snd = new Audio('sound/scream.mp3');
snd.loop = true;
snd.play();
}
var from = {
x: this.model.children[1].scale.x,
y: this.model.children[1].scale.y,
z: this.model.children[1].scale.z
}
var to = {
x: from.x * scaleFactor,
y: from.y * scaleFactor,
z: from.z * scaleFactor
}
new TWEEN.Tween({x: from.x, y: from.y, z: from.z})
.to({x: to.x, y: to.y, z: to.z }, 1000)
.easing(TWEEN.Easing.Exponential.In)
.onUpdate(function () {
self.model.children[1].scale.x = this.x;
self.model.children[1].scale.y = this.y;
self.model.children[1].scale.z = this.z;
})
.start();
// Move trees
moveObjectUpByFactor(trees, scaleFactor);
// Move humans
moveObjectUpByFactor(humans, scaleFactor);
// Move clouds
moveObjectUpByFactor(clouds, scaleFactor);
// Move houses
moveObjectUpByFactor(houses, scaleFactor);
if(skillSet.inUse(skillSet.MASK)) {
moveObjectUpByFactor([skillSet.skills[skillSet.MASK].mask], scaleFactor);
}
// Move white house(s)
if(whiteHouse) {
moveObjectUpByFactor([whiteHouse], scaleFactor);
}
// Move president(s)
if(president) {
console.log('moveObjectUpByFactor president');
moveObjectUpByFactor([president], scaleFactor);
}
this.setRadius(this.radius * scaleFactor);
if(this.model.children[1].scale.x > 1 && !this.housesActivated) {
this.activateHouses();
} else if (this.housesActivated && this.size % 2 == 1) {
this.spawnHouse();
}
if(this.model.children[1].scale.x > 1.1 && !this.whiteHouseActivated) {
this.activateWhiteHouse();
}
this.spawnTree();
this.spawnHuman();
this.size++;
}
Planet.prototype.setRadius = function(radius)
{
this.radius = radius || this.model.children[1].boundRadius;
}
Planet.prototype.activateHouses = function()
{
console.log('Planet: activate houses');
this.housesActivated = true;
for(var i = 0; i < 3; i++) {
this.spawnHouse();
}
}
Planet.prototype.activateWhiteHouse = function()
{
console.log('Planet: activate white house');
this.whiteHouseActivated = true;
this.spawnWhiteHouse();
}
Planet.prototype.spawnWhiteHouse = function()
{
whiteHouse = new WhiteHouse(function(model){
var self = this;
planet.model.add(model);
});
}
Planet.prototype.spawnHouse = function()
{
houses.push(new House(function(model){
var self = this;
planet.model.add(model);
model.children[1].on('click', function(e){
if(skillSet.inUse(skillSet.DESTROYTREE)) {
skillSet.skills[skillSet.DESTROYTREE].destroy(self);
}
});
}));
}
Planet.prototype.spawnTree = function()
{
trees.push(new Tree(function(model){
var self = this;
planet.model.add(model);
model.children[1].on('click', function(e){
if(skillSet.inUse(skillSet.DESTROYTREE)) {
skillSet.skills[skillSet.DESTROYTREE].destroy(self);
}
});
}));
}
Planet.prototype.spawnHuman = function()
{
humans.push(new Human(function(model){
planet.model.add(model);
model.position.x = planet.radius - 1;
model.lookAt(planet.model.position);
}));
}
var moveObjectUpByFactor = function(array, factor) {
_.each(array, function(object) {
new TWEEN.Tween({x: object.model.position.x, y: object.model.position.y, z: object.model.position.z})
.to({x: object.model.position.x * factor, y: object.model.position.y * factor, z: object.model.position.z * factor }, 1000)
.easing(TWEEN.Easing.Exponential.In)
.onStart(function() {
object.mayMove = false;
})
.onUpdate(function () {
object.model.position.x = this.x;
object.model.position.y = this.y;
object.model.position.z = this.z;
})
.onComplete(function() {
object.mayMove = true;
})
.start();
});
}
<file_sep>var FearScore = function()
{
var self = this;
this.$container;
this.$score;
this.score = 0;
this.init = function()
{
$("body").append('<div id="score-fear" class="hasInfo" data-info="Collected Fear"><img src="img/fear.png" /><span /></div>');
this.$container = $("#score-fear");
this.$score = this.$container.children('span');
this.set(this.score);
}
this.set = function(n)
{
this.$score.text(n);
}
this.add = function(n)
{
this.score += n;
this.set(this.score);
}
}<file_sep>var House = function(loaded)
{
this.model;
this.loaded = loaded;
this.model = 'models/house.obj';
this.texture = 'models/textures/house-uv.png';
this.init();
}
House.prototype = new Dystopia.Object3D();
House.prototype.init = function() {
this.load();
}
House.prototype._loaded = function(model) {
var self = this;
this.model.position.y = 1;
this.model.lookAt(planet.model.position);
this.model.updateMatrix();
this.move(new THREE.Vector3(
toRadian(-180 + (Math.random() * 360)),
toRadian(-180 + (Math.random() * 360)),
toRadian(-180 + (Math.random() * 360))
));
new TWEEN.Tween({x: this.model.position.x, y: this.model.position.y, z: this.model.position.z})
.to({
x: this.model.position.x * ((planet.radius - 2) / 1),
y: this.model.position.y * ((planet.radius - 2) / 1),
z: this.model.position.z * ((planet.radius - 2) / 1)
}, 1000)
.easing(TWEEN.Easing.Exponential.In)
.onUpdate(function () {
self.model.position.x = this.x;
self.model.position.y = this.y;
self.model.position.z = this.z;
})
.start();
this.loaded(model);
}
House.prototype.destroy = function() {
var position = this.model.position;
var rotation = this.model.rotation;
// Replace this model with a new one
planet.model.remove(this.model);
this.model = 'models/tree-destroyed.obj';
this.texture = 'models/textures/tree-destroyed-uv.png';
this.loaded = function(model) {
planet.model.add(model);
model.position = position;
model.rotation = rotation;
}
this.load();
// This action gains 5 to the complete planet fear
planetFear.gain(5);
}
House.prototype.positionOnPlanet = function()
{
this.model.position.y = planet.radius - 2;
}<file_sep>var Vector2D = function(x, y)
{
this.x = x;
this.y = y;
this.rotate = function(degrees)
{
var x = (this.x * Math.cos(toRadian(degrees))) - (this.y * Math.sin(toRadian(degrees)));
var y = (this.x * Math.sin(toRadian(degrees))) + (this.y * Math.cos(toRadian(degrees)));
return new Vector2D(x, y);
}
this.add = function(vector)
{
return new Vector2D(this.x + vector.x, this.y + vector.y);
}
this.substract = function(vector)
{
return new Vector2D(this.x - vector.x, this.y - vector.y);
}
this.isZero = function()
{
return this.x === 0 && this.y === 0;
}
this.workToZero = function(step)
{
this.x = workToZero(this.x, step);
this.y = workToZero(this.y, step);
}
}<file_sep>var Shop = function()
{
var self = this;
this.$button
this.init = function()
{
var self = this;
$("body").append('<div id="shop-button" class="hasInfo right" data-info="Shop"><div /></div>');
this.$buttonContainer = $("#shop-button");
this.$button = this.$buttonContainer.children('div');
this.$buttonContainer.css({
left: skillSet.$set.offset().left + skillSet.$set.width() + 20,
top: skillSet.$set.offset().top
});
// Add base element of the shop, the container
$("body").append('<div id="shop"><div class="content"><h2>Shop</h2><div class="close">x</div></div></div>');
this.$container = $("#shop");
// Set up the holder for the content of the shop
var content = this.$container.children(".content");
content.append('<div class="left" /><div class="right" />');
content.css({
height: ($(window).height() - 100) * 0.7,
width: 800
}).children(".left").css("height", content.height() - content.children('h2').outerHeight());
this.$container.css({
top: ($(window).height() - this.$container.height()) / 2,
left: ($(window).width() - this.$container.width()) / 2
}).hide()
this.fill();
var closeButton = content.children(".close");
closeButton.bind('click', function(){
self.close();
});
this.$button.click(function(){
self.open();
});
}
this.open = function() {
console.log("Shop: open");
this.fill();
this.$container.show();
}
this.close = function() {
console.log("Shop: close");
this.$container.hide();
}
this.fill = function() {
console.log("Shop: fill");
var content = this.$container.children(".content");
var left = content.children(".left");
left.children().remove();
for(pos in skillSet.skills) {
if(skillSet.skills[pos]) {
left.append(this.createSkillTile(skillSet.skills[pos]));
}
}
var right = content.children(".right");
right.children().remove();
for(skill in Skills) {
var skill = new Skills[skill]();
var hasSkill = false;
for(pos in skillSet.skills) {
if(skillSet.skills[pos] && skillSet.skills[pos].title == skill.title) {
hasSkill = true;
}
}
right.append(this.createSkillTile(skill, true, hasSkill));
}
}
this.buy = function(skill) {
skill.level = 1;
skillSet.skills[skill.id] = skill;
skillSet.fill();
fearScore.add(-skill.levels[skill.level].cost);
this.fill();
}
this.createSkillTile = function(skill, buy, fade) {
if(!buy && !skill.levels[skill.level + 1]) {
return;
}
// Amount of fear this item costs
var cost = skill.levels[(buy ? 1 : skill.level + 1)].cost;
var tile = $('<div class="skill ' + (fade ? 'bought' : '') + '" />');
tile.append('<div class="img"><img src="' + skill.icon + '" /></div>')
var info = tile.append('<div class="info" />').children(".info");
info.append('<h3>' + skill.title + '</h3>');
info.append('<p>' + skill.description + '</p>');
if(!buy) {
info.append('<p><span style="color:#0000ff">' + skill.levels[skill.level + 1].gain + '</span></p>');
}
info.append('<p><span style="color:#ff0000">' + cost + ' Fear' + (cost > fearScore.score ? ' (not enough Fear)' : '') + '</span></p>');
tile.append('<button>' + (buy ? 'Buy' : 'Upgrade') + '</button>');
var button = tile.children('button');
button.data('skill', skill);
button.bind('click', function(e){
e.preventDefault();
if(!$(this).hasClass('no-click')) {
shop.close();
shop.buy($(this).data('skill'));
}
});
if(cost > fearScore.score) {
button.addClass('no-click');
}
tile.append('<br class="clear">');
return tile;
}
}
<file_sep>var PlanetFear = function()
{
var self = this;
this.$container;
this.$percentage;
this.percentage = 0;
this.max = 100;
this.gained = 0;
this.init = function()
{
var self = this;
$("body").append('<div id="planet-fear" class="hasInfo right" data-info="Planet Fear"><span /></div>');
this.$container = $("#planet-fear");
this.$percentage = this.$container.children('span');
this.set(this.percentage);
setInterval(function(){
// Remove some of the planet fear
self.drain();
}, 2000);
this.totalScare = setInterval(this.scarePlanet, 2000);
}
this.set = function(n)
{
this.$percentage.text(n + "%");
}
this.add = function(n)
{
this.percentage += n;
this.set(this.percentage);
planet.updateFear();
}
this.drain = function()
{
if(this.percentage > ((this.gained / this.max) * 100)) {
this.add(-1);
planet.updateFear();
}
}
this.gain = function(n)
{
this.gained += n;
this.add(n);
}
this.scarePlanet = function() {
if(self.percentage > 0) {
for(var i = 0; i < humans.length; i++) {
humans[i].scare(1);
}
}
if(self.totalScare) {
clearInterval(self.totalScare);
}
console.log("Set total planet scare:", (150 - self.percentage) * 100);
self.totalScare = setInterval(self.scarePlanet, (150 - self.percentage) * 100);
}
}
<file_sep>var Dystopia = {
Object3D: function()
{
this.opacity = 1;
this.mayMove = true;
this.load = function()
{
var self = this;
var texture = new THREE.Texture();
var loader = new THREE.ImageLoader();
loader.addEventListener( 'load', function ( event ) {
texture.image = event.content;
texture.needsUpdate = true;
});
loader.load( this.texture );
var loader = new THREE.OBJLoader();
loader.addEventListener( 'load', function ( event ) {
self.model = event.content;
for ( var i = 0, l = self.model.children.length; i < l; i ++ ) {
self.model.children[i].material.map = texture;
// self.model.children[i].material.map.generateMipmaps = false;
self.model.children[i].material.opacity = self.opacity;
}
self._loaded(self.model);
});
loader.load( this.model );
}
this._loaded = function(model) { this.loaded(model); }
this.move = function(direction, axis) {
if(!this.mayMove) {
return false;
}
axis = axis || "XYZ";
var m4 = new THREE.Matrix4().setRotationFromEuler(direction, axis);
m4.multiplySelf(this.model.matrix);
this.model.matrix = m4;
this.model.position.getPositionFromMatrix(m4);
this.model.rotation.setEulerFromRotationMatrix(m4);
}
}
}
<file_sep>var Human = function(loaded)
{
this.model;
this.loaded = loaded;
this.model = 'models/human.obj';
this.texture = 'models/textures/human-uv.png';
this.startPosition = false;
this.isScared = false;
this.init();
}
Human.prototype = new Dystopia.Object3D();
Human.prototype.init = function()
{
this.load();
}
Human.prototype.update = function()
{
if(this.direction && this.model.position && this.model.rotation && this.startPosition)
{
this.move(this.direction);
}
if(this.model.position && !this.startPosition)
{
this.move(new THREE.Vector3(
toRadian(-180 + (Math.random() * 360)),
toRadian(-180 + (Math.random() * 360)),
toRadian(-180 + (Math.random() * 360))
));
this.direction = new THREE.Vector3(toRadian(-0.5 + (Math.random() * 1)), toRadian(-0.5 + (Math.random() * 1)), toRadian(-0.5 + (Math.random() * 1)));
this.startPosition = true;
}
}
Human.prototype.dropFear = function()
{
console.log('Human: drop fear');
var self = this;
planetFear.add(1);
fears.push(new Fear(function(model){
planet.model.add(model);
model.position = self.model.position.clone();
model.lookAt(planet.model.position);
}))
}
Human.prototype.scare = function(n)
{
console.log('Human: scare');
var self = this;
if(this.model.children[1].scale.z < 0.513) {
planet.model.remove(this.model);
return;
}
if(this.isScared) {
return;
}
// Scream
var snd = new Audio("sound/scream.mp3"); // buffers automatically when created
snd.play();
// Define that this human is scared at the moment
this.isScared = true;
// Whether the human is blue at the mometn
var blue = false;
// The original material
var material = this.model.children[0].material;
// The blue material
var blueMat = new THREE.MeshBasicMaterial({color: 0x5b89ff});
var count = 0;
var interval = setInterval(function(){
// After four times kill the interval
if(count == n * 2) {
clearInterval(interval);
self.isScared = false;
return;
}
// If the human is blue make him normal
if(blue) {
var mat = material;
blue = false;
// If the human is not blue make him blue and let drop one fear
} else {
var mat = blueMat;
blue = true;
self.dropFear();
}
// Give all its meshes the right materail / color
for(var i = 0; i < self.model.children.length; i++) {
self.model.children[i].material = mat;
}
count++;
}, 500);
this.model.children[1].scale.multiplyScalar(0.8);
// 0.512
console.log('Human scale:', this.model.children[1].scale.z);
}
<file_sep>var Cloud = function(loaded)
{
this.model;
this.loaded = loaded;
this.model = 'models/cloud.obj';
this.texture = 'models/textures/cloud-uv.png';
this.opacity = 0.5;
this.startPosition = false;
this.direction;
this.init();
}
Cloud.prototype = new Dystopia.Object3D();
Cloud.prototype.init = function() {
this.load();
}
Cloud.prototype._loaded = function(model) {
this.model.alpha = 0.5;
this.loaded(model);
}
Cloud.prototype.update = function() {
if(this.direction && this.model.position && this.model.rotation && this.startPosition) {
this.move(this.direction);
}
if(this.model.position && !this.startPosition)
{
this.move(new THREE.Vector3(
toRadian(-180 + (Math.random() * 360)),
toRadian(-180 + (Math.random() * 360)),
toRadian(-180 + (Math.random() * 360))
));
this.direction = new THREE.Vector3(toRadian(-0.1 + (Math.random() * 0.2)), toRadian(-0.1 + (Math.random() * 0.2)), toRadian(-0.1 + (Math.random() * 0.2)));
this.startPosition = true;
}
// if(this.model.position)
// {
// var v2 = new Vector2D(this.model.position.x, this.model.position.y);
// v2 = v2.rotate(0.1);
// this.model.position.x = v2.x, this.model.position.y = v2.y;
// this.model.rotation.y += toRadian(0.1);
// }
}
| 7973794e3ad58e2439e56210ba84525a47803d1e | [
"JavaScript",
"Markdown"
] | 14 | JavaScript | ArcoMul/dystopia | e1fd964562439ac7b356bd71a84e6d3744e52e92 | b4acb3cc962646314f2c591544a1e0a64eeb2a8d |
refs/heads/master | <repo_name>diananova/lab6<file_sep>/dictionary.h
#include <iostream>
#include <stdexcept>
#include <vector>
#include <fstream>
#include <chrono> // necessario compilare con -std=c++11
#include <stdlib.h> // srand, rand
#include <string> // std::string
#include "string-utility.h"
using namespace std::chrono;
using namespace std;
namespace dict {
enum Error {OK, FAIL};
typedef string Key;
typedef string Value;
const Key emptyKey = "###RESERVED KEYWORD### EMPTY KEY";
const Value emptyValue = "###RESERVED KEYWORD### EMPTY VALUE";
struct dictionaryElem {
Key key;
Value value;
};
struct Node {
dictionaryElem keyVal; /* elemento del dictionary, ovvero coppia chiave-valore */
Node* leftChild;
Node* rightChild;
};
typedef dictionaryElem Elem;
typedef Node* Dictionary;
Error insertElem(const Key, const Value, Dictionary&);
Error deleteElem(const Key, Dictionary&);
Value search(const Key, const Dictionary&);
Dictionary createEmptyDict();
} //end namespace dict
dict::Dictionary readFromFile(string);
dict::Dictionary readFromStdin();
dict::Dictionary readFromStream(istream&);
void print(const dict::Dictionary&);
<file_sep>/dictionarytree.cpp
#include "dictionary.h"
using namespace dict;
Dictionary dict::createEmptyDict() {
Node *root = new Node;
root->leftChild = NULL;
root->rightChild = NULL;
Dictionary d = root;
return d;
}
bool isEmpty(const Dictionary &d) {
return d==NULL;
}
Error dict::insertElem(const Key k, const Value v, Dictionary& d) { //works
Elem e;
e.key = k;
e.value = v;
if (isEmpty(d)) {
Node* new_node = new Node;
new_node->keyVal = e;
new_node->leftChild = NULL;
new_node->rightChild = NULL;
d = new_node;
return OK;
}
else if (e.key==d->keyVal.key) {
cout<<"elemento gia' presente"<<endl;
return FAIL;
}
else if (e.key < d->keyVal.key)
dict::insertElem(k, v, d->leftChild);
else if (e.key > d->keyVal.key)
dict::insertElem(k, v, d->rightChild);
return FAIL;
}
dictionaryElem deleteMin(Dictionary &d) { //funzione aux
if (isEmpty(d->leftChild)) //a points to the smallest element
d = d->rightChild; //deleted
else
deleteMin(d->leftChild); //traverse till if condition is true
return d->keyVal;
}
Error dict::deleteElem(const Key k, Dictionary& d) {
if (isEmpty(d))
return FAIL;
if (k < d->keyVal.key)
dict::deleteElem(k, d->leftChild);
else if (k > d->keyVal.key)
dict::deleteElem(k, d->rightChild);
//k = d->keval.key
else if ((isEmpty(d->leftChild)) && (isEmpty(d->rightChild)))
d = NULL; //non ha figli quindi lo cancello
else if (isEmpty(d->leftChild)) //d ha solo figlio destro
d = d->rightChild;
else if (isEmpty(d->rightChild)) //d ha solo figlio sinistro
d = d->leftChild;
else //both children are present
d->keyVal = deleteMin(d->rightChild);
return OK;
}
Value dict::search(const Key k, const Dictionary &d) {
if (isEmpty(d))
return emptyValue;
if (k==d->keyVal.key)
return d->keyVal.value;
else if (k < d->keyVal.key)
return dict::search(k, d->leftChild);
else if (k > d->keyVal.key)
return dict::search(k, d->rightChild);
else
return emptyValue;
}
void print(const dict::Dictionary &d)
{
if (isEmpty(d))
return;
cout<<d->keyVal.key<<" "<<d->keyVal.value<<endl;
print(d->leftChild);
print(d->rightChild);
}
dict::Dictionary readFromFile(string nome_file)
{
ifstream ifs(nome_file.c_str()); // apertura di uno stream associato ad un file, in lettura
if (!ifs) {
cout << "\nErrore apertura file, verificare di avere inserito un nome corretto\n";
return createEmptyDict();
}
// cout << "\n[dict::readFromFile] Apertura file completata\n";
return readFromStream(ifs);
}
dict::Dictionary readFromStdin()
{
cout << "\nInserire una sequenza di linee che rispettano la sintassi key: value.<enter>\nDigitare CTRL^ D per terminare l'inserimento\n";
Dictionary d = readFromStream((std::cin));
// Questa serve per aggirare un bug di alcune versioni attuali di glibc.
clearerr(stdin);
return d;
}
dict::Dictionary readFromStream(istream& str)
{
Dictionary d = createEmptyDict();
string key, kcopy;
string value;
getline (str, key, ':');
getline (str, value);
while (!str.eof())
{
kcopy = key;
removeBlanksAndLower(kcopy);
insertElem(kcopy, value, d); // FINCHE' NON IMPLEMENTATE LA INSERTELEM, NON PUO' FUNZIONARE CORRETTAMENTE: la insertElem e' la prima funzione che dovete implementare
getline (str, key, ':');
getline (str, value);
}
str.clear();
return d;
}
| 4021417c98857f039c56f0358e7fa6c88f35be95 | [
"C++"
] | 2 | C++ | diananova/lab6 | b682bbe00c819306f0323b3e35950537e74381f9 | 94931ad1e17b487a5118d245a8178cbcc043260d |
refs/heads/master | <file_sep>import java.util.*;
import java.lang.*;
import java.io.*;
interface User{
void menu();
void details();
int rewards(int x);
}
class Zotato{
private int deliveryCharge;
private double companyBalance;
private HashMap<Integer,Restaurant> r=new HashMap<>();
private int noRes=0;
private HashMap<Integer,Customer> c=new HashMap<>();
private int noCus=0;
private Scanner input=new Scanner(System.in);
Zotato(){
deliveryCharge=0;
r=new HashMap<>();
c=new HashMap<>();
companyBalance=0;
}
public void updateCollection() {
for (Map.Entry<Integer,Restaurant> e : r.entrySet()) {
this.companyBalance+=e.getValue().returnToZotato();
this.deliveryCharge+=e.getValue().returnDelivery();
}
}
public void addRestaurant(String s,String add,boolean a,boolean f) { //if a is true it is authentic, similarly for f
Restaurant r1;
if(a) {
r1=new authenticRestaurant(s+" (Authentic)",add);
}
else if(f) {
r1=new fastFoodRestaurant(s+" (Fast Food)",add);
}
else {
r1=new Restaurant(s,add);
}
this.noRes++;
r.put(noRes,r1);
}
public void addCustomer(String s1,String a,boolean e,boolean s) {
Customer c1;
if(e) {
c1=new eliteCustomer(s1+" (Elite customer)",a);
}
else if(s) {
c1=new specialCustomer(s1+" (Special customer)",a);
}
else {
c1=new Customer(s1,a);
}
this.noCus++;
c.put(noCus,c1);
}
public void enterAsOwner() {
restList();
int vari=input.nextInt();
r.get(vari).menu();
}
public void enterAsCustomer() {
cusList();
int vari=input.nextInt();
c.get(vari).setRestaurants(r);
c.get(vari).menu();
}
public void userDetails() {
System.out.println("1.Customer List");
System.out.println("2.Restaurant List");
int x=input.nextInt();
if(x==1) {
cusList();
int vari=input.nextInt();
c.get(vari).details();
}
else {
restList();
int vari=input.nextInt();
r.get(vari).restLoc();
}
}
public void restList() {
for (Map.Entry<Integer,Restaurant> e : r.entrySet()) {
System.out.println(e.getKey()+" "+e.getValue().getName());
}
}
public void cusList() {
for (Map.Entry<Integer,Customer> e : c.entrySet()) {
System.out.println(e.getKey()+" "+e.getValue().getName());
}
}
public void companyAccountDetails() {
this.updateCollection();
System.out.println("Total company balance - INR "+this.companyBalance);
System.out.println("Total Delivery Charges Collected - INR "+this.deliveryCharge);
}
public void updateDelivery(int x) {
this.deliveryCharge+=x;
}
public void companyBalance(int x) {
this.companyBalance+=x;
}
}
class Customer implements User{
private String name;
final private String address;
private HashMap<Integer,Restaurant> r;
protected HashMap<foodItem,Integer> f;
protected int rewardPoints;
protected double wallet=1000.0;
protected Restaurant res;
protected Scanner input=new Scanner(System.in);
protected ArrayList<String> lastOrders;
Customer(String s,String a){
this.name=s;
this.address=a;
r=new HashMap<>();
f=new HashMap<>();
res=null;
rewardPoints=0;
lastOrders=new ArrayList<String>();
}
public void setRestaurants(HashMap<Integer,Restaurant> r1) {
this.r=r1;
}
public void printLastOrders() {
for(String x:lastOrders) {
System.out.println(x);
}
}
@Override
public void menu() {
System.out.println("Welcome "+this.name);
System.out.println("1. Select Restaurant");
System.out.println("2. Checkout cart");
System.out.println("3. Reward won");
System.out.println("4. Print the recent orders");
System.out.println("5.Exit");
int ch=input.nextInt();
int first=1;
while(ch!=5) {
if(first!=1) {
System.out.println("1. Search Item");
System.out.println("2. Checkout cart");
System.out.println("3. Reward won");
System.out.println("4. Print the recent orders");
System.out.println("5.Exit");
ch=input.nextInt();
}
else {
first+=1;
for (Map.Entry<Integer,Restaurant> e : r.entrySet()) {
System.out.println(e.getKey()+" "+e.getValue().getName());
}
int vari=input.nextInt();
res=r.get(vari);
//chooseRestaurant(r.get(vari));
}
switch(ch) {
case 1:
chooseRestaurant(res);
break;
case 2:
this.checkout();
break;
case 3:
this.rewardPointsEarned();
break;
case 4:
this.printLastOrders();
break;
case 5:
System.out.println("EXIT");
break;
}
}
}
@Override
public void details() {
System.out.println(this.name+" , "+this.address+" , "+this.wallet);
}
@Override
public int rewards(int finalAmount) {
return res.rewards(finalAmount);
}
public void rewardPointsEarned() {
System.out.println("Reward points earned are : "+this.rewardPoints);
}
public void cutTotal(double cost) {
if(this.rewardPoints==0) {
wallet-=cost;
}
else {
if(this.rewardPoints>cost) {
this.rewardPoints-=cost;
}
else {
cost-=this.rewardPoints;
this.rewardPoints=0;
this.wallet-=cost;
}
}
}
public void checkout() {
double cost=0;
int total_items=0;
String addFinal="";
System.out.println("Items in Cart- ");
for (Map.Entry<foodItem,Integer> e : f.entrySet()) {
foodItem f1=e.getKey();
f1.checkoutDetails(e.getValue());
if(cost+f1.getPrice()*e.getValue()<wallet) {
cost+=f1.getPrice()*e.getValue()*(1-(double)f1.getOffer()/100);
total_items+=e.getValue();
addFinal+=" Bought item: "+f1.getFname()+" , "+e.getValue();
}
else {
System.out.println("Wallet does not have the required amount hence remove some items");
for (Map.Entry<foodItem,Integer> e1 : f.entrySet()) {
foodItem f2=e1.getKey();
System.out.println("Do you want to remove? "+f2.getFname());
System.out.println("Enter 1 for yes else 0");
int ask=input.nextInt();
if(ask==1) {
f.remove(f2);
}
}
}
}
if(total_items==0) {
System.out.println("No items in quantity.");
}
else {
System.out.println();
double x=res.discount(cost);
cost=cost-x;
int rewards=this.rewards((int)cost);
res.updateTotal(cost);
System.out.println("Delivery charge- INR 40/-");
addFinal+=" from restaurant "+res.getName();
cost+=40;
res.updateDelivery(40);
addFinal+=" Delivery charge 40";
System.out.println("Total order value- INR "+cost);
System.out.println("1. Proceed to Checkout. ");
int vari=input.nextInt();
if(vari==1) {
cutTotal(cost);
System.out.println(total_items+" items successfully bough for "+cost+" INR.");
this.lastOrders.add(addFinal);
cost=0;
this.rewardPoints+=rewards;
f.clear();
}
}
}
public double deliveryCharge(int cost) {
return (cost+40);
}
public void chooseRestaurant(Restaurant r) {
r.details();
int itemno=input.nextInt();
System.out.println("Enter item quantity (has an upper limit)");
//you cannot order more than specified
int qty=input.nextInt();
foodItem f1=r.getItem(itemno);
if(f.containsKey(f1)) {
if(f1.getQuantity()<qty+f.get(f1)) {
System.out.println("Maximum quanitity exceeded, adding maximum in cart");
f.replace(f1,f1.getQuantity());
}
else {
f.replace(f1,qty+f.get(f1));
}
}
else {
if(f1.getQuantity()<qty) {
System.out.println("Maximum quanitity exceeded, adding maximum in cart");
f.put(f1,f1.getQuantity());
}
else {
f.put(f1,qty);
}
}
System.out.println("Item added to cart");
}
public String getName() {
return this.name;
}
}
class eliteCustomer extends Customer{
eliteCustomer(String s,String a) {
super(s,a);
}
@Override
public double deliveryCharge(int cost) {
return (cost);
}
@Override
public void checkout() {
double cost=0;
int total_items=0;
String addFinal="";
System.out.println("Items in Cart- ");
for (Map.Entry<foodItem,Integer> e : f.entrySet()) {
foodItem f1=e.getKey();
f1.checkoutDetails(e.getValue());
if(cost+f1.getPrice()*e.getValue()<wallet) {
cost+=f1.getPrice()*e.getValue()*(1-(double)f1.getOffer()/100);
total_items+=e.getValue();
addFinal+=" Bought item: "+f1.getFname()+" , "+e.getValue();
}
else {
System.out.println("Wallet does not have the required amount hence remove some items");
for (Map.Entry<foodItem,Integer> e1 : f.entrySet()) {
foodItem f2=e1.getKey();
System.out.println("Do you want to remove? "+f2.getFname());
System.out.println("Enter 1 for yes else 0");
int ask=input.nextInt();
if(ask==1) {
f.remove(f2);
}
}
}
}
if(total_items==0) {
System.out.println("No items in quantity.");
}
else {
System.out.println();
double x=res.discount(cost);
cost=cost-x;
int reward=this.rewards((int)cost);
if(cost>200) {
cost-=50;
}
res.updateTotal(cost);
System.out.println("Delivery charge- INR 0/-");
addFinal+=" from restaurant "+res.getName();
addFinal+=" Delivery charge 0";
System.out.println("Total order value- INR "+cost);
System.out.println("1. Proceed to Checkout. ");
int vari=input.nextInt();
if(vari==1) {
cutTotal(cost);
System.out.println(total_items+" items successfully bough for "+cost+" INR.");
this.lastOrders.add(addFinal);
cost=0;
this.rewardPoints+=reward;
f.clear();
}
}
}
}
class specialCustomer extends Customer{
specialCustomer(String s,String a) {
super(s,a);
}
@Override
public double deliveryCharge(int cost) {
return (cost+20);
}
@Override
public void checkout() {
double cost=0;
int total_items=0;
String addFinal="";
System.out.println("Items in Cart- ");
for (Map.Entry<foodItem,Integer> e : f.entrySet()) {
foodItem f1=e.getKey();
f1.checkoutDetails(e.getValue());
if(cost+f1.getPrice()*e.getValue()<wallet) {
cost+=f1.getPrice()*e.getValue()*(1-(double)f1.getOffer()/100);
total_items+=e.getValue();
addFinal+=" Bought item: "+f1.getFname()+" , "+e.getValue();
}
else {
System.out.println("Wallet does not have the required amount hence remove some items");
for (Map.Entry<foodItem,Integer> e1 : f.entrySet()) {
foodItem f2=e1.getKey();
System.out.println("Do you want to remove? "+f2.getFname());
System.out.println("Enter 1 for yes else 0");
int ask=input.nextInt();
if(ask==1) {
f.remove(f2);
}
}
}
}
if(total_items==0) {
System.out.println("No items in quantity.");
}
else {
System.out.println();
double x=res.discount(cost);
cost=cost-x;
int reward=this.rewards((int)cost);
if(cost>200) {
cost-=25;
}
res.updateTotal(cost);
System.out.println("Delivery charge- INR 20/-");
addFinal+=" from restaurant "+res.getName();
cost+=20;
res.updateDelivery(20);
addFinal+=" Delivery charge 20";
System.out.println("Total order value- INR "+cost);
System.out.println("1. Proceed to Checkout. ");
int vari=input.nextInt();
if(vari==1) {
cutTotal(cost);
System.out.println(total_items+" items successfully bough for "+cost+" INR.");
this.lastOrders.add(addFinal);
cost=0;
this.rewardPoints+=reward;
f.clear();
}
}
}
}
class Restaurant implements User{
private Scanner input=new Scanner(System.in);
final private String name;
final private String address;
private ArrayList<foodItem> f; //itemcode is noOfItems+1
private int noOfItems;
private int rewardPoints;
private int discount;
private int ordersTaken;
protected double totalEarning=0;
protected int deliveryAmt=0;
Restaurant(String r,String a){
this.name=r;
this.address=a;
f=new ArrayList<>();
noOfItems=0;
rewardPoints=0;
discount=0;
rewardPoints=0;
ordersTaken=0;
}
public String getName() {
return this.name;
}
public foodItem getItem(int x) {
return f.get(x-1);
}
@Override
public void menu() {
System.out.println("Welcome "+this.name);
System.out.println("1. Add item");
System.out.println("2. Edit item");
System.out.println("3. Print Rewards");
System.out.println("4. Discount on bill value");
System.out.println("5.Exit");
int ch=input.nextInt();
int first=1;
while(ch!=5) {
if(first!=1) {
System.out.println("1. Add item");
System.out.println("2. Edit item");
System.out.println("3. Print Rewards");
System.out.println("4. Discount on bill value");
System.out.println("5.Exit");
ch=input.nextInt();
}
else {
first+=1;
}
switch(ch) {
case 1:
System.out.println("Enter food item details");
System.out.println("Food name ");
input.nextLine();
String ss=input.nextLine();
System.out.println("Item price");
int x=input.nextInt();
System.out.println("Item quantity");
int y=input.nextInt();
System.out.println("Item category ");
input.nextLine();
String s11=input.nextLine();;
System.out.println("Offer");
int z=input.nextInt();
f.add(new foodItem(ss,x,y,s11,z,this.noOfItems+1));
noOfItems++;
System.out.print(this.noOfItems+" ");
f.get(noOfItems-1).itemDetails();
break;
case 2:
this.details();
int vari=input.nextInt(); //chosen code
System.out.println("Choose an attribute to edit: ");
System.out.println("1. Food name");
System.out.println("2. Item price");
System.out.println("3. Item quantity");
System.out.println("4. Item category");
System.out.println("5. Offer");
int edit=input.nextInt();
if(edit==1) {
String s;
System.out.println("Enter new name ");
s=input.next();
f.get(vari-1).setFname(s);
}
else if(edit==4) {
String s;
System.out.println("Enter new category ");
s=input.next();
f.get(vari-1).setCategory(s);
}
else if(edit==2) {
System.out.println("Enter new price ");
int n=input.nextInt();
f.get(vari-1).setPrice(n);
}
else if(edit==3) {
System.out.println("Enter new quantity ");
int n=input.nextInt();
f.get(vari-1).setQuantity(n);
}
else if(edit==5) {
System.out.println("Enter new offer ");
int n=input.nextInt();
f.get(vari-1).setOffer(n);
}
System.out.print(vari+" "+this.name+" - ");
f.get(vari-1).itemDetails();
System.out.println();
break;
case 3:
System.out.println("Reward Points : "+this.getRewards());
break;
case 4:
System.out.println("Offers on bill value - ");
discount=input.nextInt();
break;
case 5:
System.out.println("Exit");
break;
default:
System.out.println("Wrong choice, enter a valid choice");
break;
}
}
}
public void restLoc() {
System.out.println(this.name+" , "+this.address+" , Orders Taken: "+this.ordersTaken);
}
public void updateDelivery(int x) {
this.deliveryAmt+=x;
}
@Override
public void details() {
System.out.println("Choose item by code");
for(foodItem x:f) {
System.out.print(x.getCode()+" "+this.name+" - ");
x.itemDetails();
//System.out.println();
}
}
@Override
public int rewards(int total) {
int x=(int)total/100;
x*=5;
this.rewardPoints+=x;
return(x);
}
public double returnToZotato() {
double x=this.totalEarning;
this.totalEarning=0;
return x/100;
}
public void addRewards(int x) {
this.rewardPoints+=x;
}
public void updateTotal(double x) {
this.ordersTaken+=1;
this.totalEarning+=x;
}
public double discount(double total) {
return total*discount/100;
}
public int getRewards() {
return this.rewardPoints; //ensure rewards is called before calling this
}
public double getDiscount() {
return discount;
}
public double returnDelivery() {
return this.deliveryAmt;
}
}
class authenticRestaurant extends Restaurant{
authenticRestaurant(String r,String a) {
super(r,a);
}
@Override
public double discount(double total) {
double y=(double)total*super.getDiscount()/100;
double x=total-y;
if(x>100) {
return(y+50);
}
else {
return(y);
}
}
@Override
public int rewards(int total) { //handle rewards here
int x=(int)total/200;
super.addRewards(x*25);
//rewards=total*25/200
return(x*25);
}
}
class fastFoodRestaurant extends Restaurant{
fastFoodRestaurant(String r,String a) {
super(r,a);
}
@Override
public int rewards(int total) {
//rewards=total*10/150
int x=(int)total/150;
super.addRewards(x*10);
return(x*10);
}
}
class foodItem{
private String fname;
private int price;
private int maxquantity; //this is maximum quantity the person can buy
private String category;
private int offer;
private final int code;
foodItem(String n,int p,int q,String s,int o,int ite){
this.fname=n;
this.price=p;
this.maxquantity=q;
this.category=s;
this.offer=o;
this.code=ite;
}
public String getFname() {
return this.fname;
}
public void setFname(String s) {
this.fname=s;
}
public int getPrice() {
return this.price;
}
public void setPrice(int p) {
this.price=p;
}
public int getQuantity() {
return this.maxquantity;
}
public void setQuantity(int q) {
this.maxquantity=q;
}
public String getCategory() {
return this.category;
}
public void setCategory(String s) {
this.category=s;
}
public int getOffer() {
return this.offer;
}
public void setOffer(int f) {
this.offer=f;
}
public void itemDetails() {
System.out.println(this.fname +" "+this.price+" "+this.maxquantity+" "+this.offer+"% off "+this.category);
}
public void checkoutDetails(int qty) {
System.out.print(this.fname +" "+this.price+" "+qty+" "+this.offer+"% off "+this.category);
}
public int getCode() {
return this.code;
}
}
public class week2 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int ch=0;
Zotato z=new Zotato();
z.addRestaurant("Shah","Delhi",true,false);
z.addRestaurant("Ravi's","Mumbai",false,false);
z.addRestaurant("The Chinese","Kolkata",true,false);
z.addRestaurant("Wang's","Haryana",false,true);
z.addRestaurant("Paradise","Agra",false,false);
z.addCustomer("Ram","Chennai",true,false);
z.addCustomer("Sam","Dubai",true,false);
z.addCustomer("Tim","Gujarat",false,true);
z.addCustomer("Kim","Chennai",false,false);
z.addCustomer("Jim","Chennai",false,false);
while(ch!=5) {
System.out.println("Welcome to Zotato: ");
System.out.println("1. Enter as Restaurant Owner");
System.out.println("2. Enter as Customer ");
System.out.println("3.Check User Details");
System.out.println("4. Company Account details");
System.out.println("5.Exit");
ch=input.nextInt();
switch(ch){
case 1:
z.enterAsOwner();
break;
case 2:
z.enterAsCustomer();
break;
case 3:
z.userDetails();
break;
case 4:
z.companyAccountDetails();
break;
case 5:
System.out.println("Exit");
break;
default:
System.out.println("Wrong choice, enter a valid choice");
break;
}
}
}
}
<file_sep>import java.util.*;
class Gameplay<T>{
private int total;
private HashMap<Integer,Player> p=new HashMap<Integer,Player>();
private Random rand=new Random();
private T user;
private int round=0;
private boolean[] alive;
private int left;
private Mafia mafia=new Mafia(0);
private Detective detective=new Detective(0);
private Healer healer=new Healer(0);
private Scanner input=new Scanner(System.in);
private ArrayList<Mafia> mfs;
Gameplay(int t,T o){
mfs=new ArrayList<Mafia>();
this.total=t;
alive=new boolean[total+1];
this.user=o;
p.put(1,(Player)this.user);
round=1;
alive=new boolean[total+1];
for(int i=1;i<=total;i++) {
alive[i]=true;
}
left=total;
}
public void startGame() {
generatePlayer();
boolean com=this.user instanceof Commoner;
System.out.println("You are Player1.");
System.out.println(user.toString());
if(!com) {
printSimilar();
}
while(!gameOver()) {
startRound();
}
}
private void remainingPlayers() {
System.out.print(left+" players are remaining: ");
for(int i=1;i<=total;i++) {
if(alive[i]) {
System.out.print("Player"+i+" ,");
}
}
System.out.println(" are alive.");
}
private void startRound() {
System.out.println("ROUND "+round++);
remainingPlayers();
int dead=0;
int test=0;
int heal=0;
if(this.user instanceof Mafia && alive[1]) {
dead=mafia.choosePlayerForRole(p,true,alive);
while(p.get(dead) instanceof Mafia) {
System.out.println("Mafia cannot kill a mafia");
dead=mafia.choosePlayerForRole(p,true,alive);
}
}
else {
dead=mafia.choosePlayerForRole(p,false,alive);
while(p.get(dead) instanceof Mafia) {
dead=mafia.choosePlayerForRole(p,false,alive);
}
}
if(this.user instanceof Detective && alive[1]) {
test=detective.choosePlayerForRole(p,true,alive);
while(p.get(test) instanceof Detective) {
System.out.println("Detective cannot test a detective");
test=detective.choosePlayerForRole(p,true,alive);
}
}
else {
test=detective.choosePlayerForRole(p,false,alive);
while(p.get(test) instanceof Detective) {
test=detective.choosePlayerForRole(p,false,alive);
}
}
if(!detectivesAlive()) {
test=0;
}
if(this.user instanceof Healer && alive[1]) {
heal=healer.choosePlayerForRole(p,true,alive);
}
else {
heal=healer.choosePlayerForRole(p,false,alive);
}
System.out.println("-- End of actions-- ");
int votingDone=0;
if(heal==dead && dead!=0 && alive[heal]) {
p.get(heal).setHp(500); //if healing and target is same no one is killed and hp is set to 500
System.out.println("No one is killed");
}
else {
if(dead!=0 && alive[dead] && !(p.get(dead) instanceof Mafia)) {
if(mafiaHp()>=p.get(dead).getHp()) {
int a=p.get(dead).getHp();
int b=mafiasLeft();
decreaseMafiasHp((int)a/b,a);
alive[dead]=false;
left-=1;
System.out.println("Player"+dead+" has died.");
}
else {
int a=p.get(dead).getHp();
int b=mafiasLeft();
decreaseMafiasHp((int)a/b,a);
System.out.println("No one died");
}
}
if(heal!=0 && alive[heal]) {
int var=p.get(heal).getHp();
p.get(heal).setHp(500+var);
}
if(test!=0 && alive[test]) {
System.out.println("Player"+test+" has been voted out.");
alive[test]=false;
left-=1;
}
else {
conductVoting();
votingDone=1;
}
}
if(votingDone==0) {
conductVoting();
votingDone=1;
}
}
private void conductVoting() {
ArrayList<Integer> voting=new ArrayList<Integer>();
int temp;
if(alive[1]) {
System.out.println("Select Player to vote out");
int var=input.nextInt();
while(var<0 || var>alive.length-1 || !alive[var]) {
System.out.println("Choose a valid person to vote out");
var=input.nextInt();
}
voting.add(var);
}
for(int i=2;i<=total;i++) {
if(alive[i]) {
voting.add(p.get(i).vote(alive));
}
}
temp=voting.get(1);
Collections.sort(voting);
int cur=1;
int ele=-1;
int maxi=-1;
for(int i=0;i<voting.size();i++) {
if(i!=0) {
if(voting.get(i)==voting.get(i-1)) {
cur+=1;
}
else {
maxi=Math.max(cur,maxi);
if(maxi==cur) {
ele=voting.get(i-1);
}
cur=1;
}
}
}
ele=temp;
if(alive[ele]) {
System.out.println("Player"+ele+ " has been voted out");
alive[ele]=false;
left-=1;
}
}
private boolean detectivesAlive() {
for(int i=1;i<=total;i++) {
Player x=p.get(i);
if(alive[i] && x.equals(detective)) {
return true;
}
}
return false;
}
private boolean gameOver() {
int maf=0;
for(int i=1;i<=total;i++) {
Player x=p.get(i);
if(x instanceof Mafia && alive[i]) {
maf++;
}
}
if(maf>=left-maf) {
System.out.println("Mafias win");
tellAll();
return true;
}
else if(maf==0) {
System.out.println("Mafias lose");
tellAll();
return true;
}
else {
return false;
}
}
private void tellAll() {
for(int i=1;i<=total;i++) {
Player x=p.get(i);
if(x instanceof Mafia) {
System.out.print("Player"+i+" , ");
}
}
System.out.println("were Mafia");
for(int i=1;i<=total;i++) {
Player x=p.get(i);
if(x instanceof Detective) {
System.out.print("Player"+i+" , ");
}
}
System.out.println("were Detectives");
for(int i=1;i<=total;i++) {
Player x=p.get(i);
if(x instanceof Healer) {
System.out.print("Player"+i+" , ");
}
}
System.out.println("were Healer");
for(int i=1;i<=total;i++) {
Player x=p.get(i);
if(x instanceof Commoner) {
System.out.print("Player"+i+" , ");
}
}
System.out.println("were Commoners");
}
private void decreaseMafiasHp(int dec,int y) {
Collections.sort(mfs,new SortByHp());
int overallDamage=y;
int i=1;
int maxi=total*3;
while(overallDamage>0) {
Player x=p.get(i);
if(x instanceof Mafia && alive[i]) {
int var=x.getHp();
if(var>=dec) {
x.setHp(var-dec);
overallDamage-=dec;
}
else {
x.setHp(0);
overallDamage-=var;
}
}
if(i<total) {
i+=1;
}
else if(i==total){
i=1;
}
maxi-=1;
if(maxi==0) {
overallDamage=0;
}
}
}
private int mafiasLeft() {
int h=0;
for(int i=1;i<=total;i++) {
Player x=p.get(i);
if(x instanceof Mafia && alive[i]) {
h+=1;
}
}
return h;
}
private int mafiaHp() {
int h=0;
for(int i=1;i<=total;i++) {
Player x=p.get(i);
if(x instanceof Mafia && alive[i]) {
h+=x.getHp();
}
}
return(h);
}
private void printSimilar() {
ArrayList<Integer> arr=new ArrayList<Integer>();
for(int i=2;i<=total;i++) {
Player x=p.get(i);
if(x instanceof Mafia && this.user instanceof Mafia) {
arr.add(i);
}
else if(x instanceof Detective && this.user instanceof Detective) {
arr.add(i);
}
else if(x instanceof Healer && this.user instanceof Healer){
arr.add(i);
}
}
if(this.user instanceof Mafia) {
System.out.print("Other Mafias are: [ ");
for(int i:arr) {
System.out.print("Player "+i+" , ");
}
System.out.println("] ");
}
if(this.user instanceof Healer) {
System.out.print("Other Healers are: [ ");
for(int i:arr) {
System.out.print("Player "+i+" , ");
}
System.out.println("] ");
}
if(this.user instanceof Detective) {
System.out.print("Other Detectives are: [ ");
for(int i:arr) {
System.out.print("Player "+i+" , ");
}
System.out.println("] ");
}
}
private void generatePlayer() {
int healers=0;
int mafias=0;
int detectives=0;
if(user instanceof Healer)
{
healers=Math.max(1,(int)total/10)-1;
}
else {
healers=Math.max(1,(int)total/10);
}
if(user instanceof Mafia)
{
mafias=(int)total/5-1;
}
else {
mafias=(int)total/5;
}
if(user instanceof Detective)
{
detectives=(int)total/5-1;
}
else {
detectives=(int)total/5;
}
Set<Integer> s=new LinkedHashSet<Integer>();
while(s.size()<total-1) {
int x=2+rand.nextInt(total-1);
s.add(x);
}
int start=2;
Iterator<Integer> i=s.iterator();
while(i.hasNext()) {
if(healers>0) {
healers-=1;
p.put(i.next(),new Healer(start));
}
else if(mafias>0) {
mafias-=1;
Mafia nm=new Mafia(start);
p.put(i.next(),nm);
mfs.add(nm);
}
else if(detectives>0) {
detectives-=1;
p.put(i.next(),new Detective(start));
}
else {
p.put(i.next(),new Commoner(start));
}
start+=1;
}
}
}
abstract class Player{
protected int pNo;
protected String type;
protected int hp=0;
protected Random rand=new Random();
protected Scanner input=new Scanner(System.in);
protected int playerNo;
protected int vote(boolean alive[]) {
return(validRandom(alive));
}
protected int validInput(boolean alive[]) {
int n=input.nextInt();
if(n<0 ||n>alive.length-1 || !alive[n]) {
while(n>alive.length-1 || !alive[n] || n<0) {
System.out.println("Either the player you entered has already died or is out of bounds. Choose someone else.");
n=input.nextInt();
}
}
return n;
}
protected int validRandom(boolean alive[]) { //invalid is not considered
int n=1+rand.nextInt(alive.length-1);
if(n<0 ||n>alive.length-1 || !alive[n]) {
while(n>alive.length-1 || !alive[n]) {
n=1+rand.nextInt(alive.length-1);
}
}
return n;
}
public String toString() { //tostring object class
String v="";
v+="You are a ";
if(this instanceof Mafia) {
v+="Mafia. ";
}
else if(this instanceof Detective) {
v+="Detective. ";
}
else if(this instanceof Healer) {
v+="Healer. ";
}
else if(this instanceof Commoner) {
v+="Commoner. ";
}
return(v);
}
public boolean equals(Object o) { //equals for object class
if(o!=null && getClass()==o.getClass() ) {
return(true);
}
return false;
}
abstract int getHp();
abstract void setHp(int h);
abstract int choosePlayerForRole(HashMap<Integer,Player> p,boolean b,boolean alive[]);
}
class SortByHp implements Comparator<Player>{ //Comparator for sorting mafias on basis of hp
@Override
public int compare(Player o1, Player o2) {
return o1.getHp()-o2.getHp();
}
}
class Commoner extends Player{
Commoner(int n){
super();
hp=1000;
playerNo=n;
}
@Override
public int getHp(){
return hp;
}
@Override
public void setHp(int h){
this.hp=h;
}
@Override
public int choosePlayerForRole(HashMap<Integer,Player> p,boolean b,boolean alive[]) {
//no role
return 0;
}
}
class Healer extends Player{
Healer(int n){
super();
hp=800;
playerNo=n;
}
@Override
public void setHp(int h){
this.hp=h;
}
@Override
public int getHp(){
return hp;
}
@Override
public int choosePlayerForRole(HashMap<Integer, Player> p,boolean b,boolean alive[]) {
int heal=0;
if(b) {
System.out.print("Choose a player to heal ");
heal=validInput(alive);
}
else {
heal=validRandom(alive);
}
System.out.println("Healers have chosen someone to heal.");
return heal;
}
}
class Detective extends Player{
Detective(int n){
super();
hp=800;
playerNo=n;
}
@Override
public void setHp(int h){
this.hp=h;
}
@Override
public int getHp(){
return hp;
}
@Override
public int choosePlayerForRole(HashMap<Integer, Player> p,boolean b,boolean alive[]) { //check that the query should not be a detective
int test=0;
int f=0;
if(b) {
System.out.print("Choose a player to test ");
test=validInput(alive);
if(p.get(test) instanceof Mafia) {
System.out.println("Player "+test+" is a mafia");
f=test;
}
else {
System.out.println("Player "+test+" is not a mafia");
}
}
else {
test=validRandom(alive);
}
System.out.println("Detectives have chosen a player to test"); //this can be printed multiple times if invalid input is chosen
return f; //f=player number if mafia else 0
}
}
class Mafia extends Player{
Mafia(int n){
super();
hp=2500;
playerNo=n;
}
@Override
public void setHp(int h){
this.hp=h;
}
@Override
public int getHp(){
return hp;
}
@Override
public int choosePlayerForRole(HashMap<Integer, Player> p,boolean b,boolean alive[]) {
int target=0;
if(b) {
System.out.print("Choose a target: ");
target=validInput(alive);
}
else {
target=validRandom(alive);
System.out.println("Mafias have chosen a target. "); //this can be printed multiple times if invalid input is chosen
}
return target;
}
}
public class week3 {
static Scanner input=new Scanner(System.in);
static Random rand=new Random();
public static void main(String[] args) {
int n=0,f=0;
int type=0;
System.out.println("Welcome to Mafia");
while(f!=1) {
System.out.print("Enter Number of Players : ");
n=input.nextInt();
if(n>=6) {
f=1;
}
else {
System.out.println("Number of players should be greater than 5");
}
}
f=0;
System.out.println("Choose a Character");
System.out.println("1) Mafia");
System.out.println("2) Detective");
System.out.println("3) Healer");
System.out.println("4) Commoner");
System.out.println("5) Assign Randomly");
while(f!=1) {
type=input.nextInt();
if(type<6 && type>0) {
f=1;
}
else {
System.out.println("Enter a valid type between 1 to 5");
}
}
if(type==5) {
type=1+rand.nextInt(4);
}
if(type==1) {
Mafia m=new Mafia(1);
Gameplay<Mafia> g=new Gameplay<Mafia>(n,m);
g.startGame();
}
else if(type==2) {
Detective d=new Detective(1);
Gameplay<Detective> g=new Gameplay<Detective>(n,d);
g.startGame();
}
else if(type==3) {
Healer h=new Healer(1);
Gameplay<Healer> g=new Gameplay<Healer>(n,h);
g.startGame();
}
else {
Commoner c=new Commoner(1);
Gameplay<Commoner> g=new Gameplay<Commoner>(n,c);
g.startGame();
}
}
}
<file_sep># Advanced-Programming-Labs
These are the Lab assignments done for Advanced Programming Course offered at IIIT Delhi which is about Object Oriented Programming in Java.
The code along with their respective problem statements is present in the src folder.
| 97d338dc6d804c121fef83a916b148f154bd8d3f | [
"Markdown",
"Java"
] | 3 | Java | bhavyanarang/Advanced-Programming-Labs | 5715b99c4100c97c6eb7277d33a9448ea4cc95e9 | 52632a14f38c99475c50b61faee8bffa62c37312 |
refs/heads/main | <repo_name>wajehulhasan/caravel_Lexicon<file_sep>/README.md
[](https://opensource.org/licenses/Apache-2.0) [](https://github.com/efabless/caravel_project_example/actions/workflows/user_project_ci.yml) [](https://github.com/efabless/caravel_project_example/actions/workflows/caravel_build.yml)
SPDX-FileCopyrightText: 2020 Efabless Corporation 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. SPDX-License-Identifier: Apache-2.0
*LEXICON RISC-V Core 1.0 from MERL*
This repository contains the Lexicon Core design RTL. Lexicon Is A Machine-Mode (M-Mode) Only, 32-Bit Cpu Small Core Which Supports Risc-V’s Integer (I), Compressed Instruction (C), Multiplication And Division (M), And Instruction-Fetch Fence, And Csr Extensions. The Core Contains A 4-Stage, Scalar, In-Order Pipeline
Directory Structure
├── verlog # User verilog Directory
│ ├── rtl # RTL
│ ├── dv # Design Verification
│ ├── gl # Gate Level Netlist
The Lexicon Source Code is avaialable here
├── verlog # User verilog Directory
│ ├── rtl # RTL
| ├── user_project_wrapper.v # User Project Wrapper source file
| ├── user_proj_example.v # User Project Example source file
| ├── Lexicon # Lexicon folder
| ├── Lexicon.v # Lexicon source file
| ├── sky130_sram_1kbyte_1rw1r_32x256_8.v # 1KB sram
The Design Verification Testbench is available here
├── verlog # User verilog Directory
│ ├── dv # Design Verification
│ ├── Lexicon # Design Test Directory
│ ├── hex # Hex files folder
| ├── asm # Assmebly files folder
The synthesized netlist is present here:
├── verlog # User verilog Directory
│ ├── gl # Gate Level Netlis
│ ├── user_project_wrapper.v # User Project Wrapper Netlist
│ ├── user_proj_example.v # User Project Example Netlist
The hardened macros are placed here:
├── def # def Directory
│ ├── user_project_wrapper.def # User Project Wrapper def file
├── lef # lef Directory
│ ├── user_project_wrapper.lef # User Project Wrapper lef file
│ ├── user_proj_example.lef # User Project Example lef file
├── gds # gds Directory
│ ├── user_project_wrapper.gdz.gz # User Project Wrapper gds
│ ├── user_proj_example.gdz.gz # User Project Example gds
Testing of Design
Go to verilog/dv/Lexicon/ directory
Set the GCC_PATH environment variable.
Set the PDK_PATH environment variable.
Copy the given program hex file into uart.hex.
run the make commad for RTL simulation
run the SIM=GL make command for netlist simulation
Note: Dont forget to add 00000FFF instruction in the end of the uart.hex to stop the uart transmission if you are using your own codes.
<file_sep>/verilog/dv/Lexicon/Lexicon.c
// SPDX-FileCopyrightText: 2020 Efabless Corporation
//
// 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.
// SPDX-License-Identifier: Apache-2.0
#include "verilog/dv/caravel/defs.h"
#include "verilog/dv/caravel/stub.c"
void main()
{
//reg_mprj_io_0 = GPIO_MODE_USER_STD_INPUT_NOPULL;
//reg_mprj_io_1 = GPIO_MODE_USER_STD_INPUT_NOPULL;
//reg_mprj_io_2 = GPIO_MODE_USER_STD_INPUT_NOPULL;
//reg_mprj_io_3 = GPIO_MODE_USER_STD_INPUT_NOPULL;
//reg_mprj_io_4 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_5 = GPIO_MODE_USER_STD_INPUT_NOPULL;
// reg_mprj_io_6 = GPIO_MODE_USER_STD_OUTPUT;
// reg_mprj_io_7 = GPIO_MODE_USER_STD_OUTPUT;
//reg_mprj_io_6 = GPIO_MODE_USER_STD_OUTPUT;
//reg_mprj_io_7 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_8 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_9 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_10 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_11 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_12 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_13 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_14 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_15 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_16 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_17 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_18 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_19 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_20 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_21 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_22 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_23 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_24 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_25 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_26 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_27 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_28 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_29 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_30 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_31 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_32 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_33 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_34 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_35 = GPIO_MODE_USER_STD_OUTPUT;
//reg_mprj_io_36 = GPIO_MODE_USER_STD_OUTPUT;
reg_mprj_io_37 = GPIO_MODE_MGMT_STD_OUTPUT;
reg_mprj_xfer = 1;
while(reg_mprj_xfer == 1);
reg_la2_oenb = reg_la2_iena = 0x00000002;
reg_la2_data = 0x00000000; // reset
reg_la2_data = 0x00000001;
reg_la2_oenb = reg_la2_iena = 0x00000003;
reg_la1_oenb = reg_la1_iena = 0x00000000;
reg_la1_data = 0x00000015C; // Clk_per_bit
reg_la0_oenb = reg_la0_iena = 0x00000002;
reg_la0_data = 0x00000000;
reg_mprj_datah = 0x20;
}
| a1d6af4c8baeeb82541aceab14e401ea5b038577 | [
"Markdown",
"C"
] | 2 | Markdown | wajehulhasan/caravel_Lexicon | 79c0a87d0ca10ff8e969e8b6dd3fe08826dc68c1 | 1f198fb47e182b9abbfdf46116ad13bb0330a895 |
refs/heads/master | <repo_name>JustalK/Scripts<file_sep>/ssh2719492.sh~
#!/bin/bash
VAL=$(head -n 1 password.txt);
sshpass -p $VAL ssh -o StrictHostKeyChecking=no <EMAIL>;
<file_sep>/README.md
Scripts for SUPERSOGO - I'm a lazy man
<file_sep>/ssh2719492.sh
#!/bin/bash
VAL=$(head -n 1 password.txt);
sshpass -p $VAL ssh -o StrictHostKeyChecking=no <EMAIL>;
<file_sep>/ssh5856121.sh~
#!/bin/bash
sshpass -p "<PASSWORD>@" ssh -o StrictHostKeyChecking=no <EMAIL>;
<file_sep>/ssh5856121.sh
#!/bin/bash
VAL=$(head -n 1 password.txt);
sshpass -p $VAL ssh -o StrictHostKeyChecking=no <EMAIL>;
| 652361e15f13b699ddb9bd48eeb7b8ee458e004e | [
"Markdown",
"Shell"
] | 5 | Shell | JustalK/Scripts | cfcff46d1efa130ed3e04295ded9a775fb55d7a2 | e24ceb6a81c9bb73841002ef453f0ac6e4a5020d |
refs/heads/master | <file_sep>$(document).ready(function(){
var get_goat_position=null;
var get_goat_name=null;
var get_tiger_name=null;
$(".tiger").click(function(){
var get_tiger_position = $(this).data('position');
var get_tiger_name = $(this).data('name');
console.log(get_tiger_position)
console.log(get_tiger_name)
});
$(".pointer").click(function(){
var get_pointer_position = $(this).data('position');
var nameArr = get_pointer_position.toString().split('.');
console.log(nameArr);
$('.'+get_goat_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_tiger_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
})
$(".goat").click(function(){
get_goat_position= null;
get_goat_name = null;
get_goat_position = $(this).data('position');
get_goat_name = $(this).data('name');
console.log(get_goat_position);
console.log(get_goat_name);
});
})<file_sep># game
It is prototype and starting phase of game learning.
It is the game which I have played in my childhood.
<file_sep>$(document).ready(function(){
var get_position=null;
var get_name=null;
var get_position1=null;
$(".tiger").click(function(){
get_position1= null;
get_name = null;
get_position1 = $(this).attr('data-position');
get_name = $(this).data('name');
console.log(get_position1);
console.log(get_name);
});
var count=0;
var prevPos=null;
var count2=0;
var prevPos2=null;
$(".pointer").click(function(){
var get_pointer_position = $(this).attr('data-position');
var nameArr = get_pointer_position.toString().split('.');
console.log(nameArr);
var ss=null;
var ss1=null;
var delCheck=1;
if(count>0 && get_name == "tiger1"){
get_position1=prevPos;
console.log(get_position1);
}
if(get_name == "tiger2" && count2>0){
get_position1=prevPos2;
console.log(get_position1);
}
if(get_position1){
var delPos=[(parseInt(get_position1.toString().split('.')[0])+parseInt(nameArr[0]))/2,(parseInt(get_position1.toString().split('.')[1])+parseInt(nameArr[1]))/2];
// console.log(delPos);
ss = delPos[0]+'.'+delPos[1];
ss1 = $("[data-position='"+ss+"']")[1];
// console.log($(ss1).attr('class').split(' ')[0]);
// console.log(ddddd)
if(get_name == "tiger1")
{
count++;
}
if(get_name == "tiger2")
{
count2++;
}
if(get_name == "tiger1"){
prevPos= get_pointer_position;
}
if(get_name == "tiger2"){
prevPos2 = get_pointer_position;
}
}
if(get_name == "tiger1" || get_name == "tiger2"){
if(get_position1== "1.1" && ((nameArr[0] == "0" && (nameArr[1] == "0" || nameArr[1] == "1"|| nameArr[1] == "2")) || (nameArr[0] == "1" && (nameArr[1] == "0" || nameArr[1] == "2" || (nameArr[1] =="3" && $(ss1).attr('class').split(' ')[0] == "goat"))) || (nameArr[0] == "2" && (nameArr[1] == "0" || nameArr[1] == "1"|| nameArr[1] == "2")) || (nameArr[0] == "3" && ((nameArr[1] == "1" || nameArr[1] == "3") && $(ss1).attr('class').split(' ')[0] == "goat")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "1.3" && ((nameArr[0] == "0" && (nameArr[1] == "2" || nameArr[1] == "3"|| nameArr[1] == "4")) || (nameArr[0] == "1" && (nameArr[1] == "2" || nameArr[1] == "4" || (nameArr[1] =="1" && $(ss1).attr('class').split(' ')[0] == "goat"))) || (nameArr[0] == "2" && (nameArr[1] == "2" || nameArr[1] == "3"|| nameArr[1] == "4")) || (nameArr[0] == "3" && ((nameArr[1] == "1" || nameArr[1] == "3") && $(ss1).attr('class').split(' ')[0] == "goat")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "3.1" && ((nameArr[0] == "2" && (nameArr[1] == "0" || nameArr[1] == "1"|| nameArr[1] == "2")) || (nameArr[0] == "3" && (nameArr[1] == "0" || nameArr[1] == "2" || (nameArr[1] =="3" && $(ss1).attr('class').split(' ')[0] == "goat"))) || (nameArr[0] == "4" && (nameArr[1] == "0" || nameArr[1] == "1"|| nameArr[1] == "2")) || (nameArr[0] == "1" && ((nameArr[1] == "1" || nameArr[1] == "3") && $(ss1).attr('class').split(' ')[0] == "goat")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "3.3" && ((nameArr[0] == "2" && (nameArr[1] == "2" || nameArr[1] == "3"|| nameArr[1] == "4")) || (nameArr[0] == "3" && (nameArr[1] == "2" || nameArr[1] == "4" || (nameArr[1] =="1" && $(ss1).attr('class').split(' ')[0] == "goat"))) || (nameArr[0] == "4" && (nameArr[1] == "2" || nameArr[1] == "3"|| nameArr[1] == "4")) || (nameArr[0] == "1" && ((nameArr[1] == "1" || nameArr[1] == "3") && $(ss1).attr('class').split(' ')[0] == "goat")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "2.2" && ((nameArr[0] == "1" && (nameArr[1] == "1" || nameArr[1] == "2"|| nameArr[1] == "3")) || (nameArr[0] == "2" && (nameArr[1] == "1" || nameArr[1] == "3" || ((nameArr[1] == "0" || nameArr[1] == "4") && $(ss1).attr('class').split(' ')[0] == "goat"))) || (nameArr[0] == "3" && (nameArr[1] == "1" || nameArr[1] == "2"|| nameArr[1] == "3")) || (nameArr[0] == "0" && (nameArr[1] == "0" || nameArr[1] == "2" || nameArr[1] == "4") && $(ss1).attr('class').split(' ')[0] == "goat") || (nameArr[0] == "4" && (nameArr[1] == "0" || nameArr[1] == "2" || nameArr[1] == "4") && $(ss1).attr('class').split(' ')[0] == "goat"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "0.0" && ((nameArr[0] == "0" && (nameArr[1] == "1" || (nameArr[1] == "2" && $(ss1).attr('class').split(' ')[0] == "goat"))) || (nameArr[0] == "1" && (nameArr[1] == "0" || nameArr[1] == "1")) || (nameArr[0] == "2" && ((nameArr[1] == "2" || nameArr[1] == "0") && $(ss1).attr('class').split(' ')[0] == "goat")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "0.4" && ((nameArr[0] == "0" && (nameArr[1] == "3" || (nameArr[1] == "2" && $(ss1).attr('class').split(' ')[0] == "goat"))) || (nameArr[0] == "1" && (nameArr[1] == "3" || nameArr[1] == "4")) || (nameArr[0] == "2" && ((nameArr[1] == "2" || nameArr[1] == "4") && $(ss1).attr('class').split(' ')[0] == "goat")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "4.0" && ((nameArr[0] == "4" && nameArr[1] == "1" || (nameArr[1] == "2" && $(ss1).attr('class').split(' ')[0] == "goat")) || (nameArr[0] == "3" && (nameArr[1] == "0" || nameArr[1] == "1")) || (nameArr[0] == "2" && ((nameArr[1] == "2" || nameArr[1] == "0") && $(ss1).attr('class').split(' ')[0] == "goat")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "4.4" && ((nameArr[0] == "3" && (nameArr[1] == "4" || nameArr[1] == "3")) || (nameArr[0] == "4" && (nameArr[1] == "3" || (nameArr[1] == "2" && $(ss1).attr('class').split(' ')[0] == "goat"))) || (nameArr[0] == "2" && ((nameArr[1] == "2" || nameArr[1] == "4") && $(ss1).attr('class').split(' ')[0] == "goat")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "0.1" && ((nameArr[0] == "0" && (nameArr[1] == "0" || nameArr[1] == "2" || (nameArr[1] == "3" && $(ss1).attr('class').split(' ')[0] == "goat"))) || (nameArr[0] == "1" && nameArr[1] == "1") || nameArr[0] == "2" && (nameArr[1] == "1" && $(ss1).attr('class').split(' ')[0] == "goat"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "0.3" && ((nameArr[0] == "0" && (nameArr[1] == "2" || nameArr[1] == "4" || (nameArr[1] == "1" && $(ss1).attr('class').split(' ')[0] == "goat"))) || (nameArr[0] == "1" && nameArr[1] == "3") || nameArr[0] == "2" && (nameArr[1] == "3" && $(ss1).attr('class').split(' ')[0] == "goat"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "1.0" && ((nameArr[1] == "0" && (nameArr[0] == "0" || nameArr[0] == "2")) || (nameArr[0] == "1" && (nameArr[1] == "1" || (nameArr[1] == "2" && $(ss1).attr('class').split(' ')[0] == "goat"))) || nameArr[0] == "3" && (nameArr[1] == "0" && $(ss1).attr('class').split(' ')[0] == "goat"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "1.4" && ((nameArr[1] == "4" && (nameArr[0] == "0" || nameArr[0] == "2")) || (nameArr[0] == "1" && (nameArr[1] == "3" || (nameArr[1] == "2" && $(ss1).attr('class').split(' ')[0] == "goat"))) || nameArr[0] == "3" && (nameArr[1] == "4" && $(ss1).attr('class').split(' ')[0] == "goat"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "3.0" && ((nameArr[1] == "0" && (nameArr[0] == "2" || nameArr[0] == "4")) || (nameArr[0] == "3" && (nameArr[1] == "1" || (nameArr[1] == "2" && $(ss1).attr('class').split(' ')[0] == "goat"))) || nameArr[0] == "1" && (nameArr[1] == "0" && $(ss1).attr('class').split(' ')[0] == "goat"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "3.4" && ((nameArr[1] == "4" && (nameArr[0] == "2" || nameArr[0] == "4")) || (nameArr[0] == "3" && (nameArr[1] == "3" || (nameArr[1] == "2" && $(ss1).attr('class').split(' ')[0] == "goat"))) || nameArr[0] == "1" && (nameArr[1] == "4" && $(ss1).attr('class').split(' ')[0] == "goat"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "4.1" && ((nameArr[0] == "4" && (nameArr[1] == "0" || nameArr[1] == "2" || (nameArr[1] == "3" && $(ss1).attr('class').split(' ')[0] == "goat"))) || (nameArr[0] == "3" && nameArr[1] == "1") || nameArr[0] == "2" && (nameArr[1] == "1" && $(ss1).attr('class').split(' ')[0] == "goat"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "4.3" && ((nameArr[0] == "4" && (nameArr[1] == "2" || nameArr[1] == "4" || (nameArr[1] == "1" && $(ss1).attr('class').split(' ')[0] == "goat"))) || (nameArr[0] == "3" && nameArr[1] == "3") || nameArr[0] == "2" && (nameArr[1] == "3" && $(ss1).attr('class').split(' ')[0] == "goat"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "1.2" && ((nameArr[0] == "1" && (nameArr[1] == "1" || nameArr[1] == "3" || ((nameArr[1] =="0" || nameArr[1] == "4") && $(ss1).attr('class').split(' ')[0] == "goat"))) || nameArr[1] == "2" && (nameArr[0] == "0" || nameArr[0] == "2") || (nameArr[0] == "3" && (nameArr[1] == "2" && $(ss1).attr('class').split(' ')[0] == "goat")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "2.1" && ((nameArr[0] == "2" && (nameArr[1] == "0" || nameArr[1] == "2" || (nameArr[1] == "3" && $(ss1).attr('class').split(' ')[0] == "goat"))) || nameArr[1] == "1" && (nameArr[0] == "1" || nameArr[0] == "3") || ((nameArr[0] == "0" || nameArr[0] == "4") && $(ss1).attr('class').split(' ')[0] == "goat"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "2.3" && ((nameArr[0] == "2" && (nameArr[1] == "2" || nameArr[1] == "4" || (nameArr[1] == "1" && $(ss1).attr('class').split(' ')[0] == "goat"))) || nameArr[1] == "3" && (nameArr[0] == "1" || nameArr[0] == "3" || ((nameArr[0] == "0" || nameArr[0] == "4") && $(ss1).attr('class').split(' ')[0] == "goat")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "3.2" && ((nameArr[0] == "3" && (nameArr[1] == "1" || nameArr[1] == "3" || ((nameArr[1] == "0" || nameArr[1] == "4") && $(ss1).attr('class').split(' ')[0] == "goat"))) || nameArr[1] == "2" && (nameArr[0] == "2" || nameArr[0] == "4") || (nameArr[0] == "1" && (nameArr[1] == "2" && $(ss1).attr('class').split(' ')[0] == "goat")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "0.2" && ((nameArr[0] == "0" && (nameArr[1] == "1" || nameArr[1] == "3" || (nameArr[1] == "0" || nameArr[1] == "4") && $(ss1).attr('class').split(' ')[0] == "goat")) || nameArr[0] == "1" && (nameArr[1] == "1" || nameArr[1] == "2" || nameArr[1] == "3") || (nameArr[0] == "2" && ((nameArr[1] == "0" || nameArr[1] == "4" || nameArr[1] == "2") && $(ss1).attr('class').split(' ')[0] == "goat")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "2.0" && ((nameArr[1] == "0" && (nameArr[0] == "1" || nameArr[0] == "3" || (nameArr[0] == "0" || nameArr[0] == "4") && $(ss1).attr('class').split(' ')[0] == "goat")) || nameArr[1] == "1" && (nameArr[0] == "1" || nameArr[0] == "2" || nameArr[0] == "3") || (nameArr[1] == "2" && ((nameArr[0] == "0" || nameArr[0] == "4" || nameArr[0] == "2") && $(ss1).attr('class').split(' ')[0] == "goat")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "2.4" && ((nameArr[1] == "4" && (nameArr[0] == "1" || nameArr[0] == "3" || ((nameArr[0] == "0" || nameArr[0] == "4") && $(ss1).attr('class').split(' ')[0] == "goat"))) || nameArr[1] == "3" && (nameArr[0] == "1" || nameArr[0] == "2" || nameArr[0] == "3") || (nameArr[1] == "2" && ((nameArr[0] == "0" || nameArr[0] == "4" || nameArr[0] == "2") && $(ss1).attr('class').split(' ')[0] == "goat")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position1 == "4.2" && ((nameArr[0] == "4" && (nameArr[1] == "1" || nameArr[1] == "3" || ((nameArr[1] == "0" || nameArr[1] == "4") && $(ss1).attr('class').split(' ')[0] == "goat"))) || nameArr[0] == "3" && (nameArr[1] == "1" || nameArr[1] == "2" || nameArr[1] == "3") || (nameArr[0] == "2" && ((nameArr[1] == "0" || nameArr[1] == "4" || nameArr[1] == "2") && $(ss1).attr('class').split(' ')[0] == "goat")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else{
alert("Wrong move");
delCheck =null;
}
}
else{
if(get_position == "1.1" && ((nameArr[0] == "0" && (nameArr[1] == "0" || nameArr[1] == "1"|| nameArr[1] == "2")) || (nameArr[0] == "1" && (nameArr[1] == "0" || nameArr[1] == "2")) || (nameArr[0] == "2" && (nameArr[1] == "0" || nameArr[1] == "1"|| nameArr[1] == "2")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "1.3" && ((nameArr[0] == "0" && (nameArr[1] == "2" || nameArr[1] == "3"|| nameArr[1] == "4")) || (nameArr[0] == "1" && (nameArr[1] == "2" || nameArr[1] == "4")) || (nameArr[0] == "2" && (nameArr[1] == "2" || nameArr[1] == "3"|| nameArr[1] == "4")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "3.1" && ((nameArr[0] == "2" && (nameArr[1] == "0" || nameArr[1] == "1"|| nameArr[1] == "2")) || (nameArr[0] == "3" && (nameArr[1] == "0" || nameArr[1] == "2")) || (nameArr[0] == "4" && (nameArr[1] == "0" || nameArr[1] == "1"|| nameArr[1] == "2")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "3.3" && ((nameArr[0] == "2" && (nameArr[1] == "2" || nameArr[1] == "3"|| nameArr[1] == "4")) || (nameArr[0] == "3" && (nameArr[1] == "2" || nameArr[1] == "4")) || (nameArr[0] == "4" && (nameArr[1] == "2" || nameArr[1] == "3"|| nameArr[1] == "4")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "0.0" && ((nameArr[0] == "0" && nameArr[1] == "1") || (nameArr[0] == "1" && (nameArr[1] == "0" || nameArr[1] == "1")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "0.4" && ((nameArr[0] == "0" && nameArr[1] == "3") || (nameArr[0] == "1" && (nameArr[1] == "3" || nameArr[1] == "4")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "4.0" && ((nameArr[0] == "4" && nameArr[1] == "1") || (nameArr[0] == "3" && (nameArr[1] == "0" || nameArr[1] == "1")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "4.4" && ((nameArr[0] == "3" && nameArr[1] == "4") || (nameArr[1] == "3" && (nameArr[0] == "3" || nameArr[0] == "4")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "0.1" && ((nameArr[0] == "0" && (nameArr[1] == "0" || nameArr[1] == "2")) || (nameArr[0] == "1" && nameArr[1] == "1"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "0.3" && ((nameArr[0] == "0" && (nameArr[1] == "2" || nameArr[1] == "4")) || (nameArr[0] == "1" && nameArr[1] == "3"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "1.0" && ((nameArr[1] == "0" && (nameArr[0] == "0" || nameArr[0] == "2")) || (nameArr[0] == "1" && nameArr[1] == "1"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "1.4" && ((nameArr[1] == "4" && (nameArr[0] == "0" || nameArr[0] == "2")) || (nameArr[0] == "1" && nameArr[1] == "3"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "3.0" && ((nameArr[1] == "0" && (nameArr[0] == "2" || nameArr[0] == "4")) || (nameArr[0] == "3" && nameArr[1] == "1"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "3.4" && ((nameArr[1] == "4" && (nameArr[0] == "2" || nameArr[0] == "4")) || (nameArr[0] == "3" && nameArr[1] == "3"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "4.1" && ((nameArr[0] == "4" && (nameArr[1] == "0" || nameArr[1] == "2")) || (nameArr[0] == "3" && nameArr[1] == "1"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "4.3" && ((nameArr[0] == "4" && (nameArr[1] == "2" || nameArr[1] == "4")) || (nameArr[0] == "3" && nameArr[1] == "3"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "1.2" && ((nameArr[0] == "1" && (nameArr[1] == "1" || nameArr[1] == "3")) || nameArr[1] == "2" && (nameArr[0] == "0" || nameArr[0] == "2"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "2.1" && ((nameArr[0] == "2" && (nameArr[1] == "0" || nameArr[1] == "2")) || nameArr[1] == "1" && (nameArr[0] == "1" || nameArr[0] == "3"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "2.3" && ((nameArr[0] == "2" && (nameArr[1] == "2" || nameArr[1] == "4")) || nameArr[1] == "3" && (nameArr[0] == "1" || nameArr[0] == "3"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "3.2" && ((nameArr[0] == "3" && (nameArr[1] == "1" || nameArr[1] == "3")) || nameArr[1] == "2" && (nameArr[0] == "2" || nameArr[0] == "4"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "0.2" && ((nameArr[0] == "0" && (nameArr[1] == "1" || nameArr[1] == "3")) || nameArr[0] == "1" && (nameArr[1] == "1" || nameArr[1] == "2" || nameArr[1] == "3"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "2.0" && ((nameArr[1] == "0" && (nameArr[0] == "1" || nameArr[0] == "3")) || nameArr[1] == "1" && (nameArr[0] == "1" || nameArr[0] == "2" || nameArr[0] == "3"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "2.4" && ((nameArr[1] == "4" && (nameArr[0] == "1" || nameArr[0] == "3")) || nameArr[1] == "3" && (nameArr[0] == "1" || nameArr[0] == "2" || nameArr[0] == "3"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "4.2" && ((nameArr[0] == "4" && (nameArr[1] == "1" || nameArr[1] == "3")) || nameArr[0] == "3" && (nameArr[1] == "1" || nameArr[1] == "2" || nameArr[1] == "3"))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else if(get_position == "2.2" && ((nameArr[0] == "1" && (nameArr[1] == "1" || nameArr[1] == "2"|| nameArr[1] == "3")) || (nameArr[0] == "2" && (nameArr[1] == "1" || nameArr[1] == "3")) || (nameArr[0] == "3" && (nameArr[1] == "1" || nameArr[1] == "2"|| nameArr[1] == "3")))){
$('.'+get_name).css({'top':nameArr[0]*100-5+'px', 'left':nameArr[1]*100-5+'px'});
$('.'+get_name).attr("data-position", nameArr[0]+'.'+nameArr[1]);
}
else{
alert("Wrong move");
}
}
if((get_name == "tiger1" || get_name == "tiger2") && get_position1 && delCheck != null){
try{
if($(ss1).attr('class').split(' ')[0] == "goat"){
var ddddd = $("[data-position='"+ss+"']")[1].remove();
console.log("Del "+ss);
}
}
catch(err) {
// break;
}
}
get_name = null;
})
$(".goat").click(function(){
get_position= null;
// get_name = null;
get_position = $(this).attr('data-position');
get_name = $(this).data('name');
console.log(get_position);
// console.log(get_name);
});
})
| 37c07b49418cdd0e60bcdd0bd57ea13478567bb4 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | sumit1136/game | 0edeb6c284b0a19e8d4b5804bc0dc8e461fe2d21 | de8c785b8549502f74c21d007b435a04d69f7469 |
refs/heads/master | <repo_name>andrezottis/BarApp<file_sep>/app/src/main/java/br/com/ftec/andrezottis/barapp/NotaBarActivity.java
package br.com.ftec.andrezottis.barapp;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RatingBar;
import android.widget.TextView;
public class NotaBarActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nota_bar);
Intent intent = getIntent();
String nomeBar= intent.getStringExtra(ContaBarActivity.NOTA_BAR);
TextView nomeBarView = (TextView) findViewById(R.id.textViewNomeBar);
nomeBarView.setText(nomeBar);
final RatingBar estrelas = (RatingBar) findViewById(R.id.ratingBarNota);
estrelas.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
listaNota();
}
});
}
// @TargetApi(Build.VERSION_CODES.M)
public void listaNota(){
RatingBar notaEstrela = (RatingBar) findViewById(R.id.ratingBarNota);
float notaInserida = notaEstrela.getRating();
TextView nota = (TextView) findViewById(R.id.textViewNota);
if(notaInserida<=1){
nota.setText("Péssimo");
// nota.setTextColor(getColor(R.color.vermelho));
}else if(notaInserida<=2){
nota.setText("Ruim");
// nota.setTextColor(getColor(R.color.vermelho));
}else if(notaInserida<=3){
nota.setText("Regular");
// nota.setTextColor(getColor(R.color.amarelo));
}else if(notaInserida<=4){
nota.setText("Bom");
// nota.setTextColor(getColor(R.color.verde));
}else{
nota.setText("Ótimo");
// nota.setTextColor(getColor(R.color.verde));
}
}
}
<file_sep>/app/src/main/java/br/com/ftec/andrezottis/barapp/ContaBarActivity.java
package br.com.ftec.andrezottis.barapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ContaBarActivity extends AppCompatActivity {
public final static String NOTA_BAR ="NotaBar";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conta_bar);
Intent intent = getIntent();
String nomeBar= intent.getStringExtra(BuscaBarActivity.CONTA_BAR);
TextView nomeBarView = (TextView) findViewById(R.id.textViewNomeBar);
nomeBarView.setText(nomeBar);
}
public void alerta(String mens) {
String mensagem=mens;
Toast.makeText(ContaBarActivity.this, mensagem, Toast.LENGTH_SHORT).show();
}
public void limparConta (View view){
//codigo de limpar os campos
EditText petisco = (EditText) findViewById(R.id.editTextPetisco);
EditText bebida = (EditText) findViewById(R.id.editTextBebida);
CheckBox gorjeta = (CheckBox) findViewById(R.id.checkBoxGorjeta);
TextView valorTot = (TextView) findViewById(R.id.textViewValorTotal);
petisco.setText("");
bebida.setText("");
gorjeta.setChecked(false);
valorTot.setText("R$ 0,00");
}
public void calcularConta (View view){
EditText petisco = (EditText) findViewById(R.id.editTextPetisco);
EditText bebida = (EditText) findViewById(R.id.editTextBebida);
CheckBox gorjeta = (CheckBox) findViewById(R.id.checkBoxGorjeta);
TextView valorTot = (TextView) findViewById(R.id.textViewValorTotal);
float valorGorjeta=0;
String valorPetisco=petisco.getText().toString().trim();
String valorBebida=bebida.getText().toString().trim();
if (valorPetisco.equals("")) {
String mensagem = "O campo Nome do Bar deve ser preechido";
alerta(mensagem);
}else if(valorBebida.equals("")){
String mensagem = "O campo Cidade deve ser preechido";
alerta(mensagem);
}else{
//calcula
if(gorjeta.isChecked()) {
valorGorjeta = 10;
}
float vlPetisco=Float.parseFloat(valorPetisco);
float vlBebida=Float.parseFloat(valorBebida);
float vlTotal= vlBebida+vlPetisco+valorGorjeta;
valorTot.setText("R$ "+vlTotal+"");
}
}
public void avaliarBar (View view){
//codigo de avaliar o bar
Intent intent = new Intent(this, NotaBarActivity.class);
TextView nomeBarView = (TextView) findViewById(R.id.textViewNomeBar);
String message = nomeBarView.getText().toString();
intent.putExtra(NOTA_BAR, message);
startActivity(intent);
}
}
| 5cb75a385f7601597ad7227037b01c734d441e58 | [
"Java"
] | 2 | Java | andrezottis/BarApp | b68bd846e22c867f289955b6671683f3e56b0f8b | f822ea51b18b609f1039a79239f73ad6d413fe10 |
refs/heads/master | <file_sep>package com.yeejoin.commonapplication.viewmodel;
import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import android.support.annotation.NonNull;
import com.yeejoin.commonapplication.data.DataRepository;
import com.yeejoin.commonapplication.data.Injection;
import com.yeejoin.commonapplication.data.model.entity.Login;
/**
* Created by maodou on 2017/12/28.
*
* 个人信息页ViewModel
*/
public class PersonalViewModel extends AndroidViewModel {
private LiveData<Login> loginInfo = null;
private DataRepository dataRepository = null;
public PersonalViewModel(@NonNull Application application) {
super(application);
dataRepository = Injection.getDataRepository(application);
}
public LiveData<Login> getLoginInfo(){
return dataRepository.getLastLogin();
}
}
<file_sep>package com.yeejoin.commonapplication.data;
import android.app.Application;
import com.yeejoin.commonapplication.data.local.LocalDataSource;
import com.yeejoin.commonapplication.data.remote.RemoteDataSource;
/**
* Created by maodou on 2017/12/28.
*/
public class Injection {
public static DataRepository getDataRepository(Application application){
return DataRepository.getInstance(RemoteDataSource.getInstance(),
LocalDataSource.getInstance(),application);
}
}
<file_sep>package com.yeejoin.commonapplication.data.model.entity;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
/**
* Created by maodou on 2017/12/28.
*/
@Entity
public class Site {
@PrimaryKey
@ColumnInfo(name = "site_id")
public int id;
public String siteLevelDescription;
public int sitePersonNumMax;
public int sitePersonNumMin;
public int siteClassNum;
}
<file_sep>package com.yeejoin.commonapplication.data.model.entity;
import android.arch.persistence.room.Embedded;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.arch.persistence.room.RoomWarnings;
/**
* Created by maodou on 2017/12/28.
* 单位Entity
*/
@SuppressWarnings(RoomWarnings.PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED)
@Entity
public class Company {
@PrimaryKey
public int id;
public String companyName;
public String companyLevel;
public String description;
public String parentId;
public String compCode;
public String contact;
public double latitude;
public double longitude;
public String address;
public String telephone;
public String email;
@Embedded(prefix = "site")
public Site site;
}
<file_sep>package com.yeejoin.commonapplication.data.local.dao;
import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;
import com.yeejoin.commonapplication.data.model.entity.NetConfig;
import java.util.List;
/**
* Created by maodou on 2017/12/28.
* 网络配置Dao
*/
@Dao
public interface NetConfigDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAll(List<NetConfig> configs);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void saveNetConfig(NetConfig config);
@Update
void updateNetConfig(NetConfig config);
@Delete
void deleteNetConfig(NetConfig config);
@Query("SELECT * FROM netconfig")
LiveData<List<NetConfig>> loadNetConfig();
}
<file_sep>package com.yeejoin.commonapplication.fragment;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.yeejoin.commonapplication.R;
import com.yeejoin.commonapplication.data.model.entity.User;
import com.yeejoin.commonapplication.viewmodel.PersonalViewModel;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by maodou on 2017/12/28.
*/
public class PersonalFragment extends Fragment {
@BindView(R.id.ivAvatar)
ImageView mIvAvatar;
@BindView(R.id.tvNameAndRole)
TextView mTvNameAndRole;
@BindView(R.id.tvCompany)
TextView mTvCompany;
@BindView(R.id.tvPhone)
TextView mTvPhone;
private PersonalViewModel mViewModel = null;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_personal,container,false);
ButterKnife.bind(this,view);
init();
return view;
}
private void init(){
mViewModel = ViewModelProviders.of(this).get(PersonalViewModel.class);
mViewModel.getLoginInfo()
.observe(this, login -> {
if (login != null && login.user != null)
setData(login.user);
});
}
private void setData(User user){
Glide.with(this)
.load(R.drawable.default_avatar)
.apply(RequestOptions.circleCropTransform())
.into(mIvAvatar);
mTvNameAndRole.setText(user.name + " " + user.role.name);
mTvPhone.setText(user.mobile == null ? "" : user.mobile);
mTvCompany.setText(user.company.companyName);
}
}
<file_sep>package com.yeejoin.commonapplication.data.local.dao;
import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;
import com.yeejoin.commonapplication.data.model.entity.Login;
/**
* Created by maodou on 2017/12/28.
* 登录Dao
*/
@Dao
public interface LoginDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertLogin(Login login);
@Delete
void deleteLogin(Login login);
@Update
void updateLogin(Login login);
@Query("SELECT * FROM login LIMIT 1")
LiveData<Login> loadLogin();
@Query("DELETE FROM login")
void deleteAll();
}
<file_sep>package com.yeejoin.commonapplication.data.model.entity;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
/**
* Created by maodou on 2017/12/28.
* 角色Entity
*/
@Entity
public class Role {
@PrimaryKey
public int id;
public String name;
public String description;
public String roleType;
}
<file_sep>package com.yeejoin.commonapplication.viewmodel;
import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import android.support.annotation.NonNull;
import com.yeejoin.commonapplication.data.DataRepository;
import com.yeejoin.commonapplication.data.Injection;
import com.yeejoin.commonapplication.data.model.entity.Login;
/**
* Created by maodou on 2017/12/28.
*/
public class BaseViewModel extends AndroidViewModel {
private DataRepository dataRepository = null;
public BaseViewModel(@NonNull Application application) {
super(application);
dataRepository = Injection.getDataRepository(application);
}
public LiveData<Boolean> tokenValid(String token){
return dataRepository.tokenValid(token);
}
public LiveData<Login> getLastLogin(){
return dataRepository.getLastLogin();
}
}
<file_sep>package com.yeejoin.commonapplication.data;
import android.app.Application;
import android.arch.lifecycle.LiveData;
import android.support.annotation.NonNull;
import com.yeejoin.commonapplication.data.model.entity.Login;
import com.yeejoin.commonapplication.data.model.entity.NetConfig;
import com.yeejoin.commonapplication.utils.Util;
import java.util.List;
/**
* Created by maodou on 2017/12/28.
*/
public class DataRepository {
private static DataRepository instance = null;
private final DataSource mRemoteDataSource;
private final DataSource mLocalDataSource;
private static Application sApplication = null;
private DataRepository(@NonNull DataSource remoteDataSource,
@NonNull DataSource localDataSource){
mRemoteDataSource = remoteDataSource;
mLocalDataSource = localDataSource;
}
public static DataRepository getInstance(@NonNull DataSource remoteDataSource,
@NonNull DataSource localDataSource,
Application application){
if (instance == null){
synchronized (DataRepository.class){
if (instance == null){
instance = new DataRepository(remoteDataSource,localDataSource);
sApplication = application;
}
}
}
return instance;
}
public LiveData<List<NetConfig>> getNetConfigs(){
return Util.isNetworkConnected(sApplication) ? mRemoteDataSource.getNetConfigs() : mLocalDataSource.getNetConfigs();
}
public LiveData<Login> login(String username, String password){
return mRemoteDataSource.login(username, password);
}
public LiveData<Login> getLastLogin(){
return mLocalDataSource.getLastLogin();
}
public LiveData<Boolean> tokenValid(String token){
return mRemoteDataSource.tokenValid(token);
}
}
<file_sep>package com.yeejoin.commonapplication.base;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.yeejoin.commonapplication.utils.Util;
import butterknife.ButterKnife;
/**
* Created by maodou on 2017/12/28.
*/
public abstract class BaseActivity extends AppCompatActivity {
private WindowManager windowManager = null;
private View mParentView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getResourceId());
ButterKnife.bind(this);
mParentView = getWindow().getDecorView();
windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
init();
}
/**
* @return 屏幕宽度
*/
private int getScreenWidth(){
return windowManager == null ? -1 : windowManager.getDefaultDisplay().getWidth();
}
/**
* @return 屏幕高度
*/
private int getScreenHeight(){
return windowManager == null ? -1 : windowManager.getDefaultDisplay().getHeight();
}
protected abstract int getResourceId();
protected abstract void init();
protected void showToast(@StringRes int resId) throws Resources.NotFoundException{
makeText(BaseActivity.this.getResources().getText(resId));
}
protected void showToast(CharSequence charsequence){
makeText(charsequence);
}
private void makeText(CharSequence charsequence){
String tag = "BaseActivity.showToast";
Context applicationContext = getApplicationContext();
try {
Toast.makeText(applicationContext, charsequence, Toast.LENGTH_SHORT).show();
} catch (NullPointerException e){
Log.e(tag,"Context cannot be null!");
}
}
protected void showSnackBar(CharSequence msg){
Util.showSnackbar(mParentView,msg);
}
protected void showSnackBar(@StringRes int resId){
Util.showSnackbar(mParentView,getResources().getText(resId));
}
}
<file_sep>package com.yeejoin.commonapplication.base;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by maodou on 2017/12/28.
*/
public class RetrofitFactory {
public static Retrofit getRetrofitClient(String baseUrl){
return new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
public static OkHttpClient provideClient(){
return new OkHttpClient.Builder()
.addInterceptor(new TokenInterceptor())
.writeTimeout(5000, TimeUnit.MILLISECONDS)
.readTimeout(5000,TimeUnit.MILLISECONDS)
.build();
}
public static BaseNetworkService provideService(boolean hasToken, String baseUrl){
Retrofit.Builder builder = new Retrofit.Builder();
builder.baseUrl(baseUrl);
builder.addConverterFactory(GsonConverterFactory.create());
builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
if (hasToken)
builder.client(provideClient());
return builder.build().create(BaseNetworkService.class);
}
}
<file_sep>package com.yeejoin.commonapplication.base;
import com.yeejoin.commonapplication.data.model.DataListResult;
import com.yeejoin.commonapplication.data.model.entity.Login;
import com.yeejoin.commonapplication.data.model.entity.NetConfig;
import com.yeejoin.commonapplication.data.model.entity.TokenValid;
import com.yeejoin.commonapplication.request.LoginRequest;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
/**
* Created by maodou on 2017/12/28.
*/
public interface BaseNetworkService {
@GET(APISettings.TokenValid)
Call<TokenValid> tokenValid(@Path("authToken") String token);
@POST(APISettings.LoginUrl)
Call<Login> login(@Body LoginRequest request);
@GET(APISettings.NetConfig)
Call<DataListResult<List<NetConfig>>> getNetConfig();
}
<file_sep>package com.yeejoin.commonapplication;
import android.app.Application;
import com.yeejoin.commonapplication.data.Injection;
import com.yeejoin.commonapplication.data.local.db.AppDatabase;
import com.yeejoin.commonapplication.data.model.entity.Login;
import com.yeejoin.commonapplication.data.model.entity.NetConfig;
import java.util.ArrayList;
import java.util.List;
/**
* Created by maodou on 2017/12/28.
*/
public class MyApplication extends Application {
private static MyApplication instance = null;
private AppExecutors appExecutors;
private Login loginInfo = null;
public static MyApplication getInstance(){
return instance;
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
appExecutors = new AppExecutors();
loginInfo = Injection.getDataRepository(this)
.getLastLogin().getValue();
}
public Login getLoginInfo() {
return loginInfo;
}
public void setLoginInfo(Login loginInfo) {
this.loginInfo = loginInfo;
}
public AppExecutors getAppExecutors() {
return appExecutors;
}
public AppDatabase getDatabase(){
return AppDatabase.getInstance(this);
}
}
<file_sep>package com.yeejoin.commonapplication.request;
/**
* Created by maodou on 2017/12/28.
*/
public class LoginRequest {
public String userName;
public String password;
public String loginType = "APP";
}
| ee57897ee508b77a6383b782d3372c4e6e5151c2 | [
"Java"
] | 15 | Java | jiazhen-chou/DeploymentSystem | b3e03986eaab29010a57de93e7999e9ce1d5da3a | dfbd8db949387e1125be77f0fdecc85d38fae3d1 |
refs/heads/master | <repo_name>echo-team/stardust<file_sep>/main.py
import arcade
import structure
from constants import SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_TITLE
from Screens.instruction import Instruction
from Screens.level_1_view import Lvl_1
from Screens.level_2_view import Lvl_2
from Screens.level_3_view import Lvl_3
from Screens.MenuScreen import MenuScreen
# TODO: remove for Linux
from ctypes import windll
windll.shcore.SetProcessDpiAwareness(1)
class Window(arcade.Window):
def __init__(self, width, height):
super().__init__(width, height)
arcade.set_background_color(arcade.color.BLACK)
self.screens = {
'instruction': Instruction(),
'level1': Lvl_1(),
'level2': Lvl_2(),
'level3': Lvl_3(),
'menu': MenuScreen(self)
}
window = Window(SCREEN_WIDTH, SCREEN_HEIGHT)
window.total_score = 0
window.level = 1
window.screens['menu'].show(None)
arcade.run()
<file_sep>/Widgets/Menu.py
import arcade
class MenuItem:
def __init__(self, x, y, width, height, text):
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
self.fontSize = 15
self.fontWeight = 0
def draw(self):
arcade.draw_text(
self.text, self.x, self.y + (self.height - self.fontSize) / 2,
arcade.color.WHITE, self.fontSize,
font_name = '../assets/fonts/source_code_pro.ttf')
class Menu:
def __init__(self, x, y, itemWidth, itemHeight):
self.x = x
self.y = y
self.itemWidth = itemWidth
self.itemHeight = itemHeight
self.items = []
def addItem(self, text):
item = MenuItem(
self.x,
self.y - self.itemHeight * len(self.items),
self.itemWidth,
self.itemHeight,
text)
self.items.append(item)
def draw(self):
for item in self.items:
item.draw()
<file_sep>/Coin_Folder/coin.py
import arcade
import os
from constants import SCREEN_WIDTH, SCREEN_HEIGHT
file_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(file_path)
class Coin(arcade.Sprite):
def __init__(self, filename, sprite_scaling):
super().__init__(filename, sprite_scaling)
self.change_x = 0
self.change_y = 0
def update(self):
# Move the coin
self.center_x += self.change_x
self.center_y += self.change_y
# If we are out-of-bounds, then 'bounce'
if self.left < 0:
self.change_x *= -1
if self.right > SCREEN_WIDTH:
self.change_x *= -1
if self.bottom < 0:
self.change_y *= -1
if self.top > SCREEN_HEIGHT:
self.change_y *= -1<file_sep>/Screens/GameScreen.py
import arcade
class GameScreen(arcade.View):
def show_menu_if_esc(self, key, previousScreen):
if key == arcade.key.ESCAPE:
arcade.get_window().screens['menu'].show(previousScreen)<file_sep>/Coin_Folder/bonus_coin.py
import arcade
import math
class Bonus_Coin(arcade.Sprite):
def __init__(self, filename, sprite_scaling):
super().__init__(filename, sprite_scaling)
# Current angle in radians
self.circle_angle = 0
# How far away from the center to orbit, in pixels
self.circle_radius = 0
# How fast to orbit, in radians per frame
self.circle_speed = 0.009
# Set the center of the point we will orbit around
self.circle_center_x = 0
self.circle_center_y = 0
def update(self):
# Calculate a new x, y
self.center_x = self.circle_radius * math.sin(self.circle_angle) \
+ self.circle_center_x
self.center_y = self.circle_radius * math.cos(self.circle_angle) \
+ self.circle_center_y
# Increase the angle in prep for the next round.
self.circle_angle += self.circle_speed<file_sep>/Screens/level_1_view.py
import arcade
import random
import os
from constants import SCREEN_HEIGHT, SCREEN_WIDTH, SPRITE_SCALING_COIN, SPRITE_SCALING_PLAYER, MOVEMENT_SPEED
from Screens.GameScreen import GameScreen
from Coin_Folder.coin import Coin
file_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(file_path)
class Lvl_1(GameScreen):
def __init__(self):
super().__init__()
def init(self):
self.time_taken = 0
self.frame_count = 0
self.player_list = arcade.SpriteList()
self.coin_list = arcade.SpriteList()
# Set up the player info
self.player_sprite = arcade.Sprite("../assets/images/rocket.png", SPRITE_SCALING_PLAYER)
self.player_sprite.center_x = 50
self.player_sprite.center_y = 50
self.player_sprite.change_x = 0
self.player_sprite.change_y = 0
self.player_list.append(self.player_sprite)
self.score = 0
self.level = 1
# Create the coins
for i in range(15):
# Create the coin instance
coin = Coin("../assets/images/ammo_box.png", SPRITE_SCALING_COIN)
# Position the coin
coin.center_x = random.randrange(SCREEN_WIDTH)
coin.center_y = random.randrange(SCREEN_HEIGHT)
coin.change_x = random.randrange(-3, 4)
coin.change_y = random.randrange(-3, 4)
# Add the coin to the lists
self.coin_list.append(coin)
def show(self):
self.init()
arcade.get_window().show_view(self)
def on_show(self):
arcade.set_background_color(arcade.color.BLACK)
# Don't show the mouse cursor
self.window.set_mouse_visible(False)
def on_draw(self):
arcade.start_render()
self.coin_list.draw()
self.player_list.draw()
# Put the text on the screen.
output = f"Score: {self.score}"
arcade.draw_text(output, 10, 10, arcade.color.WHITE, 14, font_name='../assets/fonts/source_code_pro.ttf')
output = f"Level: {self.level}"
arcade.draw_text(output, 10, 25, arcade.color.WHITE, 14, font_name='../assets/fonts/source_code_pro.ttf')
def on_mouse_motion(self, x, y, dx, dy):
# Move the center of the player sprite to match the mouse x, y
self.player_sprite.center_x = x
self.player_sprite.center_y = y
def on_key_press(self, key, modifiers):
super().show_menu_if_esc(key, self)
# Called whenever the user presses a key.
if key == arcade.key.LEFT:
self.player_sprite.change_x = -MOVEMENT_SPEED
elif key == arcade.key.RIGHT:
self.player_sprite.change_x = MOVEMENT_SPEED
elif key == arcade.key.UP:
self.player_sprite.change_y = MOVEMENT_SPEED
elif key == arcade.key.DOWN:
self.player_sprite.change_y = -MOVEMENT_SPEED
def on_key_release(self, key, modifiers):
# Called whenever a user releases a key.
if key == arcade.key.LEFT or key == arcade.key.RIGHT:
self.player_sprite.change_x = 0
elif key == arcade.key.UP or key == arcade.key.DOWN:
self.player_sprite.change_y = 0
def on_update(self, delta_time: float):
self.time_taken += delta_time
# Move the player
self.player_sprite.center_y += self.player_sprite.change_y
self.player_sprite.center_x += self.player_sprite.change_x
# See if the player hit the edge of the screen. If so, change direction
if self.player_sprite.center_x < 55:
self.player_sprite.center_x = 55
if self.player_sprite.center_x > SCREEN_WIDTH - 55:
self.player_sprite.center_x = SCREEN_WIDTH - 55
if self.player_sprite.center_y < 55:
self.player_sprite.center_y = 55
if self.player_sprite.center_y > SCREEN_HEIGHT - 55:
self.player_sprite.center_y = SCREEN_HEIGHT - 55
self.coin_list.update()
self.player_list.update()
coin_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list)
# Loop through each colliding sprite, remove it, and add to the
# score.
for coin in coin_hit_list:
coin.remove_from_sprite_lists()
self.score += 1
if len(self.coin_list) == 0 and self.level == 1:
self.level += 1
self.window.screens['level2'].show(self.score)
<file_sep>/Screens/level_3_view.py
import arcade
import os
import math
from constants import SCREEN_WIDTH, SCREEN_TITLE, SCREEN_HEIGHT, SPRITE_SCALING_PLAYER, SPRITE_SCALING_LASER_BOSS, \
SPRITE_SCALING_BOSS, SPRITE_SCALING_COIN, SPRITE_SCALING_LASER, MOVEMENT_SPEED, \
BULLET_SPEED, BOSS_BULLET_SPEED
from Screens.GameScreen import GameScreen
file_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(file_path)
class Lvl_3(GameScreen):
def __init__(self):
super().__init__()
def init(self, bullet_amount, hp):
self.time_taken = 0
self.frame_count = 0
self.player_list = arcade.SpriteList()
self.bullet_list = arcade.SpriteList()
self.boss_list = arcade.SpriteList()
self.bullet_boss_list = arcade.SpriteList()
# Set up the player info
self.player_sprite = arcade.Sprite("../assets/images/rocket.png", SPRITE_SCALING_PLAYER)
self.player_sprite.center_x = 50
self.player_sprite.center_y = 50
self.player_sprite.change_x = 0
self.player_sprite.change_y = 0
self.player_list.append(self.player_sprite)
self.bullet_amount = bullet_amount
self.boss_hp = 20
self.hp = hp
self.level = 3
# Create the boss
boss = arcade.Sprite("../assets/images/ufo.png", SPRITE_SCALING_BOSS)
boss.center_x = SCREEN_WIDTH / 2
boss.center_y = SCREEN_HEIGHT - boss.height / 4
self.boss_list.append(boss)
def show(self, bullet_amount, hp):
self.init(bullet_amount, hp)
arcade.get_window().show_view(self)
def on_show(self):
arcade.set_background_color(arcade.color.BLACK)
# Don't show the mouse cursor
self.window.set_mouse_visible(False)
def on_draw(self):
""" Draw everything """
arcade.start_render()
self.bullet_list.draw()
self.player_list.draw()
self.bullet_boss_list.draw()
self.boss_list.draw()
# Put the text on the screen.
output = f"Bullets: {self.bullet_amount}"
arcade.draw_text(output, 10, 10, arcade.color.WHITE, 14, font_name='../assets/fonts/source_code_pro.ttf')
output = f"Level: {self.level}"
arcade.draw_text(output, 10, 25, arcade.color.WHITE, 14, font_name='../assets/fonts/source_code_pro.ttf')
output = f"HP: {self.hp}"
arcade.draw_text(output, 10, 40, arcade.color.WHITE, 14, font_name='../assets/fonts/source_code_pro.ttf')
output = f"Boss's hp: {self.boss_hp}"
arcade.draw_text(output, 10, 55, arcade.color.WHITE, 14, font_name='../assets/fonts/source_code_pro.ttf')
def on_mouse_motion(self, x, y, dx, dy):
# Move the center of the player sprite to match the mouse x, y
self.player_sprite.center_x = x
self.player_sprite.center_y = y
def on_mouse_press(self, x, y, button, modifiers):
bullet = arcade.Sprite("../assets/images/bullet.png", SPRITE_SCALING_LASER)
bullet.center_x = self.player_sprite.center_x
bullet.center_y = self.player_sprite.center_y
bullet.change_y = BULLET_SPEED
self.bullet_amount -= 1
self.bullet_list.append(bullet)
def on_key_press(self, key, modifiers):
super().show_menu_if_esc(key, self)
# Called whenever the user presses a key.
if key == arcade.key.LEFT:
self.player_sprite.change_x = -MOVEMENT_SPEED
elif key == arcade.key.RIGHT:
self.player_sprite.change_x = MOVEMENT_SPEED
elif key == arcade.key.UP:
self.player_sprite.change_y = MOVEMENT_SPEED
elif key == arcade.key.DOWN:
self.player_sprite.change_y = -MOVEMENT_SPEED
elif key == arcade.key.SPACE and self.level == 3:
bullet = arcade.Sprite("../assets/images/boss_bullet.png", SPRITE_SCALING_LASER)
bullet.center_x = self.player_sprite.center_x
bullet.center_y = self.player_sprite.center_y + 30
bullet.change_y = BULLET_SPEED
self.bullet_amount -= 1
self.bullet_list.append(bullet)
def on_key_release(self, key, modifiers):
# Called whenever a user releases a key.
if key == arcade.key.LEFT or key == arcade.key.RIGHT:
self.player_sprite.change_x = 0
elif key == arcade.key.UP or key == arcade.key.DOWN:
self.player_sprite.change_y = 0
def on_update(self, delta_time: float):
self.time_taken += delta_time
# Move the player
self.player_sprite.center_y += self.player_sprite.change_y
self.player_sprite.center_x += self.player_sprite.change_x
# See if the player hit the edge of the screen. If so, change direction
if self.player_sprite.center_x < 55:
self.player_sprite.center_x = 55
if self.player_sprite.center_x > SCREEN_WIDTH - 55:
self.player_sprite.center_x = SCREEN_WIDTH - 55
if self.player_sprite.center_y < 55:
self.player_sprite.center_y = 55
if self.player_sprite.center_y > SCREEN_HEIGHT - 55:
self.player_sprite.center_y = SCREEN_HEIGHT - 55
self.player_list.update()
self.frame_count += 1
# Loop through each enemy that we have
for boss in self.boss_list:
# First, calculate the angle to the player. We could do this
# only when the bullet fires, but in this case we will rotate
# the enemy to face the player each frame, so we'll do this
# each frame.
# Position the start at the enemy's current location
start_x = boss.center_x
start_y = boss.center_y
# Get the destination location for the bullet
dest_x = self.player_sprite.center_x
dest_y = self.player_sprite.center_y
# Do math to calculate how to get the bullet to the destination.
# Calculation the angle in radians between the start points
# and end points. This is the angle the bullet will travel.
x_diff = dest_x - start_x
y_diff = dest_y - start_y
angle = math.atan2(y_diff, x_diff)
# Set the enemy to face the player.
boss.angle = math.degrees(angle) + 90
# Shoot every 60 frames change of shooting each frame
if self.frame_count % 45 == 0:
bullet_boss = arcade.Sprite("../assets/images/boss_bullet.png", SPRITE_SCALING_LASER_BOSS)
bullet_boss.center_x = start_x
bullet_boss.center_y = start_y
# Angle the bullet sprite
bullet_boss.angle = math.degrees(angle) + 90
# Taking into account the angle, calculate our change_x
# and change_y. Velocity is how fast the bullet travels.
bullet_boss.change_x = math.cos(angle) * BOSS_BULLET_SPEED
bullet_boss.change_y = math.sin(angle) * BOSS_BULLET_SPEED
self.bullet_boss_list.append(bullet_boss)
# Get rid of the bullet when it flies off-screen
bullet_boss_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.bullet_boss_list)
for bullet_boss in bullet_boss_hit_list:
self.hp -=1
bullet_boss.remove_from_sprite_lists()
self.bullet_boss_list.update()
bullet_player_hit_list = arcade.check_for_collision_with_list(boss, self.bullet_list)
for bullet in bullet_player_hit_list:
self.boss_hp -= 1
bullet.remove_from_sprite_lists()
self.bullet_list.update()
if self.hp == 0 or self.bullet_amount == 0:
self.window.screens['menu'].show(None, victory = False)
if self.boss_hp == 0:
self.window.screens['menu'].show(None, victory = True, score = self.hp)
<file_sep>/Screens/instruction.py
import arcade
import os
from PIL import ImageFont
from constants import SCREEN_WIDTH, SCREEN_HEIGHT
from Screens.GameScreen import GameScreen
file_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(file_path)
class Instruction(GameScreen):
def __init__(self):
super().__init__()
font = ImageFont.truetype('../assets/fonts/source_code_pro.ttf', 15)
text_width, text_height = font.getsize('Press mouse\'s button or space to shoot')
self.text = [
'Use mouse or arrows to move',
'Press mouse\'s button or space to shoot',
'Press Esc to pause',
'Press Enter to continue'
]
self.text_pos = {
'x': (SCREEN_WIDTH - text_width) / 2,
'y': (SCREEN_HEIGHT - (text_height + 5) * len(self.text)) / 2,
'delta': 20
}
def show(self):
arcade.get_window().show_view(self)
def on_show(self):
arcade.set_background_color(arcade.color.BLACK)
def on_draw(self):
arcade.start_render()
for index in range(len(self.text)):
arcade.draw_text(
self.text[index],
self.text_pos['x'], SCREEN_HEIGHT - self.text_pos['y'] - index * self.text_pos['delta'],
arcade.color.WHITE, font_size=15, font_name='../assets/fonts/source_code_pro.ttf')
def on_key_press(self, key, modifiers):
super().show_menu_if_esc(key, self)
if key == arcade.key.ENTER:
self.window.screens['level1'].show()
def on_mouse_press(self, _x, _y, _button, _modifiers):
self.window.screens['level1'].show()
<file_sep>/constants.py
# --- Constants ---
SPRITE_SCALING_PLAYER = 0.25
SPRITE_SCALING_COIN = 0.15
SPRITE_SCALING_LASER = 0.15
SPRITE_SCALING_EXPLOSION = 0.3
SPRITE_SCALING_BOSS = 0.15
SPRITE_SCALING_LASER_BOSS = 0.5
COIN_COUNT = 30
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "STARDUST"
MOVEMENT_SPEED = 5
BULLET_SPEED = 5
BOSS_BULLET_SPEED = 8<file_sep>/Screens/level_2_view.py
import arcade
import random
import os
import math
from constants import SCREEN_HEIGHT, SCREEN_WIDTH, SPRITE_SCALING_COIN, SPRITE_SCALING_PLAYER, MOVEMENT_SPEED
from Screens.GameScreen import GameScreen
from Coin_Folder.coin import Coin
from Coin_Folder.bonus_coin import Bonus_Coin
file_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(file_path)
class Lvl_2(GameScreen):
def __init__(self):
super().__init__()
def init(self, score):
self.frame_count = 0
self.player_list = arcade.SpriteList()
self.coin_list = arcade.SpriteList()
self.bonus_coin_list = arcade.SpriteList()
# Set up the player info
self.player_sprite = arcade.Sprite("../assets/images/rocket.png", SPRITE_SCALING_PLAYER)
self.player_sprite.center_x = 50
self.player_sprite.center_y = 50
self.player_sprite.change_x = 0
self.player_sprite.change_y = 0
self.player_list.append(self.player_sprite)
self.score = score
self.level = 2
self.hp = 3
self.time = 0
# Create the coins
for i in range(15):
# Create the coin instance
coin = Coin("../assets/images/ammo_box.png", SPRITE_SCALING_COIN)
# Position the coin
coin.center_x = random.randrange(SCREEN_WIDTH)
coin.center_y = random.randrange(SCREEN_HEIGHT)
coin.change_x = random.randrange(-3, 4)
coin.change_y = random.randrange(-3, 4)
# Add the coin to the lists
self.coin_list.append(coin)
for i in range(4):
# Create the coin instance
bonus_coin = Bonus_Coin("../assets/images/heal_box.png", SPRITE_SCALING_COIN)
# Position the center of the circle the coin will orbit
bonus_coin.circle_center_x = random.randrange(SCREEN_WIDTH)
bonus_coin.circle_center_y = random.randrange(SCREEN_HEIGHT)
# Random radius from 10 to 200
bonus_coin.circle_radius = random.randrange(10, 200)
# Random start angle from 0 to 2pi
bonus_coin.circle_angle = random.random() * 2 * math.pi
self.bonus_coin_list.append(bonus_coin)
def show(self, score):
self.init(score)
arcade.get_window().show_view(self)
def on_show(self):
arcade.set_background_color(arcade.color.BLACK)
# Don't show the mouse cursor
self.window.set_mouse_visible(False)
def on_draw(self):
arcade.start_render()
self.coin_list.draw()
self.player_list.draw()
self.bonus_coin_list.draw()
# Put the text on the screen.
output = f"Score: {self.score}"
arcade.draw_text(output, 10, 10, arcade.color.WHITE, 14, font_name='../assets/fonts/source_code_pro.ttf')
output = f"Level: {self.level}"
arcade.draw_text(output, 10, 25, arcade.color.WHITE, 14, font_name='../assets/fonts/source_code_pro.ttf')
output = f"HP: {self.hp}"
arcade.draw_text(output, 10, 40, arcade.color.WHITE, 14, font_name='../assets/fonts/source_code_pro.ttf')
output = f"Time left: {10 - math.floor(self.time)}"
arcade.draw_text(output, 10, 55, arcade.color.WHITE, 14, font_name='../assets/fonts/source_code_pro.ttf')
def on_mouse_motion(self, x, y, dx, dy):
# Move the center of the player sprite to match the mouse x, y
self.player_sprite.center_x = x
self.player_sprite.center_y = y
def on_key_press(self, key, modifiers):
super().show_menu_if_esc(key, self)
# Called whenever the user presses a key.
if key == arcade.key.LEFT:
self.player_sprite.change_x = -MOVEMENT_SPEED
elif key == arcade.key.RIGHT:
self.player_sprite.change_x = MOVEMENT_SPEED
elif key == arcade.key.UP:
self.player_sprite.change_y = MOVEMENT_SPEED
elif key == arcade.key.DOWN:
self.player_sprite.change_y = -MOVEMENT_SPEED
def on_key_release(self, key, modifiers):
# Called whenever a user releases a key.
if key == arcade.key.LEFT or key == arcade.key.RIGHT:
self.player_sprite.change_x = 0
elif key == arcade.key.UP or key == arcade.key.DOWN:
self.player_sprite.change_y = 0
def on_update(self, delta_time: float):
self.time += delta_time
# Move the player
self.player_sprite.center_y += self.player_sprite.change_y
self.player_sprite.center_x += self.player_sprite.change_x
# See if the player hit the edge of the screen. If so, change direction
if self.player_sprite.center_x < 55:
self.player_sprite.center_x = 55
if self.player_sprite.center_x > SCREEN_WIDTH - 55:
self.player_sprite.center_x = SCREEN_WIDTH - 55
if self.player_sprite.center_y < 55:
self.player_sprite.center_y = 55
if self.player_sprite.center_y > SCREEN_HEIGHT - 55:
self.player_sprite.center_y = SCREEN_HEIGHT - 55
self.coin_list.update()
self.player_list.update()
self.bonus_coin_list.update()
coin_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list)
# Loop through each colliding sprite, remove it, and add to the
# score.
for coin in coin_hit_list:
coin.remove_from_sprite_lists()
self.score += 1
bonus_coin_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.bonus_coin_list)
for bonus_coin in bonus_coin_hit_list:
bonus_coin.remove_from_sprite_lists()
self.hp += 1
if self.time > 10 or len(self.coin_list) == 0:
self.window.screens['level3'].show(self.score, self.hp)<file_sep>/structure.py
import sys
sys.path.append('./Widgets')
sys.path.append('./Screens')<file_sep>/README.md
# Stardust
<file_sep>/Screens/MenuScreen.py
import arcade
from PIL import ImageFont
from Widgets.Menu import Menu
from Widgets.Highlight import Highlight
class MenuScreen(arcade.View):
def __init__(self, window):
font = ImageFont.truetype('../assets/fonts/source_code_pro.ttf', 15)
itemWidth, itemHeight = font.getsize('Hight scores')
itemHeight += 10
font = ImageFont.truetype('../assets/fonts/lemon_milk.otf', 40)
itemWidth, tmpHeight = font.getsize('STARUST')
titleWidth, titleHeight = font.getsize('STAR')
self.window = window
windowWidth, windowHeight = window.get_size()
self.titleFontSize = 40
self.title = { 'x': (windowWidth - itemWidth) / 2, 'y': windowHeight - (windowHeight - titleHeight - itemHeight * 3) / 2 }
self.titleText = 'STAR'
self.subtitle = { 'x': self.title['x'] + titleWidth, 'y': self.title['y'] - titleHeight }
self.subtitleText = 'DUST'
self.score = None
self.scoreFontSize = 15
self.scorePosition = { 'x': self.title['x'] + titleWidth + 20, 'y': self.title['y'] + titleHeight / 2 + 8 }
self.scoreNumber = { 'x': self.scorePosition['x'], 'y': self.title['y'] + 8 }
self.focused = 0
self.highlight = Highlight()
self.items = [
{ 'name': 'Start', 'listener': self.start },
{ 'name': 'Continue', 'listener': self.resume },
{ 'name': 'Exit', 'listener': self.exit }
]
self.menu = Menu(self.title['x'], self.title['y'] - itemHeight - 20, itemWidth, itemHeight)
for item in self.items:
self.menu.addItem(item['name'])
self.highlight.move(self.menu.items[0])
self.previousScreen = None
def exit(self):
arcade.close_window()
def resume(self):
if self.previousScreen != None:
self.window.show_view(self.previousScreen)
def start(self):
self.score = None
self.window.screens['instruction'].show()
def show(self, previousScreen, victory = None, score = 0):
self.window.set_mouse_visible(True)
self.previousScreen = previousScreen
self.window.show_view(self)
if victory == None:
self.titleText = 'STAR'
self.subtitleText = 'DUST'
elif victory:
self.titleText = 'YOU'
self.subtitleText = 'WIN'
self.score = score if score > 0 else None
else:
self.titleText = 'GAME'
self.subtitleText = 'OVER'
def on_draw(self):
arcade.start_render()
arcade.draw_text(
self.titleText, self.title['x'], self.title['y'],
arcade.color.WHITE, self.titleFontSize, font_name="../assets/fonts/lemon_milk.otf")
arcade.draw_text(
self.subtitleText, self.subtitle['x'], self.subtitle['y'],
arcade.color.WHITE, self.titleFontSize, font_name="../assets/fonts/lemon_milk.otf")
if self.score != None:
arcade.draw_text(
'score:', self.scorePosition['x'], self.scorePosition['y'],
arcade.color.WHITE, self.scoreFontSize, font_name="../assets/fonts/source_code_pro.ttf")
arcade.draw_text(
str(self.score), self.scoreNumber['x'], self.scoreNumber['y'],
arcade.color.WHITE, self.scoreFontSize, font_name="../assets/fonts/source_code_pro.ttf")
self.menu.draw()
self.highlight.draw()
def on_key_press(self, key, modifier):
if key == arcade.key.UP:
self.focused = (self.focused - 1) % len(self.items)
self.highlight.move(self.menu.items[self.focused])
elif key == arcade.key.DOWN:
self.focused = (self.focused + 1) % len(self.items)
self.highlight.move(self.menu.items[self.focused])
elif key == arcade.key.ENTER:
self.items[self.focused]['listener']()
def on_mouse_motion(self, x, y, dx, dy):
covered = self.highlight.mouseMove(x, y, self.menu.items)
if covered != None:
self.focused = covered[0]
def on_mouse_press(self, _x, _y, _button, _modifiers):
self.items[self.focused]['listener']()
<file_sep>/Widgets/Highlight.py
import arcade
class Highlight:
def __init__(self):
self.x = 0
self.y = 0
self.fontSize = 15
self.fontWeight = 15
def move(self, widget):
self.x = widget.x - 15
self.y = widget.y + (widget.height - widget.fontSize) / 2
def mouseMove(self, x, y, widgets):
for index, widget in enumerate(widgets):
if (widget.x <= x and widget.x + widget.width >= x and
widget.y <= y and widget.y + widget.height >= y):
self.move(widget)
return [index, widget]
return None
def draw(self):
arcade.draw_text(
'>', self.x, self.y,
arcade.color.WHITE, self.fontSize,
font_name = '../assets/fonts/source_code_pro.ttf') | b457a7147906785de029bc6a27e7c3c559f1ca7b | [
"Markdown",
"Python"
] | 14 | Python | echo-team/stardust | 916a2e311983eaa1440704a412aaacb22ec6002b | eb20df935a10564ffe561ebff8f626414c48c1c0 |
refs/heads/main | <file_sep># Tic-tac-toe-game
This program simulates a Tic tac toe game
<file_sep>//Tic tac toe game
#include<iostream>
#include<cstdlib>
#include<cctype>
using namespace std;
void TurnPlayerO ( char[][3],char&); //Function prototypes
void TurnPlayerX ( char[][3], char&);
void PrintGrid();
void PrintWinner(int);
const int ROWS= 3;
const int COLUMNS =3;
char grid[ROWS][COLUMNS] = {'A','B','C',
'D','E','F',
'G','H','I'};
int main()
{
int count; //to keep track of turns
char letter;
cout<<"Welcome to the TIC TAC TOE GAME!!!"<<endl;
//Printing initial grid table;
cout<<"Initial grid table: "<<endl;
PrintGrid();
cout<<endl<<"The first turn is for the Os"<<endl;
count = 1;
while ( count <= 9)
{
if (( count % 2 ) != 0 )
{
TurnPlayerO(grid,letter); //Place on the grid the turn for the Os
}
else
{
TurnPlayerX(grid,letter); //Place on the grid the turn for the Xs
}
PrintGrid();
if (((grid[0][0] == grid[0][1]) && (grid[0][0] == grid[0][2])) || //if statement checks out if there is a winner
((grid[1][0] == grid[1][1]) && (grid[1][0] == grid[1][2])) ||
((grid[2][0] == grid[2][1]) && (grid[2][0] == grid[2][2])) ||
((grid[0][0] == grid[1][0]) && (grid[0][0] == grid[2][0])) ||
((grid[0][1] == grid[1][1]) && (grid[0][1] == grid[2][1])) ||
((grid[0][2] == grid[1][2]) && (grid[0][2] == grid[2][2])) ||
((grid[0][0] == grid[1][1]) && (grid[0][0] == grid[2][2])) ||
((grid[0][2] == grid[1][1]) && (grid[0][2] == grid[2][0])))
{
PrintWinner(count); //Prints a winner
}
count++;
}
if(count >= 10 )
{
cout<<"It is a TIE!!\a";
}
return 0;
}
//Function definitions
//************************************************************************************
void TurnPlayerO ( char grid[][3],char& letter )
//The user is prompt to enter a letter of the grid, the O will be
//place on the spot of the letter.
{
cout<<"Enter the letter in which you would like to place the O: ";
cin>>letter;
switch(toupper(letter)) //Converts the letter to uppercase, in case the user uses a lowercase
{
case 'A': grid[0][0]='O';
break;
case 'B': grid[0][1]='O';
break;
case 'C': grid[0][2]='O';
break;
case 'D': grid[1][0]='O';
break;
case 'E': grid[1][1]='O';
break;
case 'F': grid[1][2]='O';
break;
case 'G': grid[2][0]='O';
break;
case 'H': grid[2][1]='O';
break;
case 'I': grid[2][2]='O';
break;
default: break;
}
}
//************************************************************************************
void TurnPlayerX ( char grid[][3],char& letter)
//The user is prompt to enter a letter of the grid, the X will be
//place on the spot of the letter.
{
cout<<"Enter the letter in which you would like to place the X: ";
cin>>letter;
switch(toupper(letter)) //Converts the letter to uppercase, in case the user uses a lowercase
{
case 'A': grid[0][0]='X';
break;
case 'B': grid[0][1]='X';
break;
case 'C': grid[0][2]='X';
break;
case 'D': grid[1][0]='X';
break;
case 'E': grid[1][1]='X';
break;
case 'F': grid[1][2]='X';
break;
case 'G': grid[2][0]='X';
break;
case 'H': grid[2][1]='X';
break;
case 'I': grid[2][2]='X';
break;
default: break;
}
}
//************************************************************************************
void PrintGrid()
//Prints the actual grid table of the game
{
for (int i=0; i < 3; i++)
{
for (int j=0; j < 3; j++)
{
cout<<grid[i][j]<<" ";
}
cout<<endl;
}
}
//************************************************************************************
void PrintWinner(int count)
//Prints the winner of the game
// IF count is an even number
// the X-Player wins.
// ELSE
// the O-Player wins.
{
if ((count % 2 ) != 0)
{
cout<<"The winner is the O-PLAYER!!"<<endl;
cout<<"The game is over\a";
exit(0);
}
else
{
cout<<"The winner is the X-PLAYER!!";
cout<<"The game is over\a";
exit(0);
}
}
| 4e183a8dff4f809833822dcfd84702e3a66d3840 | [
"Markdown",
"C++"
] | 2 | Markdown | Ara947/Tic-tac-toe-game | 3be57efb7186def35baf74a6e898a68b14b0797d | 6702bf748068ec71f1491eb9f0b1db5b6bb00ebe |
refs/heads/master | <file_sep><?php
namespace sisVeterinaria\Http\Controllers;
use DB;
use Illuminate\Http\Request;
class HistorialController extends Controller
{
public function __construct()
{
}
public function index(Request $request)
{
if ($request) {
$query = trim($request->get('searchText'));
$Historial = DB::table('mascota as m')
->join('cita as c', 'm.idmascota', '=', 'c.idmascota')
->join('personal as p', 'c.idpersonal', '=', 'p.idpersonal')
->join('servicio as s', 'c.idservicio', '=', 's.idservicio')
->join('propietario as pr', 'm.idpropietario', '=', 'pr.idpropietario')
->select('c.idcita as id', 'c.fecha as fecha', 'm.nombre as mn', 'pr.nombre as prn', 'pr.ap_paterno as prap', 'pr.ap_materno as pram', 'm.especie as e', 'c.observacion as obs', 's.nombre as s', 's.descripcion as des', 'p.nombre as pn', 'p.ap_paterno as pap', 'p.ap_materno as pam')
->where('p.nombre', 'LIKE', '%' . $query . '%')
->orwhere('p.ap_paterno', 'LIKE', '%' . $query . '%')
->orwhere('p.ap_materno', 'LIKE', '%' . $query . '%')
->orwhere('pr.nombre', 'LIKE', '%' . $query . '%')
->orwhere('pr.ap_paterno', 'LIKE', '%' . $query . '%')
->orwhere('pr.ap_materno', 'LIKE', '%' . $query . '%')
->orwhere('m.nombre', 'LIKE', '%' . $query . '%')
->orwhere('s.nombre', 'LIKE', '%' . $query . '%')
->orwhere('c.fecha', 'LIKE', '%' . $query . '%')
->orwhere('s.descripcion', 'LIKE', '%' . $query . '%')
->orderBy('c.fecha', 'asc')
->paginate(8);
return view('administrador.historial.index', ["Historial" => $Historial, "searchText" => $query]);
}
}
public function create()
{
$propietario = DB::table('propietario')
->get();
return view('administrador.historial.create', ["propietario" => $propietario]);
}
public function store()
{
}
public function show()
{
}
public function edit()
{
}
public function update()
{
}
public function destroy()
{
}
}
<file_sep><?php
namespace sisVeterinaria;
use Illuminate\Database\Eloquent\Model;
class Tipo extends Model
{
//hace referncia a la tabla de la base de datos
protected $table='tipo';
protected $primaryKey = 'idtipo';
public $timestamps=false;
protected $fillable=[
'cargo',
];
protected $guarded=[
];
}
<file_sep><?php
namespace sisVeterinaria;
use Illuminate\Database\Eloquent\Model;
class Personal extends Model
{
//hace referncia a la tabla de la base de datos
protected $table='personal';
protected $primaryKey = 'idpersonal';
public $timestamps=false;
protected $fillable=[
'nombre',
'ap_paterno',
'ap_materno',
'ci',
'telf',
'direccion',
];
protected $guarded=[
];
}
<file_sep><?php
namespace sisVeterinaria\Http\Controllers;
use DB;
use Illuminate\Http\Request;
use Illuminate\support\Facades\Redirect;
use sisVeterinaria\Http\Requests\MascotaFormRequest;
use sisVeterinaria\Mascota;
class MascotaController extends Controller
{
public function __construct()
{
}
public function index(Request $request)
{
if ($request) {
$query = trim($request->get('searchText'));
$Mascota = DB::table('mascota as m')
->join('propietario as p', 'm.idpropietario', '=', 'p.idpropietario')
->select('m.idmascota', 'm.nombre', 'm.raza', 'm.especie', 'm.sexo', 'm.descripcion', 'm.fecha_registro', 'p.nombre as pn', 'p.ap_paterno as pp', 'p.ap_materno as pm')
->where('m.nombre', 'LIKE', '%' . $query . '%')
->orwhere('m.raza', 'LIKE', '%' . $query . '%')
->orwhere('m.especie', 'LIKE', '%' . $query . '%')
->orwhere('m.sexo', 'LIKE', '%' . $query . '%')
->orwhere('m.descripcion', 'LIKE', '%' . $query . '%')
->orderBy('m.idmascota', 'asc')
->paginate(8);
return view('administrador.mascota.index', ["Mascota" => $Mascota, "searchText" => $query]);
}
}
public function create()
{
$propietario = DB::table('propietario')
->get();
return view('administrador.mascota.create', ["propietario" => $propietario]);
}
public function store(MascotaFormRequest $request)
{
$Mascota = new Mascota;
$Mascota->nombre = $request->get('nombre');
$Mascota->raza = $request->get('raza');
$Mascota->especie = $request->get('especie');
$Mascota->sexo = $request->get('sexo');
$Mascota->descripcion = $request->get('descripcion');
$Mascota->fecha_registro = $request->get('fecha');
$Mascota->idpropietario = $request->get('propietario');
$Mascota->save();
return Redirect::to('administrador/mascota');
}
public function show($id)
{
return view("administrador.mascota.show", ["mascota" => Mascota::findOrFail($id)]);
}
public function edit($id)
{
$mascota = Mascota::findOrfail($id);
$idp = DB::table('mascota as m')
->join('propietario as p', 'm.idpropietario', '=', 'p.idpropietario')
->select('p.idpropietario as idp', 'p.nombre as nombre', 'p.ap_paterno as app', 'p.ap_materno as pm')
->where('m.idmascota', '=', $id)
->first();
return view("administrador.mascota.edit", ["mascota" => $mascota, "idp" => $idp]);
}
public function update(MascotaFormRequest $request, $id)
{
$Mascota = Mascota::findOrFail($id);
$Mascota->nombre = $request->get('nombre');
$Mascota->raza = $request->get('raza');
$Mascota->especie = $request->get('especie');
$Mascota->sexo = $request->get('sexo');
$Mascota->descripcion = $request->get('descripcion');
$Mascota->fecha_registro = $request->get('fecha');
$Mascota->idpropietario = $Mascota->idpropietario;
$Mascota->update();
return Redirect::to('administrador/mascota');
}
public function destroy($id)
{
$mascota = Mascota::findOrfail($id);
$mascota->delete();
return Redirect::to('administrador/mascota');
}
}
<file_sep><?php
namespace sisVeterinaria;
use Illuminate\Database\Eloquent\Model;
class Usuario extends Model
{
//hace referncia a la tabla de la base de datos
protected $table='usuario';
protected $primaryKey = 'idusuario';
public $timestamps=false;
protected $fillable=[
'usuario',
'pass',
'idpersonal',
'idtipo',
];
protected $guarded=[
];
}
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.8.0
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 04-05-2018 a las 01:50:06
-- Versión del servidor: 10.1.31-MariaDB
-- Versión de PHP: 7.1.16
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `veterinaria`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `cita`
--
CREATE TABLE `cita` (
`idcita` int(11) NOT NULL,
`fecha` date DEFAULT NULL,
`hora` time DEFAULT NULL,
`producto` varchar(45) DEFAULT NULL,
`observacion` varchar(200) DEFAULT NULL,
`estado` varchar(45) DEFAULT NULL,
`prox_cita` date DEFAULT NULL,
`peso` decimal(11,2) DEFAULT NULL,
`edad` int(11) DEFAULT NULL,
`idpersonal` int(11) NOT NULL,
`idmascota` int(11) NOT NULL,
`idservicio` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `mascota`
--
CREATE TABLE `mascota` (
`idmascota` int(11) NOT NULL,
`nombre` varchar(45) DEFAULT NULL,
`raza` varchar(45) DEFAULT NULL,
`especie` varchar(20) DEFAULT NULL,
`sexo` varchar(45) DEFAULT NULL,
`descripcion` varchar(100) DEFAULT NULL,
`fecha_registro` date DEFAULT NULL,
`idpropietario` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `personal`
--
CREATE TABLE `personal` (
`idpersonal` int(11) NOT NULL,
`nombre` varchar(45) DEFAULT NULL,
`ap_paterno` varchar(45) DEFAULT NULL,
`ap_materno` varchar(45) DEFAULT NULL,
`ci` int(11) DEFAULT NULL,
`telf` int(11) DEFAULT NULL,
`direccion` varchar(45) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Volcado de datos para la tabla `personal`
--
INSERT INTO `personal` (`idpersonal`, `nombre`, `ap_paterno`, `ap_materno`, `ci`, `telf`, `direccion`) VALUES
(1, 'Cristal', 'Flores', 'Hilari', 6879878, 68475866, 'direccion 1'),
(2, 'Cinthia', 'Alvarez', 'de la Torre', 7382372, 78327833, 'direccion cinthia'),
(3, 'Wendy', 'Guzman', 'Rojas', 7234834, 37483283, 'direccion wen'),
(4, 'Diego', 'Chavez', 'Soria', 7384728, 73488237, 'direccion 4'),
(5, 'Daniel', 'Gironas', 'Perez', 7382372, 83727384, 'direccion dani'),
(6, 'Gabriel', 'a', 'a', 9, 9, 'a'),
(7, 'b', 'b', 'b', 1, 1, 'b'),
(11, 'pp', 'pp', 'pp', 111, 22, 'pp');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `propietario`
--
CREATE TABLE `propietario` (
`idpropietario` int(11) NOT NULL,
`nombre` varchar(45) DEFAULT NULL,
`ap_paterno` varchar(45) DEFAULT NULL,
`ap_materno` varchar(45) DEFAULT NULL,
`telf` int(11) DEFAULT NULL,
`ci` int(11) DEFAULT NULL,
`direccion` varchar(100) DEFAULT NULL,
`rfid` varchar(45) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Volcado de datos para la tabla `propietario`
--
INSERT INTO `propietario` (`idpropietario`, `nombre`, `ap_paterno`, `ap_materno`, `telf`, `ci`, `direccion`, `rfid`) VALUES
(2, 'Leonardo', 'Guzmán', 'Rojas', 76676186, 6722116, 'C. Illampu Esq. Sagarnaga', '100200'),
(3, 'Ingrit', 'Romano', 'Rojas', 214536, 784512, 'Av. Pioneros', '101201');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `servicio`
--
CREATE TABLE `servicio` (
`idservicio` int(11) NOT NULL,
`nombre` varchar(45) DEFAULT NULL,
`descripcion` varchar(45) DEFAULT NULL,
`frecuencia` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `tipo`
--
CREATE TABLE `tipo` (
`idtipo` int(11) NOT NULL,
`cargo` varchar(45) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Volcado de datos para la tabla `tipo`
--
INSERT INTO `tipo` (`idtipo`, `cargo`) VALUES
(1, 'ADMINISTRADOR'),
(2, 'VETERINARIO'),
(3, 'RECEPCIONISTA');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuario`
--
CREATE TABLE `usuario` (
`idusuario` int(11) NOT NULL,
`usuario` varchar(45) DEFAULT NULL,
`pass` varchar(45) DEFAULT NULL,
`idpersonal` int(11) NOT NULL,
`idtipo` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Volcado de datos para la tabla `usuario`
--
INSERT INTO `usuario` (`idusuario`, `usuario`, `pass`, `idpersonal`, `idtipo`) VALUES
(1, 'cris', 'cris', 1, 1),
(2, 'cinthia', 'cinthia', 2, 2),
(3, 'wen', 'wen', 3, 3),
(4, 'diego', 'diego', 4, 2),
(5, 'dani', 'dani', 5, 1),
(6, 'a', 'a', 6, 3),
(7, 'b', 'b', 7, 1),
(11, 'pp', 'pp', 11, 2);
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `cita`
--
ALTER TABLE `cita`
ADD PRIMARY KEY (`idcita`);
--
-- Indices de la tabla `mascota`
--
ALTER TABLE `mascota`
ADD PRIMARY KEY (`idmascota`);
--
-- Indices de la tabla `personal`
--
ALTER TABLE `personal`
ADD PRIMARY KEY (`idpersonal`);
--
-- Indices de la tabla `propietario`
--
ALTER TABLE `propietario`
ADD PRIMARY KEY (`idpropietario`);
--
-- Indices de la tabla `servicio`
--
ALTER TABLE `servicio`
ADD PRIMARY KEY (`idservicio`);
--
-- Indices de la tabla `tipo`
--
ALTER TABLE `tipo`
ADD PRIMARY KEY (`idtipo`);
--
-- Indices de la tabla `usuario`
--
ALTER TABLE `usuario`
ADD PRIMARY KEY (`idusuario`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `cita`
--
ALTER TABLE `cita`
MODIFY `idcita` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `mascota`
--
ALTER TABLE `mascota`
MODIFY `idmascota` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `personal`
--
ALTER TABLE `personal`
MODIFY `idpersonal` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
--
-- AUTO_INCREMENT de la tabla `propietario`
--
ALTER TABLE `propietario`
MODIFY `idpropietario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT de la tabla `servicio`
--
ALTER TABLE `servicio`
MODIFY `idservicio` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `usuario`
--
ALTER TABLE `usuario`
MODIFY `idusuario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
namespace sisVeterinaria\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UsuarioFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'usuario'=>'required|max:45',
'pass'=>'<PASSWORD>:45',
'idpersonal'=>'required|max:11',
'idpersonal'=>'max:11',
'idtipo'=>'max:11',
];
}
}
<file_sep><?php
namespace sisVeterinaria\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Illuminate\support\Facades\Redirect;
use sisVeterinaria\Http\Requests\PropietarioRequest;
use sisVeterinaria\Propietario;
class PropietarioController extends Controller
{
//Primera vista en pantalla al ingresar al menu de propietario
public function index(Request $request)
{
if ($request) {
$query = trim($request->get('searchText'));
$propietario = DB::table('propietario')
->select('idpropietario', 'nombre', 'ap_paterno', 'ap_materno','telf', 'ci', 'direccion', 'rfid')
->where('nombre', 'LIKE', '%' . $query . '%')
->orwhere('ap_paterno', 'LIKE', '%' . $query . '%')
->orwhere('ap_materno', 'LIKE', '%' . $query . '%')
->orwhere('ci', 'LIKE', '%' . $query . '%')
->orwhere('telf', 'LIKE', '%' . $query . '%')
->orderBy('idpropietario', 'asc')
->paginate(8);
return view('administrador.propietario.index', ["Propietario" => $propietario, "searchText" => $query]);
}
}
public function create()
{
return view("administrador.propietario.create");
}
//Registra los datos ingresados
public function store(PropietarioRequest $request)
{
$Propietario = new Propietario;
$Propietario ->nombre = $request->get('nombre');
$Propietario ->ap_paterno = $request->get('ap_paterno');
$Propietario ->ap_materno = $request->get('ap_materno');
$Propietario ->telf = $request->get('telf');
$Propietario ->ci = $request->get('ci');
$Propietario ->direccion = $request->get('direccion');
$Propietario ->rfid = $request->get('rfid');
$Propietario ->save();
return Redirect::to('administrador/propietario');
}
//Mostrar datos del propietario
public function show($id)
{
return view("administrador.propietario.show", ["propietario" => propietario::findOrFail($id)]);
}
//editar datos del propietario
public function edit($id)
{
return view("administrador.propietario.edit", ["propietario" => Propietario::findOrfail($id)]);
}
//Actualiza los datos del propietario
public function update(PropietarioRequest $request, $id)
{
$propietario = Propietario::findOrFail($id);
$propietario->nombre = $request->get('nombre');
$propietario->ap_paterno = $request->get('ap_paterno');
$propietario->ci = $request->get('ci');
$propietario->ap_materno = $request->get('ap_materno');
$propietario->telf = $request->get('telf');
$propietario->direccion = $request->get('direccion');
$propietario->rfid = $request->get('rfid');
$propietario->update();
return Redirect::to('administrador/propietario');
}
public function destroy($id)
{
$propietario = Propietario::findOrfail($id);
$propietario->delete();
return Redirect::to('administrador/propietario');
}
}
<file_sep><?php
Route::get('/', function () {
return view('');
});
Route::resource('administrador/personal', 'PersonalController');
Route::resource('administrador/propietario', 'PropietarioController');
Route::resource('administrador/mascota', 'MascotaController');
Route::resource('administrador/historial', 'HistorialController');
Route::resource('veterinario/propietario', 'PropietarioController');
Route::resource('veterinario/mascota', 'MascotaController');
Route::resource('veterinario/historial', 'HistorialController');
Route::resource('recepcionista/propietario', 'PropietarioController');
Route::resource('recepcionista/mascota', 'MascotaController');
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
<file_sep><?php
namespace sisVeterinaria;
use Illuminate\Database\Eloquent\Model;
class Cita extends Model
{
protected $table = 'cita';
protected $primaryKey = 'idcita';
public $timestamps = false;
protected $fillable = [
'fecha',
'hora',
'producto',
'observacion',
'estado',
'prox_cita',
'peso',
'edad',
'idpersonal',
'idmascota',
'idservicio',
];
protected $guarded = [
];
}
<file_sep><?php
namespace sisVeterinaria\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class MascotaFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'nombre' => 'required|max:45',
'raza' => 'required|max:45',
'especie' => 'max:45',
'sexo' => 'required|max:8',
'descripcion' => 'max:100',
'fecha_registro' => 'max:45',
'idpropietario' => 'max:8',
];
}
}
<file_sep><?php
namespace sisVeterinaria\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CitaFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'cargo' => 'max:45',
'fecha' => 'max:45',
'hora' => 'max:45',
'producto' => 'max:45',
'observacion' => 'max:200',
'estado' => 'max:45',
'prox_cita' => 'max:45',
'peso' => '',
'edad' => 'max:11',
'idpersonal' => 'max:11',
'idmascota' => 'max:11',
'idservicio' => 'max:11',
];
}
}
<file_sep><?php
namespace sisVeterinaria\Http\Controllers;
use DB;
use Illuminate\Http\Request;
use Illuminate\support\Facades\Redirect;
use sisVeterinaria\Http\Requests\PersonalFormRequest;
use sisVeterinaria\Personal;
use sisVeterinaria\Usuario;
class PersonalController extends Controller
{
public function __construct()
{
}
public function index(Request $request)
{
if ($request) {
$query = trim($request->get('searchText'));
$Personal = DB::table('personal as p')
->join('usuario as u', 'p.idpersonal', '=', 'u.idpersonal')
->join('tipo as t', 'u.idtipo', '=', 't.idtipo')
->select('p.idpersonal', 'p.nombre', 'p.ap_paterno', 'p.ap_materno', 'p.ci', 'p.telf', 'p.direccion', 't.cargo as cargo')
->where('p.nombre', 'LIKE', '%' . $query . '%')
->orwhere('p.ap_paterno', 'LIKE', '%' . $query . '%')
->orwhere('p.ap_materno', 'LIKE', '%' . $query . '%')
->orwhere('p.ci', 'LIKE', '%' . $query . '%')
->orwhere('p.telf', 'LIKE', '%' . $query . '%')
->orderBy('p.idpersonal', 'asc')
->paginate(8);
return view('administrador.personal.index', ["Personal" => $Personal, "searchText" => $query]);
}
}
public function create()
{
return view("administrador.personal.create");
}
public function store(PersonalFormRequest $request)
{
$Personal = new Personal;
$Personal->nombre = $request->get('nombre');
$Personal->ap_paterno = $request->get('ap_paterno');
$Personal->ap_materno = $request->get('ap_materno');
$Personal->ci = $request->get('ci');
$Personal->telf = $request->get('telf');
$Personal->direccion = $request->get('direccion');
$Personal->save();
$usuario = new Usuario;
$usuario->usuario = $request->get('usuario');
$usuario->pass = $request->get('pass');
$usuario->idpersonal = $Personal->idpersonal;
$usuario->idtipo = $request->get('cargo');
$usuario->save();
return Redirect::to('administrador/personal');
}
public function show($id)
{
return view("administrador.personal.show", ["personal" => Personal::findOrFail($id)]);
}
public function edit($id)
{
$personal = Personal::findOrfail($id);
$usu = DB::table('usuario as u')
->join('tipo as t', 'u.idtipo', '=', 't.idtipo')
->select('u.idusuario', 'u.usuario', 'u.pass', 't.cargo as cargo', 'u.idpersonal', 'u.idtipo', 't.idtipo as idtipo')
->where('u.idpersonal', '=', $id)
->first();
$tipo = DB::table('tipo')
->get();
return view("administrador.personal.edit", ["personal" => $personal, "usu" => $usu, "tipos" => $tipo]);
}
public function update(PersonalFormRequest $request, $id)
{
$personal = Personal::findOrFail($id);
$personal->nombre = $request->get('nombre');
$personal->ap_paterno = $request->get('ap_paterno');
$personal->ci = $request->get('ci');
$personal->ap_materno = $request->get('ap_materno');
$personal->telf = $request->get('telf');
$personal->direccion = $request->get('direccion');
$personal->update();
$usuario = Usuario::findOrfail($id);
$usuario->usuario = $request->get('usuario');
$usuario->pass = $request->get('pass');
$usuario->idpersonal = $personal->idpersonal;
$usuario->idtipo = $request->get('cargo');
$usuario->update();
return Redirect::to('administrador/personal');
}
public function destroy($id)
{
$personal = Personal::findOrfail($id);
$personal->delete();
$usuarios = Usuario::findOrFail($id);
$usuarios->delete();
return Redirect::to('administrador/personal');
}
}
| 6a28bf2201d6a0cbcc7bb4e6ff52f6a4811e30d3 | [
"SQL",
"PHP"
] | 13 | PHP | wenguz/sisVeterinariaB | 7a9a55c41847efb34bd66b1a6e9e542af03e5f19 | 72766bc38130fe230f632e0d8b10d3fd55c3b34c |
refs/heads/master | <file_sep>require "tti_spec_helper"
require "net/tti/message"
module Net
module TTI
describe Authentication do
auth_request = (
"037304010106020101010103010173797374656d010d0d415554485f50415353" +
"574f524401404046343638364543394337303541313145343930434337303031" +
"3431313038453431393136343130374643423342364237434431393346363045" +
"4532433235354600010d0d415554485f5445524d494e414c010707756e6b6e6f" +
"776e00010c0c415554485f534553534b45590140404332344242313730423644" +
"4635394431304239434439453835363841314334453342433438463946454438" +
"3338363933464136323035304231444332463937410101" ).tns_unhexify
context "when serializing authentication messages" do
subject {Authentication.new( :username => "system" )}
before :each do
subject.sequence_number = 4 # Sequence number in example
end
it "should properly serialize authentication request" do
subject.enc_password = "<PASSWORD>".tns_unhexify
subject.add_parameter("AUTH_TERMINAL", "unknown")
subject.enc_client_session_key = "C24BB170B6DF59D10B9CD9E8568A1C4E3BC48F9FED838693FA62050B1DC2F97A".tns_unhexify
expect(subject).to eql_binary_string( auth_request )
end
it "should properly serialize authentication request when calling #add_parameter" do
subject.add_parameter( "AUTH_PASSWORD", "<PASSWORD>" )
subject.add_parameter("AUTH_TERMINAL", "unknown")
subject.add_parameter( "AUTH_SESSKEY", "<KEY>", 1 )
expect(subject).to eql_binary_string( auth_request )
end
end
end
end
end
<file_sep>require "tti_spec_helper"
require "net/tti/data_types"
shared_examples_for "a KeyValuePair that reads properly" do
subject {Net::TTI::DataTypes::KeyValuePair.read( binary_string )}
its(:kvp_key) {should == kvp_key}
its(:kvp_value) {should == kvp_value}
its(:flags) {should == flags}
end
shared_examples_for "a KeyValuePair that functions properly" do
it "should serialize properly when built from #initialize arguments" do
kvp = Net::TTI::DataTypes::KeyValuePair.new( :kvp_key => kvp_key, :kvp_value => kvp_value, :flags => flags )
expect(kvp.to_binary_s).to eql(binary_string)
end
it "should serialize properly when built from accessors" do
kvp = Net::TTI::DataTypes::KeyValuePair.new
kvp.kvp_key = kvp_key
kvp.kvp_value = kvp_value
kvp.flags = flags
expect(kvp.to_binary_s).to eql(binary_string)
end
it_should_behave_like "a KeyValuePair that reads properly"
end
module Net::TTI::DataTypes
describe KeyValuePair do
let(:flags) {0x00}
context "with a simple key-value pair" do
it_should_behave_like "a KeyValuePair that functions properly" do
let(:binary_string) {"010d0d415554485f5445524d494e414c010707756e6b6e6f776e00".tns_unhexify}
let(:kvp_key) {"AUTH_TERMINAL"}
let(:kvp_value) {"unknown"}
let(:flags) {0x00}
end
end
context "with a value with special characters" do
it_should_behave_like "a KeyValuePair that functions properly" do
let(:binary_string) {"0105055445535432010e0e544553545c544553543a5445535400".tns_unhexify}
let(:kvp_key) {"TEST2"}
let(:kvp_value) {"TEST\\TEST:TEST"}
end
end
context "with a simple key-value pair with flags" do
it_should_behave_like "a KeyValuePair that functions properly" do
let(:binary_string) {"01040454455354010404544553540144".tns_unhexify}
let(:kvp_key) {"TEST"}
let(:kvp_value) {"TEST"}
let(:flags) {68}
end
end
context "with a key-value pair with no value" do
it_should_behave_like "a KeyValuePair that functions properly" do
let(:binary_string) {"01040454455354010000".tns_unhexify}
let(:kvp_key) {"TEST"}
let(:kvp_value) {""}
end
end
context "with an AUTH_SESSKEY key-value pair" do
it_should_behave_like "a KeyValuePair that functions properly" do
let(:binary_string) {
( "010c0c415554485f534553534b45590140403938313146433737383734314141" +
"4344304438433335324232333941373939383745423944374544324231413536" +
"4245444239383430334341333535443634300101").tns_unhexify }
let(:kvp_key) {"AUTH_SESSKEY"}
let(:kvp_value) {"9811FC778741AACD0D8C352B239A79987EB9D7ED2B1A56BEDB98403CA355D640"}
let(:flags) {1}
end
end
context "with an AUTH_ALTER_SESSION key-value pair" do
# This example is a server response, which includes unknown values. We
# just need to read it correctly, not be able to build it.
it_should_behave_like "a KeyValuePair that reads properly" do
let(:binary_string) {
( "011212415554485f414c5445525f53455353494f4e015ffe40414c5445522053" +
"455353494f4e205345542054494d455f5a4f4e453d27416d65726963612f4e65" +
"775f596f726b27204e4c535f4c414e47554147453d27414d451f524943414e27" +
"204e4c535f5445525249544f52593d27414d45524943412700000101" ).tns_unhexify }
let(:kvp_key) {"AUTH_ALTER_SESSION"}
let(:kvp_value) {
"ALTER SESSION SET TIME_ZONE='America/New_York' NLS_LANGUAGE='AMERICAN' NLS_TERRITORY='AMERICA'\x00" }
let(:flags) { 0x01 }
end
end
end
end
<file_sep>require "tti_spec_helper"
require "net/tti/message"
shared_examples_for "an ErrorMessage that reads properly" do
context "when reading" do
subject{Net::TTI::ErrorMessage.read( binary_string )}
its(:message) {should eql( message )}
end
end
module Net
module TTI
describe ErrorMessage do
context "when parsing a bad-username/password error from an Oracle DB 10g server" do
it_should_behave_like "an ErrorMessage that reads properly" do
let(:binary_string) {("04010100000203f9000000000000000000000000000000000004000000000000334f52412d30313031373a20696e76616c696420757365726e616d652f70617373776f72643b206c6f676f6e2064656e6965640a").tns_unhexify }
let(:message) {"ORA-01017: invalid username/password; logon denied\n"}
end
end
context "when parsing an account-locked-out error from an Oracle DB 10g server" do
it_should_behave_like "an ErrorMessage that reads properly" do
let(:binary_string) {("0401010000026d60000000000000000000000000000000000004000000000000214f52412d32383030303a20746865206163636f756e74206973206c6f636b65640a").tns_unhexify }
let(:message) {"ORA-28000: the account is locked\n"}
end
end
context "when parsing ORA-01034 error from a Oracle DB 10g server" do
it_should_behave_like "an ErrorMessage that reads properly" do
let(:binary_string) {("040101000002040a000000000000000000000000000000000002000000000000804f52412d30313033343a204f5241434c45206e6f7420617661696c61626c650a4f52412d32373130313a20736861726564206d656d6f7279207265616c6d20646f6573206e6f742065786973740a536f6c617269732d414d443634204572726f723a20323a204e6f20737563682066696c65206f72206469726563746f72790a").tns_unhexify }
let(:message) {"ORA-01034: ORACLE not available\nORA-27101: shared memory realm does not exist\nSolaris-AMD64 Error: 2: No such file or directory\n"}
end
end
end
end
end
<file_sep>require 'net/tns/client'
module Net
module TNS
describe Client do
let(:vsnnum) { '301989888' }
describe "::parse_vsnnum" do
context "when provided a valid VSNNUM string" do
it "should return the correct version" do
expect(Client.parse_vsnnum(vsnnum)).to eql('18.0.0.0.0')
end
end
context "when provided a non-string" do
it "should raise an error" do
expect { Client.parse_vsnnum(12345678) }.to raise_error(ArgumentError)
end
end
end
end
end
end
<file_sep>require "bindata"
module Net
module TTI
module DataTypes
class Flags < BinData::Primitive
uint8 :value_length
choice :flag_value, :selection => :value_length do
virtual 0, :value => 0
uint8 1
uint16be 2
uint32be 4
end
def get
self.flag_value.to_i
end
def set(new_value)
if new_value > 0xffff
self.value_length = 4
self.flag_value = new_value
elsif new_value > 0xff
self.value_length = 2
self.flag_value = new_value
elsif new_value > 0
self.value_length = 1
self.flag_value = new_value
else
self.value_length = 0
end
end
end
end
end
end
<file_sep>require "tti_spec_helper"
require "net/tti/message"
shared_examples_for "a DataTypeNegotiationRequest that functions properly" do
it "should serialize properly" do
conn_params.ttc_version = 6
conn_params.character_set = 0xb2
conn_params.server_flags = 0x1
conn_params.server_compiletime_capabilities = Net::TTI::Capabilities.from_binary_string( "\x06\x01\x01\x01\x0f\x01\x01\x06\x01\x01\x01\x01\x01\x01\x01\x7f\xff\x03\n\x03\a\x01\x01\x7f\x01\x7f\xff\x01\t\x01\x01\xbf\x01\x05\x06\x00\x01\a\x04" )
conn_params.server_runtime_capabilities = Net::TTI::Capabilities.from_binary_string( "\x02\x01\x00\x01\x18\x00\x03")
kvp = Net::TTI::DataTypeNegotiationRequest.create_request(conn_params)
expect(kvp).to eql_binary_string(binary_string)
end
end
module Net::TTI
describe DataTypeNegotiationRequest do
context "with a request for a 11g2 server" do
it_should_behave_like "a DataTypeNegotiationRequest that functions properly" do
let(:conn_params) { Net::TTI::ConnectionParameters.new() }
let(:binary_string) {TtiSpecHelper.read_message("data_type_negotiation_request_solaris_11g2.raw")}
end
end
# TODO: fix this by passing conn_params with correct Capabilities for 10g
# context "with a request for a 10g2 server" do
# it_should_behave_like "a DataTypeNegotiationRequest that functions properly" do
# let(:conn_params) { Net::TTI::ConnectionParameters.new() }
# let(:binary_string) {TtiSpecHelper.read_message("data_type_negotiation_request_solaris_10g2.raw")}
# end
# end
end
end
<file_sep>module Net
module TNS
VERSION = "1.1.4"
end
end
<file_sep>## TNS Connection Sequence (<= 9i)
C: TNS Connect
S: TNS Accept
C: TNS Data [ANO Negotiation Request]
C: TNS Data [ANO Negotiation Response]
## TNS Connection Sequence (> 9i)
C: TNS Connect
S: TNS Resend
C: TNS Connect
S: TNS Accept
C: TNS Data [ANO Negotiation Request]
C: TNS Data [ANO Negotiation Response]
## TTI Connection Sequence
[TNS connection first]
[All TTI messages are passed via TNS Data packets]
C: TTI Protocol Negotiation Request
S: TTI Protocol Negotiation Response
C: TTI Data Type Neogitation Request
S: TTI Data Type Neogitation Response
## Authentication Sequence
[TTI connection first]
[All TTI messages are passed via TNS Data packets]
C: TTI Function Call [Pre-Authentication Request]
S: TTI OK [Pre-Authentication Response]
C: TTI Function Call [Authentication Request]
S: TTI OK [Authentication Response]
<file_sep>require "bindata"
require "net/tti/data_types/chunked_string"
require "net/tti/data_types/flags"
module Net
module TTI
module DataTypes
class KeyValuePair < BinData::Record
# Follows (simplified) format used by JDBC driver; other clients send
# KVPs with a longer, more opaque structure (e.g. each chunked string
# was preceded by a 4-byte value that, in earlier dialects appeared to
# contain the total length of the string, but in later dialects did not
# seem related to string length at all).
uint8 :unknown1, :initial_value => 0x01 # size in bytes of kvp_key_length OR boolean
uint8 :kvp_key_length, :onlyif => lambda {unknown1 != 0x00}, :value => lambda {kvp_key.length}
chunked_string :kvp_key, :onlyif => lambda {unknown1 != 0x00 && kvp_key_length != 0x00}
uint8 :unknown2, :initial_value => 0x01 # size in bytes of kvp_value_length
uint8 :kvp_value_length, :onlyif => lambda {unknown2 != 0x00}, :value => lambda {kvp_value.length}
chunked_string :kvp_value, :onlyif => lambda {unknown2 != 0x00 && kvp_value_length != 0x00}
# flags are used when AUTH_SESSKEY and AUTH_ALTER_SESSION are sent to the server
flags :flags
end
end
end
end
<file_sep>
module Net
module TTI
class Capabilities
def initialize(caps_bytes=[])
@caps_bytes = caps_bytes
end
def self.from_byte_array(bytes)
Capabilities.new(bytes)
end
def self.from_binary_string(string)
Capabilities.new( string.unpack("C*") )
end
def [](index)
@caps_bytes[index]
end
def []=(index, value)
@caps_bytes[index] = value
end
def length
@caps_bytes.length
end
def to_binary_s
@caps_bytes.pack("C*")
end
# Returns hexified bytes, delimited by spaces
# e.g. [0x01,0x41,0x81,0xa1] -> "01 41 81 a1"
def to_hexified_s
to_binary_s.scan(/../).join(" ")
end
end
end
end
<file_sep>module Net::TNS
# This module includes common string helper methods for monkey-patching
# or mixing-in to string objects.
module StringHelpers
HEXCHARS = [("0".."9").to_a, ("a".."f").to_a].flatten
# Adapted from the Ruby Black Bag (http://github.com/emonti/rbkb/)
# Convert a string to ASCII hex string
def tns_hexify
self.each_byte.map do |byte|
(HEXCHARS[(byte >> 4)] + HEXCHARS[(byte & 0xf )])
end.join()
end
# Convert ASCII hex string to raw.
#
# Parameters:
#
# d = optional 'delimiter' between hex bytes (zero+ spaces by default)
def tns_unhexify(d=/\s*/)
self.strip.gsub(/([A-Fa-f0-9]{1,2})#{d}?/) { $1.hex.chr }
end
end
end
class String
include Net::TNS::StringHelpers
end
<file_sep>require "tti_spec_helper"
require "net/tti/message"
shared_examples_for "a PreAuthenticationResponse that reads properly" do |expected_parameters|
context "when reading" do
subject {Net::TTI::PreAuthenticationResponse.read( @binary_string )}
its(:auth_sesskey) {should == @auth_sesskey}
its(:auth_vfr_data) {should == @auth_vfr_data}
context "when examining the parameters" do
it "should have the right number of parameters" do
expect(subject.parameters.count).to eql(expected_parameters.count)
end
expected_parameters.each do |expected_parameter|
expected_key = expected_parameter[:key]
it "#{expected_key} should have the right contents" do
key = subject.parameters.find {|p| p.kvp_key == expected_key}
expect(key.kvp_key).to eql(expected_parameter[:key])
expect(key.kvp_value).to eql(expected_parameter[:value])
expect(key.flags).to eql(expected_parameter[:flags] || 0)
end
end
end
end
end
module Net
module TTI
describe PreAuthenticationResponse do
context "with a 10g response" do
before :each do
@binary_string = ("080102010c0c415554485f534553534b45590140403930303739333939313736" +
"3642423930323646453138453941373030383732324633424345413535463334" +
"35423932464636343639323637303538343939354500010d0d415554485f5646" +
"525f444154410001090401010102000000000000000000000000000000000000" +
"0000020000000000").tns_unhexify
@auth_sesskey = "<KEY>".tns_unhexify
@auth_vfr_data = ""
end
parameters = [
{:key=>"AUTH_SESSKEY", :value=>"<KEY>"},
{:key=>"AUTH_VFR_DATA", :value=>"", :flags=>9},
]
it_should_behave_like "a PreAuthenticationResponse that reads properly", parameters
end
context "with an 11g response" do
before :each do
@binary_string = ("080103010C0C415554485F534553534B45590160604336374444454432354333" +
"3431353943313937434544383533373546333032444443433939314239354242" +
"4534454142363233433835443135433444423442413631373532433736323643" +
"34463143443245353145324544303445424335413600010D0D415554485F5646" +
"525F444154410114143638383736353037463035434445383644304436021B25" +
"011A1A415554485F474C4F42414C4C595F554E495155455F4442494400012020" +
"4337363744304239463736433446354646383942463445374238344438353832" +
"0004010101020000000000000000000000000000000000000001000000000000").tns_unhexify
@auth_sesskey = "C67DDED25C34159C197CED85375F302DDCC991B95BBE4EAB623C85D15C4DB4BA61752C7626C4F1CD2E51E2ED04EBC5A6".tns_unhexify
@auth_vfr_data = "68876507F05CDE86D0D6".tns_unhexify
end
parameters = [
{:key=>"AUTH_SESSKEY", :value=>"C67DDED25C34159C197CED85375F302DDCC991B95BBE4EAB623C85D15C4DB4BA61752C7626C4F1CD2E51E2ED04EBC5A6"},
{:key=>"AUTH_VFR_DATA", :value=>"68876507F05CDE86D0D6", :flags=>0x1B25,},
{:key=>"AUTH_GLOBALLY_UNIQUE_DBID\0", :value=>"<KEY>",},
]
it_should_behave_like "a PreAuthenticationResponse that reads properly", parameters
end
end
end
end
<file_sep>require "tti_spec_helper"
require "net/tti/message"
module Net
module TTI
describe PreAuthentication do
username_only1 = "0376020101060101010100010173797374656d".tns_unhexify
username_only2 = "0376020101040101010100010173797374".tns_unhexify
request1 = "0376020101060101010101010173797374656d010d0d415554485f5445524d494e414c010f0f54455354484f53542d445936424a3500".tns_unhexify
request2 = "0376020101060101010102010173797374656d010d0d415554485f5445524d494e414c010f0f54455354484f53542d445936424a3500010f0f415554485f50524f4752414d5f4e4d010b0b73716c706c75732e65786500".tns_unhexify
context "when serializing pre-authentication messages" do
subject {PreAuthentication.new( :username => "system" )}
before :each do
subject.sequence_number = 2 # Sequence number in example
end
it "should properly serialize a request with no parameters" do
expect(subject).to eql_binary_string( username_only1 )
subject.username = "syst"
expect(subject).to eql_binary_string( username_only2 )
end
it "should properly serialize a request with one parameter" do
subject.add_parameter( "AUTH_TERMINAL", "TESTHOST-DY6BJ5" )
expect(subject).to eql_binary_string( request1 )
end
it "should properly serialize a request with two parameters" do
subject.add_parameter( "AUTH_TERMINAL", "TESTHOST-DY6BJ5" )
subject.add_parameter( "AUTH_PROGRAM_NM", "sqlplus.exe" )
expect(subject).to eql_binary_string( request2 )
end
end
end
end
end
<file_sep>require "net/tti/data_types"
module Net
module TTI
class Authentication < FunctionCall
LOGON_MODE_PRE_AUTH = 0x01
LOGON_MODE_AUTH = 0x0101
uint8 :unknown1, :initial_value => 0x01
uint8 :username_length_length, :initial_value => 0x01
uint8 :username_length, :value => lambda { username.length }
uint8 :logon_mode_length, :initial_value => lambda { _logon_mode_length }
choice :logon_mode, :selection => :_logon_mode do
uint8 LOGON_MODE_PRE_AUTH, :initial_value => lambda { _logon_mode }
uint16le LOGON_MODE_AUTH, :initial_value => lambda { _logon_mode }
end
uint8 :unknown2, :initial_value => 0x01
uint8 :parameters_count_length, :initial_value => 0x01
uint8 :parameters_count, :value => lambda {parameters.count}
uint8 :unknown3, :initial_value => 0x01
uint8 :unknown4, :initial_value => 0x01
string :username
array :parameters, :type => :key_value_pair, :read_until => lambda {index == parameters_count - 1}
def _function_code
return FUNCTION_CODE_AUTH
end
private :_function_code
def _logon_mode
return Authentication::LOGON_MODE_AUTH
end
private :_logon_mode
def _logon_mode_length
case _logon_mode
when Authentication::LOGON_MODE_PRE_AUTH
return 1
when Authentication::LOGON_MODE_AUTH
return 2
end
end
private :_logon_mode
def self.create_pre_auth_request()
return PreAuthentication.new
end
def self.create_auth_request()
return Authentication.new
end
def add_parameter( key, value, flags=0 )
kvp = DataTypes::KeyValuePair.new( :kvp_key => key, :kvp_value => value, :flags => flags )
self.parameters << kvp
end
def enc_client_session_key=(enc_client_session_key)
add_parameter( "AUTH_SESSKEY", enc_client_session_key.tns_hexify.upcase, 1 )
end
def enc_password=(enc_password)
add_parameter( "AUTH_PASSWORD", enc_password.tns_hexify.upcase )
end
end
class PreAuthentication < Authentication
def _function_code
return FUNCTION_CODE_PRE_AUTH
end
private :_function_code
def _logon_mode
return Authentication::LOGON_MODE_PRE_AUTH
end
private :_logon_mode
end
end
end
<file_sep>module Net
module TTI
class ErrorMessage < Message
handles_response_for_ttc_code TTC_CODE_ERROR
# BinData fields
uint8 :ucaeocs_length
string :ucaeocs, :read_length => lambda { ucaeocs_length }
uint8 :oerrdd_length
string :oerrdd, :read_length => lambda { oerrdd_length }
uint8 :current_row_number_length
string :current_row_number, :read_length => lambda { current_row_number_length }
uint8 :retcode_length
string :retcode, :read_length => lambda { retcode_length }
string :unknown1, :read_length => 24
uint8 :message_length
string :message, :read_length => lambda { message_length }
end
end
end
<file_sep>module Net
module TTI
class ProtocolNegotiationResponse < Message
handles_response_for_ttc_code TTC_CODE_PROTOCOL_NEGOTIATION
# BinData fields
uint8 :ttc_version
# TODO throw if ttc_version is not in (4, 5, 6)
uint8 :unknown1
stringz :ttc_server
uint16le :character_set
uint8 :server_flags
uint16le :character_set_elements_length
string :character_set_elements, :read_length => lambda {character_set_elements_length * 5}
# TODO stop parsing here if ttc_version = 4
uint16be :fdo_length
string :fdo, :read_length => :fdo_length
# TODO stop parsing here is ttc_version < 6
uint8 :server_compiletime_capabilities_length
string :server_compiletime_capabilities, :read_length => :server_compiletime_capabilities_length
uint8 :server_runtime_capabilities_length
string :server_runtime_capabilities, :read_length => :server_runtime_capabilities_length
def populate_connection_parameters( conn_params )
conn_params.ttc_version = self.ttc_version
conn_params.ttc_server = self.ttc_server
conn_params.character_set = self.character_set
conn_params.server_flags = self.server_flags
conn_params.server_compiletime_capabilities = Capabilities.from_binary_string( server_compiletime_capabilities )
conn_params.server_runtime_capabilities = Capabilities.from_binary_string( server_runtime_capabilities )
ttc_server_map = {
# (start of) protocol handler string => {params}
"IBMPC/WIN_NT-" => {:architecture => :x86, :platform => :windows},
"IBMPC/WIN_NT64" => {:architecture => :x64, :platform => :windows},
"Linuxi386/Linux" => {:architecture => :x86, :platform => :linux},
"x86_64/Linux" => {:architecture => :x64, :platform => :linux},
"Sun386i/SunOS" => {:architecture => :x86, :platform => :solaris},
"AMD64/SunOS" => {:architecture => :x64, :platform => :solaris},
}
ph_match, match_params = ttc_server_map.find do |ph_start, params|
ttc_server.start_with?(ph_start)
end
if ph_match
conn_params.architecture = match_params[:architecture]
conn_params.platform = match_params[:platform]
else
raise Net::TTI::Exceptions::UnsupportedPlatform.new( ttc_server )
end
end
end
end
end
| 1662ad55eadbe21fe0023f9bb044e8c4664b83ec | [
"Markdown",
"Ruby"
] | 16 | Ruby | chinaren2003/net-tns | 06a085f84aff46673d257be368636c40e76369f8 | 1f0aebfd2c583b812431cd528144b1f52dcab5d5 |
refs/heads/master | <repo_name>ckgardner/Chord<file_sep>/structs.go
package main
import (
//"sync"
)
// Node has stuff
type Node struct {
MyAddress string
Port string
Finger []string
Successors [3]string
Predecessor string
Bucket map[string]string
Ring bool
kill chan struct{}
//Lock sync.Mutex
Ip string
Next int
}
// Nothing will do nothing
type Nothing struct{}
// Pair has a key-value pair
type Pair struct {
Key string
Value string
}
// Commnad is a struct that has a verb and a function
type command struct {
}
// Finger is an address of a node
type Finger struct {
}
// FoundNode is a boolean
type FoundNode struct{
Found bool
Node string
}
// KeyFound = struct
type KeyFound struct{
Found bool
Address string
}<file_sep>/RPC_methods.go
package main
import (
"math/big"
"fmt"
"strconv"
)
// Ping methods will all be exported
func (node *Node) Ping(nothing Nothing, response *Nothing) error {
return nil
}
// Set method exported
func (node *Node) Set(pair *Pair, reply *struct{}) error {
node.Bucket[pair.Key] = pair.Value
fmt.Println(*pair, "added to node")
return nil
}
// Get method exported
func (node *Node) Get(Key string, res *string) error {
if val, ok := node.Bucket[Key]; ok{
*res = val
return nil
}
return fmt.Errorf("pair does not exist for:", Key)
}
// Delete method exported
func (node *Node) Delete(pair *Pair, res *Nothing) error {
if val, ok := node.Bucket[pair.Key]; ok{
delete(node.Bucket, pair.Key)
fmt.Println("Removed Pair: ", pair.Key, val)
return nil
}
return fmt.Errorf("pair does not exist for pair:", pair)
}
// Notify method exported
func (node *Node) Notify(predecessor string, response *Nothing) error {
if node.Predecessor == "" || between(hashString(node.Predecessor), hashString(predecessor), hashString(node.MyAddress), false){
node.Predecessor = predecessor
}
return nil
}
func (node *Node) Dump(emp *struct{}, dump *Node)error{
dump.MyAddress = node.MyAddress
dump.Predecessor = node.Predecessor
dump.Successors = node.Successors
dump.Bucket = node.Bucket
var old string
for i := 0; i < len(node.Finger); i++{
if old != node.Finger[i]{
dump.Finger = append(dump.Finger, strconv.Itoa(i)+":\t", node.Finger[i], "\n\t\t\t")
old = node.Finger[i]
}
}
return nil
}
// FindSuccessor RPC
func (node *Node) FindSuccessor(id *big.Int, res *FoundNode) error{
if between(hashString(node.MyAddress), id, hashString(node.Successors[0]), true){
res.Node = node.Successors[0]
res.Found = true
return nil
}
res.Node = node.closestPrecedingNode(id)
return nil
}
// PutAll RPC
func (node *Node) PutAll(bucket map[string]string, empty *struct{}) error{
for k, v := range bucket{
node.Bucket[k] = v
}
return nil
}
// GetAll RPC
func (node *Node) GetAll(address string, empty *struct{}) error{
bucket := make(map[string]string)
for k, v := range node.Bucket{
if between(hashString(node.Predecessor), hashString(string(k)), hashString(address), false){
bucket[k] = v
delete(node.Bucket, k)
}
}
call(address, "Node.PutAll", bucket, &struct{}{})
return nil
}<file_sep>/chord.go
package main
import (
"fmt"
"os"
"time"
)
const (
defaultHost = "localHost"
defaultPort = "3410"
)
func main() {
myNode := new(Node)
myNode.kill = make(chan struct{})
myNode.Bucket = make(map[string]string)
myNode.Ip = getLocalAddress()
myNode.Port = ":" + defaultPort
myNode.MyAddress = myNode.Ip + myNode.Port
myNode.Successors = [3]string{getLocalAddress() + myNode.Port}
myNode.Finger = make([]string, 161)
myNode.Next = 0
fmt.Printf("myNode Address: %v\n", myNode.MyAddress)
go func () {
for {
if myNode.Ring{
time.Sleep(time.Millisecond * 1333)
myNode.stabilize()
time.Sleep(time.Millisecond * 1333)
myNode.check_predecessor()
time.Sleep(time.Millisecond * 1333)
myNode.fix_fingers()
}
}
}()
go func(){
<-myNode.kill
os.Exit(0)
}()
mainCommands(myNode)
}
// Done by <NAME> & <NAME><file_sep>/commands.go
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
func mainCommands(myNode *Node) {
log.Printf("Chord is running")
log.Printf("Command options: help, ping, port, create, join, dump, quit")
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
line = strings.TrimSpace(line)
parts := strings.SplitN(line, " ", 3)
if len(parts) == 0 {
continue
}
var nothing *Nothing
switch parts[0] {
case "help":
fmt.Println("Commnad Options:")
fmt.Println("ping, port, create, join, dump, quit")
case "ping":
if len(parts) == 1 {
if err := call(myNode.MyAddress, "Node.Ping", myNode, ¬hing); err != nil {
log.Printf("server not reachable: %v", err)
} else {
log.Println("server responded!")
}
} else if len(parts) == 2 {
if err := call(myNode.Ip+":"+parts[1], "Node.Ping", myNode, ¬hing); err != nil {
log.Printf("server not reachable: %v", err)
} else {
log.Printf("server responded!")
}
}
case "port":
if len(parts) == 1 {
log.Printf("Current port: %v", myNode.Port)
} else if len(parts) == 2 {
if !myNode.Ring {
myNode.Port = ":" + parts[1]
myNode.MyAddress = myNode.Ip + myNode.Port
log.Printf("Port is now %v", myNode.MyAddress)
} else {
log.Printf("Error, this node is already part of the ring")
}
} else {
log.Println("Usage: port <number>")
}
case "create":
var Error error
if myNode.Ring == false {
server(myNode)
myNode.Ring = true
} else {
log.Printf("Ring already exists: %v\n", Error)
}
case "join":
if len(parts) < 2 || len(parts) > 2 {
log.Printf("join <address>")
continue
}
if myNode.Ring == false {
server(myNode)
if err := join(myNode, parts[1]); err == nil {
myNode.Ring = true
} else {
log.Printf("Invalid address: %v\n", err)
}
} else {
log.Println("This ring already exists.")
}
case "get":
if len(parts) == 2 {
pair := Pair{parts[1], ""}
call(myNode.find(parts[1]), "Node.Get", pair.Key, &pair.Value)
println("The value for " + pair.Key + " is " + pair.Value)
} else {
fmt.Println("Get did not work")
}
case "delete":
if len(parts) == 2 {
pair := Pair{parts[1], ""}
call(myNode.find(string(parts[1])), "Node.Delete", pair, &pair.Value)
fmt.Println("Successfully removed:", pair.Key, pair.Value)
}
case "put":
if len(parts) == 3 {
pair := Pair{parts[1], parts[2]}
call(myNode.find(parts[1]), "Node.Set", pair, &struct{}{})
fmt.Println("You put", pair.Key, " & ", pair.Value, "on the ring")
} else {
fmt.Printf("put is not working")
}
case "dump":
if len(parts) == 1{
var dumpNode Node
err := call(myNode.MyAddress, "Node.Dump", &struct{}{}, &dumpNode)
if err == nil{
fmt.Println("Address: ", dumpNode.MyAddress)
fmt.Println("Predecessor: ", dumpNode.Predecessor)
fmt.Println("Successors: ", dumpNode.Successors)
fmt.Println("Bucket: ", dumpNode.Bucket)
fmt.Println("Fingertable: ", dumpNode.Finger)
}
}
case "quit":
call(myNode.Successors[0], "Node.PutAll", myNode.Bucket, &struct{}{})
os.Exit(3)
default:
log.Printf("I don't recognize this command")
}
}
if err := scanner.Err(); err != nil {
fmt.Printf("Error in main command loop: %v", err)
}
}
<file_sep>/server.go
package main
import (
"fmt"
"log"
"net"
"net/http"
"net/rpc"
)
func server(myNode *Node) {
location := myNode.Port
rpc.Register(myNode)
rpc.HandleHTTP()
listener, err := net.Listen("tcp", location)
if err != nil {
log.Fatal("Error thrown while listening: ", err)
}
fmt.Printf("Listening %v\n", location)
go func() {
if err := http.Serve(listener, nil); err != nil {
log.Fatalf("Serving: %v", err)
}
}()
fmt.Println("Server is on")
}
func join(myNode *Node, location string) error {
var nothing Nothing
if err := call(location, "Node.Ping", nothing, ¬hing); err != nil {
log.Printf("Connection not working: %v\n", err)
return err
}
myNode.Successors[0] = location
call(myNode.Successors[0], "Node.GetAll", location, &struct{}{})
return nil
}
func call(address string, method string, request interface{}, reply interface{}) error {
client, err := rpc.DialHTTP("tcp", address)
if err != nil {
log.Printf("rpc.DialHTTP: %v", err)
return err
}
defer client.Close()
return client.Call(method, request, reply)
}
<file_sep>/helperFunctions.go
package main
import(
"log"
"math/big"
"net/rpc"
"fmt"
)
// Stabilize method exported
func (node *Node) stabilize() error{
var predecessor string
var successors []string
if err := call(node.Successors[0], "Node.GetSuccessors", struct{}{}, &successors); err != nil{
log.Printf("could not get successors %v", err)
}else{
node.Successors[1] = successors[0]
node.Successors[2] = successors[1]
}
if node.Successors[0] == ""{
fmt.Println("Ending node is now", node.MyAddress)
node.Successors[0] = node.MyAddress
}else{
node.Successors[0] = node.Successors[1]
node.Successors[1] = node.Successors[2]
node.Successors[2] = ""
}
pred := ""
call(node.Successors[0], "Node.GetPredecessor", struct{}{}, &pred)
if between(hashString(node.MyAddress),
hashString(pred),
hashString(node.Successors[0]),
false) && pred != ""{
node.Successors[0] = pred
}
if predecessor != node.MyAddress {
//You Only Notify Successor If Current Successor Predecessor Should be You Instead
if predecessor < node.MyAddress {
if err := call(node.Successors[0], "Node.Notify", node.MyAddress, &struct{}{}); err != nil {
log.Printf("notifing the successor failed: %v", err)
}
}else{
node.Successors[0] = predecessor
fmt.Println("the nodes successor is predecessor")
}
}
return nil
}
func (node *Node) check_predecessor() error{
if node.Predecessor != "" {
client, err := rpc.DialHTTP("tcp", node.Predecessor)
if err != nil{
fmt.Println("Predecessor has failed: ", node.Predecessor)
node.Predecessor = ""
}else{
client.Close()
}
}
return nil
}
func (node *Node) GetPredecessor(empty *struct{}, predecessor *string) error{
*predecessor = node.Predecessor
return nil
}
func (node *Node) GetSuccessors(empty *struct{}, successors *[]string)error{
*successors = node.Successors[:]
return nil
}
// ClosestPrecedingNode is exported
func (node *Node) closestPrecedingNode(id *big.Int) string{
for i := len(node.Finger) - 1; i > 0; i--{
if between(hashString(node.MyAddress), hashString(node.Finger[i]), id, false){
return node.Finger[i]
}
}
return node.Successors[0]
}
func (node *Node) find(key string) string{
foundNode := FoundNode{
Found: false,
Node: "",
}
max_steps := 30
foundNode.Node = node.Successors[0]
for !foundNode.Found{
if max_steps > 0 {
err := call(foundNode.Node, "Node.FindSuccessor", hashString(key), &foundNode)
if err == nil{
max_steps--
}else{
max_steps = 0
}
}else{
return ""
}
}
return foundNode.Node
}
func (node *Node) fix_fingers() error {
node.Next++
if node.Next > len(node.Finger)-1{
node.Next = 0
}
bigInt := jump(node.MyAddress, node.Next)
bigString := bigInt.String()
address := node.find(bigString) //
if node.Finger[node.Next] != address && address != ""{
node.Finger[node.Next] = address
}
for{
node.Next++
if node.Next > len(node.Finger)-1{
node.Next = 0
return nil
}
if between(hashString(node.MyAddress), jump(node.MyAddress, node.Next), hashString(address), false) && address != ""{
node.Finger[node.Next] = address
}else{
node.Next--
return nil
}
}
}
| 1e5c35194bfefd198b5394df2889c507afeb65a5 | [
"Go"
] | 6 | Go | ckgardner/Chord | 7745f2c5da6aeb2858edd4275b08bf88653162b5 | 85830fe70fe8e519b5d08296e8ec04f1fa5d4f89 |
refs/heads/master | <repo_name>jake90059/Sin-Cos-Tan-Calculator<file_sep>/boucher_austin_lab4.c
#include <math.h>
#include <stdio.h>
int k, y, z, b;//sets the ints
char* a;//sets the char
double o, l;//sets the doubles
double x = 3.14159;//sets the value of pie
int userpromt(void)//prompts the user
{
printf("Please choose an option: (0) Sine (1) Cosine (2) Tangent (3) QUIT\nEnter your choice > ");//prompts the users
scanf("%d", &y);//scans for input
if(y < 0)//sets boundries
{
printf("%d is an invalid option. Please try again.\n", y);//tells the user their input is wrong
userpromt();//reruns the prompt running into errors
}
if(y > 3)//sets boundries
{
printf("%d is an invalid option. Please try again.\n", y);//tells the uers their input is wrong
userpromt();//reruns the prompt running into errors
}
runprogram(y);//passes the input into further programs
}
int runprogram(p)//runs the program based on what is inputted
{
z = 0;//resets the loop limit
switch(p)//switches based on p values
{
case 0://runs the sin function if p is 0
{
b = 7;
a = "sin";
for(k = 0; k < b; k++)
{
l = (x * z / 180);
l = sin(l);
printf("\%s(%d) = %.4lf\n", a, z, l);
z = z + 15;
}
break;
}
case 1://runs the cosine function if p is 1
{
b = 7;
a = "cos";
for(k = 0; k < b; k++)
{
l = (x * z / 180);
l = cos(l);
printf("\%s(%d) = %.4lf\n", a, z, l);
z = z + 15;
}
break;
}
case 2://runs the tangent function if p is 2
{
b = 6;
a = "tan";
for(k = 0; k < b; k++)
{
l = (x * z / 180);
l = tan(l);
printf("\%s(%d) = %.4lf\n", a, z, l);
z = z + 15;
}
break;
}
case 3://ends the prompt if p is 3
{
printf("You chose QUIT. Thank you, come again!\n");
return(0);
}
}
if(b == 6)//runs a final loop if b is 0
{
printf("\%s(%d) is UNDEFINED\n", a, z);
}
userpromt();//runs an infinate loop until p is 3
}
int main(void)//runs the program
{
userpromt();//starts the program
}
| 741184a2da33172df6f9cc30467ad12911d715b6 | [
"C"
] | 1 | C | jake90059/Sin-Cos-Tan-Calculator | d124c3649f702a68ba17be677b5054db2a77d062 | f0e657e7d721d8c85c2bfa298c7a63a4342cdada |
refs/heads/master | <file_sep>#![warn(clippy::all)]
#![warn(clippy::pedantic)]
use nix::libc::{ioctl, TIOCGWINSZ};
use std::cmp::Ordering;
use std::fs::{File, OpenOptions};
use std::io::prelude::*;
use std::io::{self, Error, ErrorKind, LineWriter, Read, SeekFrom, Write};
use std::os::raw::c_short;
use std::os::unix::prelude::*;
use std::path::Path;
use std::time::{Duration, Instant};
use termios::{
Termios, BRKINT, CS8, ECHO, ICANON, ICRNL, IEXTEN, INPCK, ISIG, ISTRIP, IXON, OPOST, TCSAFLUSH,
VMIN, VTIME,
};
const TAB_SIZE: u8 = 4;
/// The cursor's position relative to the terminal
#[derive(Copy, Clone, Default)]
struct CursorPosition {
x: usize,
y: usize,
}
/// An enum representing a navigation key press
enum NavigationKey {
Left,
Right,
Up,
Down,
Home,
End,
PageUp,
PageDown,
}
enum Action {
Quit,
Escape,
Save,
Delete,
Enter,
Cancel,
Find,
Input(char),
}
impl From<u8> for Action {
fn from(c: u8) -> Self {
if c == ctrl_key('q') {
Action::Quit
} else if c == ctrl_key('s') {
Action::Save
} else if c == ctrl_key('c') {
Action::Cancel
} else if c == ctrl_key('f') {
Action::Find
} else if c == b'\x1b' {
Action::Escape
} else if c == 27 || c == 127 {
Action::Delete
} else if c == b'\r' {
Action::Enter
} else {
Action::Input(c as char)
}
}
}
/// Various commands we might issue to the terminal
enum CtrlSeq {
/// Clears the entire line
ClearLine,
/// Clears the entire screen, appropriate before either drawing or quitting rilo
ClearScreen,
/// A shortcut to go the start of the terminal (0, 0)
GotoStart,
/// Hides the cursor, useful to prevent flashing
HideCursor,
/// Displays the cursor after we hide it
ShowCursor,
/// Moves the cursor to a position in the terminal
MoveCursor(CursorPosition),
InverteColor,
NormalColor,
}
impl From<CtrlSeq> for Vec<u8> {
fn from(ctrl: CtrlSeq) -> Self {
match ctrl {
CtrlSeq::ClearLine => b"\x1b[K".to_vec(),
CtrlSeq::ClearScreen => b"\x1b[2J".to_vec(),
CtrlSeq::GotoStart => b"\x1b[H".to_vec(),
CtrlSeq::HideCursor => b"\x1b[?25l".to_vec(),
CtrlSeq::ShowCursor => b"\x1b[?25h".to_vec(),
CtrlSeq::MoveCursor(cp) => format!("\x1b[{};{}H", cp.y + 1, cp.x + 1)
.as_bytes()
.to_vec(),
CtrlSeq::InverteColor => b"\x1b[7m".to_vec(),
CtrlSeq::NormalColor => b"\x1b[m".to_vec(),
}
}
}
/// A helper function to write data into stdout
fn stdout_write(buff: impl AsRef<[u8]>) {
io::stdout().lock().write_all(buff.as_ref()).unwrap();
io::stdout().lock().flush().unwrap();
}
struct RawMode {
inner: Termios,
}
impl RawMode {
pub fn enable_raw_mode() -> Self {
let fd = io::stdin().as_raw_fd();
let mut term = Termios::from_fd(fd).unwrap();
let raw_mode = Self { inner: term };
term.c_iflag &= !(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
term.c_oflag &= !(OPOST);
term.c_cflag |= CS8;
term.c_lflag &= !(ECHO | ICANON | IEXTEN | ISIG);
term.c_cc[VMIN] = 0;
term.c_cc[VTIME] = 1;
termios::tcsetattr(fd, TCSAFLUSH, &term).unwrap();
raw_mode
}
}
impl Drop for RawMode {
fn drop(&mut self) {
termios::tcsetattr(io::stdin().as_raw_fd(), TCSAFLUSH, &self.inner).unwrap();
}
}
#[derive(Default)]
#[repr(C)]
struct WindowSize {
ws_row: c_short,
ws_col: c_short,
ws_xpixel: c_short,
ws_ypxiel: c_short,
}
struct SystemMessage {
message: Option<String>,
time: Instant,
}
impl Default for SystemMessage {
fn default() -> Self {
SystemMessage {
message: None,
time: Instant::now(),
}
}
}
impl SystemMessage {
fn new(message: &str) -> Self {
SystemMessage {
message: Some(message.to_string()),
time: Instant::now(),
}
}
}
type Row = String;
struct Editor {
_mode: RawMode,
term_rows: usize,
term_cols: usize,
cur_pos: CursorPosition,
row_offset: usize,
col_offset: usize,
tab_size: u8,
file: Option<File>,
rows: Vec<Row>,
message: SystemMessage,
dirty_flag: bool,
path: Option<String>,
}
impl Editor {
fn new() -> Self {
let mode = RawMode::enable_raw_mode();
let (rows, cols) = get_window_size().expect("Couldn't get window size from terminal.");
Editor {
_mode: mode,
term_rows: (rows - 2) as usize, // -2 to leave a row for the status bar
term_cols: (cols - 1) as usize,
cur_pos: CursorPosition::default(),
row_offset: 0,
col_offset: 0,
tab_size: TAB_SIZE,
file: Option::default(),
rows: Vec::default(),
message: SystemMessage::new("HELP: Ctrl-S = save | Ctrl-Q = quit | Ctrl-F = find"),
dirty_flag: false,
path: None,
}
}
/// Handles both the internal state held in the Editor, and moves the cursor on the terminal
fn move_cursor(&mut self, ak: &NavigationKey) {
match ak {
NavigationKey::Left => {
if self.cur_pos.x != 0 {
self.cur_pos.x -= 1;
} else if self.cur_pos.x == 0 && self.col_offset != 0 {
self.col_offset -= 1;
} else if self.cur_pos.x == 0 && self.col_offset == 0 {
if self.cur_pos.y == 0 && self.row_offset != 0 {
self.row_offset -= 1;
} else if !(self.cur_pos.y == 0 && self.row_offset == 0) {
self.cur_pos.y -= 1;
}
if !(self.row_offset == 0 && self.cur_pos.y == 0) {
if let Some(current_line) = self.current_line() {
let line_length = current_line.len().saturating_sub(1);
if line_length > self.term_cols {
self.col_offset = line_length - self.term_cols;
self.cur_pos.x = self.term_cols;
} else {
self.col_offset = 0;
self.cur_pos.x = line_length;
}
}
}
}
}
NavigationKey::Right => {
if let Some(current_line) = self.current_line() {
let line_length = current_line.len();
if self.cur_pos.x == line_length
|| self.cur_pos.x + self.col_offset == line_length
{
if self.cur_pos.y + self.row_offset != self.rows.len() {
self.cur_pos.x = 0;
self.col_offset = 0;
if self.cur_pos.y == self.term_rows {
self.row_offset += 1
} else {
self.cur_pos.y += 1;
}
}
} else if self.cur_pos.x != self.term_cols {
self.cur_pos.x += 1;
} else if self.cur_pos.x == self.term_cols {
self.col_offset += 1;
}
}
}
NavigationKey::Up => {
if self.cur_pos.y != 0 {
self.cur_pos.y -= 1;
} else if self.cur_pos.y == 0 && self.row_offset != 0 {
self.row_offset -= 1;
}
if let Some(next_line) = self.current_line() {
if self.cur_pos.x > next_line.len() {
self.cur_pos.x = next_line.len();
}
}
}
NavigationKey::Down => {
let file_length = self.rows.len() - 1;
if self.row_offset + self.cur_pos.y != file_length {
if self.cur_pos.y != self.term_rows {
self.cur_pos.y += 1;
} else if self.cur_pos.y == self.term_rows
&& self.row_offset + self.term_rows != self.rows.len()
{
self.row_offset += 1;
}
if let Some(next_line) = self.current_line() {
if self.cur_pos.x > next_line.len() {
self.cur_pos.x = next_line.len().saturating_sub(1);
}
}
}
}
NavigationKey::Home => {
self.cur_pos.x = 0;
self.col_offset = 0;
}
NavigationKey::End => {
let current_line_len = self.current_line().unwrap().len();
self.cur_pos.x = match self.term_cols.cmp(¤t_line_len) {
Ordering::Greater | Ordering::Equal => current_line_len,
Ordering::Less => {
self.col_offset = current_line_len - self.term_cols;
self.term_cols
}
};
}
NavigationKey::PageUp => {
self.cur_pos.y = 0;
if let Some(next_line) = self.current_line() {
if self.cur_pos.x > next_line.len() {
self.cur_pos.x = next_line.len();
}
}
}
NavigationKey::PageDown => {
self.cur_pos.y = self.term_rows;
if let Some(next_line) = self.current_line() {
if self.cur_pos.x > next_line.len() {
self.cur_pos.x = next_line.len();
}
}
}
};
send_esc_seq(CtrlSeq::MoveCursor(CursorPosition {
x: self.rx(),
y: self.cur_pos.y,
}));
}
/// Open a file to edit/read
fn open(&mut self, filename: impl AsRef<Path> + Clone) -> io::Result<()> {
if filename.as_ref().is_file() {
self.file = OpenOptions::new()
.read(true)
.write(true)
.open(&filename)
.ok();
self.path = Some(String::from(filename.as_ref().to_str().unwrap()));
self.rows = io::BufReader::new(self.file.as_ref().unwrap())
.lines()
.map(std::result::Result::unwrap)
.collect();
}
Ok(())
}
fn save(&mut self) -> io::Result<()> {
// TODO: Move all system message handeling from main loop to this function
if let Some(f) = &mut self.file {
f.seek(SeekFrom::Start(0))?;
f.set_len(0)?;
let mut writer = LineWriter::new(f);
self.rows.iter().for_each(|row| {
writer.write_all(format!("{}\n", row).as_bytes()).unwrap();
});
writer.flush()?;
self.dirty_flag = false;
} else if let Ok(new_file) = self.prompt("Save to: ") {
let new = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&new_file)
.ok();
self.file = new;
self.save()?;
} else {
// Return error on display it
}
Ok(())
}
fn find(&mut self) -> io::Result<CursorPosition> {
let mut positions: Vec<(usize, usize)> = Vec::new();
if let Ok(search_term) = self.prompt("Find:") {
for (y, row) in self.rows.iter().enumerate() {
if let Some(x) = row.find(&search_term) {
positions.push((x, y));
}
}
if positions.is_empty() {
return Err(Error::new(
ErrorKind::NotFound,
format!("Find: Couldn't find {}", search_term),
));
} else {
return Ok(CursorPosition {
x: positions[0].0,
y: positions[0].1,
});
}
} else {
return Err(Error::new(
ErrorKind::Other,
"Find: no search term was found",
));
}
}
/// Draws out the current state held in the editor to the terminal
fn draw(&mut self) {
// We use a Vec we can push all the data on screen into, and then write it in one go into stdout
let mut append_buffer: Vec<u8> = Vec::new();
append_buffer.append(&mut CtrlSeq::ClearLine.into());
for idx in self.row_offset..=self.term_rows + self.row_offset {
if idx < self.rows.len() {
let line = &self.rows[idx];
// If the line is long enough to see anything because of horizontal scrolling
if line.len() > self.col_offset {
let range = if line.len() > self.col_offset + self.term_cols {
self.col_offset..self.col_offset + self.term_cols
} else {
self.col_offset..line.len()
};
let ranged_line = line[range].to_string();
append_buffer.extend(render_row(&ranged_line, self.tab_size));
}
} else {
append_buffer.push(b'~');
}
append_buffer.push(b'\r');
append_buffer.push(b'\n');
append_buffer.append(&mut CtrlSeq::ClearLine.into());
}
append_buffer.extend(self.render_status_bar());
send_esc_seq(CtrlSeq::HideCursor);
send_esc_seq(CtrlSeq::GotoStart);
stdout_write(append_buffer);
// self.rx = if let Some(curr_line) = self.current_line() {
// cx_to_rx(curr_line, self.cur_pos.x)
// } else {
// 0
// };
send_esc_seq(CtrlSeq::MoveCursor(CursorPosition {
x: self.rx(),
y: self.cur_pos.y,
}));
send_esc_seq(CtrlSeq::ShowCursor);
}
fn current_line(&self) -> Option<&Row> {
let current_line_idx = self.row_offset + self.cur_pos.y;
self.rows.get(current_line_idx)
}
fn rx(&self) -> usize {
self.current_line().map_or(0, |line| {
line[0..self.cur_pos.x]
.chars()
.fold(0, |acc, c| match c.cmp(&'\t') {
Ordering::Equal => acc + 4,
_ => acc + 1,
})
})
}
fn render_status_bar(&self) -> Vec<u8> {
//TODO: Make the status bar nicer
let mut v = Vec::new();
v.append(&mut CtrlSeq::InverteColor.into());
match self.file {
None => v.extend(
format!(
"[No open file] {}",
self.message.message.as_ref().unwrap_or(&String::from(""))
)
.into_bytes(),
),
Some(_) => {
let open_file = format!(
"[Open: {}] ",
self.path.as_ref().unwrap_or(&String::from(""))
);
v.extend(open_file.as_bytes());
let current_line_idx = self.cur_pos.y + self.row_offset;
let percentages = ((current_line_idx + 1) * 100)
.checked_div(self.rows.len())
.unwrap_or(0);
let lines = format!("{}/{}", current_line_idx + 1, self.rows.len());
v.extend(lines.as_bytes());
let formatted = format!(" {}%", percentages);
v.extend(formatted.as_bytes());
if let Some(message) = &self.message.message {
if self.message.time.elapsed() < Duration::from_secs(5) {
let display_message = format!(" {}", message);
v.extend(display_message.as_bytes());
}
}
}
}
v.extend(vec![b' '; self.term_cols.saturating_sub(v.len())]);
// TODO: This is not good :(
let mut v = v[0..self.term_cols].to_vec();
v.append(&mut CtrlSeq::NormalColor.into());
v
}
fn prompt(&mut self, prompt_prefix: &str) -> io::Result<String> {
let mut input = String::new();
let mut buff = [0; 1];
loop {
self.message = SystemMessage::new(&format!("{} {}", prompt_prefix, input));
self.draw();
if io::stdin().read(&mut buff)? != 0 {
match buff[0].into() {
Action::Cancel => {
return Err(Error::new(
ErrorKind::Other,
"prompt: action cancelled".to_string(),
));
}
Action::Input(c) => input.push(c),
Action::Enter => return Ok(input),
Action::Delete => {
input.pop();
}
_ => {}
};
}
}
}
fn insert_newline(&mut self) {
self.dirty_flag = true;
let x = self.cur_pos.x + self.col_offset;
let y = self.cur_pos.y + self.row_offset;
let curr_line = self.current_line().unwrap().to_owned();
self.rows.insert(y, String::new());
self.rows[y] = curr_line[0..x].to_string();
self.rows[y + 1] = curr_line[x..].to_string();
self.cur_pos.x = 0;
self.col_offset = 0;
self.cur_pos.y += 1;
self.col_offset = 0;
}
fn insert_char(&mut self, c: char) {
self.dirty_flag = true;
let x = self.cur_pos.x + self.col_offset;
let y = self.cur_pos.y + self.row_offset;
// If we are on the last row in the file
if y == self.rows.len() {
let mut row = String::new();
row.push(c);
self.rows.push(row);
} else {
let row = self.rows[y].clone();
let new_row = [&row[0..x], c.to_string().as_str(), &row[x..]].concat();
self.rows[y] = new_row;
}
self.move_cursor(&NavigationKey::Right);
}
fn remove_char(&mut self) {
self.dirty_flag = true;
let x = self.cur_pos.x + self.col_offset;
let y = self.cur_pos.y + self.row_offset;
// Remove row and move one up
if x == 0 {
if let Some(line) = &mut self.current_line() {
self.rows[y - 1] = [self.rows[y - 1].clone(), (**line).to_string()].concat();
self.rows.remove(y);
}
} else {
let row = self.rows[y].clone();
if x != 0 {
self.rows[y] = [&row[0..x - 1], &row[x..]].concat();
};
}
self.move_cursor(&NavigationKey::Left);
}
fn jump(&mut self, cp: CursorPosition) {
if cp.y > self.term_cols {
self.row_offset = cp.y;
self.cur_pos.y = 0;
} else {
self.cur_pos.y = cp.y
}
self.cur_pos.x = cp.x;
}
}
fn main() -> io::Result<()> {
let mut e = Editor::new();
// Clear the screen
send_esc_seq(CtrlSeq::HideCursor);
send_esc_seq(CtrlSeq::ClearScreen);
send_esc_seq(CtrlSeq::ShowCursor);
let args: Vec<String> = std::env::args().collect();
// TODO: Change to clap or another library that handles command line arguments
if let Some(filename) = args.get(1) {
e.open(filename)?
}
e.draw();
let mut buff = [0; 1];
loop {
if io::stdin().read(&mut buff)? != 0 {
match buff[0].into() {
Action::Quit => {
send_esc_seq(CtrlSeq::ClearScreen);
send_esc_seq(CtrlSeq::GotoStart);
break;
}
Action::Escape => {
if let Ok(ak) = handle_escape_seq() {
e.move_cursor(&ak);
}
}
Action::Save => {
if e.dirty_flag {
e.message = SystemMessage::new(match e.save() {
Ok(_) => "File saved successfully!",
Err(_) => "Error saving file!",
})
} else {
e.message = SystemMessage::new("No Changes Made!");
e.dirty_flag = false;
}
}
Action::Find => {
match e.find() {
Ok(cp) => e.jump(cp),
Err(err) => e.message = SystemMessage::new(&err.to_string()),
};
}
Action::Delete => {
e.remove_char();
}
Action::Enter => e.insert_newline(),
Action::Input(c) => {
if !c.is_ascii_control() {
e.insert_char(c)
}
}
Action::Cancel => {}
}
e.draw();
}
}
Ok(())
}
fn handle_escape_seq() -> io::Result<NavigationKey> {
let mut buffer = [0; 3];
// We need to use read() because some esc sequences are 3 bytes and some are 2
io::stdin().lock().read(&mut buffer)?;
if buffer[0] == b'[' {
let movement = match buffer[1] {
b'A' => NavigationKey::Up,
b'B' => NavigationKey::Down,
b'C' => NavigationKey::Right,
b'D' => NavigationKey::Left,
b'H' => NavigationKey::Home,
b'F' => NavigationKey::End,
b'5' => NavigationKey::PageUp,
b'6' => NavigationKey::PageDown,
_ => return Err(Error::from(ErrorKind::InvalidData)),
};
Ok(movement)
} else {
Err(Error::from(ErrorKind::InvalidData))
}
}
fn render_row(row: &str, tab_size: u8) -> Vec<u8> {
row.chars()
.flat_map(|c| match c.cmp(&'\t') {
Ordering::Equal => vec![b' '; tab_size.into()],
_ => vec![c as u8],
})
.collect()
}
/// Send an escape sequence to the actual terminal
fn send_esc_seq(ctrl: CtrlSeq) {
stdout_write(Vec::from(ctrl));
}
fn ctrl_key(c: char) -> u8 {
c as u8 & 0x1f
}
/// Gets terminal size as (X, Y) tuple. **Note:** libc returns a value in the [1..N] range, so we do the same
fn get_window_size() -> io::Result<(i16, i16)> {
let fd = io::stdin().as_raw_fd();
let mut winsize = WindowSize::default();
let return_code = unsafe { ioctl(fd, TIOCGWINSZ, &mut winsize as *mut _) };
if (return_code == -1) || (winsize.ws_col == 0) {
Err(Error::new(
ErrorKind::Other,
"get_window_size: ioctl failed or returned invalid value",
))
} else {
Ok((winsize.ws_row, winsize.ws_col))
}
}
<file_sep># rilo
writing [kilo](http://antirez.com/news/108) in rust, loosely following [this](https://viewsourcecode.org/snaptoken/kilo/index.html) tutorial.
---
**WARNING:** rilo may make your terminal behave kina wierd and corrupt your files, as it is only tested on Ubuntu and a pretty standard configuration
### TODOs:
- The whole main loop is getting a bit too noisy, there is probably a better way to do it (maybe a "run" function?, maybe split it into some input_loop with a callback)
- Do I want a better way to handle incoming input? some struct over stdin.
<file_sep>#!/usr/bin/env bash
cargo clean 2> /dev/null && cargo build --release 2> /dev/null
if [ $? -eq 0 ]; then
chmod u+x target/release/rilo && echo "Release is successful!";
else
return 1;
fi
| 7c460e5b3a52b3fa2751eba0cedf584326b89f9d | [
"Markdown",
"Rust",
"Shell"
] | 3 | Rust | AdamGS/rilo | 1fc4c823bb5d35d1d5afa10c37be240b0a8e9df7 | f218b9d9e800956562671a3081d23777d611e7b4 |
refs/heads/master | <repo_name>XuHg-zjcn/Spectrum-Transform<file_sep>/good_image_copy.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright 2018 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import shutil
import os
f = open('out.txt')
fl = f.readline()
fl = f.readline()
while len(fl) != 0:
a=fl.split()
if len(a) == 4 and a[3] == 'pass':
num=int(a[0][4:])
print(num)
vis_name = 'FLIR%04d.jpg'%num
ir_name = 'FLIR%04d.png'%num
vis_add = './hres_vis/{}'.format(vis_name)
ir_add = './hres_tir/{}'.format(ir_name)
os.mkdir('./good_imgs')
os.mkdir('./good_imgs/good_vis')
os.mkdir('./good_imgs/good_tir')
shutil.copy(vis_add, './good_imgs/good_vis/')
shutil.copy(ir_add, './good_imgs/good_tir/')
fl = f.readline()
<file_sep>/readimg_hres.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright 2018 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import imageio
import png
import numpy as np
from PIL import Image
root="./hres_img"
n=0
nlst=[]
for i in os.listdir(root):
raw_add = os.path.join(root,i)
ImSize=Image.open(raw_add).size
if ImSize == (320,240):
im2 = True
elif ImSize == (640,480):
im2 = False
else:
raise ValueError
print(raw_add, im2)
if i[-4:]=='.jpg' and i[:4]=='FLIR' and im2:
n+=1
os.system("exiftool -b -RawThermalImage %s > ./temp/tir.png"%raw_add)
im=imageio.imread('./temp/tir.png')
im=im*256+(im//256.0).astype(int)
png.from_array(im, 'L;16').save('./hres_tir/%s.png'%(i[:-4]))
os.system("exiftool -b -EmbeddedImage %s > ./hres_vis/%s.jpg"%(raw_add,i[:-4]))
nlst.append(int(i[4:-4]))
print(nlst)
np.save('nlst.npy',nlst)
print('{} images'.format(n))
<file_sep>/history and future.md
# Visible image to Thermal infrared
some years ago I broght a FLIR E4 Camera, a Visible camera 640x480 inside, I hacked thermal resolution from 80x60 to 320x240
I hope eveyone can to enjoy the Thermal image, but is expensive, over 6000 RMB, seldom person can buy it
I try transfrom normal phone camera image to thermal image
but can't get temperature from transformed image, I will using some sensor
## sensor outside
* Temperature and humidity sensor (DHT11,...)
* low resolution thermal image sensor (low cost)
* MLX90614 16x4 ~100RMB
* AMG8833 8x8 ~200RMB
* MLX90640 32x24 ~400RMB
<file_sep>/README.md
# Spectrum-Transform
GAN image band transform like visible image to thermal infrared image.
sorry, the model is bad, you don't to train it, I test on Google Colab, is not get expected result.
I don't have time to improve it now.
使用GAN转换图像的频谱,如可见光转热红外
对不起,这个模型差,你不要训练它, 我在谷歌Colab上测试过了,没有达到预期的结果
我现在没有时间去改进它
<file_sep>/as_tfrecord.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright 2018 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import tensorflow as tf
import os
from PIL import Image
import numpy as np
def _bytes_feature(value):
return tf.train.Feature(bytes_list = tf.train.BytesList(value = [value]))
f = open('outr.txt')
ir_base="../../TT/hres_tir"
vis_base="../../TT/hres_vis"
writer = tf.python_io.TFRecordWriter('./TFRecords2/')
Np=0
Nnp=0
Nerr=0
for i in f:
i=i[:-1]
i=i.split()
li=len(i)
if li == 4:
Np += 1
yshiftNpix=eval(i[1])
xshiftNpix=eval(i[2])
'''img=tf.gfile.FastGFile(Visimg_dir+i[0]+'.jpg')
img=tf.image.decode_jpeg(img)
img=tf.image.convert_image_dtype(img,dtype=tf.float32)
img=tf.image.resize_bicubic(img, (320,427))
img=tf.image.crop_and_resize(img,)'''
vis_name = os.path.join(vis_base, str(i[0])+'.jpg')
ir_name = os.path.join(ir_base, str(i[0])+'.png')
vis_img = Image.open(vis_name)
vis_img = vis_img.resize((427,320), Image.ANTIALIAS)
vis_img = np.array(vis_img)#.astype(np.float32)
vis_img = vis_img[40+yshiftNpix:
40+yshiftNpix+240,
53+xshiftNpix:
53+xshiftNpix+320]
#print(vis_img.shape)
vis_img = vis_img.tobytes()
ir_img = np.array(Image.open(ir_name)).astype(np.uint16)
#print(ir_img.shape)
ir_img = ir_img.tobytes()
example=tf.train.Example(features=tf.train.Features(feature={
'Vis_image':_bytes_feature(vis_img),
'IR_image':_bytes_feature(ir_img)}))
writer.write(example.SerializeToString())
elif li == 5:
Nnp += 1
else:
Nerr += 1
print(i)
writer.close()
print(Np, Nnp, Nerr)
<file_sep>/blocks.py
#@title
%%writefile blocks.py
"""
Copyright 2018 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import copy
import tensorflow as tf
import mobilenet_v2
slim = tf.contrib.slim
import conv_blocks as ops
#from tensorflow.python.framework import ops
#from tensorflow.python.ops import nn_ops
#from tensorflow.python.ops import array_ops
#D_V2_DEF = copy.deepcopy(mobilenet_v2.V2_DEF)
#D_V2_DEF['defaults'][(ops.expanded_conv,)].pop('normalizer_fn')
'''@ops.RegisterGradient("DepthwiseConv2dNativeBackpropInput")
def _DepthwiseConv2DNativeBackpropInputGrad(op, grad):
"""The derivatives for depth-wise deconvolution.
Args:
op: the depth-wise deconvolution op.
grad: the tensor representing the gradient w.r.t. the output
Returns:
the gradients w.r.t. the input and the filter
"""
return [None,
nn_ops.depthwise_conv2d_native_backprop_filter(
grad,
array_ops.shape(op.inputs[1]),
op.inputs[2],
op.get_attr("strides"),
op.get_attr("padding"),
data_format=op.get_attr("data_format")),
nn_ops.depthwise_conv2d_native(
grad,
op.inputs[1],
op.get_attr("strides"),
op.get_attr("padding"),
data_format=op.get_attr("data_format"))]'''
class layer_num(object):
def __init__(self):
self.__num = 0
@property
def get(self):
self.__num += 1
return self.__num
def clear(self):
self.__num = 0
is_training = False#tf.placeholder(shape=(), dtype=tf.bool)
def layer1x1(input_tensor, num_outputs,
activation_fn=tf.nn.leaky_relu, normalizer_fn=slim.batch_norm):
global is_training
with tf.variable_scope('1x1'):
net = slim.dropout(input_tensor, 0.5, \
scope='Dropout', is_training=True)
net = slim.conv2d(
net, num_outputs, [1, 1], stride=1, padding='VALID',
activation_fn=activation_fn,
normalizer_fn=normalizer_fn,
biases_initializer=tf.zeros_initializer(),
scope='Conv2d_1c_1x1')
return net
#blocks
from_mbnet2s = []
from_mbnet2s_dropout = []
keep_probs = [0.3,0.2,0.1,0.05,0.03,0.02,0.02]
def up_block(input_tensor, from_mbnet2, num_outputs, counter,
stride=None, lmul=None, fmul=None, **kwargs):
global is_training
if lmul is None:
lmul = 1
if fmul is None:
fmul = 1
if stride is None:
stride = 2
num_input = input_tensor.get_shape().as_list()[3]
num_from = from_mbnet2.get_shape().as_list()[3]
with tf.variable_scope('up_block_%d'%counter.get):
net = tf.identity(input_tensor, name='input')
from_mbnet2 = tf.identity(from_mbnet2, name='from_mbnet2')
l=len(from_mbnet2s)
from_mbnet2s.append(from_mbnet2)
#from_mbnet2 = slim.dropout(from_mbnet2, keep_probs[l],
# scope='Dropout',is_training=is_training)
from_mbnet2s_dropout.append(from_mbnet2)
if lmul != 0:
net = convt1x1(net, num_input*lmul, scope='expand')
#tf.identity(net, name='expand_out')
net = convt3x3(net, num_input*lmul, stride, scope='3x3', **kwargs)
#tf.identity(net, name='3x3_out')
if fmul != 0:
pre = convt1x1(from_mbnet2, num_from*fmul, scope='preprocess')
#tf.identity(net, name='preprocess_out')
if net.shape[1] == 8 and pre.shape[1] == 7:
net = net[:,:7,:7,:]
net = tf.concat([net, pre], 3)
net = convt1x1(net, num_outputs, scope='down', activation_fn=None)
net = tf.identity(net, name='output')
return net
def norm_block(input_tensor, num_outputs, counter,
mul=None, connect=None):
if mul is None:
mul = 6
if connect is None:
connect = True
num_input = input_tensor.get_shape().as_list()[3]
with tf.variable_scope('norm_block_%d'%counter.get):
net = tf.identity(input_tensor, name='input')
net = convt1x1(net, num_input*mul, scope='expand')
#net = tf.identity(net, name='expand_out')
net = convsep3(net, None, scope='3x3')
#net = tf.identity(net, name='3x3_out')
net = convt1x1(net, num_outputs, scope='down', activation_fn=None)
if num_input == num_outputs and connect: #check add
#net = tf.identity(net, name='down_out')
net += input_tensor
net = tf.identity(net, name='output')
return net
def only_up(input_tensor, num_outputs, counter):
#global numer
#num_input = input_tensor.get_shape().as_list()[3]
with tf.variable_scope('up_without_from_%d'%counter.get):
net = tf.identity(input_tensor, name='input')
net = convt1x1(net, num_outputs, scope='expand')
#net = tf.identity(input_tensor, name='expand_out')
net = convsep3(net, None, scope='3x3')
net = tf.identity(net, name='output')
return net
def convt1x1(input_tensor, num_outputs, **kwargs):
return slim.conv2d(input_tensor, num_outputs, [1,1],
stride=1, **kwargs)
def convt3x3(input_tensor, num_outputs, stride, scope='3x3', **kwargs):
global channal_num
with tf.variable_scope(scope):
input_tensor = tf.identity(input_tensor)
return slim.conv2d_transpose(input_tensor, num_outputs, [3,3],
stride=stride, **kwargs)
def convsep3(input_tensor, num_outputs, **kwargs):
global channal_num
return slim.separable_conv2d(input_tensor, num_outputs, [3,3],
depth_multiplier=1, stride=1, **kwargs)
G_tran=[]
def gen_transpose(input_tensor, mbnet2, Vis_RGB):
counter = layer_num()
with tf.variable_scope('transpose'):
with slim.arg_scope([slim.conv2d, \
slim.conv2d_transpose, \
slim.separable_conv2d], \
padding='SAME', \
activation_fn=tf.nn.leaky_relu, \
normalizer_fn=slim.batch_norm, \
trainable=True):
net =tf.identity(input_tensor, name='intput')
G_tran.append(net)#1
net = slim.conv2d_transpose(net, 160, [4,4], stride=1, padding='VALID')
net = up_block(net, mbnet2['layer_20'], 160, counter,
stride=1, fmul=1, lmul=0)
net = norm_block(net, 160, counter)
net = norm_block(net, 160, counter)
G_tran.append(net)
net = up_block(net, mbnet2['layer_17'], 80, counter,
stride=2, fmul=2, lmul=2, padding='SAME') # 17
net = norm_block(net, 80, counter) # 16
net = norm_block(net, 80, counter) # 15
G_tran.append(net)
net = up_block(net, mbnet2['layer_14'], 48, counter,
stride=2, fmul=2, lmul=2) # 14
net = norm_block(net, 48, counter) # 13
net = norm_block(net, 48, counter) # 12
G_tran.append(net)
net = up_block(net, mbnet2['layer_11'], 32, counter,
stride=1, fmul=2, lmul=2) # 11
net = norm_block(net, 32, counter) # 10
net = norm_block(net, 32, counter) # 9
net = norm_block(net, 32, counter) # 8
G_tran.append(net)
net = up_block(net, mbnet2['layer_7'], 16, counter,
stride=2, fmul=3, lmul=3) # 7
net = norm_block(net, 16, counter) # 6
net = norm_block(net, 16, counter) # 5
G_tran.append(net)
net = up_block(net, mbnet2['layer_4'], 16, counter,
stride=2, fmul=3, lmul=3) # 4
net = norm_block(net, 16, counter) # 3
G_tran.append(net)
net = up_block(net, mbnet2['layer_2'], 16, counter,
stride=2, fmul=3, lmul=3) # 2
G_tran.append(net)
net = norm_block(net, 16, counter) # 1
net = norm_block(net, 16, counter)
G_tran.append(net)
net = up_block(net, Vis_RGB, 16, counter,
stride=2, fmul=3, lmul=3)
G_tran.append(net)
net = norm_block(net, 8, counter, connect = False)
G_tran.append(net)
net = norm_block(net, 8, counter)
with slim.arg_scope([slim.conv2d, \
slim.conv2d_transpose, \
slim.separable_conv2d], \
padding='SAME', \
activation_fn=tf.nn.leaky_relu, \
normalizer_fn=None, \
trainable=True):
net = norm_block(net, 1, counter)
G_tran.append(net)
net = tf.identity(net, name='output')
return net
def den_block(input_tensor, num_output, counter, stride=1, mul=6, exp=None):
num_input = input_tensor.get_shape().as_list()[3]
with tf.variable_scope('den_block%i'%counter.get):
input_tensor = tf.identity(input_tensor, name='input')
if exp == False:
net = slim.conv2d(input_tensor, num_input*mul, [1,1], \
stride=1, scope='expand')
net = tf.identity(net, name='expand_out')
else:
net = input_tensor
net = slim.conv2d(net, num_input*mul, [3,3],
stride=1, scope='3x3')
#net = slim.separable_conv2d(net, num_input*mul, [3,3],
# depth_multiplier=1, stride=1, scope='3x3')
net = tf.identity(net, name='3x3_out')
net = slim.conv2d(net, num_output, [1,1], stride=stride, scope='down')
if num_input == num_output and stride==1:
net = tf.identity(net, name='down_out')
net += input_tensor
net = tf.identity(net, name='output')
return net
def den_net(input_tensor):
counter = layer_num()
endpoints = []
with tf.variable_scope('den_net'):
with slim.arg_scope([slim.conv2d, slim.separable_conv2d],
padding='SAME',
activation_fn=tf.nn.leaky_relu,
normalizer_fn=slim.layer_norm,
trainable=True):
net = tf.identity(input_tensor, name='input')
endpoints.append(net)#224
net=slim.conv2d(net, 16, [3, 3], stride=2)
net = den_block(net, 8, counter, stride=1, mul=1, exp=False)
endpoints.append(net)#112
net = den_block(net, 16, counter, stride=2, mul=6)
net = den_block(net, 16, counter, stride=1, mul=6)
endpoints.append(net)#56
net = den_block(net, 16, counter, stride=2, mul=6)
net = den_block(net, 16, counter, stride=1, mul=6)
net = den_block(net, 16, counter, stride=1, mul=6)
endpoints.append(net)#28
net = den_block(net, 32, counter, stride=2, mul=6)
net = den_block(net, 32, counter, stride=1, mul=6)
net = den_block(net, 32, counter, stride=1, mul=6)
net = den_block(net, 32, counter, stride=1, mul=6)
endpoints.append(net)#14
net = den_block(net, 48, counter, stride=1, mul=6)
net = den_block(net, 48, counter, stride=1, mul=6)
net = den_block(net, 48, counter, stride=1, mul=6)
endpoints.append(net)#14
net = den_block(net, 80, counter, stride=2, mul=6)
net = den_block(net, 80, counter, stride=1, mul=6)
net = den_block(net, 80, counter, stride=1, mul=6)
endpoints.append(net)#7
net = den_block(net,160, counter, stride=2, mul=6)
net = den_block(net,160, counter, stride=1, mul=6)
net = den_block(net,160, counter, stride=1, mul=6)
endpoints.append(net)#4
net = slim.conv2d(net, 640, [4,4], stride=1, padding='VALID')
endpoints.append(net)
net = tf.identity(input_tensor, name='ontput')
return net, endpoints
net224=[]
def den_outd(net, i):
global net224
counterN = layer_num()
dchs = net.get_shape().as_list()[3]
Nwide = net.get_shape().as_list()[1]
with tf.variable_scope('in_%d'%i, reuse=tf.AUTO_REUSE):
if Nwide >= 4:
if Nwide == 224:
print(224)
with slim.arg_scope([slim.conv2d, slim.separable_conv2d],
padding='SAME',
activation_fn=tf.nn.leaky_relu,
normalizer_fn=None,
trainable=True):
net = den_block(net, dchs*2, counterN, stride=1, mul=6)
net224.append(net)
else:
net = den_block(net, dchs*2, counterN, stride=1, mul=6)
#Nwide = net.get_shape().as_list()[1]
#print(nM)
assert net.get_shape().as_list()[1] == net.get_shape().as_list()[2]
#if Nwide > 7:
# net = slim.max_pool2d(net, [3, 3], \
# stride=2, padding='SAME')
return net
def den_out(input_list1, input_list2, G_tranlist):
assert len(input_list1) == len(input_list2)
inlen = len(input_list1)
lo=0
sjlist = []
with slim.arg_scope([slim.conv2d, slim.separable_conv2d],
padding='SAME',
activation_fn=tf.nn.leaky_relu,
normalizer_fn=slim.layer_norm,
trainable=True):
for i in range(inlen):
#with tf.variable_scope('in_%d'%counterA.get):
#dchs = input_list1[i].get_shape().as_list()[3]
if i >= 2:
G_tran = G_tranlist[-i-4]
elif i == 1:
G_tran = G_tranlist[-4]
elif i == 0:
G_tran = G_tranlist[-1]
else:
raise ValueError
net1 = input_list1[i]
net1 = tf.concat([net1, G_tran], axis=3)
net1 = den_outd(net1, i)
#print(net1.shape)
#net1 = tf.identity(net1, name='output1')
net2 = input_list2[i]
net2 = tf.concat([net2, G_tran], axis=3)
net2 = den_outd(net2, i)
#net2 = tf.identity(net2, name='output2')
sjlist.append(net1)
sjlist.append(net2)
l = tf.reduce_mean(tf.square(net2 - net1), axis=[1,2,3])
l = tf.reduce_mean(l)
lo += l
return lo, sjlist
<file_sep>/grad_mult_scan.py
from PIL import Image
from scipy.ndimage.filters import gaussian_filter
import numpy as np
import os
vis_base='./hres_vis'
ir_base='./hres_tir'
nlst = np.load('nlst.npy')
scans = np.zeros([len(nlst), 40, 40])
for ni, n in enumerate(nlst):
print(ni,'/',len(nlst))
vis_name = os.path.join(vis_base, 'FLIR%04d.jpg'%n)
ir_name = os.path.join(ir_base, 'FLIR%04d.png'%n)
vis_img = Image.open(vis_name)
vis_img = vis_img.resize((427,320), Image.ANTIALIAS)
vis_img = np.array(vis_img).astype(np.float32)
ir_img = np.array(Image.open(ir_name)).astype(np.float32)
#print(2)
vis_G = np.gradient(gaussian_filter(vis_img, 1), axis=(0,1))
ir_G = np.gradient(ir_img, axis=(0,1))
#print(3)
vis_dy = vis_G[0]
vis_dx = vis_G[1]
vis_r = np.sqrt(vis_dx**2 + vis_dy**2)
vis_r = np.linalg.norm(vis_r, axis=2)
#print(vis_r.shape)
ir_dy = ir_G[0]
ir_dx = ir_G[1]
ir_r = np.sqrt(ir_dx**2 + ir_dy**2)
#print(ir_r.shape)
for i in range(40):
for j in range(40):
scans[ni,i,j] = (ir_r*vis_r[20+i:20+i+240,33+j:33+j+320]).mean()
np.save('scans.npy',scans)
<file_sep>/image-preprocess.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright 2018 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import math
import os
import time
import argparse
import numpy as np
from PIL import Image
from scipy.ndimage.filters import gaussian_filter
import matplotlib.pyplot as plt
from matplotlib import widgets
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--vis", help="visible image dir",
default='../../TT/hres_vis')
parser.add_argument("-r", "--ir", help="IR image dir",
default='../../TT/hres_tir')
parser.add_argument("-i", "--input", help="input npy file")
parser.add_argument("-o", "--out", help="output file")
parser.add_argument("-s", "--start", help="start of file name",
type=int)
parser.add_argument("-f", "--first", help="first image num in npy file",
type=int, default=0)
args = parser.parse_args()
vis_base=args.vis
ir_base=args.ir
lnpixel = 120*0.014/math.tan(math.radians(17))
nlst = np.load('nlst.npy')
scans = np.load(args.input)
'''
l25m: the list of 25 point test of each image shape(nimage, 25)
l45mn: list 25 to 45 point test image number
l45m: shape(nimage, 20)
logtemp: [RAWlargmax, 'str', yshift, xshift]
'''
class align():
def __init__(self, filename, start_num, first_img):
timestruct = time.localtime()
strtime = time.strftime('%Y-%m-%d %H:%M:%S', timestruct)
self.outfn = filename
self.outf = open(self.outfn, 'a')
self.outf.write('-----'+strtime+'-----\n')
self.outf.close()
self.img_num = start_num
self.first_img = first_img
self.logtemp = []
self.yshiftNpix = None
self.xshiftNpix = 0
#print(num) is a speed test
def next_img(self):
self.yshiftNpix = None
self.xshiftNpix = 0
self.outf = open(self.outfn, 'a')
self.outf.write('FLIR%d'%(nlst[self.img_num]))
if len(self.logtemp) == 3:
self.outf.write(' %2d %2d %8s\n'%tuple(self.logtemp))
elif len(self.logtemp) == 5:
self.outf.write(' %2d %2d %8s %2d %2d\n'%tuple(self.logtemp))
elif len(self.logtemp) == 0:
pass
else:
raise ValueError('len logtemp not 3 or 5')
self.outf.close()
self.logtemp = []
self.img_num +=1
n = nlst[self.img_num]
self.scan = scans[self.img_num - self.first_img]
#print(1)
vis_name = os.path.join(vis_base, 'FLIR'+str(n)+'.jpg')
ir_name = os.path.join(ir_base, 'FLIR'+str(n)+'.png')
vis_img = Image.open(vis_name)
vis_img = vis_img.resize((427,320), Image.ANTIALIAS)
self.vis_img = np.array(vis_img).astype(np.float32)
ir_img = np.array(Image.open(ir_name)).astype(np.float32)
#print(2)
vis_G = np.gradient(gaussian_filter(self.vis_img, 1), axis=(0,1))
ir_G = np.gradient(ir_img, axis=(0,1))
#print(3)
vis_dy = vis_G[0]
vis_dx = vis_G[1]
vis_r = np.sqrt(vis_dx*vis_dx + vis_dy*vis_dy)
vis_r = np.linalg.norm(vis_r, axis=2)
ir_dy = ir_G[0]
ir_dx = ir_G[1]
ir_r = np.sqrt(ir_dx*ir_dx + ir_dy*ir_dy)
self.vis_norm = vis_r/np.percentile(vis_r, 99)
self.ir_norm = ir_r/np.percentile(ir_r, 99)
#print(4)
self.yshiftNpix, self.xshiftNpix = divmod(self.scan.argmax(), 40)
self.yshiftNpix -= 20
self.xshiftNpix -= 20
#print(5)
self.logtemp.append(self.yshiftNpix)
self.logtemp.append(self.xshiftNpix)
# subplot(223)
vis_norm_crop = self.vis_norm[40+self.yshiftNpix:
40+self.yshiftNpix+240,
53+self.xshiftNpix:
53+self.xshiftNpix+320]
grad_img = np.stack((vis_norm_crop,self.ir_norm,vis_norm_crop), axis=2)
grad_show.clear()
grad_show.imshow(grad_img)
# subplot(221)
vis_crop = self.vis_img[40+self.yshiftNpix:
40+self.yshiftNpix+240,
53+self.xshiftNpix:
53+self.xshiftNpix+320]/255.0
vis_show.clear()
vis_show.imshow(vis_crop)
# subplot(222)
ir_show.clear()
ir_show.imshow(ir_img)
# subplot(224)
scan_show.clear()
scan_show.imshow(self.scan,
extent=(-20.5,19.5,39.5,-20.5), cmap='gist_ncar')
scan_show.scatter(self.xshiftNpix, self.yshiftNpix, color='red')
#print(6)
try:
show_yl = lnpixel / (self.yshiftNpix)
except ZeroDivisionError:
show_yl = float('inf')
try:
show_xl = lnpixel / (self.xshiftNpix)
except ZeroDivisionError:
show_xl = float('inf')
plt.draw()
print('FLIR%d'%n)
print('y %2d %.2f'%(self.yshiftNpix, show_yl))
print('x %2d %.2f'%(self.xshiftNpix, show_xl))
def pass_click(self, event):
self.logtemp.append('pass')
self.next_img()
def not_pass_click(self, event):
self.logtemp.append('not pass')
self.next_img()
def change_value_click(self, event):
self.logtemp.append('change')
#self.logtemp.append(int(input('yshift:')))
#self.logtemp.append(int(input('xshift:')))
self.next_img()
def update_show(self):
n35 = self.yshiftNpix + 5
xsp = self.xshiftNpix
vis_crop = self.vis_img[35+n35:35+n35+240, 53+xsp:53+xsp+320]/255.0
vis_show.clear()
vis_show.imshow(vis_crop)
vis_norm_crop = self.vis_norm[35+n35:35+n35+240, 53+xsp:53+xsp+320]
grad_img = np.stack((vis_norm_crop,self.ir_norm,vis_norm_crop), axis=2)
grad_show.clear()
grad_show.imshow(grad_img)
if args.start is None:
start_num = -1
else:
start_num = np.where(np.array(nlst) == args.start)[0][0]
aligner = align(args.out, start_num, args.first)
vis_show = plt.subplot(221)
ir_show = plt.subplot(222)
grad_show = plt.subplot(223)
scan_show = plt.subplot(224)
pass_ax = plt.axes([0.81, 0.01, 0.09, 0.05])
pass_button = widgets.Button(pass_ax, 'pass')
pass_button.on_clicked(aligner.pass_click)
not_pass_ax = plt.axes([0.71, 0.01, 0.05, 0.03])
not_pass_button = widgets.Button(not_pass_ax, 'not pass')
not_pass_button.on_clicked(aligner.not_pass_click)
change_value_ax = plt.axes([0.71, 0.05, 0.05, 0.03])
change_value_button = widgets.Button(change_value_ax, 'change value')
change_value_button.on_clicked(aligner.change_value_click)
# TextBox.set_val is slowly, I no longer use it
aligner.next_img()
plt.show()
<file_sep>/main.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright 2018 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
#import numpy as np
import tensorflow as tf
#from tensorflow.python import debug as tf_debug
import mobilenet_v2
#from nets.mobilenet import mobilenet
import matplotlib.pyplot as plt
import blocks
#import importlib
#importlib.reload(blocks)
import time
slim = tf.contrib.slim
#sess = tf.InteractiveSession()
batch_size = 12
random_dim = 5
tf.reset_default_graph()
#bulid
#gen_input = tf.placeholder(shape=(None,224,224,3),dtype=tf.float32)
global G_mbnet2
global G_mnout
global G_1x1
def G(input_tensor):
net, mbnet2 = mobilenet_v2.mobilenet_v2_050(input_tensor, num_classes=0)
global G_mbnet2
global G_mnout
global G_1x1
G_mbnet2 = mbnet2
G_mnout = net
net = slim.conv2d(net, 1280, [4,4], stride=1, padding='VALID',
activation_fn=tf.nn.leaky_relu, normalizer_fn=slim.batch_norm)
net = blocks.layer1x1(net, 1280,
activation_fn=tf.nn.leaky_relu, normalizer_fn=slim.batch_norm)
G_1x1 = net
tf.summary.histogram('layer1x1',net)
net = blocks.gen_transpose(net, mbnet2, input_tensor)
return net
#den_input = tf.placeholder(shape=(None,224,224,1),dtype=tf.float32)
global endpoints1
global endpoints2
def D(input_tensor1, input_tensor2, is_summary):
global endpoints1
global endpoints2
with tf.variable_scope('D', reuse=tf.AUTO_REUSE):
# with tf.contrib.slim.arg_scope(mobilenet_v2.training_scope()):
# net, mbnet2 = mobilenet_v2.mobilenet_v2_050(input_tensor, num_classes=0)
net, endpoints1 = blocks.den_net(input_tensor1)
if is_summary:
tf.summary.histogram('den_net_gen_IR',net)
net, endpoints2 = blocks.den_net(input_tensor2)
if is_summary:
tf.summary.histogram('den_net_real_IR',net)
net, sjlist = blocks.den_out(endpoints1, endpoints2, blocks.G_tran)
return net, sjlist
def parser(record):
features = tf.parse_single_example(record,
features={'Vis_image': tf.FixedLenFeature([], tf.string),
'IR_image' : tf.FixedLenFeature([], tf.string),})
Vis_image = tf.decode_raw(features['Vis_image'],tf.uint8)
Vis_image = tf.reshape(Vis_image, [240, 320, 3])
#Vis_image = tf.random_crop(Vis_image, (224, 224, 3), seed=12345679)
#Vis_image = tf.cast(Vis_image, tf.float32)
#Vis_image = Vis_image/255.0
IR_image = tf.decode_raw(features['IR_image'],tf.uint16)
IR_image = tf.reshape(IR_image, [240, 320, 1])
#IR_image = tf.random_crop(IR_image, (224, 224, 1), seed=12345679)
#IR_image = tf.cast(IR_image, tf.float32)
#IR_image = IR_image/30000.0
return Vis_image, IR_image
def parser2(Vis_image, IR_image):
Vis_image = tf.random_crop(Vis_image, (224, 224, 3), seed=12345679)
Vis_image = tf.cast(Vis_image, tf.float32)
Vis_image = Vis_image/255.0
IR_image = tf.random_crop(IR_image, (224, 224, 1), seed=12345679)
IR_image = tf.cast(IR_image, tf.float32)
IR_image = IR_image/30000.0
return Vis_image, IR_image
tf.reset_default_graph()
tfrecords_filename = ["/gdrive/My Drive/Spectrum-Transform/colab_data/TFRecords2",
"/gdrive/My Drive/Spectrum-Transform/colab_data/TFRecords3"]
dataset = tf.data.TFRecordDataset(tfrecords_filename)
dataset = dataset.map(parser).shuffle(buffer_size=2000).repeat().map(parser2).batch(batch_size)
iterator = dataset.make_initializable_iterator()
# get the variables list is empty
# copy from https://github.com/bojone/gan/blob/master/mnist_gangp.py
#real_IR = tf.placeholder(tf.float32, shape=[None, 224, 224, 1])
#Vis = tf.placeholder(tf.float32, shape=[None, 224, 224, 3])
Vis, real_IR = iterator.get_next()
weight_intitializer = tf.truncated_normal_initializer(stddev=0.05)
with slim.arg_scope([slim.conv2d, slim.conv2d_transpose, slim.fully_connected, slim.separable_conv2d],
weights_initializer=weight_intitializer):
gen_IR = G(Vis)
#print(gen_IR.shape)
tf.summary.histogram('gen_IR',gen_IR)
tf.summary.histogram('Vis',Vis)
tf.summary.histogram('real_IR',real_IR)
eps = tf.random_uniform([batch_size, 1, 1, 1], minval=0., maxval=1.)
X_inter = tf.add(eps*real_IR, (1. - eps)*gen_IR, name='X_inter')
Dxr, _ = D(X_inter, real_IR, False)
grad = tf.gradients(Dxr, [X_inter])[0]
tf.summary.histogram('grad',grad)
grad_norm = tf.reduce_mean(tf.nn.relu(tf.square(grad) - 1.),axis=[0,1,2,3])
grad_mean, grad_std = tf.nn.moments(grad, axes=[0,1,2,3])
#print(grad_std.shape)
grad_pen = 10 * grad_norm
tf.summary.scalar('grad_mean',grad_mean)
tf.summary.scalar('grad_std',grad_std)
D_gen_IR, sjlist = D(gen_IR, real_IR, True)
for ni, i in enumerate(sjlist):
tf.summary.histogram('D%d'%ni,i)
D_gen_IR = tf.identity(D_gen_IR, name='D_gen_IR')
D_loss = grad_pen - D_gen_IR
G_loss = D_gen_IR
#loss = D_loss + G_loss
tf.summary.histogram('mbnet_layer2',G_mbnet2['layer_2'])
tf.summary.histogram('mbnet_layer4',G_mbnet2['layer_4'])
tf.summary.histogram('mbnet_layer7',G_mbnet2['layer_7'])
tf.summary.histogram('mbnet_layer11',G_mbnet2['layer_11'])
tf.summary.histogram('mbnet_layer14',G_mbnet2['layer_14'])
tf.summary.histogram('mbnet_layer18',G_mbnet2['layer_18'])
tf.summary.histogram('mobilenet_v2_out',G_mnout)
for ni, i in enumerate(blocks.G_tran):
tf.summary.histogram('transpose%d'%ni,i)
tf.summary.scalar('G_loss_D_IRs',G_loss)
tf.summary.scalar('D_loss',D_loss)
D_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='D')
G_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='MobilenetV2')
G_variables += tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='transpose')
#G_mbnet2_varlist = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='G/MobilenetV2/')
G_solver = tf.train.AdamOptimizer(1e-4, name='Adam_G').minimize(G_loss, var_list=G_variables)
D_solver = tf.train.AdamOptimizer(1e-4, name='Adam_D').minimize(D_loss, var_list=D_variables)
#op = tf.train.AdamOptimizer(1e-4).minimize(loss)
'''Gg = G_Op.compute_gradients(G_loss, G_variables)
Gg2 = []
for ni,i in enumerate(Gg):
Gg2.append((Gg[ni][1],Gg[ni][1]))
G_solver = G_Op.apply_gradients(Gg2)'''
#Vis_image, IR_image = tf.train.shuffle_batch([Vis_image, IR_image], num_threads=2, batch_size=2, capacity=2000,
# min_after_dequeue=1000)
saver = tf.train.Saver(max_to_keep=20)
merged_summary_op = tf.summary.merge_all()
#checkpoint = './mobilenet_v2_0.5_224/mobilenet_v2_0.5_224.ckpt'
#checkpoint = './checkpoint/checkpoint.ckpt'
#saver.restore(sess, checkpoint)
Pretrained_model_dir = './mobilenet_v2_0.5_224/mobilenet_v2_0.5_224.ckpt'
inception_except_logits = slim.get_variables_to_restore(include=['MobilenetV2'], exclude=['MobilenetV2/Logits'])
init_fn = slim.assign_from_checkpoint_fn(Pretrained_model_dir, inception_except_logits, ignore_missing_vars=True)
#sess.graph.finalize()
t0=time.time()
with tf.Session() as sess:
summary_writer = tf.summary.FileWriter('/gdrive/My Drive/Spectrum-Transform/colab_data/summary3', sess.graph)
init_op = tf.global_variables_initializer()
sess.run(iterator.initializer)
sess.run(init_op)
#init_fn(sess)
saver.restore(sess, '/gdrive/My Drive/Spectrum-Transform/colab_data/checkpoint/net21.ckpt-13000')
#coord=tf.train.Coordinator()
#threads= tf.train.start_queue_runners(coord=coord, sess=sess)
#IR_i, Vis_i= sess.run([IR_image, Vis_image])
wmg=True
for i in range(13000, 20001):
#IR_i2 = IR_i
#Vis_i2 = Vis_i
#IR_i, Vis_i = sess.run([IR_image, Vis_image])
#print("sess.runOK")
if i%50 == 0:
t=time.time()
print(i,(t-t0)/50)
t0=t
summary_str, G_l, D_l, gm, gs = sess.run([merged_summary_op, G_loss, D_loss, grad_mean, grad_std])
summary_writer.add_summary(summary_str, i)
#print("summaryOK")
print('loss',G_l, D_l, gm, gs)
if i%500 == 0 and i != 13000:
saver.save(sess, '/gdrive/My Drive/Spectrum-Transform/colab_data/checkpoint/net21.ckpt',
global_step=i, write_meta_graph=wmg)
print("SaveOK")
IR_i, Vis_i, gIR = sess.run([real_IR, Vis, gen_IR])
plt.subplot(131)
plt.imshow(IR_i.reshape([224*batch_size,224])[:224*3,])
plt.colorbar()
plt.subplot(132)
plt.imshow(Vis_i.reshape([224*batch_size,224,3])[:224*3,:,])
plt.subplot(133)
plt.imshow(gIR.reshape([224*batch_size,224])[:224*3,])
plt.colorbar()
plt.show()
sess.run([G_solver, D_solver])
wmg=False
#print("solverOK")
| 60774aab79522d4d68157c9f2107839a14be4e16 | [
"Markdown",
"Python"
] | 9 | Python | XuHg-zjcn/Spectrum-Transform | 7d93a499503686b3acb7c1906f1fdb76bfd0681b | e665a33a126b36351273b71602bf1aa213dae9e0 |
refs/heads/master | <repo_name>Varwen/SUID<file_sep>/src/VAC/SUID/Where/Where.php
<?php
/*
* Author <NAME>
* Copyright since 2015
*/
namespace VAC\SUID\Where;
use VAC\SUID\Abstracts\{
Where as WhereAbstract
};
use VAC\Interfaces\{
WhereInterface
};
/**
* Description of Where
*
* @author Simon
*/
class Where extends WhereAbstract
{
private $objFilled = FALSE;
private $bracket = FALSE;
private $logicOperator = FALSE;
private $column = FALSE;
private $bind = NULL;
public function prepareStatement() {
if ($this->objFilled) {
$where = '';
$trace = debug_backtrace();
if (!isset($trace[1])) {
die('Fehler');
}
if ($trace[1]['object'] instanceof WhereInterface && $trace[1]['object'] instanceof self && $this->logicOperator) {
$where .= $this->logicOperator . ' ';
}
if ($this->bracket) {
$where .= '( ';
}
$countWhereClause = count($this->column);
foreach ($this->column as $key => $value) {
$countWhereClause -= 1;
if ($value instanceof WhereInterface) {
$where .= $this->callNewWhereObj($value);
} else if (is_string($value)) {
$where .= $this->buildColumnWhere($value, $key);
if ($this->logicOperator && $countWhereClause > 0 && !(next($this->column) instanceof WhereInterface)) {
$where .= $this->logicOperator . ' ';
}
} else {
die('Fehler');
}
}
if ($this->bracket) {
$where .= ') ';
}
} else {
$where = NULL;
}
return array (self::WHERE => $where, self::WHERE_BINDS => $this->bind);
}
public function setWhere(array $column, $bracket = FALSE,
$logicalOperator = FALSE, array $bind = NULL) {
$this->column = $column;
$this->bind = $bind;
$this->checkBracket($bracket);
$this->checkLogicalOperator($logicalOperator);
$this->objFilled = TRUE;
}
protected function checkBracket($bracket) {
if (parent::checkBracket($bracket)) {
$this->bracket = $bracket;
} else {
die('Fehler');
}
}
protected function checkLogicalOperator($logicalOperator) {
if (parent::checkLogicalOperator($logicalOperator)) {
$this->logicOperator = $logicalOperator;
} else {
die('Fehler');
}
}
private function callNewWhereObj(Where $whereObj) {
$result = ($whereObj->prepareStatement());
$this->bind = array_merge((array) $this->bind,
$result[self::WHERE_BINDS]);
return ($result[self::WHERE]);
}
private function buildColumnWhere(string $column, $key) {
if (rtrim($column, '?') && !is_int($key) && array_key_exists($key,
$this->bind)) {
$where = rtrim(trim($column), '?') . $key . ' ';
} else {
$where = $column . ' ';
}
return $where;
}
}
<file_sep>/src/VAC/Interfaces/SUIDInterface.php
<?php
/*
* Author <NAME>
* Copyright since 2015
*/
namespace VAC\Interfaces;
/**
*
* @author Simon
*/
interface SUIDInterface
{
public function prepareStatement();
}
<file_sep>/src/VAC/Interfaces/WhereInterface.php
<?php
/*
* Author <NAME>
* Copyright since 2015
*/
namespace VAC\Interfaces;
/**
* Description of Where_Interface
*
* @author Simon
*/
interface WhereInterface
{
const OPERATOR_AND = 'AND';
const OPERATOR_OR = 'OR';
public function setWhere(array $column, $bracket = FALSE,
$logic_operator = FALSE, array $bind = NULL);
}
<file_sep>/src/VAC/Interfaces/WhereAbleInterface.php
<?php
/*
* Author <NAME>
* Copyright since 2015
*/
namespace VAC\Interfaces;
use VAC\Interfaces\WhereInterface;
/**
* Description of WhereAble
*
* @author Simon
*/
interface WhereAbleInterface
{
const WHERE = 'WHERE';
const WHERE_BINDS = 'BINDS';
public function where(WhereInterface $whereObj);
public function getBinds();
}
<file_sep>/README.md
# SUID
Database ORM System SUID (=Select Update Insert Delete)
<file_sep>/src/VAC/SUID/Abstracts/WhereAble.php
<?php
/*
* Author <NAME>
* Copyright since 2015
*/
namespace VAC\SUID\Abstracts;
use VAC\Interfaces\{
WhereAbleInterface
,
WhereInterface
};
use \VAC\SUID\Abstracts\SUID;
/**
* Description of WhereAble
*
* @author Simon
*/
abstract class WhereAble extends SUID implements WhereAbleInterface
{
private $where = NULL;
private $binds = NULL;
protected function buildWhere() {
$whereString = '';
if (strlen($this->where)) {
$whereString = ' ' . self::WHERE . ' ' . $this->where;
}
return $whereString;
}
public function where(WhereInterface $whereObj) {
$where = ($whereObj->prepareStatement());
$this->where = $where[self::WHERE];
$this->binds = $where[self::WHERE_BINDS];
return $this;
}
public function getBinds() {
return $this->binds;
}
}
<file_sep>/src/VAC/Interfaces/SelectInterface.php
<?php
/*
* Author <NAME>
* Copyright since 2015
*/
namespace VAC\Interfaces;
/**
*
* @author Simon
*/
interface SelectInterface
{
const SELECT = 'SELECT';
const FROM = 'FROM';
const ORDER_BY = 'ORDER BY';
const CONNECTOR_AS = 'AS';
const ORDER_ASC = 'ASC';
const ORDER_DESC = 'DESC';
const DEFAULT_ORDER = self::ORDER_ASC;
public function from($tableName, $columns = '*');
public function orderby($orderby);
}
<file_sep>/src/VAC/SUID/Abstracts/Where.php
<?php
/*
* Author <NAME>
* Copyright since 2015
*/
namespace VAC\SUID\Abstracts;
use VAC\Interfaces\WhereInterface;
use VAC\SUID\Abstracts\WhereAble;
/**
* Description of Where_Abstract
*
* @author Simon
*/
abstract class Where extends WhereAble implements WhereInterface
{
protected function checkLogicalOperator($logicalOperator) {
return ($logicalOperator === self::OPERATOR_AND || $logicalOperator === self::OPERATOR_OR || $logicalOperator === FALSE);
}
protected function checkBracket($bracket) {
return (is_bool($bracket));
}
}
<file_sep>/src/VAC/SUID/Abstracts/Select.php
<?php
/*
* Author <NAME>
* Copyright since 2015
*/
namespace VAC\SUID\Abstracts;
use VAC\Interfaces\SelectInterface;
use VAC\SUID\Abstracts\{
WhereAble
};
/**
* Description of Select_Abstract
*
* @author Simon
*/
abstract class Select extends WhereAble implements SelectInterface
{
protected function buildColumns(array $columns, string $prefix = NULL) {
$columnsString = '';
foreach ($columns as $alias => $columnName) {
if ($prefix) {
$columnName = $prefix . '.' . $columnName;
}
$columnsString .= ' ' . strtoupper($columnName);
if (is_string($alias)) {
$columnsString .= ' ' . self::CONNECTOR_AS . ' ' . strtoupper($alias);
}
$columnsString .= ',';
}
return (rtrim($columnsString, ','));
}
protected function buildFrom(string $tableName, string $as = NULL) {
$fromString = ' ' . self::FROM;
$fromString .= ' ' . strtoupper($tableName);
if ($as) {
$fromString .= ' ' . self::CONNECTOR_AS . ' ' . $as;
}
return $fromString;
}
protected function buildOrderBy(array $orderby) {
$orderbyString = '';
foreach ($orderby as $column => $order) {
if (strlen($orderbyString)) {
$orderbyString .= ',';
}
$orderbyString .= ' ' . $column . ' ' . $order;
}
if (strlen($orderbyString)) {
$orderbyString = ' ' . self::ORDER_BY . $orderbyString;
}
return $orderbyString;
}
protected function checkOrderOperator($order) {
return ($order === self::ORDER_ASC || $order === self::ORDER_DESC);
}
}
<file_sep>/index.php
<?php
require_once './namespace.php';
<file_sep>/src/VAC/SUID/Abstracts/SUID.php
<?php
/*
* Author <NAME>
* Copyright since 2015
*/
namespace VAC\SUID\Abstracts;
use VAC\Interfaces\SUIDInterface;
/**
* Description of SUID_Abstracts
*
* @author Simon
*/
abstract class SUID implements SUIDInterface
{
}
<file_sep>/src/VAC/Interfaces/AdapterInterface.php
<?php
/*
* Author <NAME>
* Copyright since 2015
*/
namespace VAC\Interfaces;
/**
*
* @author Simon
*/
interface AdapterInterface
{
public function select();
public function insert();
public function update();
public function delete();
}
<file_sep>/src/VAC/SUID/Adapter.php
<?php
/*
* Author <NAME>
* Copyright since 2015
*/
namespace VAC\SUID;
use VAC\Interfaces\{
AdapterInterface,
SelectInterface,
WhereInterface
};
/**
* Description of SUID
*
* @author Simon
*/
class Adapter implements AdapterInterface
{
/**
* @var obj SelectInterface
*/
private $select;
/**
*
* @var obj WhereInterface
*/
private $where;
public function __construct(SelectInterface $select, WhereInterface $where) {
$this->select = $select;
$this->where = $where;
}
public function select() {
return clone($this->select);
}
public function delete() {
}
public function insert() {
}
public function update() {
}
public function where() {
return clone($this->where);
}
}
<file_sep>/src/VAC/SUID/Select/Select.php
<?php
/*
* Author <NAME>
* Copyright since 2015
*/
namespace VAC\SUID\Select;
use VAC\Interfaces\{
WhereInterface
};
use VAC\SUID\Abstracts\{
Select as SelectAbstract
};
/**
* Description of Select
*
* @author Simon
*/
class Select extends SelectAbstract
{
private $columns = FALSE;
private $tableName = FALSE;
private $tablePrefix = FALSE;
private $select = NULL;
private $orderby = array ();
public function prepareStatement() {
if (!$this->columns && !$this->tableName) {
die('FEHLER');
}
$this->select = self::SELECT;
$this->select .= $this->buildColumns($this->columns, $this->tablePrefix);
$this->select .= $this->buildFrom($this->tableName, $this->tablePrefix);
$this->select .= $this->buildWhere();
$this->select .= $this->buildOrderBy($this->orderby);
return $this->select;
}
public function from($tableName, $columns = '*') {
if (is_string($columns)) {
$this->columns = array ();
$this->columns[] = $columns;
} else if (is_array($columns)) {
$this->columns = $columns;
} else {
die('FEHLER');
}
if (is_array($tableName)) {
foreach ($tableName as $prefix => $tableName) {
$this->tableName = $tableName;
}
if (is_string($prefix)) {
$this->tablePrefix = $prefix;
}
} else {
$this->tableName = $tableName;
}
return $this;
}
public function orderby($orderby) {
if (is_string($orderby)) {
$orderbyParts = split($orderby, ' ');
if (array_key_exists(1, $orderbyParts)) {
$order = trim(strtoupper($orderbyParts[1]));
} else {
$order = self::DEFAULT_ORDER;
}
$orderby = array (trim(strtoupper($orderbyParts[0])) => $order);
}
foreach ($orderby as $order) {
if ($this->checkOrderOperator($order)) {
die('Fehler');
}
}
$this->orderby = $orderby;
return $this;
}
public function where(WhereInterface $whereObj) {
parent::where($whereObj);
return $this;
}
}
| 331a0138baa07cdec274a2fc0b3b50acc9eb0682 | [
"Markdown",
"PHP"
] | 14 | PHP | Varwen/SUID | 26a3b7de1baff4b56452a57a6888434d8e07e345 | 5aa532c4f95dcb62035dccaccc0516731a8bc9cc |
refs/heads/master | <file_sep># 概要
- タップタイタンズ的なRPG x リズムゲーム
- タップすれば進んでいくが、リズムに合わせてタップをする必要があり、タイミングが良ければ良いほど高得点
- 仲間を増やして時間あたりの獲得ポイントを増やしていける
- BGMを設定できる
- BPMを変更できる
# アートワーク
- 案
- 2Dトゥーンシェード
- 太いアウトラインのアメリカっぽいイラストでいきたい。
- ストリート感
- 3Dボクセル
- 差別化要因
# ルール
- タップをすると「ポイント」を「敵」に与える
- ポイントが一定数たまると、「敵」が倒れて「コイン」がもらえる
- コインで「レベル」を上げると、タップあたり獲得ポイントが増える。
- コインで「サポートキャラ」を解放すると、タップしなくても自動で「ポイント」を稼いでくれる。
- サポートキャラをレベル上げすると、1秒あたり獲得ポイントが増える。
- 敵は次第に強くなっていく。
# システム
- クエストは常に自動で進んでいく。
- ゲームを起動していない間も、サポーターの数とレベルの分だけ敵に攻撃し、クエストを進めて行く。
- 起動してレベルを上げたり、タップしてヒーローに攻撃させることでより難しいクエストをクリアできる。
- ゲームの途中でガチャや強化(レベルアップ)、ストーリーを読み進めることができるが、その間もクエストは進んでいく。
- どの方向にクエストを進めていきたいかは、いつでも選べる。選んだ道なりのクエストを自動で進めて行く。
- しばらく放置していると、倒せないレベルの敵にぶつかり、そこでクエスト進行がストップする。(ボスに負けるとまた通常クエストに戻るので、お金は貯まる)
- ゲームに復帰した時に、貯まったお金を一度に回収する気持ち良い仕掛けがある。(もやしの一気に抜く奴みたいな)
- 転生により、レベルはリセットされるが初期値が上がる。
- イベントなどが発生した場合、イベントクエスト選択すればそのイベントを自動で進めるようになる。イベント期間が終わったらメインイベントの進行に自動で戻る。
- 動画広告を見るとコインとダイヤが貯まる。ダイヤはコインよりも何倍もの価値がある。
- クリスタルをためて、永続的な能力(獲得経験値アップなど)を身につけることができる。
- クリスタルは転生をすることでまとめて手に入る。
- クリスタルの使用は慎重に行ったほうが良い。(獲得に時間が掛かる)
- 特定のダイヤを使用しないと、解放できないサポーターキャラがいる。(レアガチャ)
- レベルが上がるほど、使えるサポーターの数が増えていく。
- クエストによって背景がどんどん変わっていく。
- 課金で手に入るダイヤ/プレイすることでしか手に入らないより貴重なクリスタルという2つの貴重な資産を用意する。
- ゲームにループ要素を組み込む。
# 必要な画面
- タイトル画面
- メイン画面
- 編成・育成
- 主人公
- 強化
- 装備強化・編成
- 武器
- 防具
- アクセサリ
- スキル
- サポーター
- 解放・強化
- スキル
- リザルト画面(非ログイン間に倒した敵、獲得したコインが分かる)
- 設定画面
# データ設計
## Settings
- BPM ビートのテンポを決める。
- TapTiming タップタイミング。ユーザーごとに最適なタイミング設定を行い、プレイ感を向上させる。
## Player ユーザーデータ
- Coin ユーザーの所持コイン。敵を倒すと獲得でき、これを使って自分のレベル上げ、サポーターの解放・レベル上げを行う。
- Point 総得点。ゲームの進行には直接関与しない。
- Kill Count
- Combo
- Hero
- Level
- PPT (Point Per Tap)
- Supporters
- Supporter
- PPA (Point Per Attack)
- Attack Interval
- Level
## Enemy
- Level
- HP
- Drop Coin
## Quest
- Reward
- Enemies List
- Enemy
## Skill
- Effect type
- Value
## Effect type
- description
<file_sep>using UnityEngine;
using System.Collections;
public class Const {
public const string PREF_USER_LEVEL = "UserLevel";
public const string PREF_USER_COIN = "UserCoin";
public const string PREF_USER_MAX_COMBO = "MaxCombo";
public const string PREF_KILL_COUNT = "KillCount";
public const string PREF_ENMEY_NUM = "EnemyNum";
public const string PREF_SUPPORTER_LEVELS = "SupporterLevels";
public const int SE_KICK = 0;
public const int SE_HAT_BAD = 1;
public const int SE_HAT_GOOD = 2;
public const int SE_HAT_GREAT = 3;
public const int SE_HAT_EXCELLENT = 4;
public const int SE_SNARE = 5;
public const int SE_LV_UP = 6;
public const int SE_KILL_ENEMY = 7;
}
<file_sep>using UnityEngine;
using System.Collections;
public class EnemyMasterTable : MasterTableBase<EnemyMaster>
{
public void Load() {
Load(convertClassToFilePath (this.GetType ().Name));
}
}
public class EnemyMaster : MasterBase
{
public string id { get; private set; }
public string name { get; private set; }
public int base_hp { get; private set; }
public string image_path { get; private set;}
public int drop_coin {get; private set;}
}
<file_sep>using UnityEngine;
using System.Collections;
public class AudioCtrl : MonoBehaviour {
public AudioSource[] _audioSourceArray;
public AudioClip[] _seArray;
// Use this for initialization
void Start () {
for (int i = 0; i < _audioSourceArray.Length; i++) {
_audioSourceArray [i].clip = _seArray [i];
}
}
public void PlaySE(int pSeNumber) {
_audioSourceArray[pSeNumber].Play ();
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class EffectCtrl : MonoBehaviour {
public GameObject _effectContainer;
public GameObject _effectPref;
GameObject[] _effectArray;
int effectNum = 3;
int pos = 0;
// Use this for initialization
void Start () {
_effectArray = new GameObject[effectNum];
for (int i = 0; i < effectNum; i++) {
GameObject go = (GameObject)Instantiate (_effectPref);
_effectArray [i] = go;
go.transform.parent = _effectContainer.transform;
go.SetActive (false);
}
}
public void showEffect() {
_effectArray [pos].SetActive (true);
if (pos == effectNum - 1) {
_effectArray [0].SetActive (false);
} else {
_effectArray [pos + 1].SetActive (false);
}
pos++;
if (pos == effectNum) {
pos = 0;
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Linq;
using System.Text.RegularExpressions;
/// <summary>
/// string型の拡張メソッドを管理するクラス
/// </summary>
public static class StringExtensions
{
/// <summary>
/// スネークケースをアッパーキャメル(パスカル)ケースに変換します
/// 例)quoted_printable_encode → QuotedPrintableEncode
/// </summary>
public static string SnakeToUpperCamel(this string self)
{
if (string.IsNullOrEmpty (self))
{
return self;
}
return self
.Split (new[] { '_' }, System.StringSplitOptions.RemoveEmptyEntries)
.Select (s => char.ToUpperInvariant (s [0]) + s.Substring (1, s.Length - 1))
.Aggregate (string.Empty, (s1, s2) => s1 + s2);
}
/// <summary>
/// スネークケースをローワーキャメル(キャメル)ケースに変換します
/// </summary>
public static string SnakeToLowerCamel(this string self)
{
if (string.IsNullOrEmpty (self))
{
return self;
}
return self.SnakeToUpperCamel ().Insert (0, char.ToLowerInvariant (self [0]).ToString ()).Remove (1, 1);
}
/// <summary>
/// ローワーキャメルケースをスネークケースに変換します
/// </summary>
public static string LowerCamelToSnake(this string self)
{
if (string.IsNullOrEmpty (self))
return self;
string convertStr = "";
int count = 0;
foreach (char c in self.ToCharArray()) {
if (char.IsUpper (c)) {
if (count != 0) {
convertStr += "_";
}
convertStr += char.ToLowerInvariant(c);
} else {
convertStr += c.ToString ();
}
count++;
}
return convertStr;
}
}<file_sep>using UnityEngine;
using System.Collections;
public class AutoFade : MonoBehaviour {
TextMesh me;
float alpha = 1.0f;
Color myColor;
// Use this for initialization
void Start () {
me = this.gameObject.GetComponent<TextMesh> ();
myColor = me.color;
alpha = myColor.a;
}
// Update is called once per frame
void Update () {
alpha -= 0.1f / 15;
myColor.a = alpha;
me.color = myColor;
}
public void resetColor() {
alpha = 1.0f;
myColor.a = alpha;
me.color = myColor;
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.Events;
using System.Collections.Generic;
public class ScrollCtrl : MonoBehaviour {
[SerializeField]
RectTransform prefab = null;
GameCtrl _gameCtrl;
List<SupporterPanelCtrl> itemList = new List<SupporterPanelCtrl>();
// Use this for initialization
void Start () {
_gameCtrl = GameObject.Find("GameCtrl").GetComponent<GameCtrl>();
}
// サポーターリストを作成するコード
public void InitSupportersList(List<Supporter> pSupportersList)
{
int count = pSupportersList.Count;
for (int i = 0; i < count; i++) {
Supporter aSupporter = pSupportersList[i];
var item = Instantiate (prefab) as RectTransform;
item.SetParent (transform, false);
// Setting
Button btn = item.GetComponentInChildren<Button>();
int aId = aSupporter.id;
btn.onClick.AddListener(() =>
{
_gameCtrl.purchaseSupporter(aId);
});
SupporterPanelCtrl spPanel = item.GetComponent<SupporterPanelCtrl>();
spPanel.init(aSupporter);
itemList.Add(spPanel);
}
}
public void updateSupportersInfo(Supporter pSp) {
//for (int i = 0; i < itemList.Count; i++) {
// if (itemList[i]
//}
itemList[pSp.id-1].setInformation(pSp);
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
public class GameCtrl : MonoBehaviour {
[Header("Control Settings")]
public AudioCtrl _audioCtrl;
public EffectCtrl _effectCtrl;
public TimeCtrl _timeCtrl;
public PlayerCtrl _playerCtrl;
public EnemyCtrl _enemyCtrl;
public SupporterCtrl _supporterCtrl;
[Header("Display Settings")]
public GameObject _circle;
public GameObject _targetCircle;
public GameObject _cubeMoving;
public GameObject _cubeTarget;
Vector3 _cubeMovingPosition;
public enum DISPLAY_MODE {
CIRCLE,
CUBE,
}
public DISPLAY_MODE display_mode;
public TextMesh _tapResultText;
public TextMesh _ScoreText;
public TextMesh _maxComboLabel;
public TextMesh _killCountLabel;
public TextMesh _damageText;
// サポーターリスト
public GameObject _supporterScrollView;
[Header("Game Settings")]
public GAME_MODE gameMode = GAME_MODE.STAND_BY;
public enum GAME_MODE
{
STAND_BY,
PLAY,
PAUSE,
DEBUG,
}
public float _BPM = 120;
public enum TIMING {
BAD,
GOOD,
GREAT,
EXCELLENT,
PERFECT,
}
// Game Logic
int comboCount;
int score = 0;
int killCount = 0;
int maxCombo = 0;
[Header("Circle Display Logic")]
Vector3 _movingCircleScale;
[Header("Cube Display Logic")]
float CUBE_WIDTH = 3f;
Vector3 _cubeTargetScale;
[Header("Debug Settings")]
public Text fpsDisplay;
public GameObject debugControls;
public GameObject debugPanel;
public Slider debugBPM;
public Slider debugGood;
public Slider debugGreat;
public Slider debugExcellent;
public Slider debugPerfect;
public int SCORE_VAL_BAD = 10;
public int SCORE_VAL_GOOD = 30;
public int SCORE_VAL_GREAT = 100;
public int SCORE_VAL_EXCELLENT = 150;
public int SCORE_VAL_PERFECT = 300;
public float DIF_VAL_GOOD = 0.1f;
public float DIF_VAL_GREAT = 0.05f;
public float DIF_VAL_EXCELLENT = 0.01f;
public float DIF_VAL_PERFECT = 0.001f;
public float TARGET_CIRCLE_SCALE_AMOUNT = 0.12f;
public float TARGET_CUBE_SCALE_AMOUNT = 2f;
public float SCALE_TIME = 0.2f;
public float RESULT_TEXT_SCALE_AMOUNT = 0.2f;
// 表示系
public TextMesh _userLvLabel;
public TextMesh _userPPTLabel;
public Text _nextLevelLabel;
public Text _purchaseBtnLabel;
public Button _openSupporterListButton;
UserData _userData;
UserData _nextUserData;
// Use this for initialization
void Start () {
Application.targetFrameRate = 60;
QualitySettings.vSyncCount = 0;
// Ctrl
_timeCtrl.Init(this);
_tapCtrl = this.GetComponentInChildren<TapCtrl>();
// COMMON
_movingCircleScale = _circle.transform.localScale;
_cubeMovingPosition = _cubeMoving.transform.position;
_cubeTargetScale = _cubeTarget.transform.localScale;
// DISPLAY MODE INITIALIZATION
if (display_mode == DISPLAY_MODE.CIRCLE) {
enableCube (false);
} else {
//DISABLE
enableCircle(false);
}
// 初期化処理
initUserData ();
showUserData ();
score = 0;
gameMode = GAME_MODE.PLAY;
}
void initUserData() {
// ユーザーレベル取得
int userLv = PlayerPrefs.GetInt (Const.PREF_USER_LEVEL);
if (userLv == 0) {
userLv = 1;
}
_userData = new UserData (userLv);
_playerCtrl.setUserData (_userData);
int nextUserLv = userLv + 1;
_nextUserData = new UserData (nextUserLv);
// サポーター情報取得
setSupporters ();
// 所持コイン取得
int userCoin = PlayerPrefs.GetInt (Const.PREF_USER_COIN);
_playerCtrl.addCoin (userCoin);
// 最大コンボ数取得
maxCombo = PlayerPrefs.GetInt(Const.PREF_USER_MAX_COMBO);
// 討伐数取得
killCount = PlayerPrefs.GetInt (Const.PREF_KILL_COUNT);
// 敵取得
_enemyCtrl.initEnemyFromDB (killCount);
}
// サポーター情報をセット
void setSupporters() {
_supporterCtrl.init ();
}
void showUserData() {
//_userLvLabel.text = "Lv: "+_userData.level;
//_userPPTLabel.text = "PPT: "+_userData.pointPerTap;
//_nextLevelLabel.text = "Next Lv : " + _nextUserData.level + "\n"
// + "PPT : " + _nextUserData.pointPerTap;
_nextLevelLabel.text = "LV:" + _userData.level + "\n" + "PPT: " + _userData.pointPerTap;
_purchaseBtnLabel.text = "LEVEL UP!\n" + _userData.nextLevelCoin + " COIN";
//_maxComboLabel.text = "MaxCombo:" + maxCombo;
//_killCountLabel.text = "Kill:" + killCount;
}
public void purchasePlayerLevel() {
int useCoinValue = _userData.nextLevelCoin;
if (_playerCtrl.getCoin () < useCoinValue) {
Debug.Log ("CAN'T BUY");
return;
}
_userData.setUserData (_userData.level + 1);
_nextUserData.setUserData (_nextUserData.level + 1);
_playerCtrl.setUserData (_userData);
_playerCtrl.useCoin (useCoinValue);
// LvUP音を再生
PlaySE(Const.SE_LV_UP);
showUserData ();
}
// サポーターの解放/レベルアップリストを開く
public void openSupporterList() {
gameMode = GAME_MODE.PAUSE;
_supporterScrollView.SetActive(true);
_openSupporterListButton.gameObject.SetActive(false);
}
// サポーターの解放/レベルップリストを閉じる
public void closeSupporterList() {
_supporterScrollView.SetActive(false);
gameMode = GAME_MODE.PLAY;
_openSupporterListButton.gameObject.SetActive(true);
}
// サポーターを解放/レベルアップ(引数にはサポーターのID)
public void purchaseSupporter(int pId) {
// 購入チェック
int useCoinValue = _supporterCtrl.getSupporterCost(pId);
Debug.Log("COIN:" + _playerCtrl.getCoin() + " supporterCost:" + useCoinValue);
if (_playerCtrl.getCoin () < useCoinValue) {
Debug.Log ("CAN'T BUY");
return;
}
if (_supporterCtrl.raiseSupporterLevel(pId))
{
Debug.Log("SUCCESS");
} else {
Debug.Log("FAILED");
return;
}
// コイン消費
_playerCtrl.useCoin(useCoinValue);
// セーブ
// サポーターを解放済みならレベルップ/そうでないなら解放
//if (isAvailableSupporter (pId)) {
// purchaseSupporterLevel (pId);
//} else {
// purchaseNewSupporter (pId);
//}
}
void purchaseNewSupporter(int pId) {
// サポータークラスのインスタンスを生成
// 初期ステータスを設定
// サポーターリストに追加する
}
void purchaseSupporterLevel(int pId) {
// サポーターリストから該当のサポーターが何番目かを取得
// 次のレベルのデータを取得
// サポーターのステータスを書き換える
}
// サポーターは解放済みかどうか
bool isAvailableSupporter(int pId) {
return true;
}
void saveData() {
PlayerPrefs.SetInt (Const.PREF_USER_LEVEL, _userData.level);
PlayerPrefs.SetInt (Const.PREF_KILL_COUNT, killCount);
PlayerPrefs.SetInt (Const.PREF_USER_COIN, _playerCtrl.getCoin ());
PlayerPrefs.SetInt (Const.PREF_ENMEY_NUM, _enemyCtrl.getEnemyNum());
PlayerPrefs.SetInt (Const.PREF_USER_MAX_COMBO, maxCombo);
}
public void resetSaveData() {
_userData.setUserData (1);
_nextUserData.setUserData (2);
showUserData ();
killCount = 0;
_killCountLabel.text = "KILL COUNT: " + killCount;
_playerCtrl.setCoin (0);
_enemyCtrl.resetEnemyMAXHP ();
_enemyCtrl.initEnemyFromDB (killCount);
_supporterCtrl.resetSupporter();
PlayerPrefs.SetInt (Const.PREF_USER_LEVEL, 1);
PlayerPrefs.SetInt (Const.PREF_KILL_COUNT, killCount);
PlayerPrefs.SetInt (Const.PREF_USER_COIN, _playerCtrl.getCoin ());
PlayerPrefs.SetInt (Const.PREF_ENMEY_NUM, 0);
}
void FixedUpdate() {
if (gameMode != GAME_MODE.PLAY &&
gameMode != GAME_MODE.PAUSE) {
return;
}
// BPMに合わせて時間を動かす
_timeCtrl.setLoopTimeFromBPM (_BPM);
_timeCtrl.clockTime ();
}
// Update is called once per frame
void Update ()
{
if (gameMode == GAME_MODE.PLAY ||
gameMode == GAME_MODE.PAUSE) {
UpdatePlay();
}
}
void UpdatePlay() {
// 表示判定
if (display_mode == DISPLAY_MODE.CIRCLE) {
stretchCircle ();
} else {
moveCube ();
}
if (gameMode == GAME_MODE.PLAY)
{
// タップを判定する
if (Input.GetMouseButtonDown(0) ||
Input.GetKeyDown(KeyCode.Space))
{
Vector2 _touchPosition = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);
if (isTapCorrectArea(_touchPosition))
{
tap();
}
}
//#elif UNITY_IOS || UNITY_ANDROID
// if (Input.touchCount > 0) {
// Touch singleTouch = Input.GetTouch (0);
// if (singleTouch.phase == TouchPhase.Began) {
// Vector2 _touchPosition = new Vector2(singleTouch.position.x, Screen.height - singleTouch.position.y);
// if (isTapCorrectArea(_touchPosition)) {
// tap ();
// }
// }
// }
//#endif
}
getSupporterValues ();
showFPSDisplay ();
}
#region SETTINGS
public void setMode(DISPLAY_MODE pMode) {
display_mode = pMode;
}
public void setModeCircle() {
display_mode = DISPLAY_MODE.CIRCLE;
enableCircle (true);
enableCube (false);
}
public void setModeBar() {
display_mode = DISPLAY_MODE.CUBE;
enableCube (true);
enableCircle (false);
}
void enableCube(bool pFlg) {
_cubeMoving.SetActive (pFlg);
_cubeTarget.SetActive (pFlg);
}
void enableCircle(bool pFlg) {
_circle.SetActive (pFlg);
_targetCircle.SetActive (pFlg);
}
public void openSettings() {
gameMode = GAME_MODE.DEBUG;
debugControls.SetActive (true);
debugBPM.value = _BPM;
debugGood.value = DIF_VAL_GOOD;
debugGreat.value = DIF_VAL_GREAT;
debugExcellent.value= DIF_VAL_EXCELLENT;
debugPerfect.value = DIF_VAL_PERFECT;
}
public void completeSettings() {
_BPM = debugBPM.value;
DIF_VAL_GOOD = debugGood.value;
DIF_VAL_GREAT = debugGreat.value;
DIF_VAL_EXCELLENT = debugExcellent.value;
DIF_VAL_PERFECT = debugPerfect.value;
debugControls.SetActive(false);
gameMode = GAME_MODE.PLAY;
}
// デバッグ用にFPSを出力
void showFPSDisplay() {
float fps = 1f / Time.deltaTime;
fpsDisplay.text = fps.ToString ("F2");
}
#endregion
TapCtrl _tapCtrl;
// タップした位置が所定の範囲内かを判定する
bool isTapCorrectArea(Vector2 pTouchPosition) {
Rect rect = _tapCtrl.getTapArea();
if (pTouchPosition.x >= rect.xMin &&
pTouchPosition.x < rect.xMax &&
pTouchPosition.y >= rect.yMin &&
pTouchPosition.y < rect.yMax)
{
return true;
}
return false;
}
void tap() {
// タップのタイミングが、Timerとどれくらいずれているかを検証。近さに応じてBAD/GOOD/GREAT/EXCELLENTの4段階評価を表示する
// タップしたときのTimerの値を取得し、近さに応じて評価を出す
TIMING tapResult = _timeCtrl.getTapResult();
// コンボかどうかをカウントする
if (tapResult == TIMING.EXCELLENT || tapResult == TIMING.GREAT) {
comboCount++;
} else {
// コンボ失敗なら、最大コンボかチェック
checkMaxCombo();
comboCount = 0;
}
// タップ演出
if (display_mode == DISPLAY_MODE.CIRCLE) {
iTween.ScaleFrom (_targetCircle, Vector3.one * TARGET_CIRCLE_SCALE_AMOUNT, SCALE_TIME);
} else {
iTween.ScaleFrom (_cubeTarget, _cubeTargetScale * TARGET_CUBE_SCALE_AMOUNT, SCALE_TIME);
}
// 評価による処理振り分け
showTapResult(tapResult);
}
void checkMaxCombo() {
if (comboCount >= maxCombo) {
// 最大コンボ数を更新
maxCombo = comboCount;
showUserData ();
saveData();
}
}
void showTapResult(TIMING pTapResult) {
string resultText = "";
int seNumber = Const.SE_HAT_BAD;
int addScore = 0;
float asc = 0.0f; // コンボ加算用float
// 遅すぎか早すぎか判定し、早すぎなら << 遅すぎなら >> と表示する。
bool isSlow = (_timeCtrl.getLastDifference () > 0);
string slowSign = "<<";
if (isSlow) {
slowSign = ">>";
}
switch (pTapResult) {
case TIMING.PERFECT:
resultText = "PERFECT!";
asc = getComboBonus (SCORE_VAL_PERFECT);
seNumber = Const.SE_HAT_EXCELLENT;
break;
case TIMING.EXCELLENT:
resultText = "EXCELLENT!";
asc = getComboBonus (SCORE_VAL_PERFECT);
seNumber = Const.SE_HAT_EXCELLENT;
break;
case TIMING.GREAT:
resultText = "GREAT!";
asc = getComboBonus (SCORE_VAL_PERFECT);
seNumber = Const.SE_HAT_GREAT;
break;
case TIMING.GOOD:
resultText = "GOOD!";
addScore += SCORE_VAL_GOOD;
seNumber = Const.SE_HAT_GOOD;
break;
case TIMING.BAD:
resultText = "BAD!";
seNumber = Const.SE_HAT_BAD;
addScore += SCORE_VAL_BAD;
break;
}
//評価によって音を変えて鳴らす
_audioCtrl.PlaySE(seNumber);
// 表記テキストの装飾
if (isSlow) {
resultText = resultText + slowSign;
} else {
resultText = slowSign + resultText;
}
// GREAT以上であればコンボ表記・エフェクト発生・コンボボーナス
if (pTapResult == TIMING.PERFECT || pTapResult == TIMING.EXCELLENT || pTapResult == TIMING.GREAT) {
resultText += "\n" + comboCount + " COMBO!";
_effectCtrl.showEffect ();
addScore += Mathf.RoundToInt (asc);
}
// スコア加算
score += addScore;
_tapResultText.text = resultText;
_ScoreText.text = "S:"+score;
iTween.ScaleFrom (_tapResultText.gameObject, Vector3.one * RESULT_TEXT_SCALE_AMOUNT, SCALE_TIME);
// プレイヤーのPPTの値から敵に与えるダメージを算出
float point = (float)addScore / 100 * _playerCtrl.getPPT ();
sendPointToEnemy (point);
}
float getComboBonus(int pResultValue) {
float addPercentage = (100 + (float)comboCount) / 100; // 1コンボあたり1%スコアがプラスされる
return (float)pResultValue * addPercentage;
}
void sendPointToEnemy(float pPoint, bool pIsPlayer = true) {
_enemyCtrl.hitPoint (pPoint);
// サポーター攻撃であればダメージ表示は行わない
if (!pIsPlayer) {
return;
}
_damageText.text = ""+Mathf.RoundToInt(pPoint);
_damageText.GetComponent<AutoFade> ().resetColor ();
iTween.ScaleFrom (_damageText.gameObject, Vector3.one * RESULT_TEXT_SCALE_AMOUNT, SCALE_TIME);
}
public void killEnemy() {
killCount++;
_killCountLabel.text = "KILL COUNT: " + killCount;
_playerCtrl.addCoin (_enemyCtrl.getDropCoinValue());
_enemyCtrl.spawnEnemy (killCount);
// 敵撃退音
PlaySE (Const.SE_KILL_ENEMY);
saveData ();
}
// サポーターのポイントを取得し、反映させる
void getSupporterValues() {
sendPointToEnemy (_supporterCtrl.getSupporterValues (), false);
}
#region Move Meters
// x秒ごとに円が収縮を繰り返す
void stretchCircle() {
float rate = _timeCtrl.getGaugeRate ();
// 大きい→小さい と動くようにrateを逆にする
_circle.transform.localScale = _movingCircleScale * (rate - 1.0f);
}
// 数秒ごとにバーが左から右い流れていく
void moveCube() {
float rate = _timeCtrl.getRate();
// 0 → 1を -3 → 3に変換し、x座標に代入
rate *= CUBE_WIDTH * 2;
rate -= CUBE_WIDTH;
Vector3 pos = _cubeMovingPosition;
pos.x = rate;
_cubeMoving.transform.position = pos;
}
#endregion
#region Audio
public void PlaySE(int pSeNumber) {
_audioCtrl.PlaySE (pSeNumber);
}
// Interface
int beatNum = 0;
public bool isPlaySnare() {
if (comboCount >= 4) {
if (beatNum == 1) {
beatNum = 0;
return true;
}
beatNum++;
}
return false;
}
#endregion
}<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SupporterCtrl : MonoBehaviour {
public GameCtrl _gameCtrl;
public ScrollCtrl _scrollCtrl;
List<SupporterMaster> _supporterMasterList = new List<SupporterMaster>();
List<SupporterLevelMaster> _supporterLevelMasterList = new List<SupporterLevelMaster>();
// Supporters
List<Supporter> supportersList;
// Level Cost Table
int[] supporterNextLevelCoin;
int[] supportersData;
// Use this for initialization
void Start () {
_gameCtrl = this.transform.parent.GetComponent<GameCtrl> ();
}
public void init() {
initSupporterMasterData ();
initUserSupporterData ();
}
// Supporter関連のマスターデータ取得
void initSupporterMasterData()
{
var entityMasterTable = new SupporterMasterTable ();
entityMasterTable.Load ();
foreach (var entityMaster in entityMasterTable.All) {
_supporterMasterList.Add (entityMaster);
}
var entityLevelMasterTable = new SupporterLevelMasterTable ();
entityLevelMasterTable.Load ();
foreach (var entityMaster in entityLevelMasterTable.All) {
_supporterLevelMasterList.Add (entityMaster);
}
}
// ユーザーデータからSupporterクラスを生成・管理
void initUserSupporterData()
{
// ユーザーのテーブル構成
// ID / LV ... LV.0 = 未開放
// コスト情報を取得
// サポーターのマスターデータを取得
int availableSupportersNumber = _supporterMasterList.Count;
// 基本のコストを取得
supporterNextLevelCoin = new int[availableSupportersNumber];
for (int i = 0; i < availableSupportersNumber; i++) {
float value = (float)_supporterMasterList [i].base_coin * _supporterLevelMasterList[0].multiple_rate_coin;
supporterNextLevelCoin [i] = Mathf.FloorToInt (value);
}
supportersList = new List<Supporter>();
// 所持サポーター情報を取得
supportersData = PlayerPrefsX.GetIntArray(Const.PREF_SUPPORTER_LEVELS);
if (supportersData.Length <= 0) { // PlayerPrefsが空の場合
supportersData = new int[availableSupportersNumber];
for (int i = 0; i < availableSupportersNumber; i++) {
supportersData [i] = 0;
}
PlayerPrefsX.SetIntArray (Const.PREF_SUPPORTER_LEVELS);
}
for (int i = 0; i < supportersData.Length; i++) {
Debug.Log ("SP DATA:"+supportersData [i]);
}
for (int i = 0; i < supportersData.Length; i++) {
// クラスを生成
int aLv;
// 解放済みサポーターか判定
bool aIsReleased = (supportersData [i] > 0) ? true : false;
if (aIsReleased) {
aLv = supportersData [i];
} else {
aLv = 0;
}
Supporter sp = getSupporterClass (i+1, aLv);
Debug.Log ("SP ID:" + sp.id + " NAME:"+sp.name+"PPS:"+sp.pointPerSecond);
supportersList.Add (sp);
setPrefab(sp.id);
if (aIsReleased)
{
// 解放済みサポーターのコストを更新する
supporterNextLevelCoin[i] = sp.nextLevelCoin;
}
else {
_supporterObjects[sp.id - 1].SetActive(false);
}
}
for (int i = 0; i < supportersData.Length; i++) {
SupporterMaster spMaster = _supporterMasterList [i];
Debug.Log ("ID: " + spMaster.id + " NAME: "+spMaster.name
+" LEVEL: "+supportersData[i]+" NEXT_COIN: "+supporterNextLevelCoin[i]);
}
_scrollCtrl.InitSupportersList (supportersList);
}
// idとレベルから、ppa、next_level_coinを算出し、supporterクラスを生成
Supporter getSupporterClass(int pId, int pLevel)
{
Supporter sp = new Supporter ();
string name = _supporterMasterList [pId - 1].name;
float basePpa = _supporterMasterList [pId - 1].base_ppa;
float atkInt = _supporterMasterList [pId - 1].atk_interval;
int baseCoin = _supporterMasterList [pId - 1].base_coin;
string imagePath = "images/supporters/" + _supporterMasterList [pId - 1].image_path;
Sprite image = Resources.Load<Sprite>(imagePath) as Sprite;
if (image != null) {
Debug.Log ("imagePath: " + imagePath + " successfully loaded! " +image);
}
string growthType = _supporterLevelMasterList [pId - 1].growth_type;
float multipleRatePpa = 1;
float multipleRateCoin = 1;
if (pLevel >= 1) {
for (int i = 0; i < _supporterLevelMasterList.Count; i++) {
if (_supporterLevelMasterList [i].growth_type == growthType &&
_supporterLevelMasterList [i].level == pLevel) {
multipleRatePpa = _supporterLevelMasterList [i].multiple_rate_ppa;
multipleRateCoin = _supporterLevelMasterList [i].multiple_rate_coin;
}
}
}
sp.id = pId;
sp.level = pLevel;
sp.name = name;
sp.pointPerAttack = basePpa * multipleRatePpa;
sp.attackInterval = atkInt;
sp.pointPerSecond = sp.getPps (sp.attackInterval, sp.pointPerAttack);
sp.nextLevelCoin = Mathf.FloorToInt((float)baseCoin * multipleRateCoin);
sp.image = image;
return sp;
}
// サポーターのポイントを取得し、反映させる
public float getSupporterValues() {
if (supportersList.Count <= 0) {
return 0;
}
float supportersPoint = 0.0f;
for (int i = 0; i < supportersList.Count; i++) {
supportersPoint += supportersList [i].getPointUpdate ();
}
return supportersPoint;
}
public int getSupporterCost(int pId) {
return supporterNextLevelCoin[pId - 1];
}
// 現在のLVに+1
public bool raiseSupporterLevel(int pId) {
Debug.Log("raiseSupporterLevel.pId:" + pId);
if (pId == 0)
{
return false;
}
// LV UP後のデータを取得
int lvNow = supportersList[pId - 1].level;
if (setSupporterLevel(pId, lvNow + 1))
{
return true;
}
return false;
}
// LVを指定
public bool setSupporterLevel(int pId, int pLevel) {
Supporter sp = getSupporterClass(pId, pLevel);
supportersList[pId - 1] = sp;
// 次のLVまでのコストを取得
supporterNextLevelCoin[pId - 1] = sp.nextLevelCoin;
// PlayerPrefsにセーブ
supportersData[pId - 1] = sp.level;
saveSupporterData();
// 表記を更新
_scrollCtrl.updateSupportersInfo(sp);
// Prefabを出現
_supporterObjects[pId - 1].SetActive(true);
return true;
}
void saveSupporterData() {
PlayerPrefsX.SetIntArray(Const.PREF_SUPPORTER_LEVELS, supportersData);
}
#region obj
public List<Vector2> _posList = new List<Vector2>();
public List<GameObject> _supporterPrefabs = new List<GameObject>();
List<GameObject> _supporterObjects = new List<GameObject>();
public GameObject Heroes;
void setPrefab(int pSupporterId) {
int spCount = _supporterObjects.Count;
Vector3 pos = setPosition((int)_posList[spCount+1].x, (int)_posList[spCount+1].y);
GameObject go = Instantiate(_supporterPrefabs[pSupporterId - 1],
_supporterPrefabs[pSupporterId - 1].transform.localPosition,
_supporterPrefabs[pSupporterId - 1].transform.localRotation) as GameObject;
go.transform.localScale = go.transform.localScale * 5;
go.transform.parent = Heroes.transform;
go.transform.localPosition = pos;
go.name = "Supporter_" + pSupporterId;
_supporterObjects.Add(go);
}
Vector3 setPosition(int xValue, int zValue) {
float frontX = 1;
if ((zValue % 2) == 0)
{
frontX = 2;
}
float frontZ = -1;
return new Vector3(frontX * (float)xValue, 0, frontZ * (float)zValue - 3);
}
#endregion
#region debug
public void resetSupporter() {
for (int i = 0; i < supportersData.Length; i++){
supportersData[i] = 0;
setSupporterLevel(i + 1, 0);
}
saveSupporterData();
}
#endregion
}<file_sep>using UnityEngine;
using System.Collections;
public class TapCtrl : MonoBehaviour {
float screenWidth;
float screenHeight;
public float widthRate = 0.99f;
public float heightRate = 0.6f;
float x, y, w, h;
Rect rect;
void Awake() {
setRect();
}
void Update() {
rect = new Rect();
setRect();
}
void setRect() {
w = Screen.width * widthRate;
h = Screen.height * heightRate;
x = (Screen.width - w) / 2;
y = (Screen.height - h) / 2;
rect.x = x;
rect.y = y;
rect.width = w;
rect.height = h;
}
public Rect getTapArea() {
return rect;
}
//void OnGUI()
//{
// GUI.Box(rect, "");
//}
}
<file_sep>using UnityEngine;
using System.Collections;
public class SupporterLevelMasterTable : MasterTableBase<SupporterLevelMaster>{
public void Load() {
Load(convertClassToFilePath (this.GetType ().Name));
}
}
public class SupporterLevelMaster : MasterBase {
public string id { get; private set; }
public int level { get; private set; }
public string growth_type { get; private set; }
public float multiple_rate_ppa { get; private set; }
public float multiple_rate_coin { get; private set; }
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class SettingCtrl : MonoBehaviour {
public Text _label;
public Slider _slider;
string _labelName;
void Start() {
_slider = this.gameObject.GetComponent<Slider> ();
_labelName = this.gameObject.name;
}
// Update is called once per frame
void Update () {
_label.text = _labelName + ":" + _slider.value;
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class Supporter {
public int id; // サポーターID
public string name; // サポーター名
public int level; //現在のレベル
public float pointPerSecond; // 現在の1秒あたりポイント
public int nextLevelCoin; // 次のレベルに必要なコイン
public Sprite image; // 画像
public float attackInterval; // pointPerSecondを元に何秒に1回攻撃するか
public float pointPerAttack; // 1回の攻撃につき、何ポイントダメージを与えるか
public void levelUp(int pAddLevel) {
level += pAddLevel;
}
public Supporter() {
//
}
public void initSupporter(int pId, int pLevel) {
id = pId;
name = getSupporterName (pId);
level = pLevel;
attackInterval = 1.0f;
pointPerAttack = 10;
pointPerSecond = getPps (attackInterval, pointPerAttack);
nextLevelCoin = 2000;
}
string getSupporterName(int pId) {
string result = "Sample Name";
return result;
}
public float getPps(float pTime, float pPPA) {
return pPPA / pTime;
}
float timer;
public float getPointUpdate() {
// Updateごとに呼び出されAttackInterval秒ごとにPointPerAttackの値を返す
timer += Time.deltaTime;
if (timer >= attackInterval) {
float amari = timer - attackInterval;
timer = amari;
// ATTACK
return pointPerAttack;
}
return 0f;
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class EnemyCtrl : MonoBehaviour {
GameCtrl _gameCtrl;
public HpCtrl _hpCtrl;
float MAX_HP;
float hp;
int dropCoin;
string imagePath;
Vector3 appear_position = new Vector3(0, -1, 1);
Vector3 standby_position = new Vector3(0, -1, 10);
public GameObject _enemies;
public GameObject[] _enemiesArray;
int enemyNum = 0;
List<EnemyMaster> _enemyMasterList = new List<EnemyMaster> ();
List<EnemyLevelMaster> _enemyLevelMasterList = new List<EnemyLevelMaster>();
public int getMaxLevel() {return _enemyLevelMasterList.Count;}
void Start() {
_gameCtrl = this.transform.parent.GetComponent<GameCtrl> ();
initEnemyData ();
initEnemiesArray ();
}
void initEnemyData() {
var enemyMasterTable = new EnemyMasterTable ();
enemyMasterTable.Load ();
foreach (var enemyMaster in enemyMasterTable.All) {
_enemyMasterList.Add (enemyMaster);
}
var enemyLevelMasterTable = new EnemyLevelMasterTable ();
enemyLevelMasterTable.Load ();
foreach (var enemyMaster in enemyLevelMasterTable.All) {
_enemyLevelMasterList.Add (enemyMaster);
}
}
void initEnemiesArray() {
int enemyNumber = _enemies.transform.childCount;
_enemiesArray = new GameObject[enemyNumber];
for (int i = 0; i < enemyNumber; i++) {
_enemiesArray [i] = _enemies.transform.GetChild (i).gameObject;
}
}
public void hitPoint(float pPoint) {
hp -= pPoint;
if (hp <= 0) {
_gameCtrl.killEnemy ();
}
_hpCtrl.setValue (hp);
}
public void spawnEnemy(int pKillCount) {
initEnemyFromDB (pKillCount);
}
public void resetEnemyMAXHP() {
hp = MAX_HP;
}
public void initEnemyFromDB(int pKillCount)
{
// 敵の種類とレベルを取得
int lv = pKillCount / _enemyMasterList.Count;
if (lv <= 0) {
lv = 1;
}
if (lv >= getMaxLevel ()) {
lv = getMaxLevel();
}
int startId = pKillCount % 3;
enemyNum = startId;
int hpBase = _enemyMasterList [startId].base_hp;
float hpLvRate = _enemyLevelMasterList [lv - 1].multiple_rate;
MAX_HP = (float)hpBase * hpLvRate;
hp = MAX_HP;
_hpCtrl.initHp (hp);
_hpCtrl.setValue (hp);
dropCoin = (int) ((float)_enemyMasterList[startId].drop_coin * _enemyLevelMasterList [lv - 1].level);
//imagePath = _enemyMasterList [startId].image_path;
//Debug.Log ("id:" + startId + " lv:" + lv + " hpBase:" + hpBase + " hpLvRate:" + hpLvRate + " hp:" + hp+" drop_coin:"+dropCoin+" image_path:"+imagePath);
//Sprite sp = Resources.Load<Sprite> (imagePath);
for (int i = 0; i < _enemiesArray.Length; i++) {
if (i == enemyNum) {
iTween.MoveTo(_enemiesArray[i], iTween.Hash("position", appear_position, "time", 0.2f, "islocal", true));
} else {
_enemiesArray[i].transform.localPosition = standby_position;
//iTween.MoveTo(_enemiesArray[i], appear_position, 0.2f);
}
}
}
public int getEnemyNum() {
return enemyNum;
}
public int getDropCoinValue() {
return dropCoin;
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.IO;
public class CSVLoader{
TextAsset _data;
public void readData(string pFileName) {
_data = Resources.Load (pFileName) as TextAsset;
StringReader sr = new StringReader (_data.text);
while (sr.Peek() > -1) {
string line = sr.ReadLine ();
string[] values = line.Split(',');
string str = "";
for (int i = 0; i < values.Length; i++) {
str += " "+values [i];
}
Debug.Log (str);
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class SupporterPanelCtrl : MonoBehaviour {
public Text _name;
public Text _pps;
public Text _nextCoin;
public Button _nextButton;
public Image _image;
void Start() {
_nextCoin = _nextButton.GetComponentInChildren<Text>();
}
public void init(Supporter pSupporter) {
setTexts(pSupporter);
// 画像を当てる
for (int j = 0; j < this.transform.childCount; j++)
{
if (this.transform.GetChild(j).name == "Image")
{
Image img = this.transform.GetChild(j).GetComponent<Image>();
img.sprite = pSupporter.image;
}
}
}
void setTexts(Supporter pSupporter) {
Text[] text = this.GetComponentsInChildren<Text>();
for (int j = 0; j < text.Length; j++)
{
if (text[j].name == "Name")
{ // Name
text[j].text = pSupporter.name + " Lv." + pSupporter.level;
}
else if (text[j].name == "PPS")
{ // PPS
text[j].text = pSupporter.pointPerSecond.ToString("F0") + " PPS";
}
else { // Button
text[j].text = pSupporter.nextLevelCoin + " COIN";
}
}
}
// Update is called once per frame
public void setInformation(Supporter pSupporter) {
setTexts(pSupporter);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class EnemyLevelMasterTable : MasterTableBase<EnemyLevelMaster>
{
public void Load() {
Load(convertClassToFilePath (this.GetType ().Name));
}
}
public class EnemyLevelMaster : MasterBase
{
public string id { get; private set; }
public int level { get; private set;}
public float multiple_rate{ get; private set; }
}
<file_sep>using UnityEngine;
using System.Collections;
public class PlayerCtrl : MonoBehaviour {
int coin;
[SerializeField]
float ppt; // point per tap
public TextMesh _pptLabel;
public TextMesh _coinLabel;
public void setUserData(UserData pUser) {
ppt = (float)pUser.pointPerTap;
}
void setPPT(float pPPT) {
ppt = pPPT;
_pptLabel.text = "PointPerTap:"+ppt;
}
public float getPPT() {
return ppt;
}
public int getCoin() {
return coin;
}
public void addCoin(int pCoin) {
coin += pCoin;
_coinLabel.text = "C:"+coin;
}
public void useCoin(int pCoin) {
coin -= pCoin;
_coinLabel.text = "C:" + coin;
}
public void setCoin(int pCoin) {
coin = pCoin;
_coinLabel.text = "C:" + coin;
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class SupporterMasterTable : MasterTableBase<SupporterMaster> {
public void Load() {
Load(convertClassToFilePath (this.GetType ().Name));
}
}
public class SupporterMaster : MasterBase
{
public string id { get; private set; }
public string name { get; private set; }
public float atk_interval { get; private set; }
public int base_ppa { get; private set; }
public string image_path { get; private set; }
public string growth_type { get; private set; }
public int base_coin {get; private set; }
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class HpCtrl : MonoBehaviour {
public Slider _hpBar;
public Text _hpText;
float maxHp;
float nowHp;
public void initHp(float pMaxHp) {
maxHp = pMaxHp;
}
public void setValue(float pNowHp) {
nowHp = pNowHp;
float rate = nowHp / maxHp;
_hpText.text = nowHp+"/"+maxHp;
_hpBar.value = rate;
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class TimeCtrl : MonoBehaviour {
GameCtrl _gameCtrl;
[SerializeField]
float loopTime;
float timer;
float rate;
public void Init(GameCtrl pGameCtrl) {
_gameCtrl = pGameCtrl;
}
// BPMの設定に合わせて1周スピードを変える
public void setLoopTimeFromBPM(float pBpm) {
// BPM=Beat Per Minute 1分間の拍の数
// BPM120 → 120 beat / 60 sec → 2 beat / 1 sec
// 1sec/2beat = loop_time
// loop_timeは0.5f
float lt = pBpm / 60;
lt = 1 / lt;
loopTime = lt;
}
public float getGaugeRate() {
timer += Time.deltaTime;
if (timer >= loopTime) {
float amari = timer - loopTime;
timer = 0;
timer += amari;
_gameCtrl.PlaySE(Const.SE_KICK);
}
rate = timer / loopTime;
return rate;
}
float lastDifference;
// タップしたタイミングとターゲットタイミングとの差に応じて評価を返す
public GameCtrl.TIMING getTapResult() {
float targetRate = 0.5f;
GameCtrl.TIMING result = GameCtrl.TIMING.BAD;
// 差異を記録しておき、タップのタイミングが遅いか早いかを算出する
lastDifference = rate - targetRate;
// 差異を絶対値にし、判定する
float difference = Mathf.Abs (lastDifference);
if (difference <= _gameCtrl.DIF_VAL_EXCELLENT) {
result = GameCtrl.TIMING.EXCELLENT;
} else if (difference <= _gameCtrl.DIF_VAL_GREAT) {
result = GameCtrl.TIMING.GREAT;
} else if (difference <= _gameCtrl.DIF_VAL_GOOD) {
result = GameCtrl.TIMING.GOOD;
} else {
result = GameCtrl.TIMING.BAD;
}
return result;
}
// 時間を計測するロジック
// BPMから一拍の時間を算出
// 取得時間を計測
public void clockTime() {
if (targetTime <= Time.realtimeSinceStartup) { //
float leftOver = Time.realtimeSinceStartup - targetTime;
initBeat(leftOver);
rate = leftOver / loopTime;
}
float now = Time.realtimeSinceStartup - startTime;
rate = now / loopTime;
}
public float getRate() {
return rate;
}
public float getRateFromTime() {
if (targetTime <= Time.realtimeSinceStartup) { //
float leftOver = Time.realtimeSinceStartup - targetTime;
initBeat(leftOver);
return leftOver / loopTime;
}
float now = Time.realtimeSinceStartup - startTime;
rate = now / loopTime;
return rate;
}
float startTime;
float targetTime;
public void initBeat(float pLeftTime = 0) {
startTime = Time.realtimeSinceStartup + pLeftTime;
targetTime = startTime + loopTime;
_gameCtrl.PlaySE (Const.SE_KICK);
if (_gameCtrl.isPlaySnare ()) {
_gameCtrl.PlaySE (Const.SE_SNARE);
}
}
public float getLastDifference() {
return lastDifference;
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class UserData {
public int level; //現在のレベル
public int pointPerTap; // 現在のタップあたりポイント
public int nextLevelCoin; // 次のレベルに必要なコイン
int DEFAULT_PPT = 50;
int DEFAULT_ADD_PPT = 100;
int DEFAULT_COIN = 300;
public UserData(int pLevel = 1) {
setUserData (pLevel);
}
public void setUserData(int pLevel) {
level = pLevel;
pointPerTap = DEFAULT_PPT + DEFAULT_ADD_PPT * pLevel;
nextLevelCoin = DEFAULT_COIN * pLevel;
}
public UserData getUserData(int pLevel) {
return this;
}
// public UserData getNextUser(int pLevel) {
// UserData ud = new UserData ();
// ud = getInitUser (pLevel);
// return ud;
// }
}<file_sep>using UnityEngine;
using System.Collections;
public class Enemy {
public int id;
public string name;
public int level;
public int hp;
public string imagePath;
public int dropCoin;
}
| e989d4b81004f7ef7d45849a24d115c82fb0ab80 | [
"Markdown",
"C#"
] | 24 | Markdown | tsoshiro/rhythm | 7f33338ad71adb27ca28df4ffb9bcaac9e201a37 | e38de7f05e58819d384a44fdcae7a970d4cb3859 |
refs/heads/master | <file_sep>console.log("Arley");<file_sep>import './components/timeline/timeline';2~ <file_sep># PersonalPage
Portafolio
| ab4030c515a9bb94fb96b1367f022fc4d221a077 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | ArleyAV/PersonalPage | 45876c78426474019bbad2b62273ef46002ca0c6 | 9ba89416d8a2ff61578ee8e0683ad92bbdb16f14 |
refs/heads/master | <file_sep>Vagrant.configure("2") do |config|
config.vm.box = "centos/7"
config.vm.network "private_network", ip: "192.168.21.120"
config.vm.network "forwarded_port", guest: 80, host: 8083
config.vm.network "forwarded_port", guest: 443, host: 8447
config.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--memory", "6144"]
vb.customize ["modifyvm", :id, "--cpus", "2"]
end
config.vm.provision "ansible" do |ansible|
ansible.verbose = "vvv"
ansible.playbook = "centos7-vagrant.yml"
end
end
<file_sep>## Useful ansible commands
Run main playbook in local environment
```
ansible-playbook -i local centos7-vagrant.yml
```
| ec322bb55eb8fe955c64b805e3f7525e94a23b2d | [
"Markdown",
"Ruby"
] | 2 | Ruby | juantimonescalona/ansible-gitlab | 9a052bd027c7f93af02dd2dc188db53f79956de6 | 151d046d76f8fdec0db905d44057c594d9a26f57 |
refs/heads/master | <repo_name>karlbohlmark/swm-node<file_sep>/app.js
(function init(){
pos = 0;
boxWidth = 900;
var move = function(op){
var transform = 'translate({0}px, 0px)'.replace('{0}', pos = op(pos, boxWidth));
console.log(transform);
document.getElementById('container').style['-webkit-transform'] = transform;
}
document.addEventListener('keydown', function(e){
switch(e.keyCode){
case 39:
move(function(pos, width){ return pos -width});
break;
case 37:
move(function(pos, width){return pos + width});
}
});
}()); | 9552acb4905fa57c66704d01c6c60e18815348f0 | [
"JavaScript"
] | 1 | JavaScript | karlbohlmark/swm-node | 0bb230565405b077652151f0cef688c427e1e429 | b4845385afadc865f621d88afdd3d7288a3e6831 |
refs/heads/master | <file_sep>matplotlib
sphinxcontrib.bibtex
numpydoc
pydata_sphinx_theme
nbsphinx
ipython
myst-parser
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import collections
import math
import operator
import geopandas as gpd
import libpysal
import numpy as np
import pandas as pd
import pygeos
import shapely
from shapely.geometry import Point
from tqdm import tqdm
from .shape import CircularCompactness
__all__ = [
"preprocess",
"network_false_nodes",
"remove_false_nodes",
"snap_street_network_edge",
"CheckTessellationInput",
"close_gaps",
"extend_lines",
]
def preprocess(
buildings, size=30, compactness=0.2, islands=True, loops=2, verbose=True
):
"""
Preprocesses building geometry to eliminate additional structures being single
features.
Certain data providers (e.g. Ordnance Survey in GB) do not provide building geometry
as one feature, but divided into different features depending their level (if they
are on ground floor or not - passages, overhangs). Ideally, these features should
share one building ID on which they could be dissolved. If this is not the case,
series of steps needs to be done to minimize errors in morphological analysis.
This script attempts to preprocess such geometry based on several condidions:
If feature area is smaller than set size it will be a) deleted if it does not
touch any other feature; b) will be joined to feature with which it shares the
longest boundary. If feature is fully within other feature, these will be joined.
If feature's circular compactness (:py:class:`momepy.CircularCompactness`)
is < 0.2, it will be joined to feature with which it shares the longest boundary.
Function does multiple loops through.
Parameters
----------
buildings : geopandas.GeoDataFrame
geopandas.GeoDataFrame containing building layer
size : float (default 30)
maximum area of feature to be considered as additional structure. Set to
None if not wanted.
compactness : float (default .2)
if set, function will resolve additional structures identified based on
their circular compactness.
islands : bool (default True)
if True, function will resolve additional structures which are fully within
other structures (share 100% of exterior boundary).
loops : int (default 2)
number of loops
verbose : bool (default True)
if True, shows progress bars in loops and indication of steps
Returns
-------
GeoDataFrame
GeoDataFrame containing preprocessed geometry
"""
blg = buildings.copy()
blg = blg.explode()
blg.reset_index(drop=True, inplace=True)
for loop in range(0, loops):
print("Loop", loop + 1, f"out of {loops}.") if verbose else None
blg.reset_index(inplace=True, drop=True)
blg["mm_uid"] = range(len(blg))
sw = libpysal.weights.contiguity.Rook.from_dataframe(blg, silence_warnings=True)
blg["neighbors"] = sw.neighbors
blg["neighbors"] = blg["neighbors"].map(sw.neighbors)
blg["n_count"] = blg.apply(lambda row: len(row.neighbors), axis=1)
blg["circu"] = CircularCompactness(blg).series
# idetify those smaller than x with only one neighbor and attaches it to it.
join = {}
delete = []
for row in tqdm(
blg.itertuples(),
total=blg.shape[0],
desc="Identifying changes",
disable=not verbose,
):
if size:
if row.geometry.area < size:
if row.n_count == 1:
uid = blg.iloc[row.neighbors[0]].mm_uid
if uid in join:
existing = join[uid]
existing.append(row.mm_uid)
join[uid] = existing
else:
join[uid] = [row.mm_uid]
elif row.n_count > 1:
shares = {}
for n in row.neighbors:
shares[n] = row.geometry.intersection(
blg.at[n, blg.geometry.name]
).length
maximal = max(shares.items(), key=operator.itemgetter(1))[0]
uid = blg.loc[maximal].mm_uid
if uid in join:
existing = join[uid]
existing.append(row.mm_uid)
join[uid] = existing
else:
join[uid] = [row.mm_uid]
else:
delete.append(row.Index)
if compactness:
if row.circu < compactness:
if row.n_count == 1:
uid = blg.iloc[row.neighbors[0]].mm_uid
if uid in join:
existing = join[uid]
existing.append(row.mm_uid)
join[uid] = existing
else:
join[uid] = [row.mm_uid]
elif row.n_count > 1:
shares = {}
for n in row.neighbors:
shares[n] = row.geometry.intersection(
blg.at[n, blg.geometry.name]
).length
maximal = max(shares.items(), key=operator.itemgetter(1))[0]
uid = blg.loc[maximal].mm_uid
if uid in join:
existing = join[uid]
existing.append(row.mm_uid)
join[uid] = existing
else:
join[uid] = [row.mm_uid]
if islands:
if row.n_count == 1:
shared = row.geometry.intersection(
blg.at[row.neighbors[0], blg.geometry.name]
).length
if shared == row.geometry.exterior.length:
uid = blg.iloc[row.neighbors[0]].mm_uid
if uid in join:
existing = join[uid]
existing.append(row.mm_uid)
join[uid] = existing
else:
join[uid] = [row.mm_uid]
for key in tqdm(
join, total=len(join), desc="Changing geometry", disable=not verbose
):
selection = blg[blg["mm_uid"] == key]
if not selection.empty:
geoms = [selection.iloc[0].geometry]
for j in join[key]:
subset = blg[blg["mm_uid"] == j]
if not subset.empty:
geoms.append(blg[blg["mm_uid"] == j].iloc[0].geometry)
blg.drop(blg[blg["mm_uid"] == j].index[0], inplace=True)
new_geom = shapely.ops.unary_union(geoms)
blg.loc[
blg.loc[blg["mm_uid"] == key].index[0], blg.geometry.name
] = new_geom
blg.drop(delete, inplace=True)
return blg[buildings.columns]
def remove_false_nodes(gdf):
"""
Clean topology of existing LineString geometry by removal of nodes of degree 2.
Parameters
----------
gdf : GeoDataFrame, GeoSeries, array of pygeos geometries
(Multi)LineString data of street network
Returns
-------
gdf : GeoDataFrame, GeoSeries
See also
--------
momepy.extend_lines
momepy.close_gaps
"""
if isinstance(gdf, (gpd.GeoDataFrame, gpd.GeoSeries)):
# explode to avoid MultiLineStrings
# double reset index due to the bug in GeoPandas explode
df = gdf.reset_index(drop=True).explode().reset_index(drop=True)
# get underlying pygeos geometry
geom = df.geometry.values.data
else:
geom = gdf
df = gpd.GeoSeries(gdf)
# extract array of coordinates and number per geometry
coords = pygeos.get_coordinates(geom)
indices = pygeos.get_num_coordinates(geom)
# generate a list of start and end coordinates and create point geometries
edges = [0]
i = 0
for ind in indices:
ix = i + ind
edges.append(ix - 1)
edges.append(ix)
i = ix
edges = edges[:-1]
points = pygeos.points(np.unique(coords[edges], axis=0))
# query LineString geometry to identify points intersecting 2 geometries
tree = pygeos.STRtree(geom)
inp, res = tree.query_bulk(points, predicate="intersects")
unique, counts = np.unique(inp, return_counts=True)
merge = res[np.isin(inp, unique[counts == 2])]
if len(merge) > 0:
# filter duplications and create a dictionary with indication of components to
# be merged together
dups = [item for item, count in collections.Counter(merge).items() if count > 1]
split = np.split(merge, len(merge) / 2)
components = {}
for i, a in enumerate(split):
if a[0] in dups or a[1] in dups:
if a[0] in components.keys():
i = components[a[0]]
elif a[1] in components.keys():
i = components[a[1]]
components[a[0]] = i
components[a[1]] = i
# iterate through components and create new geometries
new = []
for c in set(components.values()):
keys = []
for item in components.items():
if item[1] == c:
keys.append(item[0])
new.append(pygeos.line_merge(pygeos.union_all(geom[keys])))
# remove incorrect geometries and append fixed versions
df = df.drop(merge)
final = gpd.GeoSeries(new).explode().reset_index(drop=True)
if isinstance(gdf, gpd.GeoDataFrame):
return df.append(
gpd.GeoDataFrame({df.geometry.name: final}, geometry=df.geometry.name),
ignore_index=True,
)
return df.append(final, ignore_index=True)
def snap_street_network_edge(
edges,
buildings,
tolerance_street,
tessellation=None,
tolerance_edge=None,
edge=None,
verbose=True,
):
"""
Fix street network before performing :class:`momepy.Blocks`.
Extends unjoined ends of street segments to join with other segments or
tessellation boundary.
Parameters
----------
edges : GeoDataFrame
GeoDataFrame containing street network
buildings : GeoDataFrame
GeoDataFrame containing building footprints
tolerance_street : float
tolerance in snapping to street network (by how much could be street segment
extended).
tessellation : GeoDataFrame (default None)
GeoDataFrame containing morphological tessellation. If edge is not passed it
will be used as edge.
tolerance_edge : float (default None)
tolerance in snapping to edge of tessellated area (by how much could be street
segment extended).
edge : Polygon
edge of area covered by morphological tessellation (same as ``limit`` in
:py:class:`momepy.Tessellation`)
verbose : bool (default True)
if True, shows progress bars in loops and indication of steps
Returns
-------
GeoDataFrame
GeoDataFrame of extended street network.
"""
import warnings
warnings.warn(
"snap_street_network_edge() is deprecated and will be removed in momepy 0.5.0. "
"Use extend_lines() instead.",
FutureWarning,
)
df = extend_lines(edges, tolerance_street, barrier=buildings)
if edge is None and tessellation is not None:
edge = tessellation.unary_union.boundary
if edge is not None:
df = extend_lines(
df, tolerance_edge, barrier=buildings, target=gpd.GeoSeries([edge])
)
return df
class CheckTessellationInput:
"""
Check input data for :class:`Tessellation` for potential errors.
:class:`Tessellation` requires data of relatively high level of precision and there
are three particular patterns causing issues.\n
1. Features will collapse into empty polygon - these do not have tessellation
cell in the end.\n
2. Features will split into MultiPolygon - at some cases, features with narrow links
between parts split into two during 'shrinking'. In most cases that is not an issue
and resulting tessellation is correct anyway, but sometimes this result in a cell
being MultiPolygon, which is not correct.\n
3. Overlapping features - features which overlap even after 'shrinking' cause
invalid tessellation geometry.\n
:class:`CheckTessellationInput` will check for all of these. Overlapping features
have to be fixed prior Tessellation. Features which will split will cause issues
only sometimes, so
should be checked and fixed if necessary. Features which will collapse could
be ignored, but they will have to excluded from next steps of
tessellation-based analysis.
Parameters
----------
gdf : GeoDataFrame or GeoSeries
GeoDataFrame containing objects to be used as ``gdf`` in :class:`Tessellation`
shrink : float (default 0.4)
distance for negative buffer
collapse : bool (default True)
check for features which would collapse to empty polygon
split : bool (default True)
check for features which would split into Multi-type
overlap : bool (default True)
check for overlapping features (after negative buffer)
Attributes
----------
collapse : GeoDataFrame or GeoSeries
features which would collapse to empty polygon
split : GeoDataFrame or GeoSeries
features which would split into Multi-type
overlap : GeoDataFrame or GeoSeries
overlapping features (after negative buffer)
Examples
--------
>>> check = CheckTessellationData(df)
Collapsed features : 3157
Split features : 519
Overlapping features: 22
"""
import warnings
warnings.filterwarnings("ignore", "GeoSeries.isna", UserWarning)
def __init__(self, gdf, shrink=0.4, collapse=True, split=True, overlap=True):
data = gdf[~gdf.is_empty]
if split:
types = data.type
if shrink != 0:
shrink = data.buffer(-shrink)
else:
shrink = data
if collapse:
emptycheck = shrink.is_empty
self.collapse = gdf[emptycheck]
collapsed = len(self.collapse)
else:
collapsed = "NA"
if split:
type_check = shrink.type != types
self.split = gdf[type_check]
split_count = len(self.split)
else:
split_count = "NA"
if overlap:
shrink = shrink.reset_index(drop=True)
shrink = shrink[~(shrink.is_empty | shrink.geometry.isna())]
sindex = shrink.sindex
hits = shrink.bounds.apply(
lambda row: list(sindex.intersection(row)), axis=1
)
od_matrix = pd.DataFrame(
{
"origin": np.repeat(hits.index, hits.apply(len)),
"dest": np.concatenate(hits.values),
}
)
od_matrix = od_matrix[od_matrix.origin != od_matrix.dest]
duplicated = pd.DataFrame(np.sort(od_matrix, axis=1)).duplicated()
od_matrix = od_matrix.reset_index(drop=True)[~duplicated]
od_matrix = od_matrix.join(
shrink.geometry.rename("o_geom"), on="origin"
).join(shrink.geometry.rename("d_geom"), on="dest")
intersection = od_matrix.o_geom.values.intersection(od_matrix.d_geom.values)
type_filter = gpd.GeoSeries(intersection).type == "Polygon"
empty_filter = intersection.is_empty
overlapping = od_matrix.reset_index(drop=True)[empty_filter ^ type_filter]
over_rows = sorted(overlapping.origin.append(overlapping.dest).unique())
self.overlap = gdf.iloc[over_rows]
overlapping_c = len(self.overlap)
else:
overlapping_c = "NA"
print(
"Collapsed features : {0}\n"
"Split features : {1}\n"
"Overlapping features: {2}".format(collapsed, split_count, overlapping_c)
)
def network_false_nodes(gdf, tolerance=0.1, precision=3, verbose=True):
"""
Check topology of street network and eliminate nodes of degree 2 by joining
affected edges.
Parameters
----------
gdf : GeoDataFrame, GeoSeries
GeoDataFrame or GeoSeries containing edge representation of street network.
tolerance : float
nodes within a tolerance are seen as identical (floating point precision fix)
precision : int
rounding parameter in estimating uniqueness of two points based on their
coordinates
verbose : bool
if True, shows progress bars in loops
Returns
-------
gdf : GeoDataFrame, GeoSeries
"""
import warnings
warnings.warn(
"network_false_nodes() is deprecated and will be removed in momepy 0.5.0. "
"Use remove_false_nodes() instead.",
FutureWarning,
)
if not isinstance(gdf, (gpd.GeoSeries, gpd.GeoDataFrame)):
raise TypeError(
"'gdf' should be GeoDataFrame or GeoSeries, got {}".format(type(gdf))
)
# double reset_index due to geopandas issue in explode
streets = gdf.reset_index(drop=True).explode().reset_index(drop=True)
if isinstance(streets, gpd.GeoDataFrame):
series = False
else:
series = True
sindex = streets.sindex
false_xy = []
for line in tqdm(
streets.geometry,
total=streets.shape[0],
desc="Identifying false points",
disable=not verbose,
):
l_coords = list(line.coords)
start = Point(l_coords[0]).buffer(tolerance)
end = Point(l_coords[-1]).buffer(tolerance)
real_first_matches = sindex.query(start, predicate="intersects")
real_second_matches = sindex.query(end, predicate="intersects")
if len(real_first_matches) == 2:
false_xy.append(
(round(l_coords[0][0], precision), round(l_coords[0][1], precision))
)
if len(real_second_matches) == 2:
false_xy.append(
(round(l_coords[-1][0], precision), round(l_coords[-1][1], precision))
)
false_unique = list(set(false_xy))
x, y = zip(*false_unique)
points = gpd.points_from_xy(x, y).buffer(tolerance)
geoms = streets
idx = max(geoms.index) + 1
for x, y, point in tqdm(
zip(x, y, points), desc="Merging segments", total=len(x), disable=not verbose
):
predic = geoms.sindex.query(point, predicate="intersects")
matches = geoms.iloc[predic].geometry
try:
snap = shapely.ops.snap(matches.iloc[0], matches.iloc[1], tolerance,)
multiline = snap.union(matches.iloc[1])
linestring = shapely.ops.linemerge(multiline)
if linestring.type == "LineString":
if series:
geoms.loc[idx] = linestring
else:
geoms.loc[idx, geoms.geometry.name] = linestring
idx += 1
elif linestring.type == "MultiLineString":
for g in linestring.geoms:
if series:
geoms.loc[idx] = g
else:
geoms.loc[idx, geoms.geometry.name] = g
idx += 1
geoms = geoms.drop(matches.index)
except (IndexError, ValueError):
warnings.warn(
"An exception during merging occured. "
f"Lines at point [{x}, {y}] were not merged."
)
streets = geoms.explode().reset_index(drop=True)
if series:
streets.crs = gdf.crs
return streets
return streets
def close_gaps(gdf, tolerance):
"""Close gaps in LineString geometry where it should be contiguous.
Snaps both lines to a centroid of a gap in between.
Parameters
----------
gdf : GeoDataFrame, GeoSeries
GeoDataFrame or GeoSeries containing LineString representation of a network.
tolerance : float
nodes within a tolerance will be snapped together
Returns
-------
GeoSeries
See also
--------
momepy.extend_lines
momepy.remove_false_nodes
"""
geom = gdf.geometry.values.data
coords = pygeos.get_coordinates(geom)
indices = pygeos.get_num_coordinates(geom)
# generate a list of start and end coordinates and create point geometries
edges = [0]
i = 0
for ind in indices:
ix = i + ind
edges.append(ix - 1)
edges.append(ix)
i = ix
edges = edges[:-1]
points = pygeos.points(np.unique(coords[edges], axis=0))
buffered = pygeos.buffer(points, tolerance / 2)
dissolved = pygeos.union_all(buffered)
exploded = [
pygeos.get_geometry(dissolved, i)
for i in range(pygeos.get_num_geometries(dissolved))
]
centroids = pygeos.centroid(exploded)
snapped = pygeos.snap(geom, pygeos.union_all(centroids), tolerance)
return gpd.GeoSeries(snapped, crs=gdf.crs)
def extend_lines(gdf, tolerance, target=None, barrier=None, extension=0):
"""Extends lines from gdf to istelf or target within a set tolerance
Extends unjoined ends of LineString segments to join with other segments or
target. If ``target`` is passed, extend lines to target. Otherwise extend
lines to itself.
If ``barrier`` is passed, each extended line is checked for intersection
with ``barrier``. If they intersect, extended line is not returned. This
can be useful if you don't want to extend street network segments through
buildings.
Parameters
----------
gdf : GeoDataFrame
GeoDataFrame containing LineString geometry
tolerance : float
tolerance in snapping (by how much could be each segment
extended).
target : GeoDataFrame, GeoSeries
target geometry to which ``gdf`` gets extended. Has to be
(Multi)LineString geometry.
barrier : GeoDataFrame, GeoSeries
extended line is not used if it intersects barrier
extension : float
by how much to extend line beyond the snapped geometry. Useful
when creating enclosures to avoid floating point imprecision.
Returns
-------
GeoDataFrame
GeoDataFrame of with extended geometry
See also
--------
momepy.close_gaps
momepy.remove_false_nodes
"""
# explode to avoid MultiLineStrings
# double reset index due to the bug in GeoPandas explode
df = gdf.reset_index(drop=True).explode().reset_index(drop=True)
if target is None:
target = df
itself = True
else:
itself = False
# get underlying pygeos geometry
geom = df.geometry.values.data
# extract array of coordinates and number per geometry
coords = pygeos.get_coordinates(geom)
indices = pygeos.get_num_coordinates(geom)
# generate a list of start and end coordinates and create point geometries
edges = [0]
i = 0
for ind in indices:
ix = i + ind
edges.append(ix - 1)
edges.append(ix)
i = ix
edges = edges[:-1]
points = pygeos.points(np.unique(coords[edges], axis=0))
# query LineString geometry to identify points intersecting 2 geometries
tree = pygeos.STRtree(geom)
inp, res = tree.query_bulk(points, predicate="intersects")
unique, counts = np.unique(inp, return_counts=True)
ends = np.unique(res[np.isin(inp, unique[counts == 1])])
new_geoms = []
# iterate over cul-de-sac-like segments and attempt to snap them to street network
for line in ends:
l_coords = pygeos.get_coordinates(geom[line])
start = pygeos.points(l_coords[0])
end = pygeos.points(l_coords[-1])
first = list(tree.query(start, predicate="intersects"))
second = list(tree.query(end, predicate="intersects"))
first.remove(line)
second.remove(line)
t = target if not itself else target.drop(line)
if first and not second:
snapped = _extend_line(l_coords, t, tolerance)
if (
barrier is not None
and barrier.sindex.query(
pygeos.linestrings(snapped), predicate="intersects"
).size
> 0
):
new_geoms.append(geom[line])
else:
if extension == 0:
new_geoms.append(pygeos.linestrings(snapped))
else:
new_geoms.append(
pygeos.linestrings(
_extend_line(snapped, t, extension, snap=False)
)
)
elif not first and second:
snapped = _extend_line(np.flip(l_coords, axis=0), t, tolerance)
if (
barrier is not None
and barrier.sindex.query(
pygeos.linestrings(snapped), predicate="intersects"
).size
> 0
):
new_geoms.append(geom[line])
else:
if extension == 0:
new_geoms.append(pygeos.linestrings(snapped))
else:
new_geoms.append(
pygeos.linestrings(
_extend_line(snapped, t, extension, snap=False)
)
)
elif not first and not second:
one_side = _extend_line(l_coords, t, tolerance)
one_side_e = _extend_line(one_side, t, extension, snap=False)
snapped = _extend_line(np.flip(one_side_e, axis=0), t, tolerance)
if (
barrier is not None
and barrier.sindex.query(
pygeos.linestrings(snapped), predicate="intersects"
).size
> 0
):
new_geoms.append(geom[line])
else:
if extension == 0:
new_geoms.append(pygeos.linestrings(snapped))
else:
new_geoms.append(
pygeos.linestrings(
_extend_line(snapped, t, extension, snap=False)
)
)
df.iloc[ends, df.columns.get_loc(df.geometry.name)] = new_geoms
return df
def _extend_line(coords, target, tolerance, snap=True):
"""
Extends a line geometry to snap on the target within a tolerance.
"""
if snap:
extrapolation = _get_extrapolated_line(
coords[-4:] if len(coords.shape) == 1 else coords[-2:].flatten(), tolerance,
)
int_idx = target.sindex.query(extrapolation, predicate="intersects")
intersection = pygeos.intersection(
target.iloc[int_idx].geometry.values.data, extrapolation
)
if intersection.size > 0:
if len(intersection) > 1:
distances = {}
ix = 0
for p in intersection:
distance = pygeos.distance(p, pygeos.points(coords[-1]))
distances[ix] = distance
ix = ix + 1
minimal = min(distances.items(), key=operator.itemgetter(1))[0]
new_point_coords = pygeos.get_coordinates(intersection[minimal])
else:
new_point_coords = pygeos.get_coordinates(intersection[0])
coo = np.append(coords, new_point_coords)
new = np.reshape(coo, (int(len(coo) / 2), 2))
return new
return coords
extrapolation = _get_extrapolated_line(
coords[-4:] if len(coords.shape) == 1 else coords[-2:].flatten(),
tolerance,
point=True,
)
return np.vstack([coords, extrapolation])
def _get_extrapolated_line(coords, tolerance, point=False):
"""
Creates a pygeos line extrapoled in p1->p2 direction.
"""
p1 = coords[:2]
p2 = coords[2:]
a = p2
# defining new point based on the vector between existing points
if p1[0] >= p2[0] and p1[1] >= p2[1]:
b = (
p2[0]
- tolerance
* math.cos(
math.atan(
math.fabs(p1[1] - p2[1] + 0.000001)
/ math.fabs(p1[0] - p2[0] + 0.000001)
)
),
p2[1]
- tolerance
* math.sin(
math.atan(
math.fabs(p1[1] - p2[1] + 0.000001)
/ math.fabs(p1[0] - p2[0] + 0.000001)
)
),
)
elif p1[0] <= p2[0] and p1[1] >= p2[1]:
b = (
p2[0]
+ tolerance
* math.cos(
math.atan(
math.fabs(p1[1] - p2[1] + 0.000001)
/ math.fabs(p1[0] - p2[0] + 0.000001)
)
),
p2[1]
- tolerance
* math.sin(
math.atan(
math.fabs(p1[1] - p2[1] + 0.000001)
/ math.fabs(p1[0] - p2[0] + 0.000001)
)
),
)
elif p1[0] <= p2[0] and p1[1] <= p2[1]:
b = (
p2[0]
+ tolerance
* math.cos(
math.atan(
math.fabs(p1[1] - p2[1] + 0.000001)
/ math.fabs(p1[0] - p2[0] + 0.000001)
)
),
p2[1]
+ tolerance
* math.sin(
math.atan(
math.fabs(p1[1] - p2[1] + 0.000001)
/ math.fabs(p1[0] - p2[0] + 0.000001)
)
),
)
else:
b = (
p2[0]
- tolerance
* math.cos(
math.atan(
math.fabs(p1[1] - p2[1] + 0.000001)
/ math.fabs(p1[0] - p2[0] + 0.000001)
)
),
p2[1]
+ tolerance
* math.sin(
math.atan(
math.fabs(p1[1] - p2[1] + 0.000001)
/ math.fabs(p1[0] - p2[0] + 0.000001)
)
),
)
if point:
return b
return pygeos.linestrings([a, b])
| 0c4340594305664a6aa3867737b7987baecf152c | [
"Python",
"Text"
] | 2 | Text | kaszklar/momepy | 5dc84a4b3d78a8f6e63a0673ec594e063ec6a5b8 | 29d4736ec5f5c0642357ab358248be266aacef47 |
refs/heads/master | <repo_name>MasterKale/avery<file_sep>/vue.config.js
// vue.config.js
module.exports = {
configureWebpack: {
// Allow for relative paths for the various bundles
output: {
publicPath: './',
}
}
}
| 2fa396fcd6ce4c94f4650c386dd2daa16dd0ffc9 | [
"JavaScript"
] | 1 | JavaScript | MasterKale/avery | eb0d9333ffbc5c8d4feab68f6a171fdfdd38de6b | 413273fe4df26e36d6076593020683d3414986db |
refs/heads/master | <repo_name>postmates/wrench<file_sep>/pkg/spanner/testdata/migrations/000004.sql
ALTER TABLE Singers ALTER COLUMN LastName STRING(MAX) NOT NULL;
<file_sep>/cmd/errors.go
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
type Error struct {
err error
cmd *cobra.Command
}
func (e *Error) Error() string {
return fmt.Sprintf("Error command: %s, version: %s", e.cmd.Name(), Version)
}
func (e *Error) Unwrap() error {
return e.err
}
<file_sep>/pkg/spanner/testdata/migrations/000003.sql
UPDATE Singers SET LastName = "" WHERE LastName IS NULL;
<file_sep>/cmd/reset.go
package cmd
import (
"errors"
"github.com/spf13/cobra"
)
var resetCmd = &cobra.Command{
Use: "reset",
Short: "Equivalent to drop and then create",
RunE: reset,
}
func reset(c *cobra.Command, args []string) error {
if err := drop(c, args); err != nil {
return errorReset(c, err)
}
if err := create(c, args); err != nil {
return errorReset(c, err)
}
return nil
}
func errorReset(c *cobra.Command, err error) error {
if ue := errors.Unwrap(err); ue != nil {
return &Error{
cmd: c,
err: ue,
}
}
return &Error{
cmd: c,
err: err,
}
}
<file_sep>/cmd/apply.go
package cmd
import (
"context"
"errors"
"fmt"
"io/ioutil"
"github.com/spf13/cobra"
)
var (
ddlFile string
dmlFile string
partitioned bool
)
var applyCmd = &cobra.Command{
Use: "apply",
Short: "Apply DDL file to database",
RunE: apply,
}
func apply(c *cobra.Command, _ []string) error {
ctx := context.Background()
client, err := newSpannerClient(ctx, c)
if err != nil {
return err
}
defer client.Close()
if ddlFile != "" {
if dmlFile != "" {
return errors.New("Cannot specify DDL and DML at same time.")
}
ddl, err := ioutil.ReadFile(ddlFile)
if err != nil {
return &Error{
err: err,
cmd: c,
}
}
err = client.ApplyDDLFile(ctx, ddl)
if err != nil {
return &Error{
err: err,
cmd: c,
}
}
return nil
}
if dmlFile == "" {
return errors.New("Must specify DDL or DML.")
}
// apply dml
dml, err := ioutil.ReadFile(dmlFile)
if err != nil {
return &Error{
err: err,
cmd: c,
}
}
numAffectedRows, err := client.ApplyDMLFile(ctx, dml, partitioned)
if err != nil {
return &Error{
err: err,
cmd: c,
}
}
fmt.Printf("%d rows affected.\n", numAffectedRows)
return nil
}
func init() {
applyCmd.PersistentFlags().StringVar(&ddlFile, flagDDLFile, "", "DDL file to be applied")
applyCmd.PersistentFlags().StringVar(&dmlFile, flagDMLFile, "", "DML file to be applied")
applyCmd.PersistentFlags().BoolVar(&partitioned, flagPartitioned, false, "Whether given DML should be executed as a Partitioned-DML or not")
}
<file_sep>/cmd/migrate_test.go
package cmd_test
import (
"os"
"path/filepath"
"testing"
"github.com/mercari/wrench/cmd"
)
func TestCreateMigrationFile(t *testing.T) {
testdatadir := filepath.Join("testdata", "migrations")
testcases := []struct {
filename string
digits int
wantFilename string
}{
{
filename: "foo",
digits: 6,
wantFilename: filepath.Join(testdatadir, "000003_foo.sql"),
},
{
filename: "bar",
digits: 0,
wantFilename: filepath.Join(testdatadir, "3_bar.sql"),
},
}
for _, tc := range testcases {
t.Run(tc.filename, func(t *testing.T) {
filename, err := cmd.CreateMigrationFile(testdatadir, tc.filename, tc.digits)
if err != nil {
t.Fatal(err)
}
defer func() {
_ = os.Remove(filename)
}()
if tc.wantFilename != filename {
t.Errorf("filename want %v, but got %v", tc.wantFilename, filename)
}
})
}
t.Run("invalid name", func(t *testing.T) {
_, err := cmd.CreateMigrationFile(testdatadir, "あああ", 6)
if err.Error() != "Invalid migration file name." {
t.Errorf("err want `invalid name`, but got `%v`", err)
}
})
}
<file_sep>/cmd/load.go
package cmd
import (
"context"
"io/ioutil"
"github.com/spf13/cobra"
)
var loadCmd = &cobra.Command{
Use: "load",
Short: "Load schema from server to file",
RunE: load,
}
func load(c *cobra.Command, args []string) error {
ctx := context.Background()
client, err := newSpannerClient(ctx, c)
if err != nil {
return err
}
defer client.Close()
ddl, err := client.LoadDDL(ctx)
if err != nil {
return &Error{
err: err,
cmd: c,
}
}
err = ioutil.WriteFile(schemaFilePath(c), ddl, 0664)
if err != nil {
return &Error{
err: err,
cmd: c,
}
}
return nil
}
<file_sep>/pkg/spanner/testdata/schema.sql
CREATE TABLE SchemaMigrations (
Version INT64 NOT NULL,
Dirty BOOL NOT NULL,
) PRIMARY KEY(Version);
CREATE TABLE Singers (
SingerID STRING(36) NOT NULL,
FirstName STRING(1024),
) PRIMARY KEY(SingerID);
<file_sep>/cmd/create.go
package cmd
import (
"context"
"io/ioutil"
"github.com/spf13/cobra"
)
var createCmd = &cobra.Command{
Use: "create",
Short: "Create database with tables described in schema file",
RunE: create,
}
func create(c *cobra.Command, _ []string) error {
ctx := context.Background()
client, err := newSpannerClient(ctx, c)
if err != nil {
return err
}
defer client.Close()
ddl, err := ioutil.ReadFile(schemaFilePath(c))
if err != nil {
return &Error{
err: err,
cmd: c,
}
}
err = client.CreateDatabase(ctx, ddl)
if err != nil {
return &Error{
err: err,
cmd: c,
}
}
return nil
}
<file_sep>/pkg/spanner/migration.go
package spanner
import (
"bytes"
"errors"
"io/ioutil"
"path/filepath"
"regexp"
"strconv"
"strings"
)
const (
statementsSeparator = ";"
)
var (
// migrationFileRegex matches the following patterns
// 001.sql
// 001_name.sql
// 001_name.up.sql
migrationFileRegex = regexp.MustCompile(`^([0-9]+)(?:_([a-zA-Z0-9_\-]+))?(\.up)?\.sql$`)
MigrationNameRegex = regexp.MustCompile(`[a-zA-Z0-9_\-]+`)
dmlRegex = regexp.MustCompile("^(UPDATE|DELETE)[\t\n\f\r ].*")
)
const (
statementKindDDL statementKind = "DDL"
statementKindDML statementKind = "DML"
)
type (
// migration represents the parsed migration file. e.g. version_name.sql
Migration struct {
// Version is the version of the migration
Version uint
// Name is the name of the migration
Name string
// Statements is the migration statements
Statements []string
kind statementKind
}
Migrations []*Migration
statementKind string
)
func (ms Migrations) Len() int {
return len(ms)
}
func (ms Migrations) Swap(i, j int) {
ms[i], ms[j] = ms[j], ms[i]
}
func (ms Migrations) Less(i, j int) bool {
return ms[i].Version < ms[j].Version
}
func LoadMigrations(dir string) (Migrations, error) {
files, err := ioutil.ReadDir(dir)
if err != nil {
return nil, err
}
var migrations Migrations
for _, f := range files {
if f.IsDir() {
continue
}
matches := migrationFileRegex.FindStringSubmatch(f.Name())
if len(matches) != 4 {
continue
}
version, err := strconv.ParseUint(matches[1], 10, 64)
if err != nil {
continue
}
file, err := ioutil.ReadFile(filepath.Join(dir, f.Name()))
if err != nil {
continue
}
statements := toStatements(file)
kind, err := inspectStatementsKind(statements)
if err != nil {
return nil, err
}
migrations = append(migrations, &Migration{
Version: uint(version),
Name: matches[2],
Statements: statements,
kind: kind,
})
}
return migrations, nil
}
func toStatements(file []byte) []string {
contents := bytes.Split(file, []byte(statementsSeparator))
statements := make([]string, 0, len(contents))
for _, c := range contents {
if statement := strings.TrimSpace(string(c)); statement != "" {
statements = append(statements, statement)
}
}
return statements
}
func inspectStatementsKind(statements []string) (statementKind, error) {
kindMap := map[statementKind]uint64{
statementKindDDL: 0,
statementKindDML: 0,
}
for _, s := range statements {
if isDML(s) {
kindMap[statementKindDML]++
} else {
kindMap[statementKindDDL]++
}
}
if kindMap[statementKindDML] > 0 {
if kindMap[statementKindDDL] > 0 {
return "", errors.New("Cannot specify DDL and DML at same migration file.")
}
return statementKindDML, nil
}
return statementKindDDL, nil
}
func isDML(statement string) bool {
return dmlRegex.Match([]byte(statement))
}
<file_sep>/cmd/root.go
package cmd
import (
"os"
"github.com/spf13/cobra"
)
var (
Version = "unknown"
versionTemplate = `{{.Version}}
`
)
var (
project string
instance string
database string
directory string
schemaFile string
credentialsFile string
)
var rootCmd = &cobra.Command{
Use: "wrench",
}
func Execute() error {
return rootCmd.Execute()
}
func init() {
cobra.EnableCommandSorting = false
rootCmd.SilenceUsage = true
rootCmd.SilenceErrors = true
rootCmd.AddCommand(createCmd)
rootCmd.AddCommand(dropCmd)
rootCmd.AddCommand(resetCmd)
rootCmd.AddCommand(loadCmd)
rootCmd.AddCommand(applyCmd)
rootCmd.AddCommand(migrateCmd)
rootCmd.PersistentFlags().StringVar(&project, flagNameProject, spannerProjectID(), "GCP project id (optional. if not set, will use $SPANNER_PROJECT_ID or $GOOGLE_CLOUD_PROJECT value)")
rootCmd.PersistentFlags().StringVar(&instance, flagNameInstance, spannerInstanceID(), "Cloud Spanner instance name (optional. if not set, will use $SPANNER_INSTANCE_ID value)")
rootCmd.PersistentFlags().StringVar(&database, flagNameDatabase, spannerDatabaseID(), "Cloud Spanner database name (optional. if not set, will use $SPANNER_DATABASE_ID value)")
rootCmd.PersistentFlags().StringVar(&directory, flagNameDirectory, "", "Directory that schema file placed (required)")
rootCmd.PersistentFlags().StringVar(&schemaFile, flagNameSchemaFile, "", "Name of schema file (optional. if not set, will use default 'schema.sql' file name)")
rootCmd.PersistentFlags().StringVar(&credentialsFile, flagCredentialsFile, "", "Specify Credentials File")
rootCmd.Version = Version
rootCmd.SetVersionTemplate(versionTemplate)
}
func spannerProjectID() string {
projectID := os.Getenv("SPANNER_PROJECT_ID")
if projectID != "" {
return projectID
}
return os.Getenv("GOOGLE_CLOUD_PROJECT")
}
func spannerInstanceID() string {
return os.Getenv("SPANNER_INSTANCE_ID")
}
func spannerDatabaseID() string {
return os.Getenv("SPANNER_DATABASE_ID")
}
<file_sep>/cmd/cmd.go
package cmd
import (
"context"
"path/filepath"
"github.com/mercari/wrench/pkg/spanner"
"github.com/spf13/cobra"
)
const (
flagNameProject = "project"
flagNameInstance = "instance"
flagNameDatabase = "database"
flagNameDirectory = "directory"
flagCredentialsFile = "credentials_file"
flagNameSchemaFile = "schema_file"
flagDDLFile = "ddl"
flagDMLFile = "dml"
flagPartitioned = "partitioned"
defaultSchemaFileName = "schema.sql"
)
func newSpannerClient(ctx context.Context, c *cobra.Command) (*spanner.Client, error) {
config := &spanner.Config{
Project: c.Flag(flagNameProject).Value.String(),
Instance: c.Flag(flagNameInstance).Value.String(),
Database: c.Flag(flagNameDatabase).Value.String(),
CredentialsFile: c.Flag(flagCredentialsFile).Value.String(),
}
client, err := spanner.NewClient(ctx, config)
if err != nil {
return nil, &Error{
err: err,
cmd: c,
}
}
return client, nil
}
func schemaFilePath(c *cobra.Command) string {
filename := c.Flag(flagNameSchemaFile).Value.String()
if filename == "" {
filename = defaultSchemaFileName
}
return filepath.Join(c.Flag(flagNameDirectory).Value.String(), filename)
}
<file_sep>/tools.go
// +build tools
package main
import (
_ "github.com/bazelbuild/bazelisk"
)
<file_sep>/pkg/spanner/testdata/dml.sql
UPDATE Singers SET FirstName = "Bar" WHERE SingerID = "1";
<file_sep>/main.go
package main
import (
"errors"
"fmt"
"os"
"github.com/mercari/wrench/cmd"
"github.com/mercari/wrench/pkg/spanner"
)
func main() {
execute()
}
func execute() {
handleError(cmd.Execute())
}
func handleError(err error) {
if err != nil {
fmt.Fprint(os.Stderr, (fmt.Sprintf("%s\n\t%s\n", err.Error(), errorDetails(err))))
os.Exit(1)
}
}
func errorDetails(err error) string {
var se *spanner.Error
if errors.As(err, &se) {
switch se.Code {
case spanner.ErrorCodeCreateClient:
return fmt.Sprintf("Failed to connect to Cloud Spanner, %s", se.Error())
case spanner.ErrorCodeExecuteMigrations, spanner.ErrorCodeMigrationVersionDirty:
return fmt.Sprintf("Failed to execute migration, %s", se.Error())
default:
return fmt.Sprintf("Failed to execute the operation to Cloud Spanner, %s", se.Error())
}
}
var pe *os.PathError
if errors.As(err, &pe) {
return fmt.Sprintf("Invalid file path, %s", pe.Error())
}
if err := errors.Unwrap(err); err != nil {
return err.Error()
}
return "Unknown error..."
}
<file_sep>/pkg/spanner/testdata/ddl.sql
ALTER TABLE Singers ADD COLUMN Foo STRING(MAX);
<file_sep>/pkg/spanner/migration_test.go
package spanner_test
import (
"path/filepath"
"testing"
"github.com/mercari/wrench/pkg/spanner"
)
func TestLoadMigrations(t *testing.T) {
ms, err := spanner.LoadMigrations(filepath.Join("testdata", "migrations"))
if err != nil {
t.Fatal(err)
}
if len(ms) != 3 {
t.Fatalf("migrations length want 3, but got %v", len(ms))
}
testcases := []struct {
idx int
wantVersion uint
wantName string
}{
{
idx: 0,
wantVersion: 2,
wantName: "test",
},
{
idx: 1,
wantVersion: 3,
wantName: "",
},
}
for _, tc := range testcases {
if ms[tc.idx].Version != tc.wantVersion {
t.Errorf("migrations[%d].version want %v, but got %v", tc.idx, tc.wantVersion, ms[tc.idx].Version)
}
if ms[tc.idx].Name != tc.wantName {
t.Errorf("migrations[%d].name want %v, but got %v", tc.idx, tc.wantName, ms[tc.idx].Name)
}
}
}
<file_sep>/cmd/export_test.go
package cmd
var CreateMigrationFile = createMigrationFile
<file_sep>/pkg/spanner/config.go
package spanner
import "fmt"
type Config struct {
Project string
Instance string
Database string
CredentialsFile string
}
func (c *Config) URL() string {
return fmt.Sprintf(
"projects/%s/instances/%s/databases/%s",
c.Project,
c.Instance,
c.Database,
)
}
<file_sep>/pkg/spanner/testdata/migrations/000002_test.sql
ALTER TABLE Singers ADD COLUMN LastName STRING(MAX);
<file_sep>/cmd/drop.go
package cmd
import (
"context"
"github.com/spf13/cobra"
)
var dropCmd = &cobra.Command{
Use: "drop",
Short: "Drop database",
RunE: drop,
}
func drop(c *cobra.Command, _ []string) error {
ctx := context.Background()
client, err := newSpannerClient(ctx, c)
if err != nil {
return err
}
defer client.Close()
err = client.DropDatabase(ctx)
if err != nil {
return &Error{
err: err,
cmd: c,
}
}
return nil
}
<file_sep>/cmd/migrate.go
package cmd
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/mercari/wrench/pkg/spanner"
"github.com/spf13/cobra"
)
const (
migrationsDirName = "migrations"
migrationTableName = "SchemaMigrations"
)
// migrateCmd represents the migrate command
var migrateCmd = &cobra.Command{
Use: "migrate",
Short: "Migrate database",
}
func init() {
migrateCreateCmd := &cobra.Command{
Use: "create NAME",
Short: "Create a set of sequential up migrations in directory",
RunE: migrateCreate,
}
migrateUpCmd := &cobra.Command{
Use: "up [N]",
Short: "Apply all or N up migrations",
RunE: migrateUp,
}
migrateVersionCmd := &cobra.Command{
Use: "version",
Short: "Print current migration version",
RunE: migrateVersion,
}
migrateSetCmd := &cobra.Command{
Use: "set V",
Short: "Set version V but don't run migration (ignores dirty state)",
RunE: migrateSet,
}
migrateCmd.AddCommand(
migrateCreateCmd,
migrateUpCmd,
migrateVersionCmd,
migrateSetCmd,
)
migrateCmd.PersistentFlags().String(flagNameDirectory, "", "Directory that migration files placed (required)")
}
func migrateCreate(c *cobra.Command, args []string) error {
name := ""
if len(args) > 0 {
name = args[0]
}
dir := filepath.Join(c.Flag(flagNameDirectory).Value.String(), migrationsDirName)
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.Mkdir(dir, os.ModePerm); err != nil {
return &Error{
cmd: c,
err: err,
}
}
}
filename, err := createMigrationFile(dir, name, 6)
if err != nil {
return &Error{
cmd: c,
err: err,
}
}
fmt.Printf("%s is created\n", filename)
return nil
}
func migrateUp(c *cobra.Command, args []string) error {
ctx := context.Background()
limit := -1
if len(args) > 0 {
n, err := strconv.Atoi(args[0])
if err != nil {
return &Error{
cmd: c,
err: err,
}
}
limit = n
}
client, err := newSpannerClient(ctx, c)
if err != nil {
return err
}
defer client.Close()
if err = client.EnsureMigrationTable(ctx, migrationTableName); err != nil {
return &Error{
cmd: c,
err: err,
}
}
dir := filepath.Join(c.Flag(flagNameDirectory).Value.String(), migrationsDirName)
migrations, err := spanner.LoadMigrations(dir)
if err != nil {
return &Error{
cmd: c,
err: err,
}
}
return client.ExecuteMigrations(ctx, migrations, limit, migrationTableName)
}
func migrateVersion(c *cobra.Command, args []string) error {
ctx := context.Background()
client, err := newSpannerClient(ctx, c)
if err != nil {
return err
}
defer client.Close()
if err = client.EnsureMigrationTable(ctx, migrationTableName); err != nil {
return &Error{
cmd: c,
err: err,
}
}
v, _, err := client.GetSchemaMigrationVersion(ctx, migrationTableName)
if err != nil {
var se *spanner.Error
if errors.As(err, &se) && se.Code == spanner.ErrorCodeNoMigration {
fmt.Println("No migrations.")
return nil
}
return &Error{
cmd: c,
err: err,
}
}
fmt.Println(v)
return nil
}
func migrateSet(c *cobra.Command, args []string) error {
ctx := context.Background()
if len(args) == 0 {
return &Error{
cmd: c,
err: errors.New("Parameters are not passed."),
}
}
version, err := strconv.Atoi(args[0])
if err != nil {
return &Error{
cmd: c,
err: err,
}
}
client, err := newSpannerClient(ctx, c)
if err != nil {
return err
}
defer client.Close()
if err = client.EnsureMigrationTable(ctx, migrationTableName); err != nil {
return &Error{
cmd: c,
err: err,
}
}
if err := client.SetSchemaMigrationVersion(ctx, uint(version), false, migrationTableName); err != nil {
return &Error{
cmd: c,
err: err,
}
}
return nil
}
func createMigrationFile(dir string, name string, digits int) (string, error) {
if name != "" && !spanner.MigrationNameRegex.MatchString(name) {
return "", errors.New("Invalid migration file name.")
}
ms, err := spanner.LoadMigrations(dir)
if err != nil {
return "", err
}
var v uint = 1
if len(ms) > 0 {
v = ms[len(ms)-1].Version + 1
}
vStr := fmt.Sprint(v)
padding := digits - len(vStr)
if padding > 0 {
vStr = strings.Repeat("0", padding) + vStr
}
var filename string
if name == "" {
filename = filepath.Join(dir, fmt.Sprintf("%s.sql", vStr))
} else {
filename = filepath.Join(dir, fmt.Sprintf("%s_%s.sql", vStr, name))
}
fp, err := os.Create(filename)
if err != nil {
return "", err
}
fp.Close()
return filename, nil
}
<file_sep>/pkg/spanner/errors.go
package spanner
import "google.golang.org/grpc/status"
type ErrorCode int
const (
ErrorCodeCreateClient = iota + 1
ErrorCodeCloseClient
ErrorCodeCreateDatabase
ErrorCodeDropDatabase
ErrorCodeLoadSchema
ErrorCodeUpdateDDL
ErrorCodeUpdateDML
ErrorCodeUpdatePartitionedDML
ErrorCodeExecuteMigrations
ErrorCodeGetMigrationVersion
ErrorCodeSetMigrationVersion
ErrorCodeNoMigration
ErrorCodeMigrationVersionDirty
ErrorCodeWaitOperation
)
type Error struct {
Code ErrorCode
err error
}
func (e *Error) Error() string {
if st, ok := status.FromError(e.err); ok {
return st.Message()
}
return e.err.Error()
}
<file_sep>/_examples/schema.sql
CREATE TABLE Singers (
SingerID STRING(36) NOT NULL,
FirstName STRING(1024),
) PRIMARY KEY(SingerID);
<file_sep>/_examples/migrations/000001.sql
ALTER TABLE Singers ADD COLUMN LastName STRING(1024);
<file_sep>/go.mod
module github.com/mercari/wrench
require (
cloud.google.com/go v0.41.0
github.com/bazelbuild/bazelisk v0.0.8
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/spf13/cobra v0.0.3
github.com/spf13/pflag v1.0.3 // indirect
golang.org/x/net v0.0.0-20190628185345-da137c7871d7 // indirect
golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7 // indirect
google.golang.org/api v0.7.0
google.golang.org/genproto v0.0.0-20190716160619-c506a9f90610
google.golang.org/grpc v1.22.0
)
go 1.13
| 6fc1ef120b8025c4435782a9f27eef0f1d6eef58 | [
"SQL",
"Go Module",
"Go"
] | 26 | SQL | postmates/wrench | 599f517d6d8963ef429c3e3d5cb60b8d0c30fea9 | d0a9f552d5b03c837e512235a75c5732e8bfa412 |
refs/heads/main | <repo_name>dannypak716/blogger-pro<file_sep>/src/components/Article.test.js
import React from "react";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import moment from "moment";
import "@testing-library/jest-dom";
import Article from "./Article";
const testArticle = {
id: 7,
headline: "Test Article",
createdOn: Date.now(),
author: "Author",
image: 134,
summary: "Summary of Test Article",
body: "Informative sentences about the test article.",
};
test("renders component", () => {
render(<Article article={testArticle} />);
});
test("renders headline and author", () => {
render(<Article article={testArticle} />);
screen.getByText("Test Article");
screen.getByText("By Author");
screen.getByText("Summary of Test Article");
screen.getByText("Informative sentences about the test article.");
});
test('renders "Associated Press" if no author', () => {
const noAuthor = {
...testArticle,
author: "",
};
render(<Article article={noAuthor} />);
screen.getByText("By Associated Press");
});
test("delete button deletes article", () => {
const handleDeleteTest = jest.fn();
render(<Article article={testArticle} handleDelete={handleDeleteTest} />);
const deleteButton = screen.getByTestId("deleteButton");
userEvent.click(deleteButton);
expect(handleDeleteTest).toBeCalled();
});
<file_sep>/src/components/View.test.js
import React from "react";
import { render } from "@testing-library/react";
import moment from "moment";
import View from "./View";
import articleService from "./../services/articleServices.js";
jest.mock("./../services/articleServices.js");
test("renders no articles", async () => {
articleService.mockResolvedValueOnce([]);
render(<View />);
});
test("renders three articles", async () => {
articleService.mockResolvedValueOnce([
{
id: 7,
headline: "Test Article",
createdOn: Date.now(),
author: "Author",
image: 134,
summary: "Summary of Test Article",
body: "Informative sentences about the test article.",
},
{
id: 77,
headline: "Test Article 2",
createdOn: Date.now(),
author: "Author 2",
image: 456,
summary: "Summary of Test Article 2",
body: "Informative sentences about the second test article.",
},
{
id: 3,
headline: "The Third Headline",
createdOn: Date.now(),
author: "",
image: 789,
summary: "Summary of Test Article 3",
body: "Informative sentences about the third test article.",
},
]);
render(<View />);
}); | f236bd1a67fb38d65e8a2ba269e6cd197266920d | [
"JavaScript"
] | 2 | JavaScript | dannypak716/blogger-pro | 76d3b414be086b59f5a128b1b6a415843688a09c | 75e40de263d4bc08c079b9c3f74a62f935708fe3 |
refs/heads/master | <repo_name>olivmed/travelG2<file_sep>/config/routes.ini
[routes]
#doc route
GET /doc = App_controller->doc
#main routes
GET / = App_controller->home
GET /travel = App_controller->travel<file_sep>/app/Models/App.php
<?php
class App extends Prefab{
function __construct(){
F3::set('dB',new DB\SQL(
'mysql:host='.F3::get('db_host').';port=3306;dbname='.F3::get('db_server'),
F3::get('db_user'),
F3::get('db_pw')));
}
function locationDetails(){
return F3::get('dB')->exec('select * from location limit 1');
}
function __destruct(){
}
}
?><file_sep>/app/Controllers/App_controller.php
<?php
class App_controller{
function __construct(){
}
function home(){
$App=new App();
$location=$App->locationDetails();
F3::set('location',$location);
//F3::set('location',App::instance()->locationDetails(););
echo Views::instance()->render('travelr.html');
}
function travel(){
$App=new App();
$title=$App->getTravel();
F3::set('title',$title);
echo Views::instance()->render('travelr.html');
}
function doc(){
echo Views::instance()->render('userref.html');
}
function __destruct(){
}
}
?> | eb0ee8c890da617e6130e8dce9b52dd726d8a984 | [
"PHP",
"INI"
] | 3 | INI | olivmed/travelG2 | fabe062ffda4a02b891a4f5e2bba04a2c72f3d4a | 9de906e8d8ff3750d25d3f0375ba5f856b779bff |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ParticleSystemPooler : MonoBehaviour
{
int amountPer = 10;
[System.Serializable]
public class PoolableParticleSystem
{
public string name;
public GameObject particleSystemObject;
public PoolableParticleSystem(string _name, GameObject _pso)
{
name = _name;
particleSystemObject = _pso;
}
}
public PoolableParticleSystem[] poolableParticleSystems;
private Dictionary<string, List<ParticleSystem>> poolableParticleSystemDictionary;
public static ParticleSystemPooler instance;
private void Start()
{
instance = this;
InitializeDictionary();
}
private void InitializeDictionary()
{
poolableParticleSystemDictionary = new Dictionary<string, List<ParticleSystem>>();
foreach(PoolableParticleSystem pps in poolableParticleSystems)
{
List<ParticleSystem> ppsList = new List<ParticleSystem>();
for(int i = 0; i < amountPer; i++)
{
GameObject spawnedPS = Instantiate(pps.particleSystemObject, transform.position, Quaternion.identity);
spawnedPS.transform.SetParent(transform);
ppsList.Add(spawnedPS.GetComponent<ParticleSystem>());
}
poolableParticleSystemDictionary.Add(pps.name, ppsList);
}
}
public void SpawnParticleSystem(string tag, Vector3 position)
{
List<ParticleSystem> psList;
if (poolableParticleSystemDictionary.TryGetValue(tag, out psList))
{
ParticleSystem particleSystem = psList[0];
particleSystem.transform.position = position;
particleSystem.Play();
psList.RemoveAt(0);
psList.Add(particleSystem);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPC : Entity, IInteractable
{
public enum NPC_Behavior
{
STATIC,
RANDOM,
CUSTOM
}
public NPC_Behavior behavior;
[System.Serializable]
public class NPC_Command
{
public EntityCommand command;
public int value = 1;
}
public float baseWaitTimeBetweenActions = 2.0f;
public Dialogue dialogue;
public NPC_Command[] customCommands;
public bool customLoop;
public string colorString = "black";
public override void Start()
{
base.Start();
if (behavior.Equals(NPC_Behavior.RANDOM))
{
StartCoroutine(RandomMovement());
} else if(behavior.Equals(NPC_Behavior.CUSTOM))
{
StartCoroutine(CustomMovement());
}
}
private IEnumerator RandomMovement()
{
while(true)
{
int r = Random.Range(0, 3);
MoveInDirection((Direction)r);
while (isMoving)
{
yield return null;
}
yield return new WaitForSeconds(baseWaitTimeBetweenActions);
}
}
private IEnumerator CustomMovement()
{
do
{
for (int i = 0; i < customCommands.Length; i++)
{
NPC_Command npcCommand = customCommands[i];
ExecuteCommand(npcCommand.command, npcCommand.value);
while(isMoving)
{
yield return null;
}
yield return new WaitForSeconds(baseWaitTimeBetweenActions);
}
} while (customLoop);
}
public void OnInteract()
{
StartCoroutine(StartDialogueCoroutine());
}
private IEnumerator StartDialogueCoroutine()
{
Direction d = direction;
FacePlayer();
StopMovement();
pokemonGameManager.StartDialogue(dialogue, colorString);
while(DialogueManager.instance.IsDialogueDisplayed())
{
yield return null;
}
FaceDirection(d);
StartMovement();
}
}
<file_sep>using UnityEngine;
[System.Serializable]
public class MoveData : ScriptableObject {
public int ID;
public new string name;
public string internalName;
public string description;
public string functionCode;
public string target;
/// <summary>
/// a - The move makes physical contact with the target.
/// b - The target can use Protect or Detect to protect itself from the move.
/// c - The target can use Magic Coat to redirect the effect of the move.Use this flag if the move deals no damage but causes a negative effect on the target. (Flags c and d are mutually exclusive.)
/// d - The target can use Snatch to steal the effect of the move. Use this flag for most moves that target the user. (Flags c and d are mutually exclusive.)
/// e - The move can be copied by Mirror Move.
/// f - The move has a 10% chance of making the opponent flinch if the user is holding a King's Rock/Razor Fang. Use this flag for all damaging moves that don't already have a flinching effect.
/// g - If the user is frozen, the move will thaw it out before it is used.
/// h - The move has a high critical hit rate.
/// i - The move is a biting move (powered up by the ability Strong Jaw).
/// j - The move is a punching move(powered up by the ability Iron Fist).
/// k - The move is a sound-based move.
/// l - The move is a powder-based move (Grass-type Pokémon are immune to them).
/// m - The move is a pulse-based move(powered up by the ability Mega Launcher).
/// n - The move is a bomb-based move(resisted by the ability Bulletproof).
/// </summary>
public char[] flags;
public bool isSpecial;
public int basePower;
public int accuracy;
public int totalPP;
public int additionalEffectChance;
public int priority;
public PokemonTypeData type;
public string flagDesc(char flag)
{
switch(flag)
{
case 'a': return "The move makes physical contact with the target.";
case 'b': return "The target can use Protect or Detect to protect itself from the move.";
case 'c': return "The target can use Magic Coat to redirect the effect of the move.Use this flag if the move deals no damage but causes a negative effect on the target. (Flags c and d are mutually exclusive.)";
case 'd': return "The target can use Snatch to steal the effect of the move. Use this flag for most moves that target the user. (Flags c and d are mutually exclusive.)";
case 'e': return "The move can be copied by Mirror Move.";
case 'f': return "The move has a 10% chance of making the opponent flinch if the user is holding a King's Rock/Razor Fang. Use this flag for all damaging moves that don't already have a flinching effect.";
case 'g': return "If the user is frozen, the move will thaw it out before it is used.";
case 'h': return "The move has a high critical hit rate.";
case 'i': return "The move is a biting move (powered up by the ability Strong Jaw).";
case 'j': return "The move is a punching move(powered up by the ability Iron Fist).";
case 'k': return "The move is a sound-based move.";
case 'l': return "The move is a powder-based move (Grass-type Pokémon are immune to them).";
case 'm': return "The move is a pulse-based move(powered up by the ability Mega Launcher).";
case 'n': return "The move is a bomb-based move(resisted by the ability Bulletproof).";
default:
return "nil";
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
using UnityEditor;
[ExecuteAlways]
public class TilemapLayerShader : MonoBehaviour
{
public Color hiddenLayerColor = Color.grey;
Tilemap[] tilemapLayers;
private void Start()
{
if(Application.IsPlaying(gameObject))
{
ResetColors();
} else {
tilemapLayers = GetComponentsInChildren<Tilemap>();
}
}
private void OnRenderObject()
{
if (!Application.IsPlaying(gameObject)) {
if (tilemapLayers != null && tilemapLayers.Length > 0 && Selection.gameObjects.Length > 0)
{
Tilemap selectedTilemap = Selection.activeGameObject.GetComponent<Tilemap>();
foreach (Tilemap t in tilemapLayers)
{
if (selectedTilemap != null && !t.Equals(selectedTilemap))
{
t.color = hiddenLayerColor;
}
else
{
t.color = Color.white;
}
}
} else
{
ResetColors();
}
}
}
private void ResetColors()
{
foreach (Tilemap t in tilemapLayers)
{
t.color = Color.white;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickupableItem : MonoBehaviour, IInteractable
{
public ItemData item;
public void OnInteract()
{
string[] dString = { Player.instance.name + " found one " + item.name + "!", Player.instance.name + " put the " + item.name + " in the " + item.itemType + " pocket." };
Dialogue d = new Dialogue(dString);
PokemonGameManager.instance.StartDialogue(d);
gameObject.SetActive(false);
}
}
<file_sep>using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class LearnedMove
{
public MoveData move;
public int level;
public LearnedMove(MoveData _move, int _level)
{
move = _move;
level = _level;
}
}
[System.Serializable]
public class Evolution
{
public enum EvolutionType
{
LEVEL,
ITEM
}
public PokemonData resultant;
public int levelToEvolve;
public ItemData itemToEvolve;
public EvolutionType evolutionType;
public Evolution(PokemonData _resultant, int _levelToEvolve)
{
resultant = _resultant;
levelToEvolve = _levelToEvolve;
evolutionType = EvolutionType.LEVEL;
}
public Evolution(PokemonData _resultant, ItemData _itemToEvolve)
{
resultant = _resultant;
itemToEvolve = _itemToEvolve;
evolutionType = EvolutionType.ITEM;
}
}
[System.Serializable]
public class PokemonData : ScriptableObject {
public enum EggGroup
{
NONE,
MONSTER,
WATER1,
BUG,
FLYING,
FIELD,
FAIRY,
GRASS,
HUMANLIKE,
WATER3,
MINERAL,
AMORPHOUS,
WATER2,
DITTO,
DRAGON,
UNDISCOVERED
};
public enum GrowthRate
{
ERRATIC,
FAST,
MEDIUM,
PARABOLIC,
SLOW,
FLUCTUATING
};
public enum Habitat
{
CAVE,
FOREST,
GRASSLAND,
MOUNTAIN,
RARE,
ROUGHTERRAIN,
SEA,
URBAN,
WATERSEDGE
}
public int number;
public new string name;
public string internalName;
public string kind;
public float height;
public float weight;
public string dexEntry;
public Sprite sprite, backSprite, shinySprite, shinyBackSprite, footprintSprite;
public PokemonTypeData type1, type2;
public EggGroup eggGroup1, eggGroup2;
public GrowthRate growthRate;
public Habitat habitat;
public float femaleRatio;
public List<AbilityData> standardAbilities;
public AbilityData hiddenAbility;
public int baseHP, baseAttack, baseDefense, baseSpeed, baseSpecialAttack, baseSpecialDefense;
public int EV_HP, EV_Attack, EV_Defense, EV_Speed, EV_SpecialAttack, EV_SpecialDefense;
public int baseEXP;
public int rareness;
public int baseHappiness;
public int stepsToHatch;
public List<Evolution> evolutions;
public List<LearnedMove> learnedMoves;
public List<MoveData> eggMoves;
public void Init()
{
evolutions = new List<Evolution>();
standardAbilities = new List<AbilityData>();
learnedMoves = new List<LearnedMove>();
eggMoves = new List<MoveData>();
}
public MoveData[] GetBestMovesAtLevel(int level)
{
MoveData[] ret = new MoveData[4];
int index = 0;
for(int i = learnedMoves.Count-1; i >= 0; i--)
{
if(learnedMoves[i].level > level)
{
continue;
} else
{
ret[index] = learnedMoves[i].move;
index++;
if (index>3)
{
break;
}
}
}
return ret;
}
public static float String2GenderRate(string genderRate)
{
switch (genderRate)
{
case "AlwaysMale":
return 0.0f;
case "FemaleOneEighth":
return 0.125f;
case "Female25Percent":
return 0.25f;
case "Female50Percent":
return 0.5f;
case "Female75Percent":
return 0.75f;
case "FemaleSevenEighths":
return 0.875f;
case "AlwaysFemale":
return 1.0f;
case "Genderless":
default:
return -1f;
}
}
private static int[] ExpTableErratic = new int[]
{
0, 15, 52, 122, 237, 406, 637, 942, 1326, 1800,
2369, 3041, 3822, 4719, 5737, 6881, 8155, 9564, 11111, 12800,
14632, 16610, 18737, 21012, 23437, 26012, 28737, 31610, 34632, 37800,
41111, 44564, 48155, 51881, 55737, 59719, 63822, 68041, 72369, 76800,
81326, 85942, 90637, 95406, 100237, 105122, 110052, 115105, 120001, 125000,
131324, 137795, 144410, 151165, 158056, 165079, 172229, 179503, 186894, 194400,
202013, 209728, 217540, 225443, 233431, 241496, 249633, 257834, 267406, 276458,
286328, 296358, 305767, 316074, 326531, 336255, 346965, 357812, 567807, 378880,
390077, 400293, 411686, 423190, 433572, 445239, 457001, 467489, 479378, 491346,
501878, 513934, 526049, 536557, 548720, 560922, 571333, 583539, 591882, 600000
};
private static int[] ExpTableFast = new int[]
{
0, 6, 21, 51, 100, 172, 274, 409, 583, 800,
1064, 1382, 1757, 2195, 2700, 3276, 3930, 4665, 5487, 6400,
7408, 8518, 9733, 11059, 12500, 14060, 15746, 17561, 19511, 21600,
23832, 26214, 28749, 31443, 34300, 37324, 40522, 43897, 47455, 51200,
55136, 59270, 63605, 68147, 72900, 77868, 83058, 88473, 94119, 100000,
106120, 112486, 119101, 125971, 133100, 140492, 148154, 156089, 164303, 172800,
181584, 190662, 200037, 209715, 219700, 229996, 240610, 251545, 262807, 274400,
286328, 298598, 311213, 324179, 337500, 351180, 365226, 379641, 394431, 409600,
425152, 441094, 457429, 474163, 491300, 508844, 526802, 545177, 563975, 583200,
602856, 622950, 643485, 664467, 685900, 707788, 730138, 752953, 776239, 800000
};
private static int[] XPTableMedium = new int[]
{
0, 8, 27, 64, 125, 216, 343, 512, 729, 1000,
1331, 1728, 2197, 2744, 3375, 4096, 4913, 5832, 6859, 8000,
9261, 10648, 12167, 13824, 15625, 17576, 19683, 21952, 24389, 27000,
29791, 32768, 35937, 39304, 42875, 46656, 50653, 54872, 59319, 64000,
68921, 74088, 79507, 85184, 91125, 97336, 103823, 110592, 117649, 125000,
132651, 140608, 148877, 157464, 166375, 175616, 185193, 195112, 205379, 216000,
226981, 238328, 250047, 262144, 274625, 287496, 300763, 314432, 328509, 343000,
357911, 373248, 389017, 405224, 421875, 438976, 456533, 474552, 493039, 512000,
531441, 551368, 571787, 592704, 614125, 636056, 658503, 681472, 704969, 729000,
753571, 778688, 804357, 830584, 857375, 884736, 912673, 941192, 970299, 1000000
};
private static int[] XPTableParabolic = new int[]
{
0, 9, 57, 96, 135, 179, 236, 314, 419, 560,
742, 973, 1261, 1612, 2035, 2535, 3120, 3798, 4575, 5460,
6458, 7577, 8825, 10208, 11735, 13411, 15244, 17242, 19411, 21760,
24294, 27021, 29949, 33084, 36435, 40007, 43808, 47846, 52127, 56660,
61450, 66505, 71833, 77440, 83335, 89523, 96012, 102810, 109923, 117360,
125126, 133229, 141677, 150476, 159635, 169159, 179056, 189334, 199999, 211060,
222522, 234393, 246681, 259392, 272535, 286115, 300140, 314618, 329555, 344960,
360838, 377197, 394045, 411388, 429235, 447591, 466464, 485862, 505791, 526260,
547274, 568841, 590969, 613664, 636935, 660787, 685228, 710266, 735907, 762160,
789030, 816525, 844653, 873420, 902835, 932903, 963632, 995030, 1027103, 1059860
};
private static int[] ExpTableSlow = new int[]
{
0, 10, 33, 80, 156, 270, 428, 640, 911, 1250,
1663, 2160, 2746, 3430, 4218, 5120, 6141, 7290, 8573, 10000,
11576, 13310, 15208, 17280, 19531, 21970, 24603, 27440, 30486, 33750,
37238, 40960, 44921, 49130, 53593, 58320, 63316, 68590, 74148, 80000,
86151, 92610, 99383, 106480, 113906, 121670, 129778, 138240, 147061, 156250,
165813, 175760, 186096, 196830, 207968, 219520, 231491, 243890, 256723, 270000,
283726, 297910, 312558, 327680, 343281, 359370, 375953, 393040, 410636, 428750,
447388, 466560, 486271, 506530, 527343, 548720, 570666, 593190, 616298, 640000,
664301, 689210, 714733, 740880, 767656, 795070, 823128, 851840, 881211, 911250,
941963, 973360, 1005446, 1038230, 1071718, 1105920, 1140841, 1176490, 1212873, 1250000
};
private static int[] ExpTableFluctuating = new int[]
{
0, 4, 13, 32, 65, 112, 178, 276, 393, 540,
745, 967, 1230, 1591, 1957, 2457, 3046, 3732, 4526, 5440,
6482, 7666, 9003, 10506, 12187, 14060, 16140, 18439, 20974, 23760,
26811, 30146, 33780, 37731, 42017, 46656, 50653, 55969, 60505, 66560,
71677, 78533, 84277, 91998, 98415, 107069, 114205, 123863, 131766, 142500,
151222, 163105, 172697, 185807, 196322, 210739, 222231, 238036, 250562, 267840,
281456, 300293, 315059, 335544, 351520, 373744, 390991, 415050, 433631, 459620,
479600, 507617, 529063, 559209, 582187, 614566, 639146, 673863, 700115, 737280,
765275, 804997, 834809, 877201, 908905, 954084, 987754, 1035837, 1071552, 1122660,
1160499, 1214753, 1254796, 1312322, 1354652, 1415577, 1460276, 1524731, 1571884, 1640000
};
public static int GetLevelXP(GrowthRate growthRate, int currentLevel)
{
int exp = 0;
if (currentLevel > 100)
{
currentLevel = 100;
}
if (growthRate == GrowthRate.ERRATIC)
{
exp = ExpTableErratic[currentLevel - 1]; //Because the array starts at 0, not 1.
}
else if (growthRate == GrowthRate.FAST)
{
exp = ExpTableFast[currentLevel - 1];
}
else if (growthRate == GrowthRate.MEDIUM)
{
exp = XPTableMedium[currentLevel - 1];
}
else if (growthRate == GrowthRate.PARABOLIC)
{
exp = XPTableParabolic[currentLevel - 1];
}
else if (growthRate == GrowthRate.SLOW)
{
exp = ExpTableSlow[currentLevel - 1];
}
else if (growthRate == GrowthRate.FLUCTUATING)
{
exp = ExpTableFluctuating[currentLevel - 1];
}
return exp;
}
}
<file_sep>using System.Collections;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(PixelPerfectMainCamera))]
public class PixelPerfectMainCameraEditor : Editor
{
PixelPerfectMainCamera comp;
void OnEnable()
{
comp = (PixelPerfectMainCamera)target;
}
public override void OnInspectorGUI()
{
EditorGUI.BeginChangeCheck();
comp.PPU = EditorGUILayout.IntField("Pixels Per Unit", comp.PPU);
comp.screenHeight = EditorGUILayout.IntField("Screen height", comp.screenHeight);
comp.screenWidth = EditorGUILayout.IntField("Screen width", comp.screenWidth);
if (EditorGUI.EndChangeCheck()) {
comp.UpdateOrthoSize();
}
EditorGUILayout.LabelField("Calculated Orthographic Size", comp.orthoSize + "");
if(GUILayout.Button("Apply to Main Camera"))
{
comp.ApplyOrthoSize();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Dialogue
{
[TextArea(3, 5)]
public string[] sentences;
public Dialogue(string[] _sentences)
{
sentences = _sentences;
}
public Dialogue(string _sentence)
{
sentences = new string[1] { _sentence };
}
}
<file_sep>using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(PokemonData))]
public class PokemonDataEditor : Editor {
PokemonData comp;
public void OnEnable()
{
comp = (PokemonData)target;
}
public override void OnInspectorGUI()
{
//base.OnInspectorGUI();
GUIStyle descriptionStyle = new GUIStyle(EditorStyles.wordWrappedLabel)
{
fontSize = 15,
font = (Font)Resources.Load("Fonts/consola"),
richText = true
};
GUIStyle headerStyle = new GUIStyle(EditorStyles.boldLabel)
{
font = (Font)Resources.Load("Fonts/pkmnrs"),
fontSize = 24,
alignment = TextAnchor.MiddleLeft
};
GUIStyle captionStyle = new GUIStyle(EditorStyles.label)
{
fontSize = 14,
richText = true,
alignment = TextAnchor.MiddleCenter
};
GUIStyle textureStyle = new GUIStyle(EditorStyles.label)
{
alignment = TextAnchor.MiddleCenter
};
//BASIC DATA
EditorGUILayout.LabelField("BASIC DATA", headerStyle, GUILayout.Height(32f));
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(
"<b>No. " + comp.number + ": " + comp.name + "\n" +
"The <color=blue>" + comp.kind + "</color> Pokemon, " +
"lives in <color=blue>" + comp.habitat.ToString().ToLower() + "</color> area\n<color=blue>" +
comp.height + "</color> m <color=blue>" + comp.weight + "</color> kg\n\n" +
"</b><i>\"" + comp.dexEntry + "\"</i>",
descriptionStyle, GUILayout.Width(500f), GUILayout.Height(156f));
GUILayout.Label(comp.footprintSprite.texture, textureStyle, GUILayout.Width(64f), GUILayout.Height(128f));
GUILayout.Label("", textureStyle, GUILayout.Width(64f));
EditorGUILayout.EndHorizontal();
if (comp.femaleRatio >= 0f)
{
EditorGUILayout.LabelField(
"Has a <color=blue>" + comp.femaleRatio * 100f + "</color>% chance to be female", descriptionStyle
);
} else
{
EditorGUILayout.LabelField(
"Is <color=blue>genderless</color>", descriptionStyle
);
}
EditorGUILayout.LabelField(
"Takes an egg <color=blue>" + comp.stepsToHatch + "</color> steps to hatch", descriptionStyle
);
EditorGUILayout.LabelField(
"Has a catch ratio of <color=blue>" + comp.rareness + "</color>", descriptionStyle
);
EditorGUILayout.LabelField(
"Starts with <color=blue>" + comp.baseHappiness + "</color> base happiness", descriptionStyle
);
EditorGUILayout.LabelField(
"Grows experience at a <color=blue>" + comp.growthRate.ToString() + "</color> speed", descriptionStyle
);
EditorGUILayout.LabelField(
"On defeat, yields base <color=blue>" + comp.baseEXP + "</color> EXP to victor", descriptionStyle
);
//TYPES
GUI.backgroundColor = Color.black;
EditorGUILayout.LabelField("", EditorStyles.helpBox);
EditorGUILayout.LabelField("TYPES", headerStyle, GUILayout.Height(32f));
EditorGUILayout.BeginHorizontal();
GUI.color = Color.white;
GUIStyle toolbarStyle = new GUIStyle(EditorStyles.toolbar);
toolbarStyle.alignment = TextAnchor.MiddleCenter;
toolbarStyle.normal.textColor = Color.white;
toolbarStyle.fontSize = 16;
GUI.backgroundColor = comp.type1.color;
EditorGUILayout.LabelField(comp.type1.internalName, toolbarStyle, GUILayout.Width(128));
if (!comp.type2.internalName.Equals(""))
{
GUI.backgroundColor = comp.type2.color;
EditorGUILayout.LabelField(comp.type2.internalName, toolbarStyle, GUILayout.Width(128));
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
toolbarStyle.normal.textColor = Color.black;
EditorGUILayout.BeginHorizontal();
GUI.backgroundColor = Color.white;
EditorGUILayout.LabelField(comp.eggGroup1.ToString(), toolbarStyle, GUILayout.Width(128));
if (!comp.eggGroup2.ToString().Equals("NONE"))
{
EditorGUILayout.LabelField(comp.eggGroup2.ToString(), toolbarStyle, GUILayout.Width(128));
}
toolbarStyle.normal.textColor = Color.white;
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
//Abilities
GUI.backgroundColor = Color.black;
EditorGUILayout.LabelField("", EditorStyles.helpBox);
EditorGUILayout.LabelField("ABILITIES", headerStyle, GUILayout.Height(32f));
EditorGUILayout.BeginHorizontal();
string abilitiesString = "<color=blue>" + comp.standardAbilities[0].name;
for(int i = 1; i < comp.standardAbilities.Count; i++)
{
abilitiesString += ", " + comp.standardAbilities[i].name;
}
EditorGUILayout.LabelField(abilitiesString + "</color>", descriptionStyle);
EditorGUILayout.EndHorizontal();
if (comp.hiddenAbility != null)
{
EditorGUILayout.LabelField("Hidden Ability: <color=blue>" + comp.hiddenAbility.name + "</color>", descriptionStyle);
}
EditorGUILayout.Separator();
//Sprites
GUI.backgroundColor = Color.black;
EditorGUILayout.LabelField("", EditorStyles.helpBox);
EditorGUILayout.LabelField("SPRITES", headerStyle, GUILayout.Height(32f));
EditorGUILayout.BeginHorizontal();
GUILayout.Label(comp.sprite.texture, textureStyle, GUILayout.Width(128f), GUILayout.Height(128f));
GUILayout.Label(comp.backSprite.texture, textureStyle, GUILayout.Width(128f), GUILayout.Height(128f));
GUILayout.Label(comp.shinySprite.texture, textureStyle, GUILayout.Width(128f), GUILayout.Height(128f));
GUILayout.Label(comp.shinyBackSprite.texture, textureStyle, GUILayout.Width(128f), GUILayout.Height(128f));
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Main Sprite", captionStyle, GUILayout.Width(128f));
EditorGUILayout.LabelField("Back Sprite", captionStyle, GUILayout.Width(128f));
EditorGUILayout.LabelField("Shiny Sprite", captionStyle, GUILayout.Width(128f));
EditorGUILayout.LabelField("Shiny Back Sprite", captionStyle, GUILayout.Width(128f));
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
//BASE STATS
GUI.backgroundColor = Color.black;
EditorGUILayout.LabelField("", EditorStyles.helpBox);
EditorGUILayout.LabelField("BASE STATS", headerStyle, GUILayout.Height(32f));
GUI.backgroundColor = Color.cyan;
EditorGUIUtility.labelWidth = 128f;
GUI.backgroundColor = Color.white;
ProgressBar(comp.baseHP / 200f, comp.baseHP + " HP");
ProgressBar(comp.baseAttack / 200f, comp.baseAttack + " Attack");
ProgressBar(comp.baseDefense / 200f, comp.baseDefense + " Defense");
ProgressBar(comp.baseSpecialAttack / 200f, comp.baseSpecialAttack + " Special Attack");
ProgressBar(comp.baseSpecialDefense / 200f, comp.baseSpecialDefense + " Special Defense");
ProgressBar(comp.baseSpeed / 200f, comp.baseSpeed + " Speed");
EditorGUILayout.Separator();
string EVYieldString = "Yields <color=blue>";
if(comp.EV_HP>0) { EVYieldString += comp.EV_HP + "</color> HP EV(s) <color=blue>"; }
else if (comp.EV_Attack > 0) { EVYieldString += comp.EV_Attack + "</color> Attack EV(s) <color=blue>"; }
else if (comp.EV_Defense > 0) { EVYieldString += comp.EV_Defense + "</color> Defense EV(s) <color=blue>"; }
else if (comp.EV_Speed > 0) { EVYieldString += comp.EV_Speed + "</color> Speed EV(s) <color=blue>"; }
else if (comp.EV_SpecialAttack > 0) { EVYieldString += comp.EV_SpecialAttack + "</color> Special Attack EV(s) <color=blue>"; }
else if (comp.EV_SpecialDefense > 0) { EVYieldString += comp.EV_SpecialDefense + "</color> Special Defense EV(s) <color=blue>"; }
EVYieldString += "</color>";
EditorGUILayout.LabelField(EVYieldString, captionStyle, GUILayout.Height(32f));
//EVOLUTIONS
if (comp.evolutions.Count > 0)
{
GUI.backgroundColor = Color.black;
EditorGUILayout.LabelField("", EditorStyles.helpBox);
EditorGUILayout.LabelField("EVOLUTIONS", headerStyle, GUILayout.Height(32f));
foreach (Evolution evolution in comp.evolutions)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(64f));
switch (evolution.evolutionType) {
case Evolution.EvolutionType.LEVEL:
GUILayout.Label(evolution.resultant.sprite.texture, GUILayout.Width(64f), GUILayout.Height(64f));
EditorGUILayout.LabelField("Evolves into <b>" + evolution.resultant.name + "</b> at level <color=blue>" + evolution.levelToEvolve + "</color>", captionStyle, GUILayout.Height(64f));
break;
case Evolution.EvolutionType.ITEM:
GUILayout.Label(evolution.resultant.sprite.texture, textureStyle, GUILayout.Width(64f), GUILayout.Height(64f));
EditorGUILayout.LabelField("Evolves into <b>" + evolution.resultant.name + "</b> with item <color=blue>" + evolution.itemToEvolve.name + "</color>", captionStyle, GUILayout.Height(64f));
GUILayout.Label(evolution.itemToEvolve.sprite.texture, textureStyle, GUILayout.Width(32f), GUILayout.Height(64f));
//GUILayout.Label("", captionStyle, GUILayout.Width(128f), GUILayout.Height(64f));
break;
default:
break;
}
EditorGUILayout.LabelField("", GUILayout.Width(64f));
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
}
}
//MOVES
if (comp.learnedMoves.Count > 0)
{
GUI.backgroundColor = Color.black;
EditorGUILayout.LabelField("", EditorStyles.helpBox);
EditorGUILayout.LabelField("MOVES", headerStyle, GUILayout.Height(32f));
foreach (LearnedMove learnedMove in comp.learnedMoves)
{
EditorGUILayout.BeginHorizontal();
GUI.backgroundColor = learnedMove.move.type.color;
EditorGUILayout.LabelField(learnedMove.move.type.internalName, toolbarStyle, GUILayout.Width(128));
GUI.backgroundColor = Color.white;
EditorGUILayout.LabelField("Learns <b>" + learnedMove.move.name.PadRight(40, '.') + "</b> at level <color=blue>" + learnedMove.level.ToString().PadLeft(2,' ') + "</color>", descriptionStyle, GUILayout.Height(20f));
//EditorGUILayout.Separator();
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.Separator();
foreach (MoveData eggMove in comp.eggMoves)
{
EditorGUILayout.BeginHorizontal();
GUI.backgroundColor = eggMove.type.color;
EditorGUILayout.LabelField(eggMove.type.internalName, toolbarStyle, GUILayout.Width(128));
GUI.backgroundColor = Color.white;
EditorGUILayout.LabelField("Learns <b>" + eggMove.name.PadRight(40, '.') + "</b> as <color=blue>egg move</color>", descriptionStyle, GUILayout.Height(20f));
//EditorGUILayout.Separator();
EditorGUILayout.EndHorizontal();
}
}
}
public void ProgressBar(float value, string label)
{
Rect rect = GUILayoutUtility.GetRect(18, 18, "TextField");
EditorGUI.ProgressBar(rect, value, label);
EditorGUILayout.Space();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Portal : MonoBehaviour
{
public Portal target;
public Direction facingDirectionExit;
public void OnEntered()
{
}
public void OnExited()
{
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawLine(transform.position, target.transform.position);
Gizmos.DrawWireCube(transform.position, Vector3.one);
}
}
<file_sep>using UnityEngine;
[System.Serializable]
public class AbilityData : ScriptableObject {
public int ID;
public new string name;
public string internalName;
public string description;
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
public class Debugger : MonoBehaviour {
public InputField field;
public static Debugger instance;
private Battle battle;
private bool active = false;
public bool IsActive() {
return active;
}
private void Awake() {
instance = this;
}
public void Start()
{
battle = Battle.instance;
}
private void Update() {
if (Input.GetKeyDown (KeyCode.BackQuote)) {
active = !active;
}
if (active) {
field.gameObject.SetActive (true);
field.ActivateInputField ();
} else {
field.text = "";
field.gameObject.SetActive (false);
}
}
public void TerminalInput() {
string[] plots = field.text.ToLower().Split (new char[] { ' ', '.' }, System.StringSplitOptions.None);
int x = 0;
if (plots.Length > 0)
{
if (plots.Length > 2)
{
if (!System.Int32.TryParse(plots[2], out x)) { }
}
switch (plots[0])
{
default:
Debug.Log("Not a command! Use 'help basic' for commands.");
break;
case "":
break;
case "startbattle":
battle.StartBattle();
break;
case "ally":
switch (plots[1])
{
case "modhp":
battle.allyPokemon.ModHP(x);
break;
case "modxp":
Debug.Log("mod xp " + battle.allyPokemon.XP);
battle.allyPokemon.ModXP(x);
break;
case "modstatus":
battle.allyPokemon.AfflictStatus(plots[2]);
break;
case "userandommove":
Debug.Log(battle.SingleAttack(battle.allyPokemon, battle.foePokemon, Random.Range(0, 4)));
break;
case "usemove":
Debug.Log(battle.SingleAttack(battle.allyPokemon, battle.foePokemon, x));
break;
}
break;
case "foe":
switch (plots[1])
{
case "modhp":
battle.foePokemon.ModHP(x);
break;
case "modxp":
battle.foePokemon.ModXP(x);
break;
case "modstatus":
battle.foePokemon.AfflictStatus(plots[2]);
break;
case "userandommove":
Debug.Log(battle.SingleAttack(battle.foePokemon, battle.allyPokemon, Random.Range(0, 4)));
break;
case "usemove":
Debug.Log(battle.SingleAttack(battle.foePokemon, battle.allyPokemon, x));
break;
}
break;
}
}
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(EntitySpriteData))]
public class EntitySpriteDataEditor : Editor
{
EntitySpriteData comp;
int timer = 0;
int indexer = 0;
int[] spriteIndexArray = { 0, 1, 0, 2 };
public void OnEnable()
{
comp = (EntitySpriteData)target;
}
public override bool RequiresConstantRepaint()
{
return true;
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
timer++;
if (timer >= 16)
{
timer = 0;
indexer++;
if (indexer >= 4) { indexer = 0; }
}
int index = spriteIndexArray[indexer];
int middle = Screen.width / 2;
if (comp.northSprites.Length == 3)
{
Rect northSpritesRect = new Rect(middle - 64, 400, 64, 96);
Sprite s = comp.northSprites[index];
DrawTexturePreview(northSpritesRect, s);
}
if (comp.eastSprites.Length == 3)
{
Rect eastSpritesRect = new Rect(middle, 400, 64, 96);
Sprite s = comp.eastSprites[index];
DrawTexturePreview(eastSpritesRect, s);
}
if (comp.southSprites.Length == 3)
{
Rect southSpritesRect = new Rect(middle + 64, 400, 64, 96);
Sprite s = comp.southSprites[index];
DrawTexturePreview(southSpritesRect, s);
}
}
private void DrawTexturePreview(Rect position, Sprite sprite)
{
Vector2 fullSize = new Vector2(sprite.texture.width, sprite.texture.height);
Vector2 size = new Vector2(sprite.textureRect.width, sprite.textureRect.height);
Rect coords = sprite.textureRect;
coords.x /= fullSize.x;
coords.width /= fullSize.x;
coords.y /= fullSize.y;
coords.height /= fullSize.y;
Vector2 ratio;
ratio.x = position.width / size.x;
ratio.y = position.height / size.y;
float minRatio = Mathf.Min(ratio.x, ratio.y);
Vector2 center = position.center;
position.width = size.x * minRatio;
position.height = size.y * minRatio;
position.center = center;
GUI.DrawTextureWithTexCoords(position, sprite.texture, coords);
}
}
<file_sep>using UnityEngine;
[System.Serializable]
public class ItemData : ScriptableObject {
public enum ItemType
{
NONE, // 0 - None
ITEM, // 1 - Items
MEDICINE, // 2 - Medicine
POKEBALL, // 3 - Poké Balls
TM, // 4 - TMs & HMs
BERRIES, // 5 - Berries
MAIL, // 6 - Mail
BATTLE, // 7 - Battle Items
KEY // 8 - Key Items
}
public enum OverworldType
{
NONE, // 0 - The item cannot be used outside of battle.
ONPOKEMON_SINGLEUSE, // 1 - The item can be used on a Pokémon, and disappears after use(e.g.Potions, Elixirs).
// The party screen will appear when using this item, allowing you to choose
// the Pokémon to use it on. Not for TMs and HMs, though.
NOTONPOKEMON, // 2 - The item can be used out of battle, but it isn't used on a Pokémon (e.g. Repel, Escape Rope, usable Key Items).
TM, // 3 - The item is a TM. It teaches a move to a Pokémon, and disappears after use (unless TMs are set to infinite use).
HM, // 4 - The item is a HM. It teaches a move to a Pokémon, but does not disappear after use.
ONPOKEMON_PERM // 5 - The item can be used on a Pokémon (like 1), but it does not disappear after use (e.g. Poké Flute).
}
public enum BattleType
{
NONE, // 0 - The item cannot be used in battle.
ONPOKEMON_SINGLEUSE, // 1 - The item can be used on one of your party Pokémon, and disappears after use(e.g.Potions, Elixirs). The party screen will appear when using this item, allowing you to choose the Pokémon to use it on.
DIRECT_SINGLEUSE, // 2 - The item is a Poké Ball, is used on the active Pokémon you are choosing a command for (e.g.X Accuracy), or is used directly (e.g.Poké Doll).
ONPOKEMON_PERM, // 3 - The item can be used on a Pokémon (like 1), but does not disappear after use (e.g. Poké Flute).
DIRECT_PERMANENT // 4 - The item can be used directly, but does not disappear after use.
}
public enum SpecialItemType
{
NONE, // 0 - The item is none of the items below.
MAIL, // 1 - The item is a Mail item.
MAIL_SPECIAL, // 2 - The item is a Mail item, and the images of the holder and two other party Pokémon appear on the Mail.
SNAG, // 3 - The item is a Snag Ball(i.e.it can capture enemy trainers' Shadow Pokémon).
POKEBALL, // 4 - The item is a Poké Ball item.
PLANTABLE_BERRY, // 5 - The item is a berry that can be planted.
KEY_ITEM, // 6 - The item is a Key Item.
EVOLUTION_STONE, // 7 - The item is an evolution stone.
FOSSIL, // 8 - The item is a fossil that can be revived.
APRICORN, // 9 - The item is an Apricorn that can be converted into a Poké Ball.
ELEMENTAL_GEM, // 10 - The item is an elemental power-raising Gem.
MULCH, // 11 - The item is mulch that can be spread on berry patches.
MEGA_STONE // 12 - The item is a Mega Stone.This does NOT include the Red/Blue Orbs.
}
public int ID;
public new string name;
public string internalName;
public string description;
public Sprite sprite;
public int price;
public ItemType itemType;
public OverworldType overworldUsabilityID;
public BattleType battleUsabilityID;
public SpecialItemType specialItemID;
/// <summary>
/// Only for HMs and TMs.
/// </summary>
public MoveData TMmoveToLearn;
}
<file_sep>[0]
Name=MissingNo
InternalName=MISSINGNO
Type1=NORMAL
Type2=
BaseStats=100,100,100,100,100,100
GenderRate=FemaleOneEighth
GrowthRate=Parabolic
BaseEXP=64
EffortPoints=0,0,0,0,0,0
Rareness=45
Happiness=70
Abilities=SLACKOFF
HiddenAbility=REGENERATOR
Moves=1,TACKLE,3,GROWL,7,LEECHSEED,9,HYPERBEAM,
EggMoves=
Compatibility=Monster
StepsToHatch=5355
Height=10.0
Weight=5.0
Color=GREY
Habitat=Grassland
RegionalNumbers=1,231
Kind=Undiscovered
Pokedex=Undiscovered
BattlerPlayerY=0
BattlerEnemyY=25
BattlerAltitude=0
Evolutions=
[1]
Name=Bulbasaur
InternalName=BULBASAUR
Type1=GRASS
Type2=POISON
BaseStats=45,49,49,45,65,65
GenderRate=FemaleOneEighth
GrowthRate=Parabolic
BaseEXP=64
EffortPoints=0,0,0,0,1,0
Rareness=45
Happiness=70
Abilities=OVERGROW
HiddenAbility=CHLOROPHYLL
Moves=1,TACKLE,3,GROWL,7,LEECHSEED,9,VINEWHIP,13,POISONPOWDER,13,SLEEPPOWDER,15,TAKEDOWN,19,RAZORLEAF,21,SWEETSCENT,25,GROWTH,27,DOUBLEEDGE,31,WORRYSEED,33,SYNTHESIS,37,SEEDBOMB
EggMoves=AMNESIA,CHARM,CURSE,ENDURE,GIGADRAIN,GRASSWHISTLE,INGRAIN,LEAFSTORM,MAGICALLEAF,NATUREPOWER,PETALDANCE,POWERWHIP,SKULLBASH,SLUDGE
Compatibility=Monster,Grass
StepsToHatch=5355
Height=0.7
Weight=6.9
Color=Green
Habitat=Grassland
RegionalNumbers=1,231
Kind=Seed
Pokedex=Bulbasaur can be seen napping in bright sunlight. There is a seed on its back. By soaking up the sun's rays, the seed grows progressively larger.
BattlerPlayerY=0
BattlerEnemyY=25
BattlerAltitude=0
Evolutions=IVYSAUR,Level,16
[2]
Name=Ivysaur
InternalName=IVYSAUR
Type1=GRASS
Type2=POISON
BaseStats=60,62,63,60,80,80
GenderRate=FemaleOneEighth
GrowthRate=Parabolic
BaseEXP=142
EffortPoints=0,0,0,0,1,1
Rareness=45
Happiness=70
Abilities=OVERGROW
HiddenAbility=CHLOROPHYLL
Moves=1,TACKLE,1,GROWL,1,LEECHSEED,3,GROWL,7,LEECHSEED,9,VINEWHIP,13,POISONPOWDER,13,SLEEPPOWDER,15,TAKEDOWN,20,RAZORLEAF,23,SWEETSCENT,28,GROWTH,31,DOUBLEEDGE,36,WORRYSEED,39,SYNTHESIS,44,SOLARBEAM
Compatibility=Monster,Grass
StepsToHatch=5355
Height=1.0
Weight=13.0
Color=Green
Habitat=Grassland
RegionalNumbers=2,232
Kind=Seed
Pokedex=To support its bulb, Ivysaur's legs grow sturdy. If it spends more time lying in the sunlight, the bud will soon bloom into a large flower.
BattlerPlayerY=0
BattlerEnemyY=21
BattlerAltitude=0
Evolutions=VENUSAUR,Level,32
[3]
Name=Venusaur
InternalName=VENUSAUR
Type1=GRASS
Type2=POISON
BaseStats=80,82,83,80,100,100
GenderRate=FemaleOneEighth
GrowthRate=Parabolic
BaseEXP=236
EffortPoints=0,0,0,0,2,1
Rareness=45
Happiness=70
Abilities=OVERGROW
HiddenAbility=CHLOROPHYLL
Moves=1,TACKLE,1,GROWL,1,LEECHSEED,1,VINEWHIP,3,GROWL,7,LEECHSEED,9,VINEWHIP,13,POISONPOWDER,13,SLEEPPOWDER,15,TAKEDOWN,20,RAZORLEAF,23,SWEETSCENT,28,GROWTH,31,DOUBLEEDGE,32,PETALDANCE,39,WORRYSEED,45,SYNTHESIS,53,SOLARBEAM
Compatibility=Monster,Grass
StepsToHatch=5355
Height=2.0
Weight=100.0
Color=Green
Habitat=Grassland
RegionalNumbers=3,233
Kind=Seed
Pokedex=Venusaur's flower is said to take on vivid colors if it gets plenty of nutrition and sunlight. The flower's aroma soothes the emotions of people.
BattlerPlayerY=0
BattlerEnemyY=9
BattlerAltitude=0
Evolutions=
[4]
Name=Charmander
InternalName=CHARMANDER
Type1=FIRE
BaseStats=39,52,43,65,60,50
GenderRate=FemaleOneEighth
GrowthRate=Parabolic
BaseEXP=62
EffortPoints=0,0,0,1,0,0
Rareness=45
Happiness=70
Abilities=BLAZE
HiddenAbility=SOLARPOWER
Moves=1,SCRATCH,1,GROWL,7,EMBER,10,SMOKESCREEN,16,DRAGONRAGE,19,SCARYFACE,25,FIREFANG,28,FLAMEBURST,34,SLASH,37,FLAMETHROWER,43,FIRESPIN,46,INFERNO
EggMoves=ANCIENTPOWER,BEATUP,BELLYDRUM,BITE,COUNTER,CRUNCH,DRAGONDANCE,DRAGONPULSE,DRAGONRUSH,FLAREBLITZ,FOCUSPUNCH,METALCLAW,OUTRAGE
Compatibility=Monster,Dragon
StepsToHatch=5355
Height=0.6
Weight=8.5
Color=Red
Habitat=Mountain
Kind=Lizard
Pokedex=The flame that burns at the tip of its tail is an indication of its emotions. The flame wavers when Charmander is happy, and blazes when it is enraged.
BattlerPlayerY=0
BattlerEnemyY=21
BattlerAltitude=0
Evolutions=CHARMELEON,Level,16
[5]
Name=Charmeleon
InternalName=CHARMELEON
Type1=FIRE
BaseStats=58,64,58,80,80,65
GenderRate=FemaleOneEighth
GrowthRate=Parabolic
BaseEXP=142
EffortPoints=0,0,0,1,1,0
Rareness=45
Happiness=70
Abilities=BLAZE
HiddenAbility=SOLARPOWER
Moves=1,SCRATCH,1,GROWL,1,EMBER,7,EMBER,10,SMOKESCREEN,17,DRAGONRAGE,21,SCARYFACE,28,FIREFANG,32,FLAMEBURST,39,SLASH,43,FLAMETHROWER,50,FIRESPIN,54,INFERNO
Compatibility=Monster,Dragon
StepsToHatch=5355
Height=1.1
Weight=19.0
Color=Red
Habitat=Mountain
RegionalNumbers=5,235
Kind=Flame
Pokedex=Without pity, its sharp claws destroy foes. If it encounters a strong enemy, it becomes agitated, and the flame on its tail flares with a bluish white color.
BattlerPlayerY=0
BattlerEnemyY=17
BattlerAltitude=0
Evolutions=CHARIZARD,Level,36
[6]
Name=Charizard
InternalName=CHARIZARD
Type1=FIRE
Type2=FLYING
BaseStats=78,84,78,100,109,85
GenderRate=FemaleOneEighth
GrowthRate=Parabolic
BaseEXP=240
EffortPoints=0,0,0,0,3,0
Rareness=45
Happiness=70
Abilities=BLAZE
HiddenAbility=SOLARPOWER
Moves=1,AIRSLASH,1,DRAGONCLAW,1,SHADOWCLAW,1,SCRATCH,1,GROWL,1,EMBER,1,SMOKESCREEN,7,EMBER,10,SMOKESCREEN,17,DRAGONRAGE,21,SCARYFACE,28,FIREFANG,32,FLAMEBURST,36,WINGATTACK,41,SLASH,47,FLAMETHROWER,56,FIRESPIN,62,INFERNO,71,HEATWAVE,77,FLAREBLITZ
Compatibility=Monster,Dragon
StepsToHatch=5355
Height=1.7
Weight=90.5
Color=Red
Habitat=Mountain
RegionalNumbers=6,236
Kind=Flame
Pokedex=A Charizard flies about in search of strong opponents. It breathes intense flames that can melt any material. However, it will never torch a weaker foe.
BattlerPlayerY=0
BattlerEnemyY=2
BattlerAltitude=0
Evolutions=
[7]
Name=Squirtle
InternalName=SQUIRTLE
Type1=WATER
BaseStats=44,48,65,43,50,64
GenderRate=FemaleOneEighth
GrowthRate=Parabolic
BaseEXP=63
EffortPoints=0,0,1,0,0,0
Rareness=45
Happiness=70
Abilities=TORRENT
HiddenAbility=RAINDISH
Moves=1,TACKLE,4,TAILWHIP,7,BUBBLE,10,WITHDRAW,13,WATERGUN,16,BITE,19,RAPIDSPIN,22,PROTECT,25,WATERPULSE,28,AQUATAIL,31,SKULLBASH,34,IRONDEFENSE,37,RAINDANCE,40,HYDROPUMP
EggMoves=AQUAJET,AQUARING,BRINE,FAKEOUT,FLAIL,FORESIGHT,HAZE,MIRRORCOAT,MIST,MUDSPORT,MUDDYWATER,REFRESH,WATERSPOUT,YAWN
Compatibility=Monster,Water1
StepsToHatch=5355
Height=0.5
Weight=9.0
Color=Blue
Habitat=WatersEdge
Kind=Tiny Turtle
Pokedex=Its shell is not just for protection. Its rounded shape and the grooves on its surface minimize resistance in water, enabling Squirtle to swim at high speeds.
BattlerPlayerY=0
BattlerEnemyY=22
BattlerAltitude=0
Evolutions=WARTORTLE,Level,16
[8]
Name=Wartortle
InternalName=WARTORTLE
Type1=WATER
BaseStats=59,63,80,58,65,80
GenderRate=FemaleOneEighth
GrowthRate=Parabolic
BaseEXP=142
EffortPoints=0,0,1,0,0,1
Rareness=45
Happiness=70
Abilities=TORRENT
HiddenAbility=RAINDISH
Moves=1,TACKLE,1,TAILWHIP,1,BUBBLE,4,TAILWHIP,7,BUBBLE,10,WITHDRAW,13,WATERGUN,16,BITE,20,RAPIDSPIN,24,PROTECT,28,WATERPULSE,32,AQUATAIL,36,SKULLBASH,40,IRONDEFENSE,44,RAINDANCE,48,HYDROPUMP
Compatibility=Monster,Water1
StepsToHatch=5355
Height=1.0
Weight=22.5
Color=Blue
Habitat=WatersEdge
RegionalNumbers=8,238
Kind=Turtle
Pokedex=Its large tail is covered with rich, thick fur that deepens in color with age. The scratches on its shell are evidence of this Pokémon's toughness in battle.
BattlerPlayerY=0
BattlerEnemyY=15
BattlerAltitude=0
Evolutions=BLASTOISE,Level,36
[9]
Name=Blastoise
InternalName=BLASTOISE
Type1=WATER
BaseStats=79,83,100,78,85,105
GenderRate=FemaleOneEighth
GrowthRate=Parabolic
BaseEXP=239
EffortPoints=0,0,0,0,0,3
Rareness=45
Happiness=70
Abilities=TORRENT
HiddenAbility=RAINDISH
Moves=1,FLASHCANNON,1,TACKLE,1,TAILWHIP,1,BUBBLE,1,WITHDRAW,4,TAILWHIP,7,BUBBLE,10,WITHDRAW,13,WATERGUN,16,BITE,20,RAPIDSPIN,24,PROTECT,28,WATERPULSE,32,AQUATAIL,39,SKULLBASH,46,IRONDEFENSE,53,RAINDANCE,60,HYDROPUMP
Compatibility=Monster,Water1
StepsToHatch=5355
Height=1.6
Weight=85.5
Color=Blue
Habitat=WatersEdge
RegionalNumbers=9,239
Kind=Shellfish
Pokedex=The waterspouts that protrude from its shell are highly accurate. Their bullets of water can precisely nail tin cans from a distance of over 160 feet.
BattlerPlayerY=0
BattlerEnemyY=10
BattlerAltitude=0
Evolutions=
[10]
Name=Caterpie
InternalName=CATERPIE
Type1=BUG
BaseStats=45,30,35,45,20,20
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=39
EffortPoints=1,0,0,0,0,0
Rareness=255
Happiness=70
Abilities=SHIELDDUST
HiddenAbility=RUNAWAY
Moves=1,TACKLE,1,STRINGSHOT,15,BUGBITE
Compatibility=Bug
StepsToHatch=4080
Height=0.3
Weight=2.9
Color=Green
Habitat=Forest
RegionalNumbers=10,24
Kind=Worm
Pokedex=Its voracious appetite compels it to devour leaves bigger than itself without hesitation. It releases a terribly strong odor from its antennae.
BattlerPlayerY=0
BattlerEnemyY=25
BattlerAltitude=0
Evolutions=METAPOD,Level,7
[11]
Name=Metapod
InternalName=METAPOD
Type1=BUG
BaseStats=50,20,55,30,25,25
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=72
EffortPoints=0,0,2,0,0,0
Rareness=120
Happiness=70
Abilities=SHEDSKIN
Moves=1,HARDEN,7,HARDEN
Compatibility=Bug
StepsToHatch=4080
Height=0.7
Weight=9.9
Color=Green
Habitat=Forest
RegionalNumbers=11,25
Kind=Cocoon
Pokedex=Its shell is as hard as an iron slab. A Metapod does not move very much because it is preparing its soft innards for evolution inside the shell.
BattlerPlayerY=0
BattlerEnemyY=25
BattlerAltitude=12
Evolutions=BUTTERFREE,Level,10
[12]
Name=Butterfree
InternalName=BUTTERFREE
Type1=BUG
Type2=FLYING
BaseStats=60,45,50,70,80,80
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=173
EffortPoints=0,0,0,0,2,1
Rareness=45
Happiness=70
Abilities=COMPOUNDEYES
HiddenAbility=TINTEDLENS
Moves=1,CONFUSION,10,CONFUSION,12,POISONPOWDER,12,STUNSPORE,12,SLEEPPOWDER,16,GUST,18,SUPERSONIC,22,WHIRLWIND,24,PSYBEAM,28,SILVERWIND,30,TAILWIND,34,RAGEPOWDER,36,SAFEGUARD,40,CAPTIVATE,42,BUGBUZZ,46,QUIVERDANCE
Compatibility=Bug
StepsToHatch=4080
Height=1.1
Weight=32.0
Color=White
Habitat=Forest
RegionalNumbers=12,26
Kind=Butterfly
Pokedex=It has a superior ability to search for delicious honey from flowers. It can seek, extract, and carry honey from flowers blooming over six miles away.
WildItemUncommon=SILVERPOWDER
BattlerPlayerY=0
BattlerEnemyY=16
BattlerAltitude=15
Evolutions=
[13]
Name=Weedle
InternalName=WEEDLE
Type1=BUG
Type2=POISON
BaseStats=40,35,30,50,20,20
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=39
EffortPoints=0,0,0,1,0,0
Rareness=255
Happiness=70
Abilities=SHIELDDUST
HiddenAbility=RUNAWAY
Moves=1,POISONSTING,1,STRINGSHOT,15,BUGBITE
Compatibility=Bug
StepsToHatch=4080
Height=0.3
Weight=3.2
Color=Brown
Habitat=Forest
RegionalNumbers=13,27
Kind=Hairy Bug
Pokedex=A Weedle has an extremely acute sense of smell. It distinguishes its favorite kinds of leaves from those it dislikes by sniffing with its big red proboscis (nose).
BattlerPlayerY=0
BattlerEnemyY=26
BattlerAltitude=0
Evolutions=KAKUNA,Level,7
[14]
Name=Kakuna
InternalName=KAKUNA
Type1=BUG
Type2=POISON
BaseStats=45,25,50,35,25,25
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=72
EffortPoints=0,0,2,0,0,0
Rareness=120
Happiness=70
Abilities=SHEDSKIN
Moves=1,HARDEN,7,HARDEN
Compatibility=Bug
StepsToHatch=4080
Height=0.6
Weight=10.0
Color=Yellow
Habitat=Forest
RegionalNumbers=14,28
Kind=Cocoon
Pokedex=It remains virtually immobile while it clings to a tree. However, on the inside, it busily prepares for evolution. This is evident from how hot its shell becomes.
BattlerPlayerY=0
BattlerEnemyY=24
BattlerAltitude=11
Evolutions=BEEDRILL,Level,10
[15]
Name=Beedrill
InternalName=BEEDRILL
Type1=BUG
Type2=POISON
BaseStats=65,80,40,75,45,80
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=173
EffortPoints=0,2,0,0,0,1
Rareness=45
Happiness=70
Abilities=SWARM
HiddenAbility=SNIPER
Moves=1,FURYATTACK,10,FURYATTACK,13,FOCUSENERGY,16,TWINEEDLE,19,RAGE,22,PURSUIT,25,TOXICSPIKES,28,PINMISSILE,31,AGILITY,34,ASSURANCE,37,POISONJAB,40,ENDEAVOR
Compatibility=Bug
StepsToHatch=4080
Height=1.0
Weight=29.5
Color=Yellow
Habitat=Forest
RegionalNumbers=15,29
Kind=Poison Bee
Pokedex=A Beedrill is extremely territorial. For safety reasons, no one should ever approach its nest. If angered, they will attack in a swarm.
WildItemUncommon=POISONBARB
BattlerPlayerY=0
BattlerEnemyY=13
BattlerAltitude=11
Evolutions=
[16]
Name=Pidgey
InternalName=PIDGEY
Type1=NORMAL
Type2=FLYING
BaseStats=40,45,40,56,35,35
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=50
EffortPoints=0,0,0,1,0,0
Rareness=255
Happiness=70
Abilities=KEENEYE,TANGLEDFEET
HiddenAbility=BIGPECKS
Moves=1,TACKLE,5,SANDATTACK,9,GUST,13,QUICKATTACK,17,WHIRLWIND,21,TWISTER,25,FEATHERDANCE,29,AGILITY,33,WINGATTACK,37,ROOST,41,TAILWIND,45,MIRRORMOVE,49,AIRSLASH,53,HURRICANE
EggMoves=AIRCUTTER,AIRSLASH,BRAVEBIRD,DEFOG,FAINTATTACK,FORESIGHT,PURSUIT,STEELWING,UPROAR
Compatibility=Flying
StepsToHatch=4080
Height=0.3
Weight=1.8
Color=Brown
Habitat=Forest
RegionalNumbers=16,10
Kind=Tiny Bird
Pokedex=It has an extremely sharp sense of direction. It can unerringly return home to its nest, however far it may be removed from its familiar surroundings.
BattlerPlayerY=0
BattlerEnemyY=22
BattlerAltitude=0
Evolutions=PIDGEOTTO,Level,18
[17]
Name=Pidgeotto
InternalName=PIDGEOTTO
Type1=NORMAL
Type2=FLYING
BaseStats=63,60,55,71,50,50
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=122
EffortPoints=0,0,0,2,0,0
Rareness=120
Happiness=70
Abilities=KEENEYE,TANGLEDFEET
HiddenAbility=BIGPECKS
Moves=1,TACKLE,1,SANDATTACK,1,GUST,5,SANDATTACK,9,GUST,13,QUICKATTACK,17,WHIRLWIND,22,TWISTER,27,FEATHERDANCE,32,AGILITY,37,WINGATTACK,42,ROOST,47,TAILWIND,52,MIRRORMOVE,57,AIRSLASH,62,HURRICANE
Compatibility=Flying
StepsToHatch=4080
Height=1.1
Weight=30.0
Color=Brown
Habitat=Forest
RegionalNumbers=17,11
Kind=Bird
Pokedex=This Pokémon flies around, patrolling its large territory. If its living space is violated, it shows no mercy in thoroughly punishing the foe with its sharp claws.
BattlerPlayerY=0
BattlerEnemyY=15
BattlerAltitude=0
Evolutions=PIDGEOT,Level,36
[18]
Name=Pidgeot
InternalName=PIDGEOT
Type1=NORMAL
Type2=FLYING
BaseStats=83,80,75,91,70,70
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=211
EffortPoints=0,0,0,3,0,0
Rareness=45
Happiness=70
Abilities=KEENEYE,TANGLEDFEET
HiddenAbility=BIGPECKS
Moves=1,TACKLE,1,SANDATTACK,1,GUST,1,QUICKATTACK,5,SANDATTACK,9,GUST,13,QUICKATTACK,17,WHIRLWIND,22,TWISTER,27,FEATHERDANCE,32,AGILITY,38,WINGATTACK,44,ROOST,50,TAILWIND,56,MIRRORMOVE,62,AIRSLASH,68,HURRICANE
Compatibility=Flying
StepsToHatch=4080
Height=1.5
Weight=39.5
Color=Brown
Habitat=Forest
RegionalNumbers=18,12
Kind=Bird
Pokedex=This Pokémon has gorgeous, glossy feathers. Many trainers are so captivated by the beautiful feathers on its head that they choose Pidgeot as their Pokémon.
BattlerPlayerY=0
BattlerEnemyY=6
BattlerAltitude=11
Evolutions=
[19]
Name=Rattata
InternalName=RATTATA
Type1=NORMAL
BaseStats=30,56,35,72,25,35
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=51
EffortPoints=0,0,0,1,0,0
Rareness=255
Happiness=70
Abilities=RUNAWAY,GUTS
HiddenAbility=HUSTLE
Moves=1,TACKLE,1,TAILWHIP,4,QUICKATTACK,7,FOCUSENERGY,10,BITE,13,PURSUIT,16,HYPERFANG,19,SUCKERPUNCH,22,CRUNCH,25,ASSURANCE,28,SUPERFANG,31,DOUBLEEDGE,34,ENDEAVOR
EggMoves=BITE,COUNTER,FINALGAMBIT,FLAMEWHEEL,FURYSWIPES,LASTRESORT,MEFIRST,REVENGE,REVERSAL,SCREECH,UPROAR
Compatibility=Field
StepsToHatch=4080
Height=0.3
Weight=3.5
Color=Purple
Habitat=Grassland
RegionalNumbers=19,17
Kind=Mouse
Pokedex=A Rattata is cautious in the extreme. Even while it is asleep, it constantly moves its ears and listens for danger. It will make its nest anywhere.
WildItemUncommon=CHILANBERRY
BattlerPlayerY=0
BattlerEnemyY=22
BattlerAltitude=0
Evolutions=RATICATE,Level,20
[20]
Name=Raticate
InternalName=RATICATE
Type1=NORMAL
BaseStats=55,81,60,97,50,70
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=145
EffortPoints=0,0,0,2,0,0
Rareness=127
Happiness=70
Abilities=RUNAWAY,GUTS
HiddenAbility=HUSTLE
Moves=1,SWORDSDANCE,1,TACKLE,1,TAILWHIP,1,QUICKATTACK,1,FOCUSENERGY,4,QUICKATTACK,7,FOCUSENERGY,10,BITE,13,PURSUIT,16,HYPERFANG,19,SUCKERPUNCH,20,SCARYFACE,24,CRUNCH,29,ASSURANCE,34,SUPERFANG,39,DOUBLEEDGE,44,ENDEAVOR
Compatibility=Field
StepsToHatch=4080
Height=0.7
Weight=18.5
Color=Brown
Habitat=Grassland
RegionalNumbers=20,18
Kind=Mouse
Pokedex=A Raticate's sturdy fangs grow steadily. To keep them ground down, it gnaws on rocks and logs. It may even chew on the walls of houses.
WildItemUncommon=CHILANBERRY
BattlerPlayerY=0
BattlerEnemyY=14
BattlerAltitude=0
Evolutions=
[21]
Name=Spearow
InternalName=SPEAROW
Type1=NORMAL
Type2=FLYING
BaseStats=40,60,30,70,31,31
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=52
EffortPoints=0,0,0,1,0,0
Rareness=255
Happiness=70
Abilities=KEENEYE
HiddenAbility=SNIPER
Moves=1,PECK,1,GROWL,5,LEER,9,FURYATTACK,13,PURSUIT,17,AERIALACE,21,MIRRORMOVE,25,AGILITY,29,ASSURANCE,33,ROOST,37,DRILLPECK
EggMoves=ASTONISH,FAINTATTACK,FEATHERDANCE,QUICKATTACK,RAZORWIND,SCARYFACE,SKYATTACK,STEELWING,TRIATTACK,UPROAR,WHIRLWIND
Compatibility=Flying
StepsToHatch=4080
Height=0.3
Weight=2.0
Color=Brown
Habitat=RoughTerrain
RegionalNumbers=21,13
Kind=Tiny Bird
Pokedex=Its loud cry can be heard over half a mile away. If its high, keening cry is heard echoing all around, it is a sign that they are warning each other of danger.
BattlerPlayerY=0
BattlerEnemyY=23
BattlerAltitude=0
Evolutions=FEAROW,Level,20
[22]
Name=Fearow
InternalName=FEAROW
Type1=NORMAL
Type2=FLYING
BaseStats=65,90,65,100,61,61
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=155
EffortPoints=0,0,0,2,0,0
Rareness=90
Happiness=70
Abilities=KEENEYE
HiddenAbility=SNIPER
Moves=1,PLUCK,1,PECK,1,GROWL,1,LEER,1,FURYATTACK,5,LEER,9,FURYATTACK,13,PURSUIT,17,AERIALACE,23,MIRRORMOVE,29,AGILITY,35,ASSURANCE,41,ROOST,47,DRILLPECK,53,DRILLRUN
Compatibility=Flying
StepsToHatch=4080
Height=1.2
Weight=38.0
Color=Brown
Habitat=RoughTerrain
RegionalNumbers=22,14
Kind=Beak
Pokedex=Its long neck and elongated beak are ideal for catching prey in soil or water. It deftly moves this extended and skinny beak to pluck prey.
WildItemUncommon=SHARPBEAK
BattlerPlayerY=0
BattlerEnemyY=4
BattlerAltitude=8
Evolutions=
[23]
Name=Ekans
InternalName=EKANS
Type1=POISON
BaseStats=35,60,44,55,40,54
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=58
EffortPoints=0,1,0,0,0,0
Rareness=255
Happiness=70
Abilities=INTIMIDATE,SHEDSKIN
HiddenAbility=UNNERVE
Moves=1,WRAP,1,LEER,4,POISONSTING,9,BITE,12,GLARE,17,SCREECH,20,ACID,25,STOCKPILE,25,SWALLOW,25,SPITUP,28,ACIDSPRAY,33,MUDBOMB,36,GASTROACID,41,HAZE,44,COIL,49,GUNKSHOT
EggMoves=BEATUP,DISABLE,IRONTAIL,POISONFANG,POISONTAIL,PURSUIT,SCARYFACE,SLAM,SNATCH,SPITE,SUCKERPUNCH,SWITCHEROO
Compatibility=Field,Dragon
StepsToHatch=5355
Height=2.0
Weight=6.9
Color=Purple
Habitat=Grassland
RegionalNumbers=23,50
Kind=Snake
Pokedex=An Ekans curls itself up in a spiral while it rests. This position allows it to quickly respond to an enemy from any direction with a threat from its upraised head.
BattlerPlayerY=0
BattlerEnemyY=21
BattlerAltitude=0
Evolutions=ARBOK,Level,22
[24]
Name=Arbok
InternalName=ARBOK
Type1=POISON
BaseStats=60,85,69,80,65,79
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=153
EffortPoints=0,2,0,0,0,0
Rareness=90
Happiness=70
Abilities=INTIMIDATE,SHEDSKIN
HiddenAbility=UNNERVE
Moves=1,ICEFANG,1,THUNDERFANG,1,FIREFANG,1,WRAP,1,LEER,1,POISONSTING,1,BITE,4,POISONSTING,9,BITE,12,GLARE,17,SCREECH,20,ACID,22,CRUNCH,27,STOCKPILE,27,SWALLOW,27,SPITUP,32,ACIDSPRAY,39,MUDBOMB,44,GASTROACID,51,HAZE,56,COIL,63,GUNKSHOT
Compatibility=Field,Dragon
StepsToHatch=5355
Height=3.5
Weight=65.0
Color=Purple
Habitat=Grassland
RegionalNumbers=24,51
Kind=Cobra
Pokedex=This Pokémon has a terrifically strong constricting power. It can even flatten steel oil drums. Once it wraps its body around its foe, escaping is impossible.
BattlerPlayerY=0
BattlerEnemyY=10
BattlerAltitude=0
Evolutions=
[25]
Name=Pikachu
InternalName=PIKACHU
Type1=ELECTRIC
BaseStats=35,55,30,90,50,40
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=105
EffortPoints=0,0,0,2,0,0
Rareness=190
Happiness=70
Abilities=STATIC
HiddenAbility=LIGHTNINGROD
Moves=1,GROWL,1,THUNDERSHOCK,5,TAILWHIP,10,THUNDERWAVE,13,QUICKATTACK,18,ELECTROBALL,21,DOUBLETEAM,26,SLAM,29,THUNDERBOLT,34,FEINT,37,AGILITY,42,DISCHARGE,45,LIGHTSCREEN,50,THUNDER
Compatibility=Field,Fairy
StepsToHatch=2805
Height=0.4
Weight=6.0
Color=Yellow
Habitat=Forest
RegionalNumbers=25,22
Kind=Mouse
Pokedex=It stores electricity in the electric sacs on its cheeks. When it releases pent-up energy in a burst, the electric power is equal to a lightning bolt.
WildItemCommon=ORANBERRY
WildItemRare=LIGHTBALL
BattlerPlayerY=0
BattlerEnemyY=15
BattlerAltitude=0
Evolutions=RAICHU,Item,THUNDERSTONE
[26]
Name=Raichu
InternalName=RAICHU
Type1=ELECTRIC
BaseStats=60,90,55,100,90,80
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=214
EffortPoints=0,0,0,3,0,0
Rareness=75
Happiness=70
Abilities=STATIC
HiddenAbility=LIGHTNINGROD
Moves=1,THUNDERSHOCK,1,TAILWHIP,1,QUICKATTACK,1,THUNDERBOLT
Compatibility=Field,Fairy
StepsToHatch=2805
Height=0.8
Weight=30.0
Color=Yellow
Habitat=Forest
RegionalNumbers=26,23
Kind=Mouse
Pokedex=If it stores too much electricity, its behavior turns aggressive. To avoid this, it occasionally discharges excess energy and calms itself down.
WildItemCommon=ORANBERRY
BattlerPlayerY=0
BattlerEnemyY=10
BattlerAltitude=0
Evolutions=
[27]
Name=Sandshrew
InternalName=SANDSHREW
Type1=GROUND
BaseStats=50,75,85,40,20,30
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=60
EffortPoints=0,0,1,0,0,0
Rareness=255
Happiness=70
Abilities=SANDVEIL
HiddenAbility=SANDRUSH
Moves=1,SCRATCH,1,DEFENSECURL,3,SANDATTACK,5,POISONSTING,7,ROLLOUT,9,RAPIDSPIN,11,SWIFT,14,FURYCUTTER,17,MAGNITUDE,20,FURYSWIPES,23,SANDTOMB,26,SLASH,30,DIG,34,GYROBALL,38,SWORDSDANCE,42,SANDSTORM,46,EARTHQUAKE
EggMoves=CHIPAWAY,COUNTER,CRUSHCLAW,ENDURE,FLAIL,METALCLAW,MUDSHOT,NIGHTSLASH,RAPIDSPIN,ROCKCLIMB
Compatibility=Field
StepsToHatch=5355
Height=0.6
Weight=12.0
Color=Yellow
Habitat=RoughTerrain
RegionalNumbers=27,48
Kind=Mouse
Pokedex=When it curls up in a ball, it can make any attack bounce off harmlessly. Its hide has turned tough and solid as a result of living in the desert.
WildItemUncommon=QUICKCLAW
BattlerPlayerY=0
BattlerEnemyY=21
BattlerAltitude=0
Evolutions=SANDSLASH,Level,22
[28]
Name=Sandslash
InternalName=SANDSLASH
Type1=GROUND
BaseStats=75,100,110,65,45,55
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=158
EffortPoints=0,0,2,0,0,0
Rareness=90
Happiness=70
Abilities=SANDVEIL
HiddenAbility=SANDRUSH
Moves=1,SCRATCH,1,DEFENSECURL,1,SANDATTACK,1,POISONSTING,3,SANDATTACK,5,POISONSTING,7,ROLLOUT,9,RAPIDSPIN,11,SWIFT,14,FURYCUTTER,17,MAGNITUDE,20,FURYSWIPES,22,CRUSHCLAW,26,SLASH,30,DIG,33,SANDTOMB,34,GYROBALL,38,SWORDSDANCE,42,SANDSTORM,46,EARTHQUAKE
Compatibility=Field
StepsToHatch=5355
Height=1.0
Weight=29.5
Color=Yellow
Habitat=RoughTerrain
RegionalNumbers=28,49
Kind=Mouse
Pokedex=It curls up in a ball to protect itself from enemy attacks. It also curls up to prevent heatstroke during the daytime when temperatures rise sharply.
WildItemUncommon=QUICKCLAW
BattlerPlayerY=0
BattlerEnemyY=18
BattlerAltitude=0
Evolutions=
[29]
Name=Nidoran
InternalName=NIDORANfE
Type1=POISON
BaseStats=55,47,52,41,40,40
GenderRate=AlwaysFemale
GrowthRate=Parabolic
BaseEXP=55
EffortPoints=1,0,0,0,0,0
Rareness=235
Happiness=70
Abilities=POISONPOINT,RIVALRY
HiddenAbility=HUSTLE
Moves=1,GROWL,1,SCRATCH,7,TAILWHIP,9,DOUBLEKICK,13,POISONSTING,19,FURYSWIPES,21,BITE,25,HELPINGHAND,31,TOXICSPIKES,33,FLATTER,37,CRUNCH,43,CAPTIVATE,45,POISONFANG
EggMoves=BEATUP,CHARM,CHIPAWAY,COUNTER,DISABLE,ENDURE,FOCUSENERGY,IRONTAIL,POISONTAIL,PURSUIT,SKULLBASH,SUPERSONIC,TAKEDOWN
Compatibility=Monster,Field
StepsToHatch=5355
Height=0.4
Weight=7.0
Color=Blue
Habitat=Grassland
RegionalNumbers=29,95
Kind=Poison Pin
Pokedex=Its highly toxic barbs are thought to have developed as protection for this small-bodied Pokémon. When enraged, it releases a horrible toxin from its horn.
BattlerPlayerY=0
BattlerEnemyY=25
BattlerAltitude=0
Evolutions=NIDORINA,Level,16
[30]
Name=Nidorina
InternalName=NIDORINA
Type1=POISON
BaseStats=70,62,67,56,55,55
GenderRate=AlwaysFemale
GrowthRate=Parabolic
BaseEXP=128
EffortPoints=2,0,0,0,0,0
Rareness=120
Happiness=70
Abilities=POISONPOINT,RIVALRY
HiddenAbility=HUSTLE
Moves=1,GROWL,1,SCRATCH,7,TAILWHIP,9,DOUBLEKICK,13,POISONSTING,20,FURYSWIPES,23,BITE,28,HELPINGHAND,35,TOXICSPIKES,38,FLATTER,43,CRUNCH,50,CAPTIVATE,58,POISONFANG
Compatibility=Monster,Field
StepsToHatch=5355
Height=0.8
Weight=20.0
Color=Blue
Habitat=Grassland
RegionalNumbers=30,96
Kind=Poison Pin
Pokedex=When it is with its friends or family, its barbs are tucked away to prevent injury. It appears to become nervous if separated from the others.
BattlerPlayerY=0
BattlerEnemyY=18
BattlerAltitude=0
Evolutions=NIDOQUEEN,Item,MOONSTONE
[31]
Name=Nidoqueen
InternalName=NIDOQUEEN
Type1=POISON
Type2=GROUND
BaseStats=90,82,87,76,75,85
GenderRate=AlwaysFemale
GrowthRate=Parabolic
BaseEXP=223
EffortPoints=3,0,0,0,0,0
Rareness=45
Happiness=70
Abilities=POISONPOINT,RIVALRY
HiddenAbility=SHEERFORCE
Moves=1,SCRATCH,1,TAILWHIP,1,DOUBLEKICK,1,POISONSTING,23,CHIPAWAY,35,BODYSLAM,43,EARTHPOWER,58,SUPERPOWER
Compatibility=Monster,Field
StepsToHatch=5355
Height=1.3
Weight=60.0
Color=Blue
Habitat=Grassland
RegionalNumbers=31,97
Kind=Drill
Pokedex=It is adept at sending foes flying with harsh tackles using its tough, scaly body. This Pokémon is at its strongest when it is defending its young.
BattlerPlayerY=0
BattlerEnemyY=7
BattlerAltitude=0
Evolutions=
[32]
Name=Nidoran
InternalName=NIDORANmA
Type1=POISON
BaseStats=46,57,40,50,40,40
GenderRate=AlwaysMale
GrowthRate=Parabolic
BaseEXP=55
EffortPoints=0,1,0,0,0,0
Rareness=235
Happiness=70
Abilities=POISONPOINT,RIVALRY
HiddenAbility=HUSTLE
Moves=1,LEER,1,PECK,7,FOCUSENERGY,9,DOUBLEKICK,13,POISONSTING,19,FURYATTACK,21,HORNATTACK,25,HELPINGHAND,31,TOXICSPIKES,33,FLATTER,37,POISONJAB,43,CAPTIVATE,45,HORNDRILL
EggMoves=AMNESIA,BEATUP,CHIPAWAY,CONFUSION,COUNTER,DISABLE,ENDURE,HEADSMASH,IRONTAIL,POISONTAIL,SUCKERPUNCH,SUPERSONIC,TAKEDOWN
Compatibility=Monster,Field
StepsToHatch=5355
Height=0.5
Weight=9.0
Color=Purple
Habitat=Grassland
RegionalNumbers=32,98
Kind=Poison Pin
Pokedex=The male Nidoran has developed muscles that freely move its ears in any direction. Even the slightest sound does not escape this Pokémon's notice.
BattlerPlayerY=0
BattlerEnemyY=22
BattlerAltitude=0
Evolutions=NIDORINO,Level,16
[33]
Name=Nidorino
InternalName=NIDORINO
Type1=POISON
BaseStats=61,72,57,65,55,55
GenderRate=AlwaysMale
GrowthRate=Parabolic
BaseEXP=128
EffortPoints=0,2,0,0,0,0
Rareness=120
Happiness=70
Abilities=POISONPOINT,RIVALRY
HiddenAbility=HUSTLE
Moves=1,LEER,1,PECK,7,FOCUSENERGY,9,DOUBLEKICK,13,POISONSTING,20,FURYATTACK,23,HORNATTACK,28,HELPINGHAND,35,TOXICSPIKES,38,FLATTER,43,POISONJAB,50,CAPTIVATE,58,HORNDRILL
Compatibility=Monster,Field
StepsToHatch=5355
Height=0.9
Weight=19.5
Color=Purple
Habitat=Grassland
RegionalNumbers=33,99
Kind=Poison Pin
Pokedex=Its horn is harder than a diamond. If it senses a hostile presence, all the barbs on its back bristle up at once, and it challenges the foe with all its might.
BattlerPlayerY=0
BattlerEnemyY=17
BattlerAltitude=0
Evolutions=NIDOKING,Item,MOONSTONE
[34]
Name=Nidoking
InternalName=NIDOKING
Type1=POISON
Type2=GROUND
BaseStats=81,92,77,85,85,75
GenderRate=AlwaysMale
GrowthRate=Parabolic
BaseEXP=223
EffortPoints=0,3,0,0,0,0
Rareness=45
Happiness=70
Abilities=POISONPOINT,RIVALRY
HiddenAbility=SHEERFORCE
Moves=1,PECK,1,FOCUSENERGY,1,DOUBLEKICK,1,POISONSTING,23,CHIPAWAY,35,THRASH,43,EARTHPOWER,58,MEGAHORN
Compatibility=Monster,Field
StepsToHatch=5355
Height=1.4
Weight=62.0
Color=Purple
Habitat=Grassland
RegionalNumbers=34,100
Kind=Drill
Pokedex=A Nidoking's thick tail packs enormously destructive power capable of toppling a metal transmission tower. Once it goes on a rampage, there is no stopping it.
BattlerPlayerY=0
BattlerEnemyY=9
BattlerAltitude=0
Evolutions=
[35]
Name=Clefairy
InternalName=CLEFAIRY
Type1=NORMAL
BaseStats=70,45,48,35,60,65
GenderRate=Female75Percent
GrowthRate=Fast
BaseEXP=113
EffortPoints=2,0,0,0,0,0
Rareness=150
Happiness=140
=CUTECHARM,MAGICGUARD
HiddenAbility=FRIENDGUARD
Moves=1,POUND,1,GROWL,4,ENCORE,7,SING,10,DOUBLESLAP,13,DEFENSECURL,16,FOLLOWME,19,BESTOW,22,WAKEUPSLAP,25,MINIMIZE,28,STOREDPOWER,31,METRONOME,34,COSMICPOWER,37,LUCKYCHANT,40,BODYSLAM,43,MOONLIGHT,46,LIGHTSCREEN,49,GRAVITY,52,METEORMASH,55,HEALINGWISH,58,AFTERYOU
Compatibility=Fairy
StepsToHatch=2805
Height=0.6
Weight=7.5
Color=Pink
Habitat=Mountain
RegionalNumbers=35,41
Kind=Fairy
Pokedex=On every night of a full moon, they come out to play. When dawn arrives, the tired Clefairy go to sleep nestled up against each other in deep and quiet mountains.
WildItemCommon=LEPPABERRY
WildItemUncommon=MOONSTONE
WildItemRare=COMETSHARD
BattlerPlayerY=0
BattlerEnemyY=25
BattlerAltitude=0
Evolutions=CLEFABLE,Item,MOONSTONE
[36]
Name=Clefable
InternalName=CLEFABLE
Type1=NORMAL
BaseStats=95,70,73,60,85,90
GenderRate=Female75Percent
GrowthRate=Fast
BaseEXP=213
EffortPoints=3,0,0,0,0,0
Rareness=25
Happiness=140
Abilities=CUTECHARM,MAGICGUARD
HiddenAbility=UNAWARE
Moves=1,SING,1,DOUBLESLAP,1,MINIMIZE,1,METRONOME
Compatibility=Fairy
StepsToHatch=2805
Height=1.3
Weight=40.0
Color=Pink
Habitat=Mountain
RegionalNumbers=36,42
Kind=Fairy
Pokedex=A Clefable uses its wings to skip lightly as if it were flying. Its bouncy step lets it even walk on water. On quiet, moonlit nights, it strolls on lakes.
WildItemCommon=LEPPABERRY
WildItemUncommon=MOONSTONE
WildItemRare=COMETSHARD
BattlerPlayerY=0
BattlerEnemyY=19
BattlerAltitude=0
Evolutions=
[37]
Name=Vulpix
InternalName=VULPIX
Type1=FIRE
BaseStats=38,41,40,65,50,65
GenderRate=Female75Percent
GrowthRate=Medium
BaseEXP=60
EffortPoints=0,0,0,1,0,0
Rareness=190
Happiness=70
Abilities=FLASHFIRE
HiddenAbility=DROUGHT
Moves=1,EMBER,4,TAILWHIP,7,ROAR,10,QUICKATTACK,12,FIRESPIN,15,CONFUSERAY,18,IMPRISON,20,FAINTATTACK,23,FLAMEBURST,26,WILLOWISP,28,HEX,31,PAYBACK,34,FLAMETHROWER,36,SAFEGUARD,39,EXTRASENSORY,42,FIREBLAST,44,GRUDGE,47,CAPTIVATE,50,INFERNO
EggMoves=DISABLE,EXTRASENSORY,FAINTATTACK,FLAIL,FLAREBLITZ,HEATWAVE,HEX,HOWL,HYPNOSIS,POWERSWAP,SECRETPOWER,SPITE,TAILSLAP
Compatibility=Field
StepsToHatch=5355
Height=0.6
Weight=9.9
Color=Brown
Habitat=Grassland
RegionalNumbers=37,127
Kind=Fox
Pokedex=It can freely control fire, making fiery orbs fly like will-o'-the-wisps. Just before evolution, its six tails grow hot as if on fire.
WildItemCommon=RAWSTBERRY
WildItemUncommon=RAWSTBERRY
WildItemRare=RAWSTBERRY
BattlerPlayerY=0
BattlerEnemyY=20
BattlerAltitude=0
Evolutions=NINETALES,Item,FIRESTONE
[38]
Name=Ninetales
InternalName=NINETALES
Type1=FIRE
BaseStats=73,76,75,100,81,100
GenderRate=Female75Percent
GrowthRate=Medium
BaseEXP=177
EffortPoints=0,0,0,1,0,1
Rareness=75
Happiness=70
Abilities=FLASHFIRE
HiddenAbility=DROUGHT
Moves=1,NASTYPLOT,1,EMBER,1,QUICKATTACK,1,CONFUSERAY,1,SAFEGUARD
Compatibility=Field
StepsToHatch=5355
Height=1.1
Weight=19.9
Color=Yellow
Habitat=Grassland
RegionalNumbers=38,128
Kind=Fox
Pokedex=It has long been said that each of the nine tails embody an enchanted power. A long-lived Ninetales will have fur that shines like gold.
WildItemCommon=RAWSTBERRY
WildItemUncommon=RAWSTBERRY
WildItemRare=RAWSTBERRY
BattlerPlayerY=0
BattlerEnemyY=10
BattlerAltitude=0
Evolutions=
[39]
Name=Jigglypuff
InternalName=JIGGLYPUFF
Type1=NORMAL
Type2=
BaseStats=115,45,20,20,45,25
GenderRate=Female75Percent
GrowthRate=Fast
BaseEXP=95
EffortPoints=2,0,0,0,0,0
Rareness=170
Happiness=70
Abilities=CUTECHARM
HiddenAbility=FRIENDGUARD
Moves=1,SING,5,DEFENSECURL,9,POUND,13,DISABLE,17,ROUND,21,ROLLOUT,25,DOUBLESLAP,29,REST,33,BODYSLAM,37,GYROBALL,41,WAKEUPSLAP,45,MIMIC,49,HYPERVOICE,53,DOUBLEEDGE
Compatibility=Fairy
StepsToHatch=2805
Height=0.5
Weight=5.5
Color=Pink
Habitat=Grassland
RegionalNumbers=39,44
Kind=Balloon
Pokedex=Nothing can avoid falling asleep hearing a Jigglypuff's song. The sound waves of its singing voice match the brain waves of someone in a deep sleep.
BattlerPlayerY=0
BattlerEnemyY=25
BattlerAltitude=0
Evolutions=WIGGLYTUFF,Item,MOONSTONE
[40]
Name=Wigglytuff
InternalName=WIGGLYTUFF
Type1=NORMAL
Type2=
BaseStats=140,70,45,45,75,50
GenderRate=Female75Percent
GrowthRate=Fast
BaseEXP=191
EffortPoints=3,0,0,0,0,0
Rareness=50
Happiness=70
Abilities=CUTECHARM
HiddenAbility=FRISK
Moves=1,SING,1,DISABLE,1,DEFENSECURL,1,DOUBLESLAP
Compatibility=Fairy
StepsToHatch=2805
Height=1.0
Weight=12.0
Color=Pink
Habitat=Grassland
RegionalNumbers=40,45
Kind=Balloon
Pokedex=Its fur is the ultimate in luxuriousness. Sleeping alongside a Wigglytuff is simply divine. Its body expands seemingly without end when it inhales.
BattlerPlayerY=0
BattlerEnemyY=13
BattlerAltitude=0
Evolutions=
[41]
Name=Zubat
InternalName=ZUBAT
Type1=POISON
Type2=FLYING
BaseStats=40,45,35,55,30,40
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=49
EffortPoints=0,0,0,1,0,0
Rareness=255
Happiness=70
Abilities=INNERFOCUS
HiddenAbility=INFILTRATOR
Moves=1,LEECHLIFE,4,SUPERSONIC,8,ASTONISH,12,BITE,15,WINGATTACK,19,CONFUSERAY,23,SWIFT,26,AIRCUTTER,30,ACROBATICS,34,MEANLOOK,37,POISONFANG,41,HAZE,45,AIRSLASH
EggMoves=BRAVEBIRD,CURSE,DEFOG,FAINTATTACK,GIGADRAIN,GUST,HYPNOSIS,NASTYPLOT,PURSUIT,QUICKATTACK,STEELWING,WHIRLWIND,ZENHEADBUTT
Compatibility=Flying
StepsToHatch=4080
Height=0.8
Weight=7.5
Color=Purple
Habitat=Cave
RegionalNumbers=41,37
Kind=Bat
Pokedex=While living in pitch-black caverns, their eyes gradually grew shut and deprived them of vision. They use ultrasonic waves to detect obstacles.
BattlerPlayerY=0
BattlerEnemyY=18
BattlerAltitude=13
Evolutions=GOLBAT,Level,22
[42]
Name=Golbat
InternalName=GOLBAT
Type1=POISON
Type2=FLYING
BaseStats=75,80,70,90,65,75
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=159
EffortPoints=0,0,0,2,0,0
Rareness=90
Happiness=70
Abilities=INNERFOCUS
HiddenAbility=INFILTRATOR
Moves=1,SCREECH,1,LEECHLIFE,1,SUPERSONIC,1,ASTONISH,4,SUPERSONIC,8,ASTONISH,12,BITE,15,WINGATTACK,19,CONFUSERAY,24,SWIFT,28,AIRCUTTER,33,ACROBATICS,38,MEANLOOK,42,POISONFANG,47,HAZE,52,AIRSLASH
Compatibility=Flying
StepsToHatch=4080
Height=1.6
Weight=55.0
Color=Purple
Habitat=Cave
RegionalNumbers=42,38
Kind=Bat
Pokedex=Its fangs easily puncture even thick animal hide. It loves to feast on the blood of people and Pokémon. It flits about in darkness and strikes from behind.
BattlerPlayerY=0
BattlerEnemyY=13
BattlerAltitude=12
Evolutions=
[43]
Name=Oddish
InternalName=ODDISH
Type1=GRASS
Type2=POISON
BaseStats=45,50,55,30,75,65
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=64
EffortPoints=0,0,0,0,1,0
Rareness=255
Happiness=70
Abilities=CHLOROPHYLL
HiddenAbility=RUNAWAY
Moves=1,ABSORB,5,SWEETSCENT,9,ACID,13,POISONPOWDER,15,STUNSPORE,17,SLEEPPOWDER,21,MEGADRAIN,25,LUCKYCHANT,29,NATURALGIFT,33,MOONLIGHT,37,GIGADRAIN,41,PETALDANCE
EggMoves=AFTERYOU,CHARM,FLAIL,INGRAIN,NATUREPOWER,RAZORLEAF,SECRETPOWER,SYNTHESIS,TEETERDANCE,TICKLE
Compatibility=Grass
StepsToHatch=5355
Height=0.5
Weight=5.4
Color=Blue
Habitat=Grassland
RegionalNumbers=43,83
Kind=Weed
Pokedex=This Pokémon grows by absorbing moonlight. During the daytime, it buries itself in the ground, leaving only its leaves exposed to avoid detection by its enemies.
BattlerPlayerY=0
BattlerEnemyY=24
BattlerAltitude=0
Evolutions=GLOOM,Level,21
[44]
Name=Gloom
InternalName=GLOOM
Type1=GRASS
Type2=POISON
BaseStats=60,65,70,40,85,75
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=138
EffortPoints=0,0,0,0,2,0
Rareness=120
Happiness=70
Abilities=CHLOROPHYLL
HiddenAbility=STENCH
Moves=1,ABSORB,1,SWEETSCENT,1,ACID,5,SWEETSCENT,9,ACID,13,POISONPOWDER,15,STUNSPORE,17,SLEEPPOWDER,23,MEGADRAIN,29,LUCKYCHANT,35,NATURALGIFT,41,MOONLIGHT,47,GIGADRAIN,53,PETALDANCE
Compatibility=Grass
StepsToHatch=5355
Height=0.8
Weight=8.6
Color=Blue
Habitat=Grassland
RegionalNumbers=44,84
Kind=Weed
Pokedex=A horribly noxious honey drools from its mouth. One whiff of the honey can result in memory loss. Some fans are said to enjoy this overwhelming stink, however.
BattlerPlayerY=0
BattlerEnemyY=22
BattlerAltitude=0
Evolutions=VILEPLUME,Item,LEAFSTONE
[45]
Name=Vileplume
InternalName=VILEPLUME
Type1=GRASS
Type2=POISON
BaseStats=75,80,85,50,100,90
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=216
EffortPoints=0,0,0,0,3,0
Rareness=45
Happiness=70
Abilities=CHLOROPHYLL
HiddenAbility=EFFECTSPORE
Moves=1,MEGADRAIN,1,AROMATHERAPY,1,STUNSPORE,1,POISONPOWDER,53,PETALDANCE,65,SOLARBEAM
Compatibility=Grass
StepsToHatch=5355
Height=1.2
Weight=18.6
Color=Red
Habitat=Grassland
RegionalNumbers=45,85
Kind=Flower
Pokedex=In seasons when it produces more pollen, the air around a Vileplume turns yellow with the powder as it walks. The pollen is highly toxic and causes paralysis.
BattlerPlayerY=0
BattlerEnemyY=15
BattlerAltitude=0
Evolutions=
[46]
Name=Paras
InternalName=PARAS
Type1=BUG
Type2=GRASS
BaseStats=35,70,55,25,45,55
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=57
EffortPoints=0,1,0,0,0,0
Rareness=190
Happiness=70
Abilities=EFFECTSPORE,DRYSKIN
HiddenAbility=DAMP
Moves=1,SCRATCH,6,STUNSPORE,6,POISONPOWDER,11,LEECHLIFE,17,FURYCUTTER,22,SPORE,27,SLASH,33,GROWTH,38,GIGADRAIN,43,AROMATHERAPY,49,RAGEPOWDER,54,XSCISSOR
EggMoves=AGILITY,BUGBITE,COUNTER,CROSSPOISON,ENDURE,FLAIL,LEECHSEED,METALCLAW,NATURALGIFT,PSYBEAM,PURSUIT,SCREECH,SWEETSCENT
Compatibility=Bug,Grass
StepsToHatch=5355
Height=0.3
Weight=5.4
Color=Red
Habitat=Forest
RegionalNumbers=46,70
Kind=Mushroom
Pokedex=A Paras has parasitic tochukaso mushrooms growing on its back. They grow by drawing nutrients from the host. They are valued as a medicine for long life.
WildItemCommon=TINYMUSHROOM
WildItemUncommon=BIGMUSHROOM
WildItemRare=BALMMUSHROOM
BattlerPlayerY=0
BattlerEnemyY=27
BattlerAltitude=0
Evolutions=PARASECT,Level,24
[47]
Name=Parasect
InternalName=PARASECT
Type1=BUG
Type2=GRASS
BaseStats=60,95,80,30,60,80
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=142
EffortPoints=0,2,1,0,0,0
Rareness=75
Happiness=70
Abilities=EFFECTSPORE,DRYSKIN
HiddenAbility=DAMP
Moves=1,CROSSPOISON,1,SCRATCH,1,STUNSPORE,1,POISONPOWDER,1,LEECHLIFE,6,STUNSPORE,6,POISONPOWDER,11,LEECHLIFE,17,FURYCUTTER,22,SPORE,29,SLASH,37,GROWTH,44,GIGADRAIN,51,AROMATHERAPY,59,RAGEPOWDER,66,XSCISSOR
Compatibility=Bug,Grass
StepsToHatch=5355
Height=1.0
Weight=29.5
Color=Red
Habitat=Forest
RegionalNumbers=47,71
Kind=Mushroom
Pokedex=Parasect are known to infest the roots of large trees en masse and drain nutrients. When an infested tree dies, they move onto another tree all at once.
WildItemCommon=TINYMUSHROOM
WildItemUncommon=BIGMUSHROOM
WildItemRare=BALMMUSHROOM
BattlerPlayerY=0
BattlerEnemyY=16
BattlerAltitude=0
Evolutions=
[48]
Name=Venonat
InternalName=VENONAT
Type1=BUG
Type2=POISON
BaseStats=60,55,50,45,40,55
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=61
EffortPoints=0,0,0,0,0,1
Rareness=190
Happiness=70
Abilities=COMPOUNDEYES,TINTEDLENS
HiddenAbility=RUNAWAY
Moves=1,TACKLE,1,DISABLE,1,FORESIGHT,5,SUPERSONIC,11,CONFUSION,13,POISONPOWDER,17,LEECHLIFE,23,STUNSPORE,25,PSYBEAM,29,SLEEPPOWDER,35,SIGNALBEAM,37,ZENHEADBUTT,41,POISONFANG,47,PSYCHIC
EggMoves=AGILITY,BATONPASS,BUGBITE,GIGADRAIN,MORNINGSUN,RAGEPOWDER,SCREECH,SECRETPOWER,SIGNALBEAM,SKILLSWAP,TOXICSPIKES
Compatibility=Bug
StepsToHatch=5355
Height=1.0
Weight=30.0
Color=Purple
Habitat=Forest
RegionalNumbers=48,109
Kind=Insect
Pokedex=Its coat of thin, stiff hair that covers its entire body is said to have evolved for protection. Its large eyes never fail to spot even miniscule prey.
BattlerPlayerY=0
BattlerEnemyY=14
BattlerAltitude=0
Evolutions=VENOMOTH,Level,31
[49]
Name=Venomoth
InternalName=VENOMOTH
Type1=BUG
Type2=POISON
BaseStats=70,65,60,90,90,75
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=158
EffortPoints=0,0,0,1,1,0
Rareness=75
Happiness=70
Abilities=SHIELDDUST,TINTEDLENS
HiddenAbility=WONDERSKIN
Moves=1,SILVERWIND,1,TACKLE,1,DISABLE,1,FORESIGHT,1,SUPERSONIC,5,SUPERSONIC,11,CONFUSION,13,POISONPOWDER,17,LEECHLIFE,23,STUNSPORE,25,PSYBEAM,29,SLEEPPOWDER,31,GUST,37,SIGNALBEAM,41,ZENHEADBUTT,47,POISONFANG,55,PSYCHIC,59,BUGBUZZ,63,QUIVERDANCE
Compatibility=Bug
StepsToHatch=5355
Height=1.5
Weight=12.5
Color=Purple
Habitat=Forest
RegionalNumbers=49,110
Kind=Poison Moth
Pokedex=Venomoth are nocturnal--they only are active at night. Their favorite prey are insects that gather around streetlights, attracted by the light in the darkness.
WildItemUncommon=SHEDSHELL
BattlerPlayerY=0
BattlerEnemyY=16
BattlerAltitude=15
Evolutions=
[50]
Name=Diglett
InternalName=DIGLETT
Type1=GROUND
BaseStats=10,55,25,95,35,45
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=53
EffortPoints=0,0,0,1,0,0
Rareness=255
Happiness=70
Abilities=SANDVEIL,ARENATRAP
HiddenAbility=SANDFORCE
Moves=1,SCRATCH,1,SANDATTACK,4,GROWL,7,ASTONISH,12,MUDSLAP,15,MAGNITUDE,18,BULLDOZE,23,SUCKERPUNCH,26,MUDBOMB,29,EARTHPOWER,34,DIG,37,SLASH,40,EARTHQUAKE,45,FISSURE
EggMoves=ANCIENTPOWER,ASTONISH,BEATUP,ENDURE,FAINTATTACK,FINALGAMBIT,HEADBUTT,MEMENTO,MUDBOMB,PURSUIT,REVERSAL,SCREECH,UPROAR
Compatibility=Field
StepsToHatch=5355
Height=0.2
Weight=0.8
Color=Brown
Habitat=Cave
RegionalNumbers=50,134
Kind=Mole
Pokedex=Diglett are raised in most farms. The reason is simple--wherever they burrow, the soil is left perfectly tilled for growing delicious crops.
WildItemUncommon=SOFTSAND
BattlerPlayerY=0
BattlerEnemyY=28
BattlerAltitude=0
Evolutions=DUGTRIO,Level,26
[51]
Name=Dugtrio
InternalName=DUGTRIO
Type1=GROUND
BaseStats=35,80,50,120,50,70
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=142
EffortPoints=0,0,0,2,0,0
Rareness=50
Happiness=70
Abilities=SANDVEIL,ARENATRAP
HiddenAbility=SANDFORCE
Moves=1,NIGHTSLASH,1,TRIATTACK,1,SCRATCH,1,SANDATTACK,1,GROWL,4,GROWL,7,ASTONISH,12,MUDSLAP,15,MAGNITUDE,18,BULLDOZE,23,SUCKERPUNCH,26,SANDTOMB,28,MUDBOMB,33,EARTHPOWER,40,DIG,45,SLASH,50,EARTHQUAKE,57,FISSURE
Compatibility=Field
StepsToHatch=5355
Height=0.7
Weight=33.3
Color=Brown
Habitat=Cave
RegionalNumbers=51,135
Kind=Mole
Pokedex=Because the triplets originally split from one body, they think exactly alike. They work cooperatively to burrow endlessly through the ground.
WildItemUncommon=SOFTSAND
BattlerPlayerY=0
BattlerEnemyY=21
BattlerAltitude=0
Evolutions=
[52]
Name=Meowth
InternalName=MEOWTH
Type1=NORMAL
BaseStats=40,45,35,90,40,40
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=58
EffortPoints=0,0,0,1,0,0
Rareness=255
Happiness=70
Abilities=PICKUP,TECHNICIAN
HiddenAbility=UNNERVE
Moves=1,SCRATCH,1,GROWL,6,BITE,9,FAKEOUT,14,FURYSWIPES,17,SCREECH,22,FAINTATTACK,25,TAUNT,30,PAYDAY,33,SLASH,38,NASTYPLOT,41,ASSURANCE,46,CAPTIVATE,49,NIGHTSLASH,54,FEINT
EggMoves=AMNESIA,ASSIST,CHARM,FLAIL,FOULPLAY,HYPNOSIS,IRONTAIL,LASTRESORT,ODORSLEUTH,PUNISHMENT,SNATCH,SPITE,TAILWHIP
Compatibility=Field
StepsToHatch=5355
Height=0.4
Weight=4.2
Color=Yellow
Habitat=Urban
RegionalNumbers=52,138
Kind=Scratch Cat
Pokedex=Meowth withdraw their sharp claws into their paws to silently sneak about. For some reason, this Pokémon loves shiny coins that glitter with light.
WildItemUncommon=QUICKCLAW
BattlerPlayerY=0
BattlerEnemyY=18
BattlerAltitude=0
Evolutions=PERSIAN,Level,28
[53]
Name=Persian
InternalName=PERSIAN
Type1=NORMAL
BaseStats=65,70,60,115,65,65
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=154
EffortPoints=0,0,0,2,0,0
Rareness=90
Happiness=70
Abilities=LIMBER,TECHNICIAN
HiddenAbility=UNNERVE
Moves=1,SWITCHEROO,1,SCRATCH,1,GROWL,1,BITE,1,FAKEOUT,6,BITE,9,FAKEOUT,14,FURYSWIPES,17,SCREECH,22,FAINTATTACK,25,TAUNT,28,SWIFT,32,POWERGEM,37,SLASH,44,NASTYPLOT,49,ASSURANCE,56,CAPTIVATE,61,NIGHTSLASH,68,FEINT
Compatibility=Field
StepsToHatch=5355
Height=1.0
Weight=32.0
Color=Yellow
Habitat=Urban
RegionalNumbers=53,139
Kind=Classy Cat
Pokedex=A Persian's six bold whiskers sense air movements to determine what is in its vicinity. It becomes docile if grabbed by the whiskers.
WildItemUncommon=QUICKCLAW
BattlerPlayerY=0
BattlerEnemyY=14
BattlerAltitude=0
Evolutions=
[54]
Name=Psyduck
InternalName=PSYDUCK
Type1=WATER
BaseStats=50,52,48,55,65,50
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=64
EffortPoints=0,0,0,0,1,0
Rareness=190
Happiness=70
Abilities=DAMP,CLOUDNINE
HiddenAbility=SWIFTSWIM
Moves=1,WATERSPORT,1,SCRATCH,4,TAILWHIP,8,WATERGUN,11,DISABLE,15,CONFUSION,18,WATERPULSE,22,FURYSWIPES,25,SCREECH,29,ZENHEADBUTT,32,AQUATAIL,36,SOAK,39,PSYCHUP,43,AMNESIA,46,HYDROPUMP,50,WONDERROOM
EggMoves=CONFUSERAY,CROSSCHOP,ENCORE,FORESIGHT,FUTURESIGHT,HYPNOSIS,MUDBOMB,PSYBEAM,REFRESH,SECRETPOWER,SLEEPTALK,SYNCHRONOISE,YAWN
Compatibility=Water1,Field
StepsToHatch=5355
Height=0.8
Weight=19.6
Color=Yellow
Habitat=WatersEdge
RegionalNumbers=54,140
Kind=Duck
Pokedex=When its headache intensifies, it starts using strange powers. However, it has no recollection of its powers, so it always looks befuddled and bewildered.
BattlerPlayerY=0
BattlerEnemyY=19
BattlerAltitude=0
Evolutions=GOLDUCK,Level,33
[55]
Name=Golduck
InternalName=GOLDUCK
Type1=WATER
BaseStats=80,82,78,85,95,80
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=175
EffortPoints=0,0,0,0,2,0
Rareness=75
Happiness=70
Abilities=DAMP,CLOUDNINE
HiddenAbility=SWIFTSWIM
Moves=1,AQUAJET,1,WATERSPORT,1,SCRATCH,1,TAILWHIP,1,WATERGUN,4,TAILWHIP,8,WATERGUN,11,DISABLE,15,CONFUSION,18,WATERPULSE,22,FURYSWIPES,25,SCREECH,29,ZENHEADBUTT,32,AQUATAIL,38,SOAK,43,PSYCHUP,49,AMNESIA,54,HYDROPUMP,60,WONDERROOM
Compatibility=Water1,Field
StepsToHatch=5355
Height=1.7
Weight=76.6
Color=Blue
Habitat=WatersEdge
RegionalNumbers=55,141
Kind=Duck
Pokedex=A Golduck is an adept swimmer. It sometimes joins competitive swimmers in training. It uses psychic powers when its forehead shimmers with light.
BattlerPlayerY=0
BattlerEnemyY=13
BattlerAltitude=0
Evolutions=
[56]
Name=Mankey
InternalName=MANKEY
Type1=FIGHTING
BaseStats=40,80,35,70,35,45
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=61
EffortPoints=0,1,0,0,0,0
Rareness=190
Happiness=70
Abilities=VITALSPIRIT,ANGERPOINT
HiddenAbility=DEFIANT
Moves=1,COVET,1,SCRATCH,1,LOWKICK,1,LEER,1,FOCUSENERGY,9,FURYSWIPES,13,KARATECHOP,17,SEISMICTOSS,21,SCREECH,25,ASSURANCE,33,SWAGGER,37,CROSSCHOP,41,THRASH,45,PUNISHMENT,49,CLOSECOMBAT,53,FINALGAMBIT
EggMoves=BEATUP,CLOSECOMBAT,COUNTER,ENCORE,FOCUSPUNCH,FORESIGHT,MEDITATE,REVENGE,REVERSAL,SLEEPTALK,SMELLINGSALT
Compatibility=Field
StepsToHatch=5355
Height=0.5
Weight=28.0
Color=Brown
Habitat=Mountain
RegionalNumbers=56,136
Kind=Pig Monkey
Pokedex=When it starts shaking and its nasal breathing turns rough, it's a sure sign of anger. However, since this happens instantly, there is no time to flee.
WildItemUncommon=PAYAPABERRY
BattlerPlayerY=0
BattlerEnemyY=20
BattlerAltitude=0
Evolutions=PRIMEAPE,Level,28
[57]
Name=Primeape
InternalName=PRIMEAPE
Type1=FIGHTING
BaseStats=65,105,60,95,60,70
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=159
EffortPoints=0,2,0,0,0,0
Rareness=75
Happiness=70
Abilities=VITALSPIRIT,ANGERPOINT
HiddenAbility=DEFIANT
Moves=1,FLING,1,SCRATCH,1,LOWKICK,1,LEER,1,FOCUSENERGY,9,FURYSWIPES,13,KARATECHOP,17,SEISMICTOSS,21,SCREECH,25,ASSURANCE,28,RAGE,35,SWAGGER,41,CROSSCHOP,47,THRASH,53,PUNISHMENT,59,CLOSECOMBAT,63,FINALGAMBIT
Compatibility=Field
StepsToHatch=5355
Height=1.0
Weight=32.0
Color=Brown
Habitat=Mountain
RegionalNumbers=57,137
Kind=Pig Monkey
Pokedex=When it becomes furious, its blood circulation becomes more robust, and its muscles are made stronger. But it also becomes much less intelligent.
WildItemUncommon=PAYAPABERRY
BattlerPlayerY=0
BattlerEnemyY=14
BattlerAltitude=0
Evolutions=
[58]
Name=Growlithe
InternalName=GROWLITHE
Type1=FIRE
BaseStats=55,70,45,60,70,50
GenderRate=Female25Percent
GrowthRate=Slow
BaseEXP=70
EffortPoints=0,1,0,0,0,0
Rareness=190
Happiness=70
Abilities=INTIMIDATE,FLASHFIRE
HiddenAbility=JUSTIFIED
Moves=1,BITE,1,ROAR,6,EMBER,8,LEER,10,ODORSLEUTH,12,HELPINGHAND,17,FLAMEWHEEL,19,REVERSAL,21,FIREFANG,23,TAKEDOWN,28,FLAMEBURST,30,AGILITY,32,RETALIATE,34,FLAMETHROWER,39,CRUNCH,41,HEATWAVE,43,OUTRAGE,45,FLAREBLITZ
EggMoves=BODYSLAM,CLOSECOMBAT,COVET,CRUNCH,DOUBLEKICK,DOUBLEEDGE,FIRESPIN,FLAREBLITZ,HEATWAVE,HOWL,IRONTAIL,MORNINGSUN,THRASH
Compatibility=Field
StepsToHatch=5355
Height=0.7
Weight=19.0
Color=Brown
Habitat=Grassland
RegionalNumbers=58,129
Kind=Puppy
Pokedex=Its superb sense of smell ensures that this Pokémon won't forget any scent, no matter what. It uses its sense of smell to detect the emotions of others.
WildItemCommon=RAWSTBERRY
WildItemUncommon=RAWSTBERRY
WildItemRare=RAWSTBERRY
BattlerPlayerY=0
BattlerEnemyY=17
BattlerAltitude=0
Evolutions=ARCANINE,Item,FIRESTONE
[59]
Name=Arcanine
InternalName=ARCANINE
Type1=FIRE
BaseStats=90,110,80,95,100,80
GenderRate=Female25Percent
GrowthRate=Slow
BaseEXP=194
EffortPoints=0,2,0,0,0,0
Rareness=75
Happiness=70
Abilities=INTIMIDATE,FLASHFIRE
HiddenAbility=JUSTIFIED
Moves=1,THUNDERFANG,1,BITE,1,ROAR,1,FIREFANG,1,ODORSLEUTH,34,EXTREMESPEED
Compatibility=Field
StepsToHatch=5355
Height=1.9
Weight=155.0
Color=Brown
Habitat=Grassland
RegionalNumbers=59,130
Kind=Legendary
Pokedex=This fleet-footed Pokémon is said to run over 6,200 miles in a single day and night. The fire that blazes wildly within its body is its source of power.
WildItemCommon=RAWSTBERRY
WildItemUncommon=RAWSTBERRY
WildItemRare=RAWSTBERRY
BattlerPlayerY=0
BattlerEnemyY=7
BattlerAltitude=0
Evolutions=
[60]
Name=Poliwag
InternalName=POLIWAG
Type1=WATER
BaseStats=40,50,40,90,40,40
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=60
EffortPoints=0,0,0,1,0,0
Rareness=255
Happiness=70
Abilities=WATERABSORB,DAMP
HiddenAbility=SWIFTSWIM
Moves=1,WATERSPORT,5,BUBBLE,8,HYPNOSIS,11,WATERGUN,15,DOUBLESLAP,18,RAINDANCE,21,BODYSLAM,25,BUBBLEBEAM,28,MUDSHOT,31,BELLYDRUM,35,WAKEUPSLAP,38,HYDROPUMP,41,MUDBOMB
EggMoves=BUBBLEBEAM,ENCORE,ENDEAVOR,ENDURE,HAZE,ICEBALL,MINDREADER,MIST,MUDSHOT,REFRESH,SPLASH,WATERPULSE,WATERSPORT
Compatibility=Water1
StepsToHatch=5355
Height=0.6
Weight=12.4
Color=Blue
Habitat=WatersEdge
RegionalNumbers=60,72
Kind=Tadpole
Pokedex=It is possible to see this Pokémon's spiral innards right through its thin skin. However, the skin is also very flexible. Even sharp fangs bounce right off it.
BattlerPlayerY=0
BattlerEnemyY=25
BattlerAltitude=0
Evolutions=POLIWHIRL,Level,25
[61]
Name=Poliwhirl
InternalName=POLIWHIRL
Type1=WATER
BaseStats=65,65,65,90,50,50
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=135
EffortPoints=0,0,0,2,0,0
Rareness=120
Happiness=70
Abilities=WATERABSORB,DAMP
HiddenAbility=SWIFTSWIM
Moves=1,WATERSPORT,1,BUBBLE,1,HYPNOSIS,5,BUBBLE,8,HYPNOSIS,11,WATERGUN,15,DOUBLESLAP,18,RAINDANCE,21,BODYSLAM,27,BUBBLEBEAM,32,MUDSHOT,37,BELLYDRUM,43,WAKEUPSLAP,48,HYDROPUMP,53,MUDBOMB
Compatibility=Water1
StepsToHatch=5355
Height=1.0
Weight=20.0
Color=Blue
Habitat=WatersEdge
RegionalNumbers=61,73
Kind=Tadpole
Pokedex=Its body surface is always wet and slick with an oily fluid. Because of this greasy covering, it can easily slip and slide out of the clutches of any enemy in battle.
WildItemUncommon=KINGSROCK
BattlerPlayerY=0
BattlerEnemyY=20
BattlerAltitude=0
Evolutions=POLIWRATH,Item,WATERSTONE
[62]
Name=Poliwrath
InternalName=POLIWRATH
Type1=WATER
Type2=FIGHTING
BaseStats=90,85,95,70,70,90
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=225
EffortPoints=0,0,3,0,0,0
Rareness=45
Happiness=70
Abilities=WATERABSORB,DAMP
HiddenAbility=SWIFTSWIM
Moves=1,BUBBLEBEAM,1,HYPNOSIS,1,DOUBLESLAP,1,SUBMISSION,32,DYNAMICPUNCH,43,MINDREADER,53,CIRCLETHROW
Compatibility=Water1
StepsToHatch=5355
Height=1.3
Weight=54.0
Color=Blue
Habitat=WatersEdge
RegionalNumbers=62,74
Kind=Tadpole
Pokedex=Its highly developed muscles never grow fatigued, however much it exercises. This Pokémon can swim back and forth across the Pacific Ocean without effort.
WildItemUncommon=KINGSROCK
BattlerPlayerY=0
BattlerEnemyY=15
BattlerAltitude=0
Evolutions=
[63]
Name=Abra
InternalName=ABRA
Type1=PSYCHIC
BaseStats=25,20,15,90,105,55
GenderRate=Female25Percent
GrowthRate=Parabolic
BaseEXP=62
EffortPoints=0,0,0,0,1,0
Rareness=200
Happiness=70
Abilities=SYNCHRONIZE,INNERFOCUS
HiddenAbility=MAGICGUARD
Moves=1,TELEPORT
EggMoves=BARRIER,ENCORE,FIREPUNCH,GUARDSPLIT,GUARDSWAP,ICEPUNCH,KNOCKOFF,POWERTRICK,SKILLSWAP,THUNDERPUNCH
Compatibility=Humanlike
StepsToHatch=5355
Height=0.9
Weight=19.5
Color=Brown
Habitat=Urban
RegionalNumbers=63,89
Kind=Psi
Pokedex=A Pokémon that sleeps 18 hours a day. Observation revealed that it uses Teleport to change its location once every hour.
WildItemUncommon=TWISTEDSPOON
BattlerPlayerY=0
BattlerEnemyY=20
BattlerAltitude=0
Evolutions=KADABRA,Level,16
[64]
Name=Kadabra
InternalName=KADABRA
Type1=PSYCHIC
BaseStats=40,35,30,105,120,70
GenderRate=Female25Percent
GrowthRate=Parabolic
BaseEXP=140
EffortPoints=0,0,0,0,2,0
Rareness=100
Happiness=70
Abilities=SYNCHRONIZE,INNERFOCUS
HiddenAbility=MAGICGUARD
Moves=1,TELEPORT,1,KINESIS,1,CONFUSION,16,CONFUSION,18,DISABLE,22,MIRACLEEYE,24,ALLYSWITCH,28,PSYBEAM,30,REFLECT,34,TELEKINESIS,36,RECOVER,40,PSYCHOCUT,42,ROLEPLAY,46,PSYCHIC,48,FUTURESIGHT,52,TRICK
Compatibility=Humanlike
StepsToHatch=5355
Height=1.3
Weight=56.5
Color=Brown
Habitat=Urban
RegionalNumbers=64,90
Kind=Psi
Pokedex=It is rumored that a boy with psychic abilities suddenly transformed into Kadabra while he was assisting research into extrasensory powers.
WildItemUncommon=TWISTEDSPOON
BattlerPlayerY=0
BattlerEnemyY=11
BattlerAltitude=0
Evolutions=ALAKAZAM,Level,32
[65]
Name=Alakazam
InternalName=ALAKAZAM
Type1=PSYCHIC
BaseStats=55,50,45,120,135,85
GenderRate=Female25Percent
GrowthRate=Parabolic
BaseEXP=221
EffortPoints=0,0,0,0,3,0
Rareness=50
Happiness=70
Abilities=SYNCHRONIZE,INNERFOCUS
HiddenAbility=MAGICGUARD
Moves=1,TELEPORT,1,KINESIS,1,CONFUSION,16,CONFUSION,18,DISABLE,22,MIRACLEEYE,24,ALLYSWITCH,28,PSYBEAM,30,REFLECT,34,TELEKINESIS,36,RECOVER,40,PSYCHOCUT,42,CALMMIND,46,PSYCHIC,48,FUTURESIGHT,52,TRICK
Compatibility=Humanlike
StepsToHatch=5355
Height=1.5
Weight=48.0
Color=Brown
Habitat=Urban
RegionalNumbers=65,91
Kind=Psi
Pokedex=While it has strong psychic abilities and high intelligence, an Alakazam's muscles are very weak. It uses psychic power to move its body.
WildItemUncommon=TWISTEDSPOON
BattlerPlayerY=0
BattlerEnemyY=10
BattlerAltitude=0
Evolutions=
[66]
Name=Machop
InternalName=MACHOP
Type1=FIGHTING
BaseStats=70,80,50,35,35,35
GenderRate=Female25Percent
GrowthRate=Parabolic
BaseEXP=61
EffortPoints=0,1,0,0,0,0
Rareness=180
Happiness=70
Abilities=GUTS,NOGUARD
HiddenAbility=STEADFAST
Moves=1,LOWKICK,1,LEER,7,FOCUSENERGY,10,KARATECHOP,13,LOWSWEEP,19,FORESIGHT,22,SEISMICTOSS,25,REVENGE,31,VITALTHROW,34,SUBMISSION,37,WAKEUPSLAP,43,CROSSCHOP,46,SCARYFACE,49,DYNAMICPUNCH
EggMoves=BULLETPUNCH,CLOSECOMBAT,COUNTER,ENCORE,FIREPUNCH,HEAVYSLAM,ICEPUNCH,KNOCKOFF,MEDITATE,POWERTRICK,ROLLINGKICK,SMELLINGSALT,THUNDERPUNCH,TICKLE
Compatibility=Humanlike
StepsToHatch=5355
Height=0.8
Weight=19.5
Color=Gray
Habitat=Mountain
RegionalNumbers=66,142
Kind=Superpower
Pokedex=It continually undertakes strenuous training to master all forms of martial arts. Its strength lets it easily hoist a sumo wrestler onto its shoulders.
BattlerPlayerY=0
BattlerEnemyY=15
BattlerAltitude=0
Evolutions=MACHOKE,Level,28
[67]
Name=Machoke
InternalName=MACHOKE
Type1=FIGHTING
BaseStats=80,100,70,45,50,60
GenderRate=Female25Percent
GrowthRate=Parabolic
BaseEXP=142
EffortPoints=0,2,0,0,0,0
Rareness=90
Happiness=70
Abilities=GUTS,NOGUARD
HiddenAbility=STEADFAST
Moves=1,LOWKICK,1,LEER,1,FOCUSENERGY,1,KARATECHOP,7,FOCUSENERGY,10,KARATECHOP,13,LOWSWEEP,19,FORESIGHT,22,SEISMICTOSS,25,REVENGE,32,VITALTHROW,36,SUBMISSION,40,WAKEUPSLAP,44,CROSSCHOP,51,SCARYFACE,55,DYNAMICPUNCH
Compatibility=Humanlike
StepsToHatch=5355
Height=1.5
Weight=70.5
Color=Gray
Habitat=Mountain
RegionalNumbers=67,143
Kind=Superpower
Pokedex=A belt is worn by a Machoke to keep its overwhelming power under control. Because it is so dangerous, no one has ever removed the belt.
BattlerPlayerY=0
BattlerEnemyY=10
BattlerAltitude=0
Evolutions=MACHAMP,Level,41
[68]
Name=Machamp
InternalName=MACHAMP
Type1=FIGHTING
BaseStats=90,130,80,55,65,85
GenderRate=Female25Percent
GrowthRate=Parabolic
BaseEXP=227
EffortPoints=0,3,0,0,0,0
Rareness=45
Happiness=70
Abilities=GUTS,NOGUARD
HiddenAbility=STEADFAST
Moves=1,WIDEGUARD,1,LOWKICK,1,LEER,1,FOCUSENERGY,1,KARATECHOP,7,FOCUSENERGY,10,KARATECHOP,13,LOWSWEEP,19,FORESIGHT,22,SEISMICTOSS,25,REVENGE,32,VITALTHROW,36,SUBMISSION,40,WAKEUPSLAP,44,CROSSCHOP,51,SCARYFACE,55,DYNAMICPUNCH
Compatibility=Humanlike
StepsToHatch=5355
Height=1.6
Weight=130.0
Color=Gray
Habitat=Mountain
RegionalNumbers=68,144
Kind=Superpower
Pokedex=It is impossible to defend against punches and chops doled out by its four arms. Its fighting spirit flares up when it faces a tough opponent.
BattlerPlayerY=0
BattlerEnemyY=3
BattlerAltitude=0
Evolutions=
[69]
Name=Bellsprout
InternalName=BELLSPROUT
Type1=GRASS
Type2=POISON
BaseStats=50,75,35,40,70,30
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=60
EffortPoints=0,1,0,0,0,0
Rareness=255
Happiness=70
Abilities=CHLOROPHYLL
HiddenAbility=GLUTTONY
Moves=1,VINEWHIP,7,GROWTH,11,WRAP,13,SLEEPPOWDER,15,POISONPOWDER,17,STUNSPORE,23,ACID,27,KNOCKOFF,29,SWEETSCENT,35,GASTROACID,39,RAZORLEAF,41,SLAM,47,WRINGOUT
EggMoves=BULLETSEED,CLEARSMOG,ENCORE,GIGADRAIN,INGRAIN,LEECHLIFE,MAGICALLEAF,NATURALGIFT,POWERWHIP,SYNTHESIS,TICKLE,WEATHERBALL,WORRYSEED
Compatibility=Grass
StepsToHatch=5355
Height=0.7
Weight=4.0
Color=Green
Habitat=Forest
RegionalNumbers=69,64
Kind=Flower
Pokedex=A Bellsprout's thin and flexible body lets it bend and sway to avoid any attack, however strong it may be. From its mouth, it leaks a fluid that melts even iron.
BattlerPlayerY=0
BattlerEnemyY=23
BattlerAltitude=0
Evolutions=WEEPINBELL,Level,21
[70]
Name=Weepinbell
InternalName=WEEPINBELL
Type1=GRASS
Type2=POISON
BaseStats=65,90,50,55,85,45
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=137
EffortPoints=0,2,0,0,0,0
Rareness=120
Happiness=70
Abilities=CHLOROPHYLL
HiddenAbility=GLUTTONY
Moves=1,VINEWHIP,1,GROWTH,1,WRAP,7,GROWTH,11,WRAP,13,SLEEPPOWDER,15,POISONPOWDER,17,STUNSPORE,23,ACID,27,KNOCKOFF,29,SWEETSCENT,35,GASTROACID,39,RAZORLEAF,41,SLAM,47,WRINGOUT
Compatibility=Grass
StepsToHatch=5355
Height=1.0
Weight=6.4
Color=Green
Habitat=Forest
RegionalNumbers=70,65
Kind=Flycatcher
Pokedex=At night, a Weepinbell hangs on to a tree branch with its hooked rear and sleeps. If it moves around in its sleep, it may wake up to find itself on the ground.
BattlerPlayerY=0
BattlerEnemyY=20
BattlerAltitude=10
Evolutions=VICTREEBEL,Item,LEAFSTONE
[71]
Name=Victreebel
InternalName=VICTREEBEL
Type1=GRASS
Type2=POISON
BaseStats=80,105,65,70,100,60
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=216
EffortPoints=0,3,0,0,0,0
Rareness=45
Happiness=70
Abilities=CHLOROPHYLL
HiddenAbility=GLUTTONY
Moves=1,STOCKPILE,1,SWALLOW,1,SPITUP,1,VINEWHIP,1,SLEEPPOWDER,1,SWEETSCENT,1,RAZORLEAF,27,LEAFTORNADO,47,LEAFSTORM,47,LEAFBLADE
Compatibility=Grass
StepsToHatch=5355
Height=1.7
Weight=15.5
Color=Green
Habitat=Forest
RegionalNumbers=71,66
Kind=Flycatcher
Pokedex=The long vine extending from its head is waved about as if it were a living thing to attract prey. When an unsuspecting victim approaches, it is swallowed whole.
BattlerPlayerY=0
BattlerEnemyY=13
BattlerAltitude=11
Evolutions=
[72]
Name=Tentacool
InternalName=TENTACOOL
Type1=WATER
Type2=POISON
BaseStats=40,40,35,70,50,100
GenderRate=Female50Percent
GrowthRate=Slow
BaseEXP=67
EffortPoints=0,0,0,0,0,1
Rareness=190
Happiness=70
Abilities=CLEARBODY,LIQUIDOOZE
HiddenAbility=RAINDISH
Moves=1,POISONSTING,5,SUPERSONIC,8,CONSTRICT,12,ACID,15,TOXICSPIKES,19,BUBBLEBEAM,22,WRAP,26,ACIDSPRAY,29,BARRIER,33,WATERPULSE,36,POISONJAB,40,SCREECH,43,HEX,47,HYDROPUMP,50,SLUDGEWAVE,54,WRINGOUT
EggMoves=ACUPRESSURE,AQUARING,AURORABEAM,BUBBLE,CONFUSERAY,HAZE,KNOCKOFF,MIRRORCOAT,MUDDYWATER,RAPIDSPIN,TICKLE
Compatibility=Water3
StepsToHatch=5355
Height=0.9
Weight=45.5
Color=Blue
Habitat=Sea
RegionalNumbers=72,164
Kind=Jellyfish
Pokedex=Its body is almost entirely composed of water. It ensnares its foe with its two long tentacles, then stabs with the poison stingers at their tips.
WildItemUncommon=POISONBARB
BattlerPlayerY=0
BattlerEnemyY=13
BattlerAltitude=8
Evolutions=TENTACRUEL,Level,30
[73]
Name=Tentacruel
InternalName=TENTACRUEL
Type1=WATER
Type2=POISON
BaseStats=80,70,65,100,80,120
GenderRate=Female50Percent
GrowthRate=Slow
BaseEXP=180
EffortPoints=0,0,0,0,0,2
Rareness=60
Happiness=70
Abilities=CLEARBODY,LIQUIDOOZE
HiddenAbility=RAINDISH
Moves=1,POISONSTING,1,SUPERSONIC,1,CONSTRICT,5,SUPERSONIC,8,CONSTRICT,12,ACID,15,TOXICSPIKES,19,BUBBLEBEAM,22,WRAP,26,ACIDSPRAY,29,BARRIER,34,WATERPULSE,38,POISONJAB,43,SCREECH,47,HEX,52,HYDROPUMP,56,SLUDGEWAVE,61,WRINGOUT
Compatibility=Water3
StepsToHatch=5355
Height=1.6
Weight=55.0
Color=Blue
Habitat=Sea
RegionalNumbers=73,165
Kind=Jellyfish
Pokedex=It lives in complex rock formations on the ocean floor and traps prey using its 80 tentacles. Its red orbs glow when it grows excited or agitated.
WildItemUncommon=POISONBARB
BattlerPlayerY=0
BattlerEnemyY=11
BattlerAltitude=7
Evolutions=
[74]
Name=Geodude
InternalName=GEODUDE
Type1=ROCK
Type2=GROUND
BaseStats=40,80,100,20,30,30
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=60
EffortPoints=0,0,1,0,0,0
Rareness=255
Happiness=70
Abilities=ROCKHEAD,STURDY
HiddenAbility=SANDVEIL
Moves=1,TACKLE,1,DEFENSECURL,4,MUDSPORT,8,ROCKPOLISH,11,ROCKTHROW,15,MAGNITUDE,18,ROLLOUT,22,ROCKBLAST,25,SMACKDOWN,29,SELFDESTRUCT,32,BULLDOZE,36,STEALTHROCK,39,EARTHQUAKE,43,EXPLOSION,46,DOUBLEEDGE,50,STONEEDGE
EggMoves=AUTOTOMIZE,BLOCK,CURSE,ENDURE,FLAIL,FOCUSPUNCH,HAMMERARM,MEGAPUNCH,ROCKCLIMB
Compatibility=Mineral
StepsToHatch=4080
Height=0.4
Weight=20.0
Color=Brown
Habitat=Mountain
RegionalNumbers=74,34
Kind=Rock
Pokedex=It climbs mountain paths using only the power of its arms. Because they look just like boulders lining paths, hikers may step on them without noticing.
WildItemUncommon=EVERSTONE
BattlerPlayerY=0
BattlerEnemyY=26
BattlerAltitude=16
Evolutions=GRAVELER,Level,25
[75]
Name=Graveler
InternalName=GRAVELER
Type1=ROCK
Type2=GROUND
BaseStats=55,95,115,35,45,45
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=137
EffortPoints=0,0,2,0,0,0
Rareness=120
Happiness=70
Abilities=ROCKHEAD,STURDY
HiddenAbility=SANDVEIL
Moves=1,TACKLE,1,DEFENSECURL,1,MUDSPORT,1,ROCKPOLISH,4,MUDSPORT,8,ROCKPOLISH,11,ROCKTHROW,15,MAGNITUDE,18,ROLLOUT,22,ROCKBLAST,27,SMACKDOWN,31,SELFDESTRUCT,36,BULLDOZE,42,STEALTHROCK,47,EARTHQUAKE,53,EXPLOSION,58,DOUBLEEDGE,64,STONEEDGE
Compatibility=Mineral
StepsToHatch=4080
Height=1.0
Weight=105.0
Color=Brown
Habitat=Mountain
RegionalNumbers=75,35
Kind=Rock
Pokedex=They descend from mountains by tumbling down steep slopes. They are so brutal, they smash aside obstructing trees and massive boulders with thunderous tackles.
WildItemUncommon=EVERSTONE
BattlerPlayerY=0
BattlerEnemyY=20
BattlerAltitude=0
Evolutions=GOLEM,Level,36
[76]
Name=Golem
InternalName=GOLEM
Type1=ROCK
Type2=GROUND
BaseStats=80,110,130,45,55,65
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=218
EffortPoints=0,0,3,0,0,0
Rareness=45
Happiness=70
Abilities=ROCKHEAD,STURDY
HiddenAbility=SANDVEIL
Moves=1,TACKLE,1,DEFENSECURL,1,MUDSPORT,1,ROCKPOLISH,4,MUDSPORT,8,ROCKPOLISH,11,ROCKTHROW,15,MAGNITUDE,18,STEAMROLLER,22,ROCKBLAST,27,SMACKDOWN,31,SELFDESTRUCT,36,BULLDOZE,42,STEALTHROCK,47,EARTHQUAKE,53,EXPLOSION,58,DOUBLEEDGE,64,STONEEDGE,69,HEAVYSLAM
Compatibility=Mineral
StepsToHatch=4080
Height=1.4
Weight=300.0
Color=Brown
Habitat=Mountain
RegionalNumbers=76,36
Kind=Megaton
Pokedex=It is said to live in volcanic craters on mountain peaks. Once a year, it sheds its hide and grows larger. The shed hide crumbles and returns to the soil.
WildItemUncommon=EVERSTONE
BattlerPlayerY=0
BattlerEnemyY=14
BattlerAltitude=0
Evolutions=
[77]
Name=Ponyta
InternalName=PONYTA
Type1=FIRE
BaseStats=50,85,55,90,65,65
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=82
EffortPoints=0,0,0,1,0,0
Rareness=190
Happiness=70
Abilities=RUNAWAY,FLASHFIRE
HiddenAbility=FLAMEBODY
Moves=1,GROWL,1,TACKLE,4,TAILWHIP,9,EMBER,13,FLAMEWHEEL,17,STOMP,21,FLAMECHARGE,25,FIRESPIN,29,TAKEDOWN,33,INFERNO,37,AGILITY,41,FIREBLAST,45,BOUNCE,49,FLAREBLITZ
EggMoves=CAPTIVATE,CHARM,DOUBLEKICK,DOUBLEEDGE,FLAMEWHEEL,HORNDRILL,HYPNOSIS,LOWKICK,MORNINGSUN,THRASH
Compatibility=Field
StepsToHatch=5355
Height=1.0
Weight=30.0
Color=Yellow
Habitat=Grassland
RegionalNumbers=77,206
Kind=Fire Horse
Pokedex=A Ponyta is very weak at birth. It can barely stand up. Its legs become stronger as it stumbles and falls while trying to keep up with its parent.
WildItemUncommon=SHUCABERRY
BattlerPlayerY=0
BattlerEnemyY=16
BattlerAltitude=0
Evolutions=RAPIDASH,Level,40
[78]
Name=Rapidash
InternalName=RAPIDASH
Type1=FIRE
BaseStats=65,100,70,105,80,80
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=175
EffortPoints=0,0,0,2,0,0
Rareness=60
Happiness=70
Abilities=RUNAWAY,FLASHFIRE
HiddenAbility=FLAMEBODY
Moves=1,POISONJAB,1,MEGAHORN,1,GROWL,1,QUICKATTACK,1,TAILWHIP,1,EMBER,4,TAILWHIP,9,EMBER,13,FLAMEWHEEL,17,STOMP,21,FLAMECHARGE,25,FIRESPIN,29,TAKEDOWN,33,INFERNO,37,AGILITY,40,FURYATTACK,41,FIREBLAST,45,BOUNCE,49,FLAREBLITZ
Compatibility=Field
StepsToHatch=5355
Height=1.7
Weight=95.0
Color=Yellow
Habitat=Grassland
RegionalNumbers=78,207
Kind=Fire Horse
Pokedex=It usually canters casually in the fields and plains. But once a Rapidash turns serious, its fiery manes flare and blaze as it gallops its way up to 150 mph.
WildItemUncommon=SHUCABERRY
BattlerPlayerY=0
BattlerEnemyY=6
BattlerAltitude=0
Evolutions=
[79]
Name=Slowpoke
InternalName=SLOWPOKE
Type1=WATER
Type2=PSYCHIC
BaseStats=90,65,65,15,40,40
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=63
EffortPoints=1,0,0,0,0,0
Rareness=190
Happiness=70
Abilities=OBLIVIOUS,OWNTEMPO
HiddenAbility=REGENERATOR
Moves=1,CURSE,1,YAWN,1,TACKLE,5,GROWL,9,WATERGUN,14,CONFUSION,19,DISABLE,23,HEADBUTT,28,WATERPULSE,32,ZENHEADBUTT,36,SLACKOFF,41,AMNESIA,45,PSYCHIC,49,RAINDANCE,54,PSYCHUP,58,HEALPULSE
EggMoves=BELLYDRUM,BLOCK,FUTURESIGHT,MEFIRST,MUDSPORT,SLEEPTALK,SNORE,STOMP,WONDERROOM,ZENHEADBUTT
Compatibility=Monster,Water1
StepsToHatch=5355
Height=1.2
Weight=36.0
Color=Pink
Habitat=WatersEdge
RegionalNumbers=79,80
Kind=Dopey
Pokedex=It catches prey by dipping its tail in water at the side of a river. But it often forgets what it is doing and spends entire days just loafing at water's edge.
WildItemUncommon=LAGGINGTAIL
BattlerPlayerY=0
BattlerEnemyY=27
BattlerAltitude=0
Evolutions=SLOWBRO,Level,37
[80]
Name=Slowbro
InternalName=SLOWBRO
Type1=WATER
Type2=PSYCHIC
BaseStats=95,75,110,30,100,80
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=172
EffortPoints=0,0,2,0,0,0
Rareness=75
Happiness=70
Abilities=OBLIVIOUS,OWNTEMPO
HiddenAbility=REGENERATOR
Moves=1,CURSE,1,YAWN,1,TACKLE,1,GROWL,5,GROWL,9,WATERGUN,14,CONFUSION,19,DISABLE,23,HEADBUTT,28,WATERPULSE,32,ZENHEADBUTT,36,SLACKOFF,37,WITHDRAW,43,AMNESIA,49,PSYCHIC,55,RAINDANCE,62,PSYCHUP,68,HEALPULSE
Compatibility=Monster,Water1
StepsToHatch=5355
Height=1.6
Weight=78.5
Color=Pink
Habitat=WatersEdge
RegionalNumbers=80,81
Kind=Hermit Crab
Pokedex=Its tail has a Shellder firmly attached with a bite. As a result, the tail can't be used for fishing anymore. This forces it to reluctantly swim and catch prey.
WildItemUncommon=KINGSROCK
BattlerPlayerY=0
BattlerEnemyY=13
BattlerAltitude=0
Evolutions=
[81]
Name=Magnemite
InternalName=MAGNEMITE
Type1=ELECTRIC
Type2=STEEL
BaseStats=25,35,70,45,95,55
GenderRate=Genderless
GrowthRate=Medium
BaseEXP=89
EffortPoints=0,0,0,0,1,0
Rareness=65
Happiness=70
Abilities=MAGNETPULL,STURDY
HiddenAbility=ANALYTIC
Moves=1,TACKLE,4,SUPERSONIC,7,THUNDERSHOCK,11,SONICBOOM,15,THUNDERWAVE,18,MAGNETBOMB,21,SPARK,25,MIRRORSHOT,29,METALSOUND,32,ELECTROBALL,35,FLASHCANNON,39,SCREECH,43,DISCHARGE,46,LOCKON,49,MAGNETRISE,53,GYROBALL,57,ZAPCANNON
Compatibility=Mineral
StepsToHatch=5355
Height=0.3
Weight=6.0
Color=Gray
Habitat=RoughTerrain
RegionalNumbers=81,119
Kind=Magnet
Pokedex=The units at its sides are extremely powerful magnets. They generate enough magnetism to draw in iron objects from over 300 feet away.
WildItemUncommon=METALCOAT
BattlerPlayerY=0
BattlerEnemyY=29
BattlerAltitude=19
Evolutions=MAGNETON,Level,30
[82]
Name=Magneton
InternalName=MAGNETON
Type1=ELECTRIC
Type2=STEEL
BaseStats=50,60,95,70,120,70
GenderRate=Genderless
GrowthRate=Medium
BaseEXP=163
EffortPoints=0,0,0,0,2,0
Rareness=60
Happiness=70
Abilities=MAGNETPULL,STURDY
HiddenAbility=ANALYTIC
Moves=1,TRIATTACK,1,TACKLE,1,SUPERSONIC,1,THUNDERSHOCK,1,SONICBOOM,4,SUPERSONIC,7,THUNDERSHOCK,11,SONICBOOM,15,THUNDERWAVE,18,MAGNETBOMB,21,SPARK,25,MIRRORSHOT,29,METALSOUND,34,ELECTROBALL,39,FLASHCANNON,45,SCREECH,51,DISCHARGE,56,LOCKON,62,MAGNETRISE,67,GYROBALL,73,ZAPCANNON
Compatibility=Mineral
StepsToHatch=5355
Height=1.0
Weight=60.0
Color=Gray
Habitat=RoughTerrain
RegionalNumbers=82,120
Kind=Magnet
Pokedex=It is actually three Magnemite linked by magnetism. It generates powerful radio waves that raise temperatures by 3.6 degrees F within a 3,300-foot radius.
WildItemUncommon=METALCOAT
BattlerPlayerY=0
BattlerEnemyY=14
BattlerAltitude=15
Evolutions=
[83]
Name=Farfetch'd
InternalName=FARFETCHD
Type1=NORMAL
Type2=FLYING
BaseStats=52,65,55,60,58,62
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=123
EffortPoints=0,1,0,0,0,0
Rareness=45
Happiness=70
Abilities=KEENEYE,INNERFOCUS
HiddenAbility=DEFIANT
Moves=1,POISONJAB,1,PECK,1,SANDATTACK,1,LEER,1,FURYCUTTER,7,FURYATTACK,9,KNOCKOFF,13,AERIALACE,19,SLASH,21,AIRCUTTER,25,SWORDSDANCE,31,AGILITY,33,NIGHTSLASH,37,ACROBATICS,43,FEINT,45,FALSESWIPE,49,AIRSLASH,55,BRAVEBIRD
EggMoves=COVET,CURSE,FEATHERDANCE,FLAIL,FORESIGHT,GUST,LEAFBLADE,MIRRORMOVE,MUDSLAP,NIGHTSLASH,QUICKATTACK,REVENGE,ROOST,STEELWING,TRUMPCARD
Compatibility=Flying,Field
StepsToHatch=5355
Height=0.8
Weight=15.0
Color=Brown
Habitat=Grassland
RegionalNumbers=83,160
Kind=Wild Duck
Pokedex=It is always seen with a stick from a plant. Apparently, there are good sticks and bad sticks. This Pokémon occasionally fights with others over choice sticks.
WildItemUncommon=STICK
BattlerPlayerY=0
BattlerEnemyY=18
BattlerAltitude=0
Evolutions=
[84]
Name=Doduo
InternalName=DODUO
Type1=NORMAL
Type2=FLYING
BaseStats=35,85,45,75,35,35
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=62
EffortPoints=0,1,0,0,0,0
Rareness=190
Happiness=70
Abilities=RUNAWAY,EARLYBIRD
HiddenAbility=TANGLEDFEET
Moves=1,PECK,1,GROWL,5,QUICKATTACK,10,RAGE,14,FURYATTACK,19,PURSUIT,23,UPROAR,28,ACUPRESSURE,32,DOUBLEHIT,37,AGILITY,41,DRILLPECK,46,ENDEAVOR,50,THRASH
EggMoves=ASSURANCE,BRAVEBIRD,ENDEAVOR,FAINTATTACK,FLAIL,HAZE,MIRRORMOVE,NATURALGIFT,QUICKATTACK,SUPERSONIC
Compatibility=Flying
StepsToHatch=5355
Height=1.4
Weight=39.2
Color=Brown
Habitat=Grassland
RegionalNumbers=84,204
Kind=Twin Bird
Pokedex=Even while eating or sleeping, one of the heads remains always vigilant for any sign of danger. When threatened, it flees at over 60 miles per hour.
WildItemUncommon=SHARPBEAK
BattlerPlayerY=0
BattlerEnemyY=15
BattlerAltitude=0
Evolutions=DODRIO,Level,31
[85]
Name=Dodrio
InternalName=DODRIO
Type1=NORMAL
Type2=FLYING
BaseStats=60,110,70,100,60,60
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=161
EffortPoints=0,2,0,0,0,0
Rareness=45
Happiness=70
Abilities=RUNAWAY,EARLYBIRD
HiddenAbility=TANGLEDFEET
Moves=1,PLUCK,1,PECK,1,GROWL,1,QUICKATTACK,1,RAGE,5,QUICKATTACK,10,RAGE,14,FURYATTACK,19,PURSUIT,23,UPROAR,28,ACUPRESSURE,34,TRIATTACK,41,AGILITY,47,DRILLPECK,54,ENDEAVOR,60,THRASH
Compatibility=Flying
StepsToHatch=5355
Height=1.8
Weight=85.2
Color=Brown
Habitat=Grassland
RegionalNumbers=85,205
Kind=Triple Bird
Pokedex=A peculiar Pokémon species with three heads. It vigorously races across grassy plains even in arid seasons with little rainfall.
WildItemUncommon=SHARPBEAK
BattlerPlayerY=0
BattlerEnemyY=3
BattlerAltitude=0
Evolutions=
[86]
Name=Seel
InternalName=SEEL
Type1=WATER
BaseStats=65,45,55,45,45,70
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=65
EffortPoints=0,0,0,0,0,1
Rareness=190
Happiness=70
Abilities=THICKFAT,HYDRATION
HiddenAbility=ICEBODY
Moves=1,HEADBUTT,3,GROWL,7,WATERSPORT,11,ICYWIND,13,ENCORE,17,ICESHARD,21,REST,23,AQUARING,27,AURORABEAM,31,AQUAJET,33,BRINE,37,TAKEDOWN,41,DIVE,43,AQUATAIL,47,ICEBEAM,51,SAFEGUARD,53,HAIL
EggMoves=DISABLE,ENCORE,FAKEOUT,HORNDRILL,ICICLESPEAR,IRONTAIL,LICK,PERISHSONG,SIGNALBEAM,SLAM,SLEEPTALK,SPITUP,STOCKPILE,SWALLOW,WATERPULSE
Compatibility=Water1,Field
StepsToHatch=5355
Height=1.1
Weight=90.0
Color=White
Habitat=Sea
RegionalNumbers=86,178
Kind=Sea Lion
Pokedex=Seel hunt for prey in frigid, ice-covered seas. When it needs to breathe, it punches a hole through the ice with the sharply protruding section of its head.
BattlerPlayerY=0
BattlerEnemyY=18
BattlerAltitude=0
Evolutions=DEWGONG,Level,34
[87]
Name=Dewgong
InternalName=DEWGONG
Type1=WATER
Type2=ICE
BaseStats=90,70,80,70,70,95
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=166
EffortPoints=0,0,0,0,0,2
Rareness=75
Happiness=70
Abilities=THICKFAT,HYDRATION
HiddenAbility=ICEBODY
Moves=1,HEADBUTT,1,GROWL,1,SIGNALBEAM,1,ICYWIND,3,GROWL,7,SIGNALBEAM,11,ICYWIND,13,ENCORE,17,ICESHARD,21,REST,23,AQUARING,27,AURORABEAM,31,AQUAJET,33,BRINE,34,SHEERCOLD,39,TAKEDOWN,45,DIVE,49,AQUATAIL,55,ICEBEAM,61,SAFEGUARD,65,HAIL
Compatibility=Water1,Field
StepsToHatch=5355
Height=1.7
Weight=120.0
Color=White
Habitat=Sea
RegionalNumbers=87,179
Kind=Sea Lion
Pokedex=It loves to snooze on bitterly cold ice. The sight of this Pokémon sleeping on a glacier was mistakenly thought to be a mermaid by a mariner long ago.
BattlerPlayerY=0
BattlerEnemyY=9
BattlerAltitude=0
Evolutions=
[88]
Name=Grimer
InternalName=GRIMER
Type1=POISON
BaseStats=80,80,50,25,40,50
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=65
EffortPoints=1,0,0,0,0,0
Rareness=190
Happiness=70
Abilities=STENCH,STICKYHOLD
HiddenAbility=POISONTOUCH
Moves=1,POISONGAS,1,POUND,4,HARDEN,7,MUDSLAP,12,DISABLE,15,SLUDGE,18,MINIMIZE,21,MUDBOMB,26,SLUDGEBOMB,29,FLING,32,SCREECH,37,SLUDGEWAVE,40,ACIDARMOR,43,GUNKSHOT,48,MEMENTO
EggMoves=ACIDSPRAY,CURSE,HAZE,IMPRISON,LICK,MEANLOOK,SCARYFACE,SHADOWPUNCH,SHADOWSNEAK,SPITUP,STOCKPILE,SWALLOW
Compatibility=Amorphous
StepsToHatch=5355
Height=0.9
Weight=30.0
Color=Purple
Habitat=Urban
RegionalNumbers=88,117
Kind=Sludge
Pokedex=Born from polluted sludge in the sea, Grimer's favorite food is anything filthy. They feed on wastewater pumped out from factories.
WildItemUncommon=NUGGET
BattlerPlayerY=0
BattlerEnemyY=22
BattlerAltitude=0
Evolutions=MUK,Level,38
[89]
Name=Muk
InternalName=MUK
Type1=POISON
BaseStats=105,105,75,50,65,100
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=175
EffortPoints=1,1,0,0,0,0
Rareness=75
Happiness=70
Abilities=STENCH,STICKYHOLD
HiddenAbility=POISONTOUCH
Moves=1,POISONGAS,1,POUND,1,HARDEN,1,MUDSLAP,4,HARDEN,7,MUDSLAP,12,DISABLE,15,SLUDGE,18,MINIMIZE,21,MUDBOMB,26,SLUDGEBOMB,29,FLING,32,SCREECH,37,SLUDGEWAVE,43,ACIDARMOR,49,GUNKSHOT,57,MEMENTO
Compatibility=Amorphous
StepsToHatch=5355
Height=1.2
Weight=30.0
Color=Purple
Habitat=Urban
RegionalNumbers=89,118
Kind=Sludge
Pokedex=It prefers warm and humid habitats. In the summertime, the toxic substances in its body intensify, making Muk reek like putrid kitchen garbage.
WildItemUncommon=NUGGET
BattlerPlayerY=0
BattlerEnemyY=8
BattlerAltitude=0
Evolutions=
[90]
Name=Shellder
InternalName=SHELLDER
Type1=WATER
BaseStats=30,65,100,40,45,25
GenderRate=Female50Percent
GrowthRate=Slow
BaseEXP=61
EffortPoints=0,0,1,0,0,0
Rareness=190
Happiness=70
Abilities=SHELLARMOR,SKILLLINK
HiddenAbility=OVERCOAT
Moves=1,TACKLE,4,WITHDRAW,8,SUPERSONIC,13,ICICLESPEAR,16,PROTECT,20,LEER,25,CLAMP,28,ICESHARD,32,RAZORSHELL,37,AURORABEAM,40,WHIRLPOOL,44,BRINE,49,IRONDEFENSE,52,ICEBEAM,56,SHELLSMASH,61,HYDROPUMP
EggMoves=AQUARING,AVALANCHE,BARRIER,BUBBLEBEAM,ICICLESPEAR,MUDSHOT,RAPIDSPIN,ROCKBLAST,SCREECH,TAKEDOWN,TWINEEDLE,WATERPULSE
Compatibility=Water3
StepsToHatch=5355
Height=0.3
Weight=4.0
Color=Purple
Habitat=Sea
RegionalNumbers=90,171
Kind=Bivalve
Pokedex=At night, it burrows a hole in the seafloor with its broad tongue to make a place to sleep. While asleep, it closes its shell, but leaves its tongue hanging out.
WildItemCommon=PEARL
WildItemUncommon=BIGPEARL
BattlerPlayerY=0
BattlerEnemyY=25
BattlerAltitude=0
Evolutions=CLOYSTER,Item,WATERSTONE
[91]
Name=Cloyster
InternalName=CLOYSTER
Type1=WATER
Type2=ICE
BaseStats=50,95,180,70,85,45
GenderRate=Female50Percent
GrowthRate=Slow
BaseEXP=184
EffortPoints=0,0,2,0,0,0
Rareness=60
Happiness=70
Abilities=SHELLARMOR,SKILLLINK
HiddenAbility=OVERCOAT
Moves=1,TOXICSPIKES,1,WITHDRAW,1,SUPERSONIC,1,PROTECT,1,AURORABEAM,13,SPIKECANNON,28,SPIKES,52,ICICLECRASH
Compatibility=Water3
StepsToHatch=5355
Height=1.5
Weight=132.5
Color=Purple
Habitat=Sea
RegionalNumbers=91,172
Kind=Bivalve
Pokedex=It swims in the sea by swallowing water, then jetting it out toward the rear. The Cloyster shoots spikes from its shell using the same system.
WildItemCommon=PEARL
WildItemUncommon=BIGPEARL
BattlerPlayerY=0
BattlerEnemyY=12
BattlerAltitude=0
Evolutions=
[92]
Name=Gastly
InternalName=GASTLY
Type1=GHOST
Type2=POISON
BaseStats=30,35,30,80,100,35
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=62
EffortPoints=0,0,0,0,1,0
Rareness=190
Happiness=70
Abilities=LEVITATE
Moves=1,HYPNOSIS,1,LICK,5,SPITE,8,MEANLOOK,12,CURSE,15,NIGHTSHADE,19,CONFUSERAY,22,SUCKERPUNCH,26,PAYBACK,29,SHADOWBALL,33,DREAMEATER,36,DARKPULSE,40,DESTINYBOND,43,HEX,47,NIGHTMARE
EggMoves=ASTONISH,CLEARSMOG,DISABLE,FIREPUNCH,GRUDGE,HAZE,ICEPUNCH,PERISHSONG,PSYWAVE,SCARYFACE,SMOG,THUNDERPUNCH
Compatibility=Amorphous
StepsToHatch=5355
Height=1.3
Weight=0.1
Color=Purple
Habitat=Cave
RegionalNumbers=92,58
Kind=Gas
Pokedex=When exposed to a strong wind, a Gastly's gaseous body quickly dwindles away. They cluster under the eaves of houses to escape the ravages of wind.
BattlerPlayerY=0
BattlerEnemyY=20
BattlerAltitude=13
Evolutions=HAUNTER,Level,25
[93]
Name=Haunter
InternalName=HAUNTER
Type1=GHOST
Type2=POISON
BaseStats=45,50,45,95,115,55
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=142
EffortPoints=0,0,0,0,2,0
Rareness=90
Happiness=70
Abilities=LEVITATE
Moves=1,HYPNOSIS,1,LICK,1,SPITE,5,SPITE,8,MEANLOOK,12,CURSE,15,NIGHTSHADE,19,CONFUSERAY,22,SUCKERPUNCH,25,SHADOWPUNCH,28,PAYBACK,33,SHADOWBALL,39,DREAMEATER,44,DARKPULSE,50,DESTINYBOND,55,HEX,61,NIGHTMARE
Compatibility=Amorphous
StepsToHatch=5355
Height=1.6
Weight=0.1
Color=Purple
Habitat=Cave
RegionalNumbers=93,59
Kind=Gas
Pokedex=If a Haunter beckons you while it is floating in darkness, don't approach it. This Pokémon will try to lick you with its tongue and steal your life away.
BattlerPlayerY=0
BattlerEnemyY=18
BattlerAltitude=14
Evolutions=GENGAR,Level,38
[94]
Name=Gengar
InternalName=GENGAR
Type1=GHOST
Type2=POISON
BaseStats=60,65,60,110,130,75
GenderRate=Female50Percent
GrowthRate=Parabolic
BaseEXP=225
EffortPoints=0,0,0,0,3,0
Rareness=45
Happiness=70
Abilities=LEVITATE
Moves=1,HYPNOSIS,1,LICK,1,SPITE,5,SPITE,8,MEANLOOK,12,CURSE,15,NIGHTSHADE,19,CONFUSERAY,22,SUCKERPUNCH,25,SHADOWPUNCH,28,PAYBACK,33,SHADOWBALL,39,DREAMEATER,44,DARKPULSE,50,DESTINYBOND,55,HEX,61,NIGHTMARE
Compatibility=Amorphous
StepsToHatch=5355
Height=1.5
Weight=40.5
Color=Purple
Habitat=Cave
RegionalNumbers=94,60
Kind=Shadow
Pokedex=Deep in the night, your shadow cast by a streetlight may suddenly overtake you. It is actually a Gengar running past you, pretending to be your shadow.
BattlerPlayerY=0
BattlerEnemyY=16
BattlerAltitude=0
Evolutions=
[95]
Name=Onix
InternalName=ONIX
Type1=ROCK
Type2=GROUND
BaseStats=35,45,160,70,30,45
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=77
EffortPoints=0,0,1,0,0,0
Rareness=45
Happiness=70
Abilities=ROCKHEAD,STURDY
HiddenAbility=WEAKARMOR
Moves=1,MUDSPORT,1,TACKLE,1,HARDEN,1,BIND,4,CURSE,7,ROCKTHROW,10,RAGE,13,ROCKTOMB,16,STEALTHROCK,19,ROCKPOLISH,22,SMACKDOWN,25,DRAGONBREATH,28,SLAM,31,SCREECH,34,ROCKSLIDE,37,SANDTOMB,40,IRONTAIL,43,DIG,46,STONEEDGE,49,DOUBLEEDGE,52,SANDSTORM
EggMoves=BLOCK,DEFENSECURL,FLAIL,HEAVYSLAM,ROCKBLAST,ROCKCLIMB,ROLLOUT,STEALTHROCK
Compatibility=Mineral
StepsToHatch=6630
Height=8.8
Weight=210.0
Color=Gray
Habitat=Cave
RegionalNumbers=95,62
Kind=Rock Snake
Pokedex=There is a magnet in its brain that prevents an Onix from losing direction while tunneling. As it grows older, its body becomes steadily rounder and smoother.
BattlerPlayerY=0
BattlerEnemyY=6
BattlerAltitude=0
Evolutions=
[96]
Name=Drowzee
InternalName=DROWZEE
Type1=PSYCHIC
BaseStats=60,48,45,42,43,90
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=66
EffortPoints=0,0,0,0,0,1
Rareness=190
Happiness=70
Abilities=INSOMNIA,FOREWARN
HiddenAbility=INNERFOCUS
Moves=1,POUND,1,HYPNOSIS,5,DISABLE,9,CONFUSION,13,HEADBUTT,17,POISONGAS,21,MEDITATE,25,PSYBEAM,29,HEADBUTT,33,PSYCHUP,37,SYNCHRONOISE,41,ZENHEADBUTT,45,SWAGGER,49,PSYCHIC,53,NASTYPLOT,57,PSYSHOCK,61,FUTURESIGHT
EggMoves=ASSIST,BARRIER,FIREPUNCH,FLATTER,GUARDSWAP,ICEPUNCH,NASTYPLOT,PSYCHOCUT,ROLEPLAY,SECRETPOWER,SKILLSWAP,THUNDERPUNCH
Compatibility=Humanlike
StepsToHatch=5355
Height=1.0
Weight=32.4
Color=Yellow
Habitat=Grassland
RegionalNumbers=96,87
Kind=Hypnosis
Pokedex=If your nose becomes itchy while you are sleeping, it's a sure sign that a Drowzee is standing above your pillow and trying to eat your dream through your nostrils.
BattlerPlayerY=0
BattlerEnemyY=16
BattlerAltitude=0
Evolutions=HYPNO,Level,26
[97]
Name=Hypno
InternalName=HYPNO
Type1=PSYCHIC
BaseStats=85,73,70,67,73,115
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=169
EffortPoints=0,0,0,0,0,2
Rareness=75
Happiness=70
Abilities=INSOMNIA,FOREWARN
HiddenAbility=INNERFOCUS
Moves=1,NIGHTMARE,1,SWITCHEROO,1,POUND,1,HYPNOSIS,1,DISABLE,1,CONFUSION,5,DISABLE,9,CONFUSION,13,HEADBUTT,17,POISONGAS,21,MEDITATE,25,PSYBEAM,29,HEADBUTT,33,PSYCHUP,37,SYNCHRONOISE,41,ZENHEADBUTT,45,SWAGGER,49,PSYCHIC,53,NASTYPLOT,57,PSYSHOCK,61,FUTURESIGHT
Compatibility=Humanlike
StepsToHatch=5355
Height=1.6
Weight=75.6
Color=Yellow
Habitat=Grassland
RegionalNumbers=97,88
Kind=Hypnosis
Pokedex=The arcing movement and glitter of the pendulum in a Hypno's hand lull the foe into deep hypnosis. While searching for prey, it polishes the pendulum.
BattlerPlayerY=0
BattlerEnemyY=10
BattlerAltitude=0
Evolutions=
[98]
Name=Krabby
InternalName=KRABBY
Type1=WATER
BaseStats=30,105,90,50,25,25
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=65
EffortPoints=0,1,0,0,0,0
Rareness=225
Happiness=70
Abilities=HYPERCUTTER,SHELLARMOR
HiddenAbility=SHEERFORCE
Moves=1,MUDSPORT,1,BUBBLE,5,VICEGRIP,9,LEER,11,HARDEN,15,BUBBLEBEAM,19,MUDSHOT,21,METALCLAW,25,STOMP,29,PROTECT,31,GUILLOTINE,35,SLAM,39,BRINE,41,CRABHAMMER,45,FLAIL
EggMoves=AGILITY,AMNESIA,ANCIENTPOWER,BIDE,CHIPAWAY,ENDURE,FLAIL,HAZE,KNOCKOFF,SLAM,TICKLE
Compatibility=Water3
StepsToHatch=5355
Height=0.4
Weight=6.5
Color=Red
Habitat=WatersEdge
RegionalNumbers=98,166
Kind=River Crab
Pokedex=Krabby live in holes dug into beaches. On sandy shores with little in the way of food, they can be seen squabbling with each other over territory.
BattlerPlayerY=0
BattlerEnemyY=21
BattlerAltitude=0
Evolutions=KINGLER,Level,28
[99]
Name=Kingler
InternalName=KINGLER
Type1=WATER
BaseStats=55,130,115,75,50,50
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=166
EffortPoints=0,2,0,0,0,0
Rareness=60
Happiness=70
Abilities=HYPERCUTTER,SHELLARMOR
HiddenAbility=SHEERFORCE
Moves=1,WIDEGUARD,1,MUDSPORT,1,BUBBLE,1,VICEGRIP,1,LEER,5,VICEGRIP,9,LEER,11,HARDEN,15,BUBBLEBEAM,19,MUDSHOT,21,METALCLAW,25,STOMP,32,PROTECT,37,GUILLOTINE,44,SLAM,51,BRINE,56,CRABHAMMER,63,FLAIL
Compatibility=Water3
StepsToHatch=5355
Height=1.3
Weight=60.0
Color=Red
Habitat=WatersEdge
RegionalNumbers=99,167
Kind=Pincer
Pokedex=It waves its huge, oversized claw in the air to communicate with others. But since the claw is so heavy, this Pokémon quickly tires.
BattlerPlayerY=0
BattlerEnemyY=14
BattlerAltitude=0
Evolutions=
[100]
Name=Voltorb
InternalName=VOLTORB
Type1=ELECTRIC
BaseStats=40,30,50,100,55,55
GenderRate=Genderless
GrowthRate=Medium
BaseEXP=66
EffortPoints=0,0,0,1,0,0
Rareness=190
Happiness=70
Abilities=SOUNDPROOF,STATIC
HiddenAbility=AFTERMATH
Moves=1,CHARGE,5,TACKLE,8,SONICBOOM,12,SPARK,15,ROLLOUT,19,SCREECH,22,CHARGEBEAM,26,LIGHTSCREEN,29,ELECTROBALL,33,SELFDESTRUCT,36,SWIFT,40,MAGNETRISE,43,GYROBALL,47,EXPLOSION,50,MIRRORCOAT
Compatibility=Mineral
StepsToHatch=5355
Height=0.5
Weight=10.4
Color=Red
Habitat=Urban
RegionalNumbers=100,121
Kind=Ball
Pokedex=It bears an uncanny and unexplained resemblance to a Poké Ball. Because it explodes at the slightest shock, even veteran trainers treat it with caution.
BattlerPlayerY=0
BattlerEnemyY=25
BattlerAltitude=0
Evolutions=ELECTRODE,Level,30
[101]
Name=Electrode
InternalName=ELECTRODE
Type1=ELECTRIC
BaseStats=60,50,70,140,80,80
GenderRate=Genderless
GrowthRate=Medium
BaseEXP=168
EffortPoints=0,0,0,2,0,0
Rareness=60
Happiness=70
Abilities=SOUNDPROOF,STATIC
HiddenAbility=AFTERMATH
Moves=1,CHARGE,1,TACKLE,1,SONICBOOM,1,SPARK,5,TACKLE,8,SONICBOOM,12,SPARK,15,ROLLOUT,19,SCREECH,22,CHARGEBEAM,26,LIGHTSCREEN,29,ELECTROBALL,35,SELFDESTRUCT,40,SWIFT,46,MAGNETRISE,51,GYROBALL,57,EXPLOSION,62,MIRRORCOAT
Compatibility=Mineral
StepsToHatch=5355
Height=1.2
Weight=66.6
Color=Red
Habitat=Urban
RegionalNumbers=101,122
Kind=Ball
Pokedex=They appear in great numbers at electric power plants. Because they feed on electricity, they cause massive and chaotic blackouts in nearby cities.
BattlerPlayerY=0
BattlerEnemyY=19
BattlerAltitude=0
Evolutions=
[102]
Name=Exeggcute
InternalName=EXEGGCUTE
Type1=GRASS
Type2=PSYCHIC
BaseStats=60,40,80,40,60,45
GenderRate=Female50Percent
GrowthRate=Slow
BaseEXP=65
EffortPoints=0,0,1,0,0,0
Rareness=90
Happiness=70
Abilities=CHLOROPHYLL
HiddenAbility=HARVEST
Moves=1,BARRAGE,1,UPROAR,1,HYPNOSIS,7,REFLECT,11,LEECHSEED,17,BULLETSEED,19,STUNSPORE,21,POISONPOWDER,23,SLEEPPOWDER,27,CONFUSION,33,WORRYSEED,37,NATURALGIFT,43,SOLARBEAM,47,EXTRASENSORY,53,BESTOW
EggMoves=ANCIENTPOWER,BLOCK,CURSE,GIGADRAIN,INGRAIN,LEAFSTORM,LUCKYCHANT,MOONLIGHT,NATURALGIFT,NATUREPOWER,POWERSWAP,SKILLSWAP,SYNTHESIS
Compatibility=Grass
StepsToHatch=5355
Height=0.4
Weight=2.5
Color=Pink
Habitat=Forest
RegionalNumbers=102,105
Kind=Egg
Pokedex=It consists of six eggs that care for each other. The eggs attract each other and spin around. When cracks increasingly appear, it is close to evolution.
BattlerPlayerY=0
BattlerEnemyY=23
BattlerAltitude=0
Evolutions=EXEGGUTOR,Item,LEAFSTONE
[103]
Name=Exeggutor
InternalName=EXEGGUTOR
Type1=GRASS
Type2=PSYCHIC
BaseStats=95,95,85,55,125,65
GenderRate=Female50Percent
GrowthRate=Slow
BaseEXP=182
EffortPoints=0,0,0,0,2,0
Rareness=45
Happiness=70
Abilities=CHLOROPHYLL
HiddenAbility=HARVEST
Moves=1,SEEDBOMB,1,BARRAGE,1,HYPNOSIS,1,CONFUSION,1,STOMP,17,PSYSHOCK,27,EGGBOMB,37,WOODHAMMER,47,LEAFSTORM
Compatibility=Grass
StepsToHatch=5355
Height=2.0
Weight=120.0
Color=Yellow
Habitat=Forest
RegionalNumbers=103,106
Kind=Coconut
Pokedex=Originally from the tropics, Exeggutor's heads grow larger from exposure to strong sunlight. It is said that when the heads fall, they group to form an Exeggcute.
BattlerPlayerY=0
BattlerEnemyY=5
BattlerAltitude=0
Evolutions=
[104]
Name=Cubone
InternalName=CUBONE
Type1=GROUND
BaseStats=50,50,95,35,40,50
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=64
EffortPoints=0,0,1,0,0,0
Rareness=190
Happiness=70
Abilities=ROCKHEAD,LIGHTNINGROD
HiddenAbility=BATTLEARMOR
Moves=1,GROWL,3,TAILWHIP,7,BONECLUB,11,HEADBUTT,13,LEER,17,FOCUSENERGY,21,BONEMERANG,23,RAGE,27,FALSESWIPE,31,THRASH,33,FLING,37,BONERUSH,41,ENDEAVOR,43,DOUBLEEDGE,47,RETALIATE
EggMoves=ANCIENTPOWER,BELLYDRUM,CHIPAWAY,DETECT,DOUBLEKICK,ENDURE,IRONHEAD,PERISHSONG,SCREECH,SKULLBASH
Compatibility=Monster
StepsToHatch=5355
Height=0.4
Weight=6.5
Color=Brown
Habitat=Mountain
RegionalNumbers=104,208
Kind=Lonely
Pokedex=It pines for the mother it will never see again. Seeing a likeness of its mother in the full moon, it cries. The stains on the skull it wears are from its tears.
WildItemUncommon=THICKCLUB
BattlerPlayerY=0
BattlerEnemyY=23
BattlerAltitude=0
Evolutions=MAROWAK,Level,28
[105]
Name=Marowak
InternalName=MAROWAK
Type1=GROUND
BaseStats=60,80,110,45,50,80
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=149
EffortPoints=0,0,2,0,0,0
Rareness=75
Happiness=70
Abilities=ROCKHEAD,LIGHTNINGROD
HiddenAbility=BATTLEARMOR
Moves=1,GROWL,1,TAILWHIP,1,BONECLUB,1,HEADBUTT,3,TAILWHIP,7,BONECLUB,11,HEADBUTT,13,LEER,17,FOCUSENERGY,21,BONEMERANG,23,RAGE,27,FALSESWIPE,33,THRASH,37,FLING,43,BONERUSH,49,ENDEAVOR,53,DOUBLEEDGE,59,RETALIATE
Compatibility=Monster
StepsToHatch=5355
Height=1.0
Weight=45.0
Color=Brown
Habitat=Mountain
RegionalNumbers=105,209
Kind=Bone Keeper
Pokedex=A Marowak is the evolved form of a Cubone that has grown tough by overcoming the grief of losing its mother. Its tempered and hardened spirit is not easily broken.
WildItemUncommon=THICKCLUB
BattlerPlayerY=0
BattlerEnemyY=20
BattlerAltitude=0
Evolutions=
[106]
Name=Hitmonlee
InternalName=HITMONLEE
Type1=FIGHTING
BaseStats=50,120,53,87,35,110
GenderRate=AlwaysMale
GrowthRate=Medium
BaseEXP=159
EffortPoints=0,2,0,0,0,0
Rareness=45
Happiness=70
Abilities=LIMBER,RECKLESS
HiddenAbility=UNBURDEN
Moves=1,REVENGE,1,DOUBLEKICK,5,MEDITATE,9,ROLLINGKICK,13,JUMPKICK,17,BRICKBREAK,21,FOCUSENERGY,25,FEINT,29,HIJUMPKICK,33,MINDREADER,37,FORESIGHT,41,WIDEGUARD,45,BLAZEKICK,49,ENDURE,53,MEGAKICK,57,CLOSECOMBAT,61,REVERSAL
Compatibility=Humanlike
StepsToHatch=6630
Height=1.5
Weight=49.8
Color=Brown
Habitat=Urban
RegionalNumbers=106,146
Kind=Kicking
Pokedex=Its legs freely stretch and contract. Using these springlike limbs, it bowls over foes with devastating kicks. After battle, it rubs down its tired legs.
BattlerPlayerY=0
BattlerEnemyY=14
BattlerAltitude=0
Evolutions=
[107]
Name=Hitmonchan
InternalName=HITMONCHAN
Type1=FIGHTING
BaseStats=50,105,79,76,35,110
GenderRate=AlwaysMale
GrowthRate=Medium
BaseEXP=159
EffortPoints=0,0,0,0,0,2
Rareness=45
Happiness=70
Abilities=KEENEYE,IRONFIST
HiddenAbility=INNERFOCUS
Moves=1,REVENGE,1,COMETPUNCH,6,AGILITY,11,PURSUIT,16,MACHPUNCH,16,BULLETPUNCH,21,FEINT,26,VACUUMWAVE,31,QUICKGUARD,36,THUNDERPUNCH,36,ICEPUNCH,36,FIREPUNCH,41,SKYUPPERCUT,46,MEGAPUNCH,51,DETECT,56,FOCUSPUNCH,61,COUNTER,66,CLOSECOMBAT
Compatibility=Humanlike
StepsToHatch=6630
Height=1.4
Weight=50.2
Color=Brown
Habitat=Urban
RegionalNumbers=107,147
Kind=Punching
Pokedex=A Hitmonchan is said to possess the spirit of a boxer who aimed to become the world champion. Having an indomitable spirit means that it will never give up.
BattlerPlayerY=0
BattlerEnemyY=12
BattlerAltitude=0
Evolutions=
[108]
Name=Lickitung
InternalName=LICKITUNG
Type1=NORMAL
BaseStats=90,55,75,30,60,75
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=77
EffortPoints=2,0,0,0,0,0
Rareness=45
Happiness=70
Abilities=OWNTEMPO,OBLIVIOUS
HiddenAbility=CLOUDNINE
Moves=1,LICK,5,SUPERSONIC,9,DEFENSECURL,13,KNOCKOFF,17,WRAP,21,STOMP,25,DISABLE,29,SLAM,33,ROLLOUT,37,CHIPAWAY,41,MEFIRST,45,REFRESH,49,SCREECH,53,POWERWHIP,57,WRINGOUT
EggMoves=AMNESIA,BELLYDRUM,BODYSLAM,CURSE,HAMMERARM,MAGNITUDE,MUDDYWATER,SLEEPTALK,SMELLINGSALT,SNORE,ZENHEADBUTT
Compatibility=Monster
StepsToHatch=5355
Height=1.2
Weight=65.5
Color=Pink
Habitat=Grassland
RegionalNumbers=108,180
Kind=Licking
Pokedex=Whenever it sees something unfamiliar, it always licks the object because it memorizes things by texture and taste. It is somewhat put off by sour things.
WildItemUncommon=LAGGINGTAIL
BattlerPlayerY=0
BattlerEnemyY=16
BattlerAltitude=0
Evolutions=
[109]
Name=Koffing
InternalName=KOFFING
Type1=POISON
BaseStats=40,65,95,35,60,45
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=68
EffortPoints=0,0,1,0,0,0
Rareness=190
Happiness=70
Abilities=LEVITATE
Moves=1,POISONGAS,1,TACKLE,4,SMOG,7,SMOKESCREEN,12,ASSURANCE,15,CLEARSMOG,18,SLUDGE,23,SELFDESTRUCT,26,HAZE,29,GYROBALL,34,SLUDGEBOMB,37,EXPLOSION,40,DESTINYBOND,45,MEMENTO
EggMoves=CURSE,DESTINYBOND,GRUDGE,PAINSPLIT,PSYBEAM,PSYWAVE,SCREECH,SPITE,SPITUP,STOCKPILE,SWALLOW
Compatibility=Amorphous
StepsToHatch=5355
Height=0.6
Weight=1.0
Color=Purple
Habitat=Urban
RegionalNumbers=109,115
Kind=Poison Gas
Pokedex=Getting up close to a Koffing will give you a chance to observe, through its thin skin, the toxic gases swirling inside. It blows up at the slightest stimulation.
WildItemUncommon=SMOKEBALL
BattlerPlayerY=0
BattlerEnemyY=18
BattlerAltitude=16
Evolutions=WEEZING,Level,35
[110]
Name=Weezing
InternalName=WEEZING
Type1=POISON
BaseStats=65,90,120,60,85,70
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=172
EffortPoints=0,0,2,0,0,0
Rareness=60
Happiness=70
Abilities=LEVITATE
Moves=1,POISONGAS,1,TACKLE,1,SMOG,1,SMOKESCREEN,4,SMOG,7,SMOKESCREEN,12,ASSURANCE,15,CLEARSMOG,18,SLUDGE,23,SELFDESTRUCT,26,HAZE,29,DOUBLEHIT,34,SLUDGEBOMB,40,EXPLOSION,46,DESTINYBOND,54,MEMENTO
Compatibility=Amorphous
StepsToHatch=5355
Height=1.2
Weight=9.5
Color=Purple
Habitat=Urban
RegionalNumbers=110,116
Kind=Poison Gas
Pokedex=By diluting its toxic gases with a special process, the highest grade of perfume can be extracted. To Weezing, gases emanating from garbage are the ultimate feast.
WildItemUncommon=SMOKEBALL
BattlerPlayerY=0
BattlerEnemyY=6
BattlerAltitude=8
Evolutions=
[111]
Name=Rhyhorn
InternalName=RHYHORN
Type1=GROUND
Type2=ROCK
BaseStats=80,85,95,25,30,30
GenderRate=Female50Percent
GrowthRate=Slow
BaseEXP=69
EffortPoints=0,0,1,0,0,0
Rareness=120
Happiness=70
Abilities=LIGHTNINGROD,ROCKHEAD
HiddenAbility=RECKLESS
Moves=1,HORNATTACK,1,TAILWHIP,8,STOMP,12,FURYATTACK,19,SCARYFACE,23,ROCKBLAST,30,BULLDOZE,34,CHIPAWAY,41,TAKEDOWN,45,DRILLRUN,52,STONEEDGE,56,EARTHQUAKE,63,HORNDRILL,67,MEGAHORN
EggMoves=COUNTER,CRUNCH,CRUSHCLAW,CURSE,DRAGONRUSH,FIREFANG,ICEFANG,IRONTAIL,MAGNITUDE,REVERSAL,ROCKCLIMB,SKULLBASH,THUNDERFANG
Compatibility=Monster,Field
StepsToHatch=5355
Height=1.0
Weight=115.0
Color=Gray
Habitat=RoughTerrain
RegionalNumbers=111,211
Kind=Spikes
Pokedex=Once it starts running, it doesn't stop. Its tiny brain makes it so stupid that it can't remember why it started running in the first place.
BattlerPlayerY=0
BattlerEnemyY=16
BattlerAltitude=0
Evolutions=RHYDON,Level,42
[112]
Name=Rhydon
InternalName=RHYDON
Type1=GROUND
Type2=ROCK
BaseStats=105,130,120,40,45,45
GenderRate=Female50Percent
GrowthRate=Slow
BaseEXP=170
EffortPoints=0,2,0,0,0,0
Rareness=60
Happiness=70
Abilities=LIGHTNINGROD,ROCKHEAD
HiddenAbility=RECKLESS
Moves=1,HORNATTACK,1,TAILWHIP,1,STOMP,1,FURYATTACK,9,STOMP,12,FURYATTACK,19,SCARYFACE,23,ROCKBLAST,30,BULLDOZE,34,CHIPAWAY,41,TAKEDOWN,42,HAMMERARM,47,DRILLRUN,56,STONEEDGE,62,EARTHQUAKE,71,HORNDRILL,77,MEGAHORN
Compatibility=Monster,Field
StepsToHatch=5355
Height=1.9
Weight=120.0
Color=Gray
Habitat=RoughTerrain
RegionalNumbers=112,212
Kind=Drill
Pokedex=Its horn, which rotates like a drill, destroys tall buildings with one strike. It stands on its hind legs, and its brain is well developed.
BattlerPlayerY=0
BattlerEnemyY=9
BattlerAltitude=0
Evolutions=
[113]
Name=Chansey
InternalName=CHANSEY
Type1=NORMAL
BaseStats=250,5,5,50,35,105
GenderRate=AlwaysFemale
GrowthRate=Fast
BaseEXP=395
EffortPoints=2,0,0,0,0,0
Rareness=30
Happiness=140
Abilities=NATURALCURE,SERENEGRACE
HiddenAbility=HEALER
Moves=1,DEFENSECURL,1,POUND,1,GROWL,5,TAILWHIP,9,REFRESH,12,DOUBLESLAP,16,SOFTBOILED,20,BESTOW,23,MINIMIZE,27,TAKEDOWN,31,SING,34,FLING,38,HEALPULSE,42,EGGBOMB,46,LIGHTSCREEN,50,HEALINGWISH,54,DOUBLEEDGE
EggMoves=AROMATHERAPY,COUNTER,ENDURE,GRAVITY,HEALBELL,HELPINGHAND,METRONOME,MUDBOMB,NATURALGIFT,PRESENT
Compatibility=Fairy
StepsToHatch=10455
Height=1.1
Weight=34.6
Color=Pink
Habitat=Urban
RegionalNumbers=113,222
Kind=Egg
Pokedex=Chansey lay nutritionally excellent eggs every day. The eggs are so delicious, they are eagerly devoured by even those who have lost their appetite.
WildItemCommon=LUCKYPUNCH
WildItemUncommon=LUCKYEGG
BattlerPlayerY=0
BattlerEnemyY=20
BattlerAltitude=0
Evolutions=
[114]
Name=Tangela
InternalName=TANGELA
Type1=GRASS
BaseStats=65,55,115,60,100,40
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=87
EffortPoints=0,0,1,0,0,0
Rareness=45
Happiness=70
Abilities=CHLOROPHYLL,LEAFGUARD
HiddenAbility=REGENERATOR
Moves=1,INGRAIN,1,CONSTRICT,4,SLEEPPOWDER,7,VINEWHIP,10,ABSORB,14,POISONPOWDER,17,BIND,20,GROWTH,23,MEGADRAIN,27,KNOCKOFF,30,STUNSPORE,33,NATURALGIFT,36,GIGADRAIN,40,ANCIENTPOWER,43,SLAM,46,TICKLE,49,WRINGOUT,53,POWERWHIP
EggMoves=AMNESIA,CONFUSION,ENDEAVOR,FLAIL,GIGADRAIN,LEAFSTORM,LEECHSEED,MEGADRAIN,NATURALGIFT,NATUREPOWER,POWERSWAP,RAGEPOWDER
Compatibility=Grass
StepsToHatch=5355
Height=1.0
Weight=35.0
Color=Blue
Habitat=Grassland
RegionalNumbers=114,182
Kind=Vine
Pokedex=Its vines snap off easily and painlessly if they are grabbed, allowing it to make a quick getaway. The lost vines are replaced by new growth the very next day.
BattlerPlayerY=0
BattlerEnemyY=22
BattlerAltitude=0
Evolutions=
[115]
Name=Kangaskhan
InternalName=KANGASKHAN
Type1=NORMAL
BaseStats=105,95,80,90,40,80
GenderRate=AlwaysFemale
GrowthRate=Medium
BaseEXP=172
EffortPoints=2,0,0,0,0,0
Rareness=45
Happiness=70
Abilities=EARLYBIRD,SCRAPPY
HiddenAbility=INNERFOCUS
Moves=1,COMETPUNCH,1,LEER,7,FAKEOUT,10,TAILWHIP,13,BITE,19,DOUBLEHIT,22,RAGE,25,MEGAPUNCH,31,CHIPAWAY,34,DIZZYPUNCH,37,CRUNCH,43,ENDURE,46,OUTRAGE,49,SUCKERPUNCH,55,REVERSAL
EggMoves=CIRCLETHROW,COUNTER,CRUSHCLAW,DISABLE,DOUBLEEDGE,ENDEAVOR,FOCUSENERGY,FOCUSPUNCH,FORESIGHT,HAMMERARM,STOMP,TRUMPCARD,UPROAR
Compatibility=Monster
StepsToHatch=5355
Height=2.2
Weight=80.0
Color=Brown
Habitat=Grassland
RegionalNumbers=115,210
Kind=Parent
Pokedex=If you come across a young Kangaskhan playing by itself, never try to catch it. The baby's parent is sure to be in the area, and it will become violently enraged.
BattlerPlayerY=0
BattlerEnemyY=9
BattlerAltitude=0
Evolutions=
[116]
Name=Horsea
InternalName=HORSEA
Type1=WATER
BaseStats=30,40,70,60,70,25
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=59
EffortPoints=0,0,0,0,1,0
Rareness=225
Happiness=70
Abilities=SWIFTSWIM,SNIPER
HiddenAbility=DAMP
Moves=1,BUBBLE,4,SMOKESCREEN,8,LEER,11,WATERGUN,14,FOCUSENERGY,18,BUBBLEBEAM,23,AGILITY,26,TWISTER,30,BRINE,35,HYDROPUMP,38,DRAGONDANCE,42,DRAGONPULSE
EggMoves=AURORABEAM,CLEARSMOG,DISABLE,DRAGONRAGE,DRAGONBREATH,FLAIL,MUDDYWATER,OCTAZOOKA,OUTRAGE,RAZORWIND,SIGNALBEAM,SPLASH,WATERPULSE
Compatibility=Water1,Dragon
StepsToHatch=5355
Height=0.4
Weight=8.0
Color=Blue
Habitat=Sea
RegionalNumbers=116,190
Kind=Dragon
Pokedex=By cleverly flicking the fins on its back side to side, it moves in any direction while facing forward. It spits ink to escape if it senses danger.
WildItemUncommon=DRAGONSCALE
BattlerPlayerY=0
BattlerEnemyY=24
BattlerAltitude=13
Evolutions=SEADRA,Level,32
[117]
Name=Seadra
InternalName=SEADRA
Type1=WATER
BaseStats=55,65,95,85,95,45
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=154
EffortPoints=0,0,1,0,1,0
Rareness=75
Happiness=70
Abilities=POISONPOINT,SNIPER
HiddenAbility=DAMP
Moves=1,BUBBLE,1,SMOKESCREEN,1,LEER,1,WATERGUN,4,SMOKESCREEN,8,LEER,11,WATERGUN,14,FOCUSENERGY,18,BUBBLEBEAM,23,AGILITY,26,TWISTER,30,BRINE,40,HYDROPUMP,48,DRAGONDANCE,57,DRAGONPULSE
Compatibility=Water1,Dragon
StepsToHatch=5355
Height=1.2
Weight=25.0
Color=Blue
Habitat=Sea
RegionalNumbers=117,191
Kind=Dragon
Pokedex=The poisonous barbs all over its body are highly valued as ingredients for making traditional herbal medicine. It shows no mercy to anything approaching its nest.
WildItemUncommon=DRAGONSCALE
BattlerPlayerY=0
BattlerEnemyY=16
BattlerAltitude=11
Evolutions=
[118]
Name=Goldeen
InternalName=GOLDEEN
Type1=WATER
BaseStats=45,67,60,63,35,50
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=64
EffortPoints=0,1,0,0,0,0
Rareness=225
Happiness=70
Abilities=SWIFTSWIM,WATERVEIL
HiddenAbility=LIGHTNINGROD
Moves=1,PECK,1,TAILWHIP,1,WATERSPORT,7,SUPERSONIC,11,HORNATTACK,17,WATERPULSE,21,FLAIL,27,AQUARING,31,FURYATTACK,37,WATERFALL,41,HORNDRILL,47,AGILITY,51,SOAK,57,MEGAHORN
EggMoves=AQUATAIL,BODYSLAM,HAZE,HYDROPUMP,MUDSHOT,MUDSPORT,MUDSLAP,PSYBEAM,SIGNALBEAM,SKULLBASH,SLEEPTALK
Compatibility=Water2
StepsToHatch=5355
Height=0.6
Weight=15.0
Color=Red
Habitat=WatersEdge
RegionalNumbers=118,78
Kind=Goldfish
Pokedex=In the springtime, schools of Goldeen can be seen swimming up falls and rivers. It metes out staggering damage with its single horn.
BattlerPlayerY=0
BattlerEnemyY=22
BattlerAltitude=11
Evolutions=SEAKING,Level,33
[119]
Name=Seaking
InternalName=SEAKING
Type1=WATER
BaseStats=80,92,65,68,65,80
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=158
EffortPoints=0,2,0,0,0,0
Rareness=60
Happiness=70
Abilities=SWIFTSWIM,WATERVEIL
HiddenAbility=LIGHTNINGROD
Moves=1,POISONJAB,1,PECK,1,TAILWHIP,1,WATERSPORT,1,SUPERSONIC,7,SUPERSONIC,11,HORNATTACK,17,WATERPULSE,21,FLAIL,27,AQUARING,31,FURYATTACK,40,WATERFALL,47,HORNDRILL,56,AGILITY,63,SOAK,72,MEGAHORN
Compatibility=Water2
StepsToHatch=5355
Height=1.3
Weight=39.0
Color=Red
Habitat=WatersEdge
RegionalNumbers=119,79
Kind=Goldfish
Pokedex=It punches holes in boulders on stream- beds. This is a clever innovation that prevents its eggs from being attacked or washed away by the current.
BattlerPlayerY=0
BattlerEnemyY=15
BattlerAltitude=10
Evolutions=
[120]
Name=Staryu
InternalName=STARYU
Type1=WATER
BaseStats=30,45,55,85,70,55
GenderRate=Genderless
GrowthRate=Slow
BaseEXP=68
EffortPoints=0,0,0,1,0,0
Rareness=225
Happiness=70
Abilities=ILLUMINATE,NATURALCURE
HiddenAbility=ANALYTIC
Moves=1,TACKLE,1,HARDEN,6,WATERGUN,10,RAPIDSPIN,12,RECOVER,15,CAMOUFLAGE,18,SWIFT,22,BUBBLEBEAM,25,MINIMIZE,30,GYROBALL,33,LIGHTSCREEN,36,BRINE,40,REFLECTTYPE,43,POWERGEM,48,COSMICPOWER,52,HYDROPUMP
Compatibility=Water3
StepsToHatch=5355
Height=0.8
Weight=34.5
Color=Brown
Habitat=Sea
RegionalNumbers=120,169
Kind=Star Shape
Pokedex=It gathers with others in the night and makes its red core glow on and off with the twinkling stars. It can regenerate limbs if they are severed from its body.
WildItemCommon=STARDUST
WildItemUncommon=STARPIECE
BattlerPlayerY=0
BattlerEnemyY=20
BattlerAltitude=7
Evolutions=STARMIE,Item,WATERSTONE
[121]
Name=Starmie
InternalName=STARMIE
Type1=WATER
Type2=PSYCHIC
BaseStats=60,75,85,115,100,85
GenderRate=Genderless
GrowthRate=Slow
BaseEXP=182
EffortPoints=0,0,0,2,0,0
Rareness=60
Happiness=70
Abilities=ILLUMINATE,NATURALCURE
HiddenAbility=ANALYTIC
Moves=1,WATERGUN,1,RAPIDSPIN,1,RECOVER,1,SWIFT,22,CONFUSERAY
Compatibility=Water3
StepsToHatch=5355
Height=1.1
Weight=80.0
Color=Purple
Habitat=Sea
RegionalNumbers=121,170
Kind=Mysterious
Pokedex=People in ancient times imagined that Starmie were transformed from the reflections of stars that twinkled on gentle waves at night.
WildItemCommon=STARDUST
WildItemUncommon=STARPIECE
BattlerPlayerY=0
BattlerEnemyY=17
BattlerAltitude=9
Evolutions=
[122]
Name=Mr. Mime
InternalName=MRMIME
Type1=PSYCHIC
Type2=
BaseStats=40,45,65,90,100,120
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=161
EffortPoints=0,0,0,0,0,2
Rareness=45
Happiness=70
Abilities=SOUNDPROOF,FILTER
HiddenAbility=TECHNICIAN
Moves=1,MAGICALLEAF,1,QUICKGUARD,1,WIDEGUARD,1,POWERSWAP,1,GUARDSWAP,1,BARRIER,1,CONFUSION,4,COPYCAT,8,MEDITATE,11,DOUBLESLAP,15,MIMIC,15,PSYWAVE,18,ENCORE,22,LIGHTSCREEN,22,REFLECT,25,PSYBEAM,29,SUBSTITUTE,32,RECYCLE,36,TRICK,39,PSYCHIC,43,ROLEPLAY,46,BATONPASS,50,SAFEGUARD
EggMoves=CONFUSERAY,FAKEOUT,FUTURESIGHT,HYPNOSIS,ICYWIND,MAGICROOM,MIMIC,NASTYPLOT,POWERSPLIT,TEETERDANCE,TRICK,WAKEUPSLAP
Compatibility=Humanlike
StepsToHatch=6630
Height=1.3
Weight=54.5
Color=Pink
Habitat=Urban
RegionalNumbers=122,158
Kind=Barrier
Pokedex=A Mr. Mime is a master of pantomime. It can convince others that something unseeable actually exists. Once believed, the imaginary object does become real.
WildItemUncommon=LEPPABERRY
BattlerPlayerY=0
BattlerEnemyY=14
BattlerAltitude=0
Evolutions=
[123]
Name=Scyther
InternalName=SCYTHER
Type1=BUG
Type2=FLYING
BaseStats=70,110,80,105,55,80
GenderRate=Female50Percent
GrowthRate=Medium
BaseEXP=100
EffortPoints=0,1,0,0,0,0
Rareness=45
Happiness=70
Abilities=SWARM,TECHNICIAN
HiddenAbility=STEADFAST
Moves=1,VACUUMWAVE,1,QUICKATTACK,1,LEER,5,FOCUSENERGY,9,PURSUIT,13,FALSESWIPE,17,AGILITY,21,WINGATTACK,25,FURYCUTTER,29,SLASH,33,RAZORWIND,37,DOUBLETEAM,41,XSCISSOR,45,NIGHTSLASH,49,DOUBLEHIT,53,AIRSLASH,57,SWORDSDANCE,61,FEINT
EggMoves=BATONPASS,BUGBUZZ,COUNTER,DEFOG,ENDURE,NIGHTSLASH,RAZORWIND,REVERSAL,SILVERWIND,STEELWING
Compatibility=Bug
StepsToHatch=6630
Height=1.5
Weight=56.0
Color=Green
Habitat=Grassland
RegionalNumbers=123,111
Kind=Mantis
Pokedex=Its blindingly fast speed adds to the sharpness of its twin forearm scythes. The scythes can slice through thick logs in one wicked stroke.
BattlerPlayerY=0
BattlerEnemyY=10
BattlerAltitude=0
Evolutions=
[124]
Name=Jynx
InternalName=JYNX
Type1=ICE
Type2=PSYCHIC
BaseStats=65,50,35,95,115,95
GenderRate=AlwaysFemale
GrowthRate=Medium
BaseEXP=159
EffortPoints=0,0,0,0,2,0
Rareness=45
Happiness=70
Abilities=OBLIVIOUS,FOREWARN
HiddenAbility=DRYSKIN
Moves=1,POUND,1,LICK,1,LOVELYKISS,1,POWDERSNOW,5,LICK,8,LOVELYKISS,11,POWDERSNOW,15,DOUBLESLAP,18,ICEPUNCH,21,HEARTSTAMP,25,MEANLOOK,28,FAKETEARS,33,WAKEUPSLAP,39,AVALANCHE,44,BODYSLAM,49,WRINGOUT,55,PERISHSONG,60,BLIZZARD
Compatibility=Humanlike
StepsToHatch=6630
Height=1.4
Weight=40.6
Color=Red
Habitat=Urban
RegionalNumbers=124,155
Kind=Human Shape
Pokedex=A Jynx sashays rhythmically as if it were dancing. Its motions are so bouncingly alluring, people seeing it are compelled to shake their hips without noticing.
WildItemCommon=ASPEARBERRY
WildItemUncommon=ASPEARBERRY
WildItemRare=ASPEARBERRY
BattlerPlayerY=0
BattlerEnemyY=16
BattlerAltitude=0
Evolutions=
[125]
Name=Electabuzz
InternalName=ELECTABUZZ
Type1=ELECTRIC
BaseStats=65,83,57,105,95,85
GenderRate=Female25Percent
GrowthRate=Medium
BaseEXP=172
EffortPoints=0,0,0,2,0,0
Rareness=45
Happiness=70
Abilities=STATIC
HiddenAbility=VITALSPIRIT
Moves=1,QUICKATTACK,1,LEER,1,THUNDERSHOCK,5,THUNDERSHOCK,8,LOWKICK,12,SWIFT,15,SHOCKWAVE,19,THUNDERWAVE,22,ELECTROBALL,26,LIGHTSCREEN,29,THUNDERPUNCH,36,DISCHARGE,42,SCREECH,49,THUNDERBOLT,55,THUNDER
Compatibility=Humanlike
StepsToHatch=6630
Height=1.1
Weight=30.0
Color=Yellow
Habitat=Grassland
RegionalNumbers=125,157
Kind=Electric
Pokedex=When a storm approaches, it competes with others to scale heights that are likely to be stricken by lightning. Some towns use Electabuzz in place of lightning rods.
WildItemUncommon=ELECTIRIZER
BattlerPlayerY=0
BattlerEnemyY=11
BattlerAltitude=0
Evolutions=
[126]
Name=Magmar
InternalName=MAGMAR
Type1=FIRE
BaseStats=65,95,57,93,100,85
GenderRate=Female25Percent
GrowthRate=Medium
BaseEXP=173
EffortPoints=0,0,0,0,2,0
Rareness=45
Happiness=70
Abilities=FLAMEBODY
HiddenAbility=VITALSPIRIT
Moves=1,SMOG,1,LEER,1,EMBER,5,EMBER,8,SMOKESCREEN,12,FAINTATTACK,15,FIRESPIN,19,CLEARSMOG,22,FLAMEBURST,26,CONFUSERAY,29,FIREPUNCH,36,LAVAPLUME,42,SUNNYDAY,49,FLAMETHROWER,55,FIREBLAST
Compatibility=Humanlike
StepsToHatch=6630
Height=1.3
Weight=44.5
Color=Red
Habitat=Mountain
RegionalNumbers=126,153
Kind=Spitfire
Pokedex=In battle, it blows out intense flames from all over its body to intimidate its foe. These fiery bursts create heat waves that ignite grass and trees in the area.
WildItemUncommon=MAGMARIZER
BattlerPlayerY=0
BattlerEnemyY=11
BattlerAltitude=0
Evolutions=
[127]
Name=Pinsir
InternalName=PINSIR
Type1=BUG
BaseStats=65,125,100,85,55,70
GenderRate=Female50Percent
GrowthRate=Slow
BaseEXP=175
EffortPoints=0,2,0,0,0,0
Rareness=45
Happiness=70
Abilities=HYPERCUTTER,MOLDBREAKER
HiddenAbility=MOXIE
Moves=1,VICEGRIP,1,FOCUSENERGY,4,BIND,8,SEISMICTOSS,11,HARDEN,15,REVENGE,18,BRICKBREAK,22,VITALTHROW,26,SUBMISSION,29,XSCISSOR,33,STORMTHROW,36,THRASH,40,SWORDSDANCE,43,SUPERPOWER,47,GUILLOTINE
EggMoves=BUGBITE,CLOSECOMBAT,FAINTATTACK,FEINT,FLAIL,FURYATTACK,MEFIRST,QUICKATTACK,SUPERPOWER
Compatibility=Bug
StepsToHatch=6630
Height=1.5
Weight=55.0
Color=Brown
Habitat=Forest
RegionalNumbers=127,113
Kind=Stag Beetle
Pokedex=Their pincers are strong enough to shatter thick logs. Because they dislike cold, Pinsir burrow and sleep under the ground on chilly nights.
BattlerPlayerY=0
BattlerEnemyY=10
BattlerAltitude=0
Evolutions=
[128]
Name=Tauros
InternalName=TAUROS
Type1=NORMAL
BaseStats=75,100,95,110,40,70
GenderRate=AlwaysMale
GrowthRate=Slow
BaseEXP=172
EffortPoints=0,1,0,1,0,0
Rareness=45
Happiness=70
Abilities=INTIMIDATE,ANGERPOINT
HiddenAbility=SHEERFORCE
Moves=1,TACKLE,3,TAILWHIP,5,RAGE,8,HORNATTACK,11,SCARYFACE,15,PURSUIT,19,REST,24,PAYBACK,29,WORKUP,35,ZENHEADBUTT,41,TAKEDOWN,48,SWAGGER,55,THRASH,63,GIGAIMPACT
Compatibility=Field
StepsToHatch=5355
Height=1.4
Weight=88.4
Color=Brown
Habitat=Grassland
RegionalNumbers=128,150
Kind=Wild Bull
Pokedex=It is not satisfied unless it is rampaging at all times. If there is no opponent for Tauros to battle, it will charge at thick trees and knock them down to calm itself.
BattlerPlayerY=0
BattlerEnemyY=13
BattlerAltitude=0
Evolutions=
[129]
Name=Magikarp
InternalName=MAGIKARP
Type1=WATER
BaseStats=20,10,55,80,15,20
GenderRate=Female50Percent
GrowthRate=Slow
BaseEXP=40
EffortPoints=0,0,0,1,0,0
Rareness=255
Happiness=70
Abilities=SWIFTSWIM
HiddenAbility=RATTLED
Moves=1,SPLASH,15,TACKLE,30,FLAIL
Compatibility=Water2,Dragon
StepsToHatch=1530
Height=0.9
Weight=10.0
Color=Red
Habitat=WatersEdge
RegionalNumbers=129,76
Kind=Fish
Pokedex=Its swimming muscles are weak, so it is easily washed away by currents. In places where water pools, you can see many Magikarp deposited there by the flow.
BattlerPlayerY=0
BattlerEnemyY=12
BattlerAltitude=10
Evolutions=GYARADOS,Level,20
[130]
Name=Gyarados
InternalName=GYARADOS
Type1=WATER
Type2=FLYING
BaseStats=95,125,79,81,60,100
GenderRate=Female50Percent
GrowthRate=Slow
BaseEXP=189
EffortPoints=0,2,0,0,0,0
Rareness=45
Happiness=70
Abilities=INTIMIDATE
HiddenAbility=MOXIE
Moves=1,THRASH,20,BITE,23,DRAGONRAGE,26,LEER,29,TWISTER,32,ICEFANG,35,AQUATAIL,38,RAINDANCE,41,HYDROPUMP,44,DRAGONDANCE,47,HYPERBEAM
Compatibility=Water2,Dragon
StepsToHatch=1530
Height=6.5
Weight=235.0
Color=Blue
Habitat=WatersEdge
RegionalNumbers=130,77
Kind=Atrocious
Pokedex=It is an extremely vicious and violent Pokémon. When humans begin to fight, it will appear and burn everything to the ground with intensely hot flames.
BattlerPlayerY=0
BattlerEnemyY=2
BattlerAltitude=2
Evolutions=
[131]
Name=Lapras
InternalName=LAPRAS
Type1=WATER
Type2=ICE
BaseStats=130,85,80,60,85,95
GenderRate=Female50Percent
GrowthRate=Slow
BaseEXP=187
EffortPoints=2,0,0,0,0,0
Rareness=45
Happiness=70
Abilities=WATERABSORB,SHELLARMOR
HiddenAbility=HYDRATION
Moves=1,SING,1,GROWL,1,WATERGUN,4,MIST,7,CONFUSERAY,10,ICESHARD,14,WATERPULSE,18,BODYSLAM,22,RAINDANCE,27,PERISHSONG,32,ICEBEAM,37,BRINE,43,SAFEGUARD,49,HYDROPUMP,55,SHEERCOLD
EggMoves=ANCIENTPOWER,AVALANCHE,CURSE,DRAGONDANCE,DRAGONPULSE,FISSURE,FORESIGHT,FUTURESIGHT,HORNDRILL,REFRESH,SLEEPTALK,TICKLE,WHIRLPOOL
Compatibility=Monster,Water1
StepsToHatch=10455
Height=2.5
Weight=220.0
Color=Blue
Habitat=Sea
RegionalNumbers=131,224
Kind=Transport
Pokedex=People have driven Lapras almost to the point of extinction. In the evenings, it is said to sing plaintively as it seeks what few others of its kind still remain.
BattlerPlayerY=0
BattlerEnemyY=11
BattlerAltitude=0
Evolutions=
[132]
Name=Ditto
InternalName=DITTO
Type1=NORMAL
BaseStats=48,48,48,48,48,48
GenderRate=Genderless
GrowthRate=Medium
BaseEXP=101
EffortPoints=1,0,0,0,0,0
Rareness=35
Happiness=70
Abilities=LIMBER
HiddenAbility=IMPOSTER
Moves=1,TRANSFORM
Compatibility=Ditto
StepsToHatch=5355
Height=0.3
Weight=4.0
Color=Purple
Habitat=Urban
RegionalNumbers=132,92
Kind=Transform
Pokedex=A Ditto rearranges its cell structure to transform itself. However, if it tries to change based on its memory, it will get details wrong.
WildItemCommon=QUICKPOWDER
WildItemUncommon=METALPOWDER
BattlerPlayerY=0
BattlerEnemyY=28
BattlerAltitude=0
Evolutions=
[133]
Name=Eevee
InternalName=EEVEE
Type1=NORMAL
BaseStats=55,55,50,55,45,65
GenderRate=FemaleOneEighth
GrowthRate=Medium
BaseEXP=65
EffortPoints=0,0,0,0,0,1
Rareness=45
Happiness=70
Abilities=RUNAWAY,ADAPTABILITY
HiddenAbility=ANTICIPATION
Moves=1,HELPINGHAND,1,TACKLE,1,TAILWHIP,5,SANDATTACK,9,GROWL,13,QUICKATTACK,17,BITE,21,COVET,25,TAKEDOWN,29,CHARM,33,BATONPASS,37,DOUBLEEDGE,41,LASTRESORT,45,TRUMPCARD
EggMoves=CHARM,COVET,CURSE,DETECT,ENDURE,FAKETEARS,FLAIL,NATURALGIFT,STOREDPOWER,SYNCHRONOISE,TICKLE,WISH,YAWN
Compatibility=Field
StepsToHatch=9180
Height=0.3
Weight=6.5
Color=Brown
Habitat=Urban
RegionalNumbers=133,184
Kind=Evolution
Pokedex=An Eevee has an unstable genetic makeup that suddenly mutates due to its environment. Radiation from various stones causes this Pokémon to evolve.
BattlerPlayerY=0
BattlerEnemyY=20
BattlerAltitude=0
Evolutions=VAPOREON,Item,WATERSTONE,JOLTEON,Item,THUNDERSTONE,FLAREON,Item,FIRESTONE
[134]
Name=Vaporeon
InternalName=VAPOREON
Type1=WATER
BaseStats=130,65,60,65,110,95
GenderRate=FemaleOneEighth
GrowthRate=Medium
BaseEXP=184
EffortPoints=2,0,0,0,0,0
Rareness=45
Happiness=70
Abilities=WATERABSORB
HiddenAbility=HYDRATION
Moves=1,HELPINGHAND,1,TACKLE,1,TAILWHIP,5,SANDATTACK,9,WATERGUN,13,QUICKATTACK,17,WATERPULSE,21,AURORABEAM,25,AQUARING,29,ACIDARMOR,33,HAZE,37,MUDDYWATER,41,LASTRESORT,45,HYDROPUMP
Compatibility=Field
StepsToHatch=9180
Height=1.0
Weight=29.0
Color=Blue
Habitat=Urban
RegionalNumbers=134,185
Kind=Bubble Jet
Pokedex=Vaporeon underwent a spontaneous mutation and grew fins and gills that allow them to live underwater. They have the ability to freely control water.
BattlerPlayerY=0
BattlerEnemyY=16
BattlerAltitude=0
Evolutions=
[135]
Name=Jolteon
InternalName=JOLTEON
Type1=ELECTRIC
BaseStats=65,65,60,130,110,95
GenderRate=FemaleOneEighth
GrowthRate=Medium
BaseEXP=184
EffortPoints=0,0,0,2,0,0
Rareness=45
Happiness=70
Abilities=VOLTABSORB
HiddenAbility=QUICKFEET
Moves=1,HELPINGHAND,1,TACKLE,1,TAILWHIP,5,SANDATTACK,9,THUNDERSHOCK,13,QUICKATTACK,17,DOUBLEKICK,21,THUNDERFANG,25,PINMISSILE,29,AGILITY,33,THUNDERWAVE,37,DISCHARGE,41,LASTRESORT,45,THUNDER
Compatibility=Field
StepsToHatch=9180
Height=0.8
Weight=24.5
Color=Yellow
Habitat=Urban
RegionalNumbers=135,186
Kind=Lightning
Pokedex=Its cells generate weak power that is amplified by its fur's static electricity to drop thunderbolts. The bristling fur is made of electrically charged needles.
BattlerPlayerY=0
BattlerEnemyY=18
BattlerAltitude=0
Evolutions=
[136]
Name=Flareon
InternalName=FLAREON
Type1=FIRE
BaseStats=65,130,60,65,95,110
GenderRate=FemaleOneEighth
GrowthRate=Medium
BaseEXP=184
EffortPoints=0,2,0,0,0,0
Rareness=45
Happiness=70
Abilities=FLASHFIRE
HiddenAbility=GUTS
Moves=1,HELPINGHAND,1,TACKLE,1,TAILWHIP,5,SANDATTACK,9,EMBER,13,QUICKATTACK,17,BITE,21,FIREFANG,25,FIRESPIN,29,SCARYFACE,33,SMOG,37,LAVAPLUME,41,LASTRESORT,45,FIREBLAST
Compatibility=Field
StepsToHatch=9180
Height=0.9
Weight=25.0
Color=Red
Habitat=Urban
RegionalNumbers=136,187
Kind=Flame
Pokedex=Flareon's fluffy fur releases heat into the air so that its body does not get excessively hot. Its body temperature can rise to a maximum of 1,650 degrees F.
BattlerPlayerY=0
BattlerEnemyY=17
BattlerAltitude=0
Evolutions=
[137]
Name=Porygon
InternalName=PORYGON
Type1=NORMAL
BaseStats=65,60,70,40,85,75
GenderRate=Genderless
GrowthRate=Medium
BaseEXP=79
EffortPoints=0,0,0,0,1,0
Rareness=45
Happiness=70
Abilities=TRACE,DOWNLOAD
HiddenAbility=ANALYTIC
Moves=1,CONVERSION2,1,TACKLE,1,CONVERSION,1,SHARPEN,7,PSYBEAM,12,AGILITY,18,RECOVER,23,MAGNETRISE,29,SIGNALBEAM,34,RECYCLE,40,DISCHARGE,45,LOCKON,51,TRIATTACK,56,MAGICCOAT,62,ZAPCANNON
Compatibility=Mineral
StepsToHatch=5355
Height=0.8
Weight=36.5
Color=Pink
Habitat=Urban
RegionalNumbers=137,220
Kind=Virtual
Pokedex=It is capable of reverting itself entirely back to program data in order to enter cyberspace. A Porygon is copy- protected so it cannot be duplicated.
BattlerPlayerY=0
BattlerEnemyY=25
BattlerAltitude=8
Evolutions=
[138]
Name=Omanyte
InternalName=OMANYTE
Type1=ROCK
Type2=WATER
BaseStats=35,40,100,35,90,55
GenderRate=FemaleOneEighth
GrowthRate=Medium
BaseEXP=71
EffortPoints=0,0,1,0,0,0
Rareness=45
Happiness=70
Abilities=SWIFTSWIM,SHELLARMOR
HiddenAbility=WEAKARMOR
Moves=1,CONSTRICT,1,WITHDRAW,7,BITE,10,WATERGUN,16,ROLLOUT,19,LEER,25,MUDSHOT,28,BRINE,34,PROTECT,37,ANCIENTPOWER,43,TICKLE,46,ROCKBLAST,52,SHELLSMASH,55,HYDROPUMP
EggMoves=AURORABEAM,BIDE,BUBBLEBEAM,HAZE,KNOCKOFF,MUDDYWATER,SLAM,SPIKES,SUPERSONIC,TOXICSPIKES,WATERPULSE,WHIRLPOOL,WRINGOUT
Compatibility=Water1,Water3
StepsToHatch=7905
Height=0.4
Weight=7.5
Color=Blue
Habitat=Sea
RegionalNumbers=138,225
Kind=Spiral
Pokedex=One of the ancient and long-since-extinct Pokémon that have been regenerated from fossils by humans. If attacked, it withdraws into its hard shell.
BattlerPlayerY=0
BattlerEnemyY=25
BattlerAltitude=0
Evolutions=OMASTAR,Level,40
[139]
Name=Omastar
InternalName=OMASTAR
Type1=ROCK
Type2=WATER
BaseStats=70,60,125,55,115,70
GenderRate=FemaleOneEighth
GrowthRate=Medium
BaseEXP=173
EffortPoints=0,0,2,0,0,0
Rareness=45
Happiness=70
Abilities=SWIFTSWIM,SHELLARMOR
HiddenAbility=WEAKARMOR
Moves=1,CONSTRICT,1,WITHDRAW,1,BITE,7,BITE,10,WATERGUN,16,ROLLOUT,19,LEER,25,MUDSHOT,28,BRINE,34,PROTECT,37,ANCIENTPOWER,40,SPIKECANNON,48,TICKLE,56,ROCKBLAST,67,SHELLSMASH,75,HYDROPUMP
Compatibility=Water1,Water3
StepsToHatch=7905
Height=1.0
Weight=35.0
Color=Blue
Habitat=Sea
RegionalNumbers=139,226
Kind=Spiral
Pokedex=An Omastar uses its tentacles to capture its prey. It is believed to have become extinct because its shell grew too large, making its movements slow and ponderous.
BattlerPlayerY=0
BattlerEnemyY=17
BattlerAltitude=0
Evolutions=
[140]
Name=Kabuto
InternalName=KABUTO
Type1=ROCK
Type2=WATER
BaseStats=30,80,90,55,55,45
GenderRate=FemaleOneEighth
GrowthRate=Medium
BaseEXP=71
EffortPoints=0,0,1,0,0,0
Rareness=45
Happiness=70
Abilities=SWIFTSWIM,BATTLEARMOR
HiddenAbility=WEAKARMOR
Moves=1,SCRATCH,1,HARDEN,6,ABSORB,11,LEER,16,MUDSHOT,21,SANDATTACK,26,ENDURE,31,AQUAJET,36,MEGADRAIN,41,METALSOUND,46,ANCIENTPOWER,51,WRINGOUT
EggMoves=AURORABEAM,BUBBLEBEAM,CONFUSERAY,FLAIL,FORESIGHT,GIGADRAIN,ICYWIND,KNOCKOFF,MUDSHOT,RAPIDSPIN,SCREECH
Compatibility=Water1,Water3
StepsToHatch=7905
Height=0.5
Weight=11.5
Color=Brown
Habitat=Sea
RegionalNumbers=140,227
Kind=Shellfish
Pokedex=It is a Pokémon that has been regenerated from a fossil. However, in rare cases, living examples have been discovered. Kabuto have not changed for 300 million years.
BattlerPlayerY=0
BattlerEnemyY=28
BattlerAltitude=0
Evolutions=KABUTOPS,Level,40
[141]
Name=Kabutops
InternalName=KABUTOPS
Type1=ROCK
Type2=WATER
BaseStats=60,115,105,80,65,70
GenderRate=FemaleOneEighth
GrowthRate=Medium
BaseEXP=173
EffortPoints=0,2,0,0,0,0
Rareness=45
Happiness=70
Abilities=SWIFTSWIM,BATTLEARMOR
HiddenAbility=WEAKARMOR
Moves=1,FEINT,1,SCRATCH,1,HARDEN,1,ABSORB,1,LEER,6,ABSORB,11,LEER,16,MUDSHOT,21,SANDATTACK,26,ENDURE,31,AQUAJET,36,MEGADRAIN,40,SLASH,45,METALSOUND,54,ANCIENTPOWER,63,WRINGOUT,72,NIGHTSLASH
Compatibility=Water1,Water3
StepsToHatch=7905
Height=1.3
Weight=40.5
Color=Brown
Habitat=Sea
RegionalNumbers=141,228
Kind=Shellfish
Pokedex=Kabutops once swam underwater to hunt for prey. It was apparently evolving from being a water dweller to living on land as evident from changes in its gills and legs.
BattlerPlayerY=0
BattlerEnemyY=8
BattlerAltitude=0
Evolutions=
[142]
Name=Aerodactyl
InternalName=AERODACTYL
Type1=ROCK
Type2=FLYING
BaseStats=80,105,65,130,60,75
GenderRate=FemaleOneEighth
GrowthRate=Slow
BaseEXP=180
EffortPoints=0,0,0,2,0,0
Rareness=45
Happiness=70
Abilities=ROCKHEAD,PRESSURE
HiddenAbility=UNNERVE
Moves=1,ICEFANG,1,FIREFANG,1,THUNDERFANG,1,WINGATTACK,1,SUPERSONIC,1,BITE,1,SCARYFACE,9,ROAR,17,AGILITY,25,ANCIENTPOWER,33,CRUNCH,41,TAKEDOWN,49,SKYDROP,57,IRONHEAD,65,HYPERBEAM,73,ROCKSLIDE,81,GIGAIMPACT
EggMoves=ASSURANCE,CURSE,DRAGONBREATH,FORESIGHT,PURSUIT,ROOST,STEELWING,TAILWIND,WHIRLWIND
Compatibility=Flying
StepsToHatch=9180
Height=1.8
Weight=59.0
Color=Purple
Habitat=Mountain
RegionalNumbers=142,229
Kind=Fossil
Pokedex=Aerodactyl is a Pokémon from the age of dinosaurs. It was regenerated from DNA extracted from amber. It is imagined to have been the king of the skies.
BattlerPlayerY=0
BattlerEnemyY=9
BattlerAltitude=10
Evolutions=
[143]
Name=Snorlax
InternalName=SNORLAX
Type1=NORMAL
BaseStats=160,110,65,30,65,110
GenderRate=FemaleOneEighth
GrowthRate=Slow
BaseEXP=189
EffortPoints=2,0,0,0,0,0
Rareness=25
Happiness=70
Abilities=IMMUNITY,THICKFAT
HiddenAbility=GLUTTONY
Moves=1,TACKLE,4,DEFENSECURL,9,AMNESIA,12,LICK,17,BELLYDRUM,20,YAWN,25,CHIPAWAY,28,REST,28,SNORE,33,SLEEPTALK,36,BODYSLAM,41,BLOCK,44,ROLLOUT,49,CRUNCH,52,HEAVYSLAM,57,GIGAIMPACT
EggMoves=AFTERYOU,CHARM,COUNTER,CURSE,DOUBLEEDGE,FISSURE,LICK,NATURALGIFT,PURSUIT,SELFDESTRUCT,WHIRLWIND,ZENHEADBUTT
Compatibility=Monster
StepsToHatch=10455
Height=2.1
Weight=460.0
Color=Black
Habitat=Mountain
RegionalNumbers=143,230
Kind=Sleeping
Pokedex=Snorlax's typical day consists of nothing more than eating and sleeping. It is such a docile Pokémon that there are children who use its big belly as a place to play.
WildItemCommon=LEFTOVERS
WildItemUncommon=LEFTOVERS
WildItemRare=LEFTOVERS
BattlerPlayerY=0
BattlerEnemyY=9
BattlerAltitude=0
Evolutions=
[144]
Name=Articuno
InternalName=ARTICUNO
Type1=ICE
Type2=FLYING
BaseStats=90,85,100,85,95,125
GenderRate=Genderless
GrowthRate=Slow
BaseEXP=261
EffortPoints=0,0,0,0,0,3
Rareness=3
Happiness=35
Abilities=PRESSURE
HiddenAbility=SNOWCLOAK
Moves=1,GUST,1,POWDERSNOW,8,MIST,15,ICESHARD,22,MINDREADER,29,ANCIENTPOWER,36,AGILITY,43,ICEBEAM,50,REFLECT,57,ROOST,64,TAILWIND,71,BLIZZARD,78,SHEERCOLD,85,HAIL,92,HURRICANE
Compatibility=Undiscovered
StepsToHatch=20655
Height=1.7
Weight=55.4
Color=Blue
Habitat=Rare
RegionalNumbers=144,240
Kind=Freeze
Pokedex=Articuno is a legendary bird Pokémon that can control ice. The flapping of its wings chills the air. As a result, it is said that when this Pokémon flies, snow will fall.
BattlerPlayerY=0
BattlerEnemyY=6
BattlerAltitude=0
Evolutions=
[145]
Name=Zapdos
InternalName=ZAPDOS
Type1=ELECTRIC
Type2=FLYING
BaseStats=90,90,85,100,125,90
GenderRate=Genderless
GrowthRate=Slow
BaseEXP=261
EffortPoints=0,0,0,0,3,0
Rareness=3
Happiness=35
Abilities=PRESSURE
HiddenAbility=LIGHTNINGROD
Moves=1,PECK,1,THUNDERSHOCK,8,THUNDERWAVE,15,DETECT,22,PLUCK,29,ANCIENTPOWER,36,CHARGE,43,AGILITY,50,DISCHARGE,57,ROOST,64,LIGHTSCREEN,71,DRILLPECK,78,THUNDER,85,RAINDANCE,92,ZAPCANNON
Compatibility=Undiscovered
StepsToHatch=20655
Height=1.6
Weight=52.6
Color=Yellow
Habitat=Rare
RegionalNumbers=145,241
Kind=Electric
Pokedex=Zapdos is a legendary bird Pokémon that has the ability to control electricity. It usually lives in thunderclouds. It gains power if it is stricken by lightning bolts.
BattlerPlayerY=0
BattlerEnemyY=8
BattlerAltitude=8
Evolutions=
[146]
Name=Moltres
InternalName=MOLTRES
Type1=FIRE
Type2=FLYING
BaseStats=90,100,90,90,125,85
GenderRate=Genderless
GrowthRate=Slow
BaseEXP=261
EffortPoints=0,0,0,0,3,0
Rareness=3
Happiness=35
Abilities=PRESSURE
HiddenAbility=FLAMEBODY
Moves=1,WINGATTACK,1,EMBER,8,FIRESPIN,15,AGILITY,22,ENDURE,29,ANCIENTPOWER,36,FLAMETHROWER,43,SAFEGUARD,50,AIRSLASH,57,ROOST,64,HEATWAVE,71,SOLARBEAM,78,SKYATTACK,85,SUNNYDAY,92,HURRICANE
Compatibility=Undiscovered
StepsToHatch=20655
Height=2.0
Weight=60.0
Color=Yellow
Habitat=Rare
RegionalNumbers=146,242
Kind=Flame
Pokedex=Moltres is a legendary bird Pokémon that can control fire. If injured, it is said to dip its body in the molten magma of a volcano to burn and heal itself.
BattlerPlayerY=0
BattlerEnemyY=6
BattlerAltitude=0
Evolutions=
[147]
Name=Dratini
InternalName=DRATINI
Type1=DRAGON
BaseStats=41,64,45,50,50,50
GenderRate=Female50Percent
GrowthRate=Slow
BaseEXP=60
EffortPoints=0,1,0,0,0,0
Rareness=45
Happiness=35
Abilities=SHEDSKIN
HiddenAbility=MARVELSCALE
Moves=1,WRAP,1,LEER,5,THUNDERWAVE,11,TWISTER,15,DRAGONRAGE,21,SLAM,25,AGILITY,31,DRAGONTAIL,35,AQUATAIL,41,DRAGONRUSH,45,SAFEGUARD,51,DRAGONDANCE,55,OUTRAGE,61,HYPERBEAM
EggMoves=AQUAJET,DRAGONBREATH,DRAGONDANCE,DRAGONPULSE,DRAGONRUSH,EXTREMESPEED,HAZE,IRONTAIL,MIST,SUPERSONIC,WATERPULSE
Compatibility=Water1,Dragon
StepsToHatch=10455
Height=1.8
Weight=3.3
Color=Blue
Habitat=WatersEdge
RegionalNumbers=147,246
Kind=Dragon
Pokedex=A Dratini continually molts and sloughs off its old skin. It does so because the life energy within its body steadily builds to reach uncontrollable levels.
WildItemUncommon=DRAGONSCALE
BattlerPlayerY=0
BattlerEnemyY=19
BattlerAltitude=0
Evolutions=DRAGONAIR,Level,30
[148]
Name=Dragonair
InternalName=DRAGONAIR
Type1=DRAGON
BaseStats=61,84,65,70,70,70
GenderRate=Female50Percent
GrowthRate=Slow
BaseEXP=147
EffortPoints=0,2,0,0,0,0
Rareness=45
Happiness=35
Abilities=SHEDSKIN
HiddenAbility=MARVELSCALE
Moves=1,WRAP,1,LEER,1,THUNDERWAVE,1,TWISTER,5,THUNDERWAVE,11,TWISTER,15,DRAGONRAGE,21,SLAM,25,AGILITY,33,DRAGONTAIL,39,AQUATAIL,47,DRAGONRUSH,53,SAFEGUARD,61,DRAGONDANCE,67,OUTRAGE,75,HYPERBEAM
Compatibility=Water1,Dragon
StepsToHatch=10455
Height=4.0
Weight=16.5
Color=Blue
Habitat=WatersEdge
RegionalNumbers=148,247
Kind=Dragon
Pokedex=A Dragonair stores an enormous amount of energy inside its body. It is said to alter the weather around it by loosing energy from the crystals on its neck and tail.
WildItemUncommon=DRAGONSCALE
BattlerPlayerY=0
BattlerEnemyY=8
BattlerAltitude=0
Evolutions=DRAGONITE,Level,55
[149]
Name=Dragonite
InternalName=DRAGONITE
Type1=DRAGON
Type2=FLYING
BaseStats=91,134,95,80,100,100
GenderRate=Female50Percent
GrowthRate=Slow
BaseEXP=270
EffortPoints=0,3,0,0,0,0
Rareness=45
Happiness=35
Abilities=INNERFOCUS
HiddenAbility=MULTISCALE
Moves=1,FIREPUNCH,1,THUNDERPUNCH,1,ROOST,1,WRAP,1,LEER,1,THUNDERWAVE,1,TWISTER,5,THUNDERWAVE,11,TWISTER,15,DRAGONRAGE,21,SLAM,25,AGILITY,33,DRAGONTAIL,39,AQUATAIL,47,DRAGONRUSH,53,SAFEGUARD,55,WINGATTACK,61,DRAGONDANCE,67,OUTRAGE,75,HYPERBEAM,81,HURRICANE
Compatibility=Water1,Dragon
StepsToHatch=10455
Height=2.2
Weight=210.0
Color=Brown
Habitat=WatersEdge
RegionalNumbers=149,248
Kind=Dragon
Pokedex=It can circle the globe in just 16 hours. It is a kindhearted Pokémon that leads lost and foundering ships in a storm to the safety of land.
WildItemUncommon=DRAGONSCALE
BattlerPlayerY=0
BattlerEnemyY=3
BattlerAltitude=0
Evolutions=
[150]
Name=Mewtwo
InternalName=MEWTWO
Type1=PSYCHIC
BaseStats=106,110,90,130,154,90
GenderRate=Genderless
GrowthRate=Slow
BaseEXP=306
EffortPoints=0,0,0,0,3,0
Rareness=3
Happiness=0
Abilities=PRESSURE
HiddenAbility=UNNERVE
Moves=1,CONFUSION,1,DISABLE,1,BARRIER,8,SWIFT,15,FUTURESIGHT,22,PSYCHUP,29,MIRACLEEYE,36,MIST,43,PSYCHOCUT,50,AMNESIA,57,POWERSWAP,57,GUARDSWAP,64,PSYCHIC,71,MEFIRST,79,RECOVER,86,SAFEGUARD,93,AURASPHERE,100,PSYSTRIKE
Compatibility=Undiscovered
StepsToHatch=30855
Height=2.0
Weight=122.0
Color=Purple
Habitat=Rare
RegionalNumbers=150,254
Kind=Genetic
Pokedex=A Pokémon that was created by genetic manipulation. However, even though the scientific power of humans made its body, they failed to give it a warm heart.
BattlerPlayerY=0
BattlerEnemyY=9
BattlerAltitude=0
Evolutions=
[151]
Name=Mew
InternalName=MEW
Type1=PSYCHIC
BaseStats=100,100,100,100,100,100
GenderRate=Genderless
GrowthRate=Parabolic
BaseEXP=270
EffortPoints=3,0,0,0,0,0
Rareness=45
Happiness=100
Abilities=SYNCHRONIZE
Moves=1,POUND,1,REFLECTTYPE,1,TRANSFORM,10,MEGAPUNCH,20,METRONOME,30,PSYCHIC,40,BARRIER,50,ANCIENTPOWER,60,AMNESIA,70,MEFIRST,80,BATONPASS,90,NASTYPLOT,100,AURASPHERE
Compatibility=Undiscovered
StepsToHatch=30855
Height=0.4
Weight=4.0
Color=Pink
Habitat=Rare
RegionalNumbers=151,255
Kind=New Species
Pokedex=A Mew is said to possess the genes of all Pokémon. It is capable of making itself invisible at will, so it entirely avoids notice even if it approaches people.
WildItemCommon=LUMBERRY
WildItemUncommon=LUMBERRY
WildItemRare=LUMBERRY
BattlerPlayerY=0
BattlerEnemyY=18
BattlerAltitude=13
Evolutions=<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class PokemonParty
{
public Pokemon[] pokemons;
public Pokemon GetFirstNonFaintedPokemon()
{
foreach (Pokemon p in pokemons)
{
if (p != null && !p.CheckForDeath())
{
return p;
}
}
return null;
}
public bool HasUsablePokemon()
{
return (GetFirstNonFaintedPokemon() != null);
}
public void InitParty()
{
foreach(Pokemon p in pokemons)
{
p.InitPokemon();
}
}
}
public class PokemonTrainer : MonoBehaviour
{
public new string name;
public PokemonParty party;
private void Start()
{
party.InitParty();
}
}<file_sep>using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
[CustomEditor(typeof(PokemonTypeData))]
public class PokemonTypeDataEditor : Editor {
PokemonTypeData comp;
public void OnEnable()
{
comp = (PokemonTypeData) target;
}
public override void OnInspectorGUI()
{
//Styling
GUIStyle headerStyle = new GUIStyle(EditorStyles.boldLabel);
headerStyle.font = (Font)Resources.Load("Fonts/pkmnrs");
headerStyle.fontSize = 24;
headerStyle.alignment = TextAnchor.MiddleLeft;
GUI.color = Color.white;
GUIStyle toolbarStyle = new GUIStyle(EditorStyles.toolbar);
toolbarStyle.alignment = TextAnchor.MiddleCenter;
toolbarStyle.normal.textColor = Color.white;
toolbarStyle.fontSize = 16;
EditorGUILayout.LabelField("Type", headerStyle, GUILayout.Width(128), GUILayout.Height(32));
GUI.backgroundColor = comp.color;
EditorGUILayout.LabelField(comp.internalName, toolbarStyle, GUILayout.Width(128));
DisplayOverflowingList("Weaknesses", comp.weaknesses, 128f, 32f, headerStyle, toolbarStyle);
DisplayOverflowingList("Resistances", comp.resistances, 128f, 32f, headerStyle, toolbarStyle);
DisplayOverflowingList("Immunities", comp.immunities, 128f, 32f, headerStyle, toolbarStyle);
}
void DisplayOverflowingList(string header, List<PokemonTypeData> typeDataList, float width, float height, GUIStyle headerStyle, GUIStyle toolbarStyle)
{
if (typeDataList.Count > 0)
{
GUI.backgroundColor = Color.white;
EditorGUILayout.Separator();
EditorGUILayout.LabelField("", EditorStyles.helpBox);
EditorGUILayout.LabelField(header, headerStyle, GUILayout.Width(width), GUILayout.Height(height));
EditorGUILayout.BeginHorizontal();
int index = 0;
foreach (PokemonTypeData typeData in typeDataList)
{
GUI.backgroundColor = typeData.color;
EditorGUILayout.LabelField(typeData.internalName, toolbarStyle, GUILayout.Width(width), GUILayout.Height(height));
index++;
if (index == Mathf.FloorToInt(Screen.width / 128f))
{
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
index = 0;
}
}
EditorGUILayout.EndHorizontal();
}
}
}
<file_sep>using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(AbilityData))]
public class AbilityDataEditor : Editor {
AbilityData comp;
private void OnEnable()
{
comp = (AbilityData)target;
}
public override void OnInspectorGUI()
{
GUIStyle headerStyle = new GUIStyle(EditorStyles.boldLabel)
{
font = (Font)Resources.Load("Fonts/pkmnrs"),
fontSize = 24,
alignment = TextAnchor.MiddleLeft
};
GUIStyle captionStyle = new GUIStyle(EditorStyles.wordWrappedLabel)
{
fontSize = 14,
richText = true,
alignment = TextAnchor.MiddleLeft
};
EditorGUILayout.LabelField(comp.ID + ": " + comp.name, headerStyle, GUILayout.Height(32f));
EditorGUILayout.LabelField(comp.description, captionStyle, GUILayout.Height(32f));
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "NewEntitySpriteData", menuName = "Entity Sprite Data", order = 0)]
public class EntitySpriteData : ScriptableObject
{
[Header("Neutral, Left Stride, Right Stride")]
public Sprite[] northSprites;
public Sprite[] eastSprites;
public Sprite[] southSprites;
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapSettings : MonoBehaviour
{
public static MapSettings instance;
[System.Serializable]
public class Encounter
{
public PokemonData pokemonData;
public int minLevel = 30;
public int maxLevel = 30;
public int percentageChance = 50;
}
public Encounter[] grassEncounters;
public Encounter[] waterEncounters;
public Encounter[] randomEncounters;
public bool encountersOn = true;
[Range(0f, .20f)]
public float grassEncounterChance = .15f;
[Range(0f, .20f)]
public float waterEncounterChance = .10f;
[Range(0f, .20f)]
public float randomEncounterChance = .05f;
private void Awake()
{
instance = this;
}
public bool TryGrassEncounter()
{
return TryEncounter(grassEncounters, grassEncounterChance);
}
public bool TryWaterEncounter()
{
return TryEncounter(waterEncounters, waterEncounterChance);
}
public bool TryRandomEncounter()
{
return TryEncounter(randomEncounters, randomEncounterChance);
}
private bool TryEncounter(Encounter[] encounters, float encounterChance)
{
if(encounters.Length <= 0) { return false; }
if (!encountersOn) { return false; }
if (Random.Range(0f, 1f) > encounterChance)
{
return false;
}
int r = Random.Range(0, 100);
foreach (Encounter e in encounters)
{
if (r > e.percentageChance)
{
r -= e.percentageChance;
continue;
}
else
{
int level = Random.Range(e.minLevel, e.maxLevel);
Debug.Log("A wild " + e.pokemonData.name + " appeared! LVL " + level);
PokemonGameManager.instance.StartWildBattle(e.pokemonData, level);
return true;
}
}
return false;
}
}
<file_sep>using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MoveData))]
public class MoveDataEditor : Editor {
MoveData comp;
private void OnEnable()
{
comp = (MoveData)target;
}
public override void OnInspectorGUI()
{
//base.OnInspectorGUI();
GUIStyle descriptionStyle = new GUIStyle(EditorStyles.wordWrappedLabel)
{
fontSize = 15,
richText = true
};
GUIStyle headerStyle = new GUIStyle(EditorStyles.boldLabel)
{
font = (Font)Resources.Load("Fonts/pkmnrs"),
fontSize = 24,
alignment = TextAnchor.MiddleLeft
};
GUIStyle captionStyle = new GUIStyle(EditorStyles.wordWrappedLabel)
{
fontSize = 16,
richText = true,
alignment = TextAnchor.UpperLeft
};
//NAME
EditorGUILayout.LabelField(comp.ID + ": " + comp.name, headerStyle, GUILayout.Height(32f));
EditorGUILayout.Separator();
//TYPE
GUI.color = Color.white;
GUIStyle toolbarStyle = new GUIStyle(EditorStyles.toolbar);
toolbarStyle.alignment = TextAnchor.MiddleCenter;
toolbarStyle.normal.textColor = Color.white;
toolbarStyle.fontSize = 16;
GUI.backgroundColor = comp.type.color;
EditorGUILayout.LabelField(comp.type.internalName, toolbarStyle, GUILayout.Width(128));
GUI.backgroundColor = Color.white;
EditorGUILayout.Separator();
//POWER AND ACCURACY
ProgressBar(comp.basePower / 200f, comp.basePower + " BASE POWER");
if (comp.accuracy > 0)
{
ProgressBar(comp.accuracy / 100f, comp.accuracy + "% ACCURACY");
} else
{
ProgressBar(1f, "DOUBTLESS ACCURACY");
}
//EXTRA DETAILS
string additionalEffectString = "";
if(comp.additionalEffectChance > 0)
{
additionalEffectString = "\n<color=blue>" + comp.additionalEffectChance + "%</color> chance to afflict opponent with <color=blue>" + comp.functionCode + "</color>";
}
EditorGUILayout.LabelField("<color=blue>" +
(comp.isSpecial ? "SPECIAL" : "PHYSICAL") + "\n" +
comp.totalPP + "</color> TOTAL PP<color=blue>\n" +
comp.priority + "</color> PRIORITY" + additionalEffectString
, captionStyle, GUILayout.Height(84));
EditorGUILayout.Separator();
EditorGUILayout.LabelField("", EditorStyles.helpBox);
//DESCRIPTION
EditorGUILayout.LabelField(comp.description, descriptionStyle);
EditorGUILayout.LabelField("", EditorStyles.helpBox);
EditorGUILayout.Separator();
//FLAGS & TARGETS
EditorGUILayout.LabelField("This move targets " + comp.target, captionStyle, GUILayout.Height(32));
EditorGUILayout.Separator();
foreach(char c in comp.flags)
{
EditorGUILayout.LabelField("<color=red>Flag " + c + ":</color> " + comp.flagDesc(c), captionStyle);
}
}
public void ProgressBar(float value, string label)
{
Rect rect = GUILayoutUtility.GetRect(18, 18, "TextField");
EditorGUI.ProgressBar(rect, value, label);
EditorGUILayout.Space();
}
}
<file_sep>[Dummy]
Name=Dummy
InternalName=Dummy
[0]
Name=Normal
InternalName=NORMAL
Weaknesses=FIGHTING
Immunities=GHOST
Color=#ababab
[1]
Name=Fighting
InternalName=FIGHTING
Weaknesses=FLYING,PSYCHIC
Resistances=ROCK,BUG,DARK
Color=#ee6e68
[2]
Name=Flying
InternalName=FLYING
Weaknesses=ROCK,ELECTRIC,ICE
Resistances=FIGHTING,BUG,GRASS
Immunities=GROUND
Color=#8c8c8c
[3]
Name=Poison
InternalName=POISON
Weaknesses=GROUND,PSYCHIC
Resistances=FIGHTING,POISON,BUG,GRASS
Color=#8c29ae
[4]
Name=Ground
InternalName=GROUND
Weaknesses=WATER,GRASS,ICE
Resistances=POISON,ROCK
Immunities=ELECTRIC
Color=#ae4c29
[5]
Name=Rock
InternalName=ROCK
Weaknesses=FIGHTING,GROUND,STEEL,WATER,GRASS
Resistances=NORMAL,FLYING,POISON,FIRE
Color=#85400f
[6]
Name=Bug
InternalName=BUG
Weaknesses=FLYING,ROCK,FIRE
Resistances=FIGHTING,GROUND,GRASS
Color=#85790f
[7]
Name=Ghost
InternalName=GHOST
Weaknesses=GHOST,DARK
Resistances=POISON,BUG
Immunities=NORMAL,FIGHTING
Color=#6f7290
[8]
Name=Steel
InternalName=STEEL
Weaknesses=FIGHTING,GROUND,FIRE
Resistances=NORMAL,FLYING,ROCK,BUG,GHOST,STEEL,GRASS,PSYCHIC,ICE,DRAGON,DARK
Immunities=POISON
Color=#bdbecc
[9]
Name=None
InternalName=
IsPseudoType=true
Color=#111111
[10]
Name=Fire
InternalName=FIRE
IsSpecialType=true
Weaknesses=GROUND,ROCK,WATER
Resistances=BUG,STEEL,FIRE,GRASS,ICE
Color=#ff680a
[11]
Name=Water
InternalName=WATER
IsSpecialType=true
Weaknesses=GRASS,ELECTRIC
Resistances=STEEL,FIRE,WATER,ICE
Color=#0a6cff
[12]
Name=Grass
InternalName=GRASS
IsSpecialType=true
Weaknesses=FLYING,POISON,BUG,FIRE,ICE
Resistances=GROUND,WATER,GRASS,ELECTRIC
Color=#6ec328
[13]
Name=Electric
InternalName=ELECTRIC
IsSpecialType=true
Weaknesses=GROUND
Resistances=FLYING,STEEL,ELECTRIC
Color=#fff200
[14]
Name=Psychic
InternalName=PSYCHIC
IsSpecialType=true
Weaknesses=BUG,GHOST,DARK
Resistances=FIGHTING,PSYCHIC
Color=#e949c6
[15]
Name=Ice
InternalName=ICE
IsSpecialType=true
Weaknesses=FIGHTING,ROCK,STEEL,FIRE
Resistances=ICE
Color=#49e9e6
[16]
Name=Dragon
InternalName=DRAGON
IsSpecialType=true
Weaknesses=ICE,DRAGON
Resistances=FIRE,WATER,GRASS,ELECTRIC
Color=#0800ff
[17]
Name=Dark
InternalName=DARK
IsSpecialType=true
Weaknesses=FIGHTING,BUG
Resistances=GHOST,DARK
Immunities=PSYCHIC
Color=#424158<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PokemonGameManager : MonoBehaviour
{
public enum GameState
{
OVERWORLD,
BATTLE,
MENU,
CUTSCENE
}
public Camera pixelPerfectCamera;
public Camera battleCamera;
public GameObject overworld;
Battle battle;
public static PokemonGameManager instance;
private Material transitionMaterial;
public GameState gameState;
private Color defaultTransitionColor;
private PlayerController player;
private DialogueManager dialogueManager;
private void Awake()
{
instance = this;
}
private void Start()
{
battle = Battle.instance;
player = PlayerController.instance;
dialogueManager = DialogueManager.instance;
transitionMaterial = pixelPerfectCamera.GetComponent<RenderTextureToScreen>().TransitionMaterial;
transitionMaterial.SetFloat("_Cutoff", 0f);
defaultTransitionColor = transitionMaterial.color;
}
public void TraversePortal(Portal start)
{
Portal destination = start.target;
StartCoroutine(TraversePortalCoroutine(start, destination));
}
private IEnumerator TraversePortalCoroutine(Portal start, Portal destination)
{
gameState = GameState.CUTSCENE;
start.OnEntered();
yield return StartCoroutine(Fade(true));
player.SetRunning(false);
player.transform.position = destination.transform.position;
player.FaceDirection(destination.facingDirectionExit);
yield return StartCoroutine(Fade(false));
player.MoveInDirection(destination.facingDirectionExit);
destination.OnExited();
yield return new WaitForSeconds(.1f);
gameState = GameState.OVERWORLD;
}
public void StartWildBattle(PokemonData pokemon, int level)
{
StartCoroutine(StartWildBattleCoroutine(pokemon, level));
}
private IEnumerator StartWildBattleCoroutine(PokemonData pokemon, int level)
{
if(gameState != GameState.OVERWORLD)
{ yield break; }
gameState = GameState.BATTLE;
yield return StartCoroutine(Fade(true, true));
dialogueManager.SetColor("");
battleCamera.enabled = true;
//overworld.SetActive(false);
battle.foePokemon.pokemonData = pokemon;
battle.foePokemon.level = level;
battle.InitWildBattle();
yield return StartCoroutine(Fade(false));
}
IEnumerator Fade(bool fadeOut, bool flashes = false)
{
if(flashes)
{
yield return new WaitForSeconds(.3f);
transitionMaterial.SetFloat("_Fade", 1f);
transitionMaterial.SetFloat("_Cutoff", 1f);
transitionMaterial.color = Color.white;
for(int i = 0; i < 30; i++)
{
transitionMaterial.SetFloat("_Fade", Mathf.Clamp01(Mathf.Sin(i/3f)));
yield return new WaitForEndOfFrame();
}
transitionMaterial.color = defaultTransitionColor;
transitionMaterial.SetFloat("_Fade", 1f);
transitionMaterial.SetFloat("_Cutoff", 0f);
}
yield return new WaitForSeconds(.2f);
int smoothness = 30;
for (int i = 0; i < smoothness; i++)
{
float cutoff = fadeOut ? i / (1.0f * smoothness) : (1 - i / (1.0f * smoothness));
transitionMaterial.SetFloat("_Cutoff", cutoff);
yield return new WaitForEndOfFrame();
}
transitionMaterial.SetFloat("_Cutoff", fadeOut? 1f : 0f);
}
public void EndBattle()
{
StartCoroutine(EndBattleCoroutine());
}
IEnumerator EndBattleCoroutine()
{
yield return StartCoroutine(Fade(true));
battleCamera.enabled = false;
//overworld.SetActive(true);
dialogueManager.SetDisplay(false);
player.StartMovement();
yield return StartCoroutine(Fade(false));
gameState = GameState.OVERWORLD;
}
public void StartDialogue(Dialogue d, string colorString = "")
{
StartCoroutine(DialogueCoroutine(d, colorString));
}
IEnumerator DialogueCoroutine(Dialogue d, string colorString = "")
{
dialogueManager.SetColor(colorString);
dialogueManager.ClearDialogue();
dialogueManager.AddDialogue(d);
gameState = GameState.CUTSCENE;
dialogueManager.DisplayNextSentence();
yield return dialogueManager.WaitForCaughtUpTextAndInput();
gameState = GameState.OVERWORLD;
dialogueManager.SetDisplay(false);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MapSettings))]
public class MapSettingsEditor : Editor
{
MapSettings comp;
private void OnEnable()
{
comp = (MapSettings)target;
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
DisplayEncounters("Grass", comp.grassEncounters);
DisplayEncounters("Water", comp.waterEncounters);
DisplayEncounters("Random", comp.randomEncounters);
}
private void DisplayEncounters(string title, MapSettings.Encounter[] encounters)
{
GUIStyle headerStyle = new GUIStyle(EditorStyles.boldLabel)
{
font = (Font)Resources.Load("Fonts/pkmnrs"),
fontSize = 24,
alignment = TextAnchor.MiddleLeft
};
GUIStyle captionStyle = new GUIStyle(EditorStyles.label)
{
fontSize = 14,
richText = true,
alignment = TextAnchor.MiddleCenter
};
GUIStyle textureStyle = new GUIStyle(EditorStyles.label)
{
alignment = TextAnchor.MiddleCenter
};
if (encounters.Length > 0)
{
GUILayout.Label(title + " Encounters", headerStyle, GUILayout.Width(256f), GUILayout.Height(96f));
EditorGUILayout.BeginHorizontal();
foreach (MapSettings.Encounter e in encounters)
{
GUILayout.Label(e.pokemonData.sprite.texture, textureStyle, GUILayout.Width(96f), GUILayout.Height(96f));
}
EditorGUILayout.EndHorizontal();
float sum = 0;
EditorGUILayout.BeginHorizontal();
foreach (MapSettings.Encounter e in encounters)
{
GUILayout.Label(
e.pokemonData.name + "\nLVL " +
e.minLevel + "-" + e.maxLevel + "\n" +
e.percentageChance + "%"
, captionStyle, GUILayout.Width(96f), GUILayout.Height(64f));
sum += e.percentageChance;
}
EditorGUILayout.EndHorizontal();
ProgressBar(sum / 100f, sum + "/100");
}
}
public void ProgressBar(float value, string label)
{
Rect rect = GUILayoutUtility.GetRect(18, 18, "TextField");
EditorGUI.ProgressBar(rect, value, label);
EditorGUILayout.Space();
}
}
<file_sep>using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class PokemonTypeData : ScriptableObject {
public new string name;
public string internalName;
public bool isSpecial;
public List<PokemonTypeData> weaknesses;
public List<PokemonTypeData> immunities;
public List<PokemonTypeData> resistances;
public Color color;
public void Init()
{
weaknesses = new List<PokemonTypeData>();
immunities = new List<PokemonTypeData>();
resistances = new List<PokemonTypeData>();
}
public bool Equals(PokemonTypeData other)
{
return internalName.Equals(other.internalName);
}
public static float Effectiveness(PokemonTypeData attackingType, Pokemon defendingPokemon)
{
return Effectiveness(attackingType, defendingPokemon.pokemonData);
}
public static float Effectiveness(PokemonTypeData attackingType, PokemonData defendingPokemon)
{
return Effectiveness(attackingType, defendingPokemon.type1) * Effectiveness(attackingType, defendingPokemon.type2);
}
public static float Effectiveness(PokemonTypeData attackingType, PokemonTypeData defendingType)
{
if(defendingType.weaknesses.Contains(attackingType))
{
return 2.0f;
} else if(defendingType.immunities.Contains(attackingType))
{
return 0.0f;
} else if(defendingType.resistances.Contains(attackingType))
{
return .5f;
}
return 1.0f;
}
}
<file_sep>using UnityEngine;
public class FontFix : MonoBehaviour {
public Font font;
private void Start()
{
font.material.mainTexture.filterMode = FilterMode.Point;
}
}
<file_sep>using UnityEngine;
[ExecuteInEditMode]
public class RenderTextureToScreen : MonoBehaviour {
public RenderTexture bl;
public Material TransitionMaterial;
void OnRenderImage(RenderTexture src, RenderTexture dst) {
if (bl != null)
{
if (TransitionMaterial != null)
Graphics.Blit(bl, dst, TransitionMaterial);
else
{
Graphics.Blit(bl, dst);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[System.Serializable]
public class DataGenerator : MonoBehaviour
{
public Dictionary<string, PokemonTypeData> pokemonTypeDataDictionary;
public Dictionary<string, PokemonData> pokemonDataDictionary;
public Dictionary<string, AbilityData> abilityDataDictionary;
public Dictionary<string, ItemData> itemDataDictionary;
public Dictionary<string, MoveData> moveDataDictionary;
[SerializeField]
private PokemonTypeData[] pokemonTypeDataSerializationArray;
[SerializeField]
private PokemonData[] pokemonDataSerializationArray;
[SerializeField]
private AbilityData[] abilityDataSerializationArray;
[SerializeField]
private ItemData[] itemDataSerializationArray;
[SerializeField]
private MoveData[] moveDataSerializationArray;
public static DataGenerator instance;
//MAX 17
public static int NUMBER_OF_TYPES = 17;
//MAX 151
public static int NUMBER_OF_POKEMON = 649; //151 //649
//MAX 164
public static int NUMBER_OF_ABILITIES = 164;
//MAX 559
public static int NUMBER_OF_MOVES = 559;
//MAX 525
public static int NUMBER_OF_ITEMS = 525;
private void Awake()
{
instance = this;
InitDictionaries();
}
private void Start()
{
Debugger();
}
private void InitDictionaries()
{
pokemonTypeDataDictionary = new Dictionary<string, PokemonTypeData>();
pokemonDataDictionary = new Dictionary<string, PokemonData>();
abilityDataDictionary = new Dictionary<string, AbilityData>();
itemDataDictionary = new Dictionary<string, ItemData>();
moveDataDictionary = new Dictionary<string, MoveData>();
foreach (PokemonTypeData pokemonTypeData in pokemonTypeDataSerializationArray)
{ pokemonTypeDataDictionary.Add(pokemonTypeData.internalName, pokemonTypeData); }
foreach (PokemonData pokemonData in pokemonDataSerializationArray)
{ pokemonDataDictionary.Add(pokemonData.internalName, pokemonData); }
foreach (AbilityData abilityData in abilityDataSerializationArray)
{ abilityDataDictionary.Add(abilityData.internalName, abilityData); }
foreach (ItemData itemData in itemDataSerializationArray)
{ itemDataDictionary.Add(itemData.internalName, itemData); }
foreach (MoveData moveData in moveDataSerializationArray)
{ moveDataDictionary.Add(moveData.internalName, moveData); }
}
public void Debugger()
{
PokemonData bulbasaur;
if(pokemonDataDictionary.TryGetValue("BULBASAUR", out bulbasaur))
{
Debug.Log(bulbasaur.name);
} else { Debug.LogError("Couldn't find Bulbasaur!"); }
}
#region cleaners
public void ClearPokemonData()
{
if (pokemonDataDictionary != null)
{
pokemonDataDictionary.Clear();
pokemonDataDictionary = null;
}
pokemonDataSerializationArray = null;
}
public void ClearTypeData()
{
if (pokemonTypeDataDictionary != null)
{
pokemonTypeDataDictionary.Clear();
pokemonTypeDataDictionary = null;
}
pokemonTypeDataSerializationArray = null;
}
public void ClearItemData()
{
if (itemDataDictionary != null)
{
itemDataDictionary.Clear();
itemDataDictionary = null;
}
itemDataSerializationArray = null;
}
public void ClearMoveData()
{
if (moveDataDictionary != null)
{
moveDataDictionary.Clear();
moveDataDictionary = null;
}
moveDataSerializationArray = null;
}
public void ClearAbilityData()
{
if (abilityDataDictionary != null)
{
abilityDataDictionary.Clear();
abilityDataDictionary = null;
}
abilityDataSerializationArray = null;
}
#endregion
#region generators
public PokemonData[] GeneratePokemon()
{
pokemonDataDictionary = new Dictionary<string, PokemonData>();
IniFileAccessor.SetPath("/Data/Text Files/pokemon.ini");
for (int i = 1; i <= NUMBER_OF_POKEMON; i++)
{
string indexStr = (i).ToString();
string paddedindexStr = indexStr.ToString().PadLeft(3, '0'); // results in 009
PokemonData pokemonData = ScriptableObject.CreateInstance<PokemonData>();
pokemonData.Init();
//NAME AND BASIC INFO
pokemonData.number = i;
pokemonData.name = IniFileAccessor.ReadValue(indexStr, "Name");
pokemonData.internalName = IniFileAccessor.ReadValue(indexStr, "InternalName");
pokemonData.kind = IniFileAccessor.ReadValue(indexStr, "Kind");
pokemonData.dexEntry = IniFileAccessor.ReadValue(indexStr, "Pokedex");
//pokemonData.habitat = (PokemonData.Habitat) Enum.Parse(typeof(PokemonData.Habitat), IniFileAccessor.ReadValue(indexStr, "Habitat").ToUpper());
//TYPE
string type1String = IniFileAccessor.ReadValue(indexStr, "Type1");
string type2String = IniFileAccessor.ReadValue(indexStr, "Type2");
pokemonTypeDataDictionary.TryGetValue(type1String, out pokemonData.type1);
pokemonTypeDataDictionary.TryGetValue(type2String, out pokemonData.type2);
string[] eggGroups = IniFileAccessor.ReadValue(indexStr, "Compatibility").Split(',');
pokemonData.eggGroup1 = (PokemonData.EggGroup)Enum.Parse(typeof(PokemonData.EggGroup), eggGroups[0].ToUpper());
if(eggGroups.Length > 1)
{
pokemonData.eggGroup2 = (PokemonData.EggGroup)Enum.Parse(typeof(PokemonData.EggGroup), eggGroups[1].ToUpper());
} else { pokemonData.eggGroup2 = PokemonData.EggGroup.NONE; }
//STATS
string[] baseStats = IniFileAccessor.ReadValue(indexStr, "BaseStats").Split(',');
if (!Int32.TryParse(baseStats[0], out pokemonData.baseHP)) { Debug.LogError("Not a number! Check DataGenerator.cs"); }
if (!Int32.TryParse(baseStats[1], out pokemonData.baseAttack)) { Debug.LogError("Not a number! Check DataGenerator.cs"); }
if (!Int32.TryParse(baseStats[2], out pokemonData.baseDefense)) { Debug.LogError("Not a number! Check DataGenerator.cs"); }
if (!Int32.TryParse(baseStats[3], out pokemonData.baseSpeed)) { Debug.LogError("Not a number! Check DataGenerator.cs"); }
if (!Int32.TryParse(baseStats[4], out pokemonData.baseSpecialAttack)) { Debug.LogError("Not a number! Check DataGenerator.cs"); }
if (!Int32.TryParse(baseStats[5], out pokemonData.baseSpecialDefense)) { Debug.LogError("Not a number! Check DataGenerator.cs"); }
string[] evStats = IniFileAccessor.ReadValue(indexStr, "EffortPoints").Split(',');
if (!Int32.TryParse(evStats[0], out pokemonData.EV_HP)) { Debug.LogError("Not a number! Check DataGenerator.cs"); }
if (!Int32.TryParse(evStats[1], out pokemonData.EV_Attack)) { Debug.LogError("Not a number! Check DataGenerator.cs"); }
if (!Int32.TryParse(evStats[2], out pokemonData.EV_Defense)) { Debug.LogError("Not a number! Check DataGenerator.cs"); }
if (!Int32.TryParse(evStats[3], out pokemonData.EV_Speed)) { Debug.LogError("Not a number! Check DataGenerator.cs"); }
if (!Int32.TryParse(evStats[4], out pokemonData.EV_SpecialAttack)) { Debug.LogError("Not a number! Check DataGenerator.cs"); }
if (!Int32.TryParse(evStats[5], out pokemonData.EV_SpecialDefense)) { Debug.LogError("Not a number! Check DataGenerator.cs"); }
pokemonData.baseEXP = Int32.Parse(IniFileAccessor.ReadValue(indexStr, "BaseEXP"));
pokemonData.rareness = Int32.Parse(IniFileAccessor.ReadValue(indexStr, "Rareness"));
pokemonData.baseHappiness = Int32.Parse(IniFileAccessor.ReadValue(indexStr, "Happiness"));
pokemonData.stepsToHatch = Int32.Parse(IniFileAccessor.ReadValue(indexStr, "StepsToHatch"));
pokemonData.growthRate = (PokemonData.GrowthRate)Enum.Parse(typeof(PokemonData.GrowthRate), IniFileAccessor.ReadValue(indexStr, "GrowthRate").ToUpper());
pokemonData.femaleRatio = PokemonData.String2GenderRate(IniFileAccessor.ReadValue(indexStr, "GenderRate"));
if (!float.TryParse(IniFileAccessor.ReadValue(indexStr, "Height"), out pokemonData.height)) { Debug.LogError("Not a number! Check DataGenerator.cs"); }
if (!float.TryParse(IniFileAccessor.ReadValue(indexStr, "Weight"), out pokemonData.weight)) { Debug.LogError("Not a number! Check DataGenerator.cs"); }
//SPRITES
pokemonData.sprite = (Sprite)AssetDatabase.LoadAssetAtPath("Assets/Graphics/Sprites/Pokemon/" + paddedindexStr + ".png", typeof(Sprite));
pokemonData.backSprite = (Sprite)AssetDatabase.LoadAssetAtPath("Assets/Graphics/Sprites/Pokemon/" + paddedindexStr + "b.png", typeof(Sprite));
pokemonData.shinySprite = (Sprite)AssetDatabase.LoadAssetAtPath("Assets/Graphics/Sprites/Pokemon/" + paddedindexStr + "s.png", typeof(Sprite));
pokemonData.shinyBackSprite = (Sprite)AssetDatabase.LoadAssetAtPath("Assets/Graphics/Sprites/Pokemon/" + paddedindexStr + "sb.png", typeof(Sprite));
pokemonData.footprintSprite = (Sprite)AssetDatabase.LoadAssetAtPath("Assets/Graphics/Sprites/Footprints/footprint" + paddedindexStr + ".png", typeof(Sprite));
//ABILITIES
string[] abilityString = IniFileAccessor.ReadValue(indexStr, "Abilities").Split(',');
string hiddenAbilityString = IniFileAccessor.ReadValue(indexStr, "HiddenAbility");
foreach(string ability in abilityString)
{
AbilityData abilityData;
if(abilityDataDictionary.TryGetValue(ability, out abilityData))
{
pokemonData.standardAbilities.Add(abilityData);
} else { Debug.LogWarning("Couldn't find Ability " + ability); }
}
AbilityData hiddenAbilityData;
if(abilityDataDictionary.TryGetValue(hiddenAbilityString, out hiddenAbilityData))
{
pokemonData.hiddenAbility = hiddenAbilityData;
} else { Debug.LogWarning("Couldn't find Hidden Ability " + hiddenAbilityString ); }
//MOVES
string[] moves = IniFileAccessor.ReadValue(indexStr, "Moves").Split(',');
for(int m = 0; m < moves.Length; m+=2)
{
int level = Int32.Parse(moves[m]);
string moveName = moves[m + 1];
MoveData moveToLearn;
if(moveDataDictionary.TryGetValue(moveName, out moveToLearn))
{
LearnedMove learnedMove = new LearnedMove(moveToLearn, level);
pokemonData.learnedMoves.Add(learnedMove);
} else { Debug.LogWarning("Couldn't find move " + moveName); }
}
string[] eggMoves = IniFileAccessor.ReadValue(indexStr, "EggMoves").Split(',');
foreach (string eggMove in eggMoves)
{
MoveData moveData;
if (moveDataDictionary.TryGetValue(eggMove, out moveData))
{
pokemonData.eggMoves.Add(moveData);
}
else { Debug.LogWarning("Couldn't find egg move " + eggMove); }
}
pokemonDataDictionary.Add(pokemonData.internalName, pokemonData);
}
//Evolutions
for (int i = 1; i <= NUMBER_OF_POKEMON; i++)
{
string indexStr = i + "";
PokemonData pokemonData;
if (pokemonDataDictionary.TryGetValue(IniFileAccessor.ReadValue(indexStr, "InternalName"), out pokemonData))
{
string[] evolutionString = IniFileAccessor.ReadValue(indexStr, "Evolutions").Split(',');
if (evolutionString.Length >= 3)
{
for (int e = 0; e < evolutionString.Length; e += 3)
{
int pokemonIndex = e;
int typeIndex = e + 1;
int levelIndex = e + 2;
PokemonData evolvedPokemonData;
if (pokemonDataDictionary.TryGetValue(evolutionString[pokemonIndex], out evolvedPokemonData))
{
switch (evolutionString[typeIndex])
{
case "Level":
int levelToEvolve = Int32.Parse(evolutionString[levelIndex]);
Evolution levelEvolution = new Evolution(evolvedPokemonData, levelToEvolve);
pokemonData.evolutions.Add(levelEvolution);
break;
case "Item":
string itemToEvolve = evolutionString[levelIndex];
ItemData itemData;
if (itemDataDictionary.TryGetValue(itemToEvolve, out itemData))
{
Evolution itemEvolution = new Evolution(evolvedPokemonData, itemData);
pokemonData.evolutions.Add(itemEvolution);
}
break;
default:
break;
}
} else { Debug.LogWarning("Couldn't find resulting Pokemon of this evolution!"); }
}
}
}
}
pokemonDataSerializationArray = new PokemonData[pokemonDataDictionary.Count];
pokemonDataDictionary.Values.CopyTo(pokemonDataSerializationArray, 0);
return pokemonDataSerializationArray;
}
public PokemonTypeData[] GenerateTypes()
{
pokemonTypeDataDictionary = new Dictionary<string, PokemonTypeData>();
IniFileAccessor.SetPath("/Data/Text Files/types.ini");
for (int i = 0; i <= NUMBER_OF_TYPES; i++)
{
string indexStr = (i).ToString();
PokemonTypeData typeData = ScriptableObject.CreateInstance<PokemonTypeData>();
typeData.Init();
typeData.name = IniFileAccessor.ReadValue(indexStr, "Name");
typeData.internalName = IniFileAccessor.ReadValue(indexStr, "InternalName");
typeData.isSpecial = IniFileAccessor.ReadValue(indexStr, "IsSpecialType").Equals("true");
Color color;
if (ColorUtility.TryParseHtmlString(IniFileAccessor.ReadValue(indexStr, "Color"), out color))
{
typeData.color = color;
}
pokemonTypeDataDictionary.Add(typeData.internalName, typeData);
}
for (int i = 0; i <= NUMBER_OF_TYPES; i++)
{
string indexStr = i + "";
string pInternalName = IniFileAccessor.ReadValue(indexStr, "InternalName");
PokemonTypeData typeData;
if (pokemonTypeDataDictionary.TryGetValue(pInternalName, out typeData))
{
string[] pWeaknesses = IniFileAccessor.ReadValue(indexStr, "Weaknesses").Split(',');
string[] pResistances = IniFileAccessor.ReadValue(indexStr, "Resistances").Split(',');
string[] pImmunities = IniFileAccessor.ReadValue(indexStr, "Immunities").Split(',');
foreach (string weakness in pWeaknesses)
{
if (weakness == "") { break; }
PokemonTypeData weaknessTypeData;
if (pokemonTypeDataDictionary.TryGetValue(weakness, out weaknessTypeData))
{
typeData.weaknesses.Add(weaknessTypeData);
}
}
foreach (string resistance in pResistances)
{
if (resistance == "") { break; }
PokemonTypeData resistanceTypeData;
if (pokemonTypeDataDictionary.TryGetValue(resistance, out resistanceTypeData))
{
typeData.resistances.Add(resistanceTypeData);
}
}
foreach (string immunity in pImmunities)
{
if (immunity == "") { break; }
PokemonTypeData immunityTypeData;
if (pokemonTypeDataDictionary.TryGetValue(immunity, out immunityTypeData))
{
typeData.immunities.Add(immunityTypeData);
}
}
}
}
pokemonTypeDataSerializationArray = new PokemonTypeData[pokemonTypeDataDictionary.Count];
pokemonTypeDataDictionary.Values.CopyTo(pokemonTypeDataSerializationArray, 0);
return pokemonTypeDataSerializationArray;
}
public AbilityData[] GenerateAbilities()
{
abilityDataDictionary = new Dictionary<string, AbilityData>();
TXTFileAccessor.SetPath("Assets/Data/Text Files/abilities.txt");
for (int i = 0; i < NUMBER_OF_ABILITIES; i++)
{
AbilityData ability = ScriptableObject.CreateInstance<AbilityData>();
string[] dataString = TXTFileAccessor.ReadValue(i).Split(',');
ability.ID = Int32.Parse(dataString[0]);
ability.internalName = dataString[1];
ability.name = dataString[2];
ability.description = dataString[3];
abilityDataDictionary.Add(ability.internalName, ability);
}
abilityDataSerializationArray = new AbilityData[abilityDataDictionary.Count];
abilityDataDictionary.Values.CopyTo(abilityDataSerializationArray, 0);
return abilityDataSerializationArray;
}
public MoveData[] GenerateMoves()
{
moveDataDictionary = new Dictionary<string, MoveData>();
TXTFileAccessor.SetPath("Assets/Data/Text Files/moves.txt");
for (int i = 0; i < NUMBER_OF_MOVES; i++)
{
MoveData move = ScriptableObject.CreateInstance<MoveData>();
string[] dataString = TXTFileAccessor.ReadValue(i).Split('\"');
string[] dataStringArray = dataString[0].Split(',');
move.ID = Int32.Parse(dataStringArray[0]);
move.internalName = dataStringArray[1];
move.name = dataStringArray[2];
move.functionCode = dataStringArray[3];
move.basePower = Int32.Parse(dataStringArray[4]);
pokemonTypeDataDictionary.TryGetValue(dataStringArray[5], out move.type);
move.isSpecial = dataStringArray[6].Equals("Special");
move.accuracy = Int32.Parse(dataStringArray[7]);
move.totalPP = Int32.Parse(dataStringArray[8]);
move.additionalEffectChance = Int32.Parse(dataStringArray[9]);
move.target = dataStringArray[10];
move.priority = Int32.Parse(dataStringArray[11]);
move.flags = dataStringArray[12].ToCharArray();
move.description = dataString[1];
moveDataDictionary.Add(move.internalName, move);
}
moveDataSerializationArray = new MoveData[moveDataDictionary.Count];
moveDataDictionary.Values.CopyTo(moveDataSerializationArray, 0);
return moveDataSerializationArray;
}
public ItemData[] GenerateItems()
{
itemDataDictionary = new Dictionary<string, ItemData>();
TXTFileAccessor.SetPath("Assets/Data/Text Files/items.txt");
for (int i = 0; i < NUMBER_OF_ITEMS; i++)
{
ItemData item = ScriptableObject.CreateInstance<ItemData>();
string[] dataString = TXTFileAccessor.ReadValue(i).Split('\"');
string[] dataStringArray = dataString[0].Split(',');
item.ID = Int32.Parse(dataStringArray[0]);
item.internalName = dataStringArray[1];
item.name = dataStringArray[2];
item.itemType = (ItemData.ItemType) Int32.Parse(dataStringArray[3]);
item.price = Int32.Parse(dataStringArray[4]);
string moveName = "";
if (dataString.Length == 3)
{
string description = dataString[1];
string[] dataStringSecondaryArray = dataString[2].Substring(1).Split(',');
item.description = description;
item.overworldUsabilityID = (ItemData.OverworldType) Int32.Parse(dataStringSecondaryArray[0]);
item.battleUsabilityID = (ItemData.BattleType) Int32.Parse(dataStringSecondaryArray[1]);
item.specialItemID = (ItemData.SpecialItemType) Int32.Parse(dataStringSecondaryArray[2]);
moveName = dataStringSecondaryArray[3];
} else
{
item.description = dataStringArray[5];
item.overworldUsabilityID = (ItemData.OverworldType) Int32.Parse(dataStringArray[6]);
item.battleUsabilityID = (ItemData.BattleType) Int32.Parse(dataStringArray[7]);
item.specialItemID = (ItemData.SpecialItemType) Int32.Parse(dataStringArray[8]);
moveName = dataStringArray[9];
}
moveName = moveName.TrimEnd(',', '\n', '\r');
MoveData moveData;
if (moveDataDictionary.TryGetValue(moveName, out moveData))
{
item.TMmoveToLearn = moveData;
}
//SPRITE
string paddedindexStr = item.ID.ToString().PadLeft(3, '0'); // results in 009
item.sprite = (Sprite)AssetDatabase.LoadAssetAtPath("Assets/Graphics/Sprites/Icons/item" + paddedindexStr + ".png", typeof(Sprite));
itemDataDictionary.Add(item.internalName, item);
}
itemDataSerializationArray = new ItemData[itemDataDictionary.Count];
itemDataDictionary.Values.CopyTo(itemDataSerializationArray, 0);
return itemDataSerializationArray;
}
#endregion
}<file_sep>using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class Battle : MonoBehaviour {
public static Color[] HPSliderBarColors = new Color[3]{
new Color32(0,192,0,255),
new Color32(192,192,0,255),
new Color32(255,64,64,255)
};
[Space(20)]
public Sprite[] genderSprites;
public Sprite[] statusSprites;
[Space(20)]
public Pokemon allyPokemon;
public Pokemon foePokemon;
[Space(20)]
public GameObject foeParent;
public GameObject foePokemonParent;
public Text foeNameText;
public Text foeLevelText;
public Image foeSprite;
public Image foeGenderSprite;
public Image foeCaughtSprite;
public Image foeStatusSprite;
public Slider foeHPSlider;
private Image foeHPSliderBar;
[Space(20)]
public GameObject allyParent;
public GameObject allyPokemonParent;
public Text allyNameText;
public Text allyLevelText;
public Text allyHealthText;
public Image allySprite;
public Image allyGenderSprite;
public Image allyStatusSprite;
public Slider allyHPSlider;
public Slider allyXPSlider;
private Image allyHPSliderBar;
[Space(20)]
public static Battle instance;
DialogueManager dialogueManager;
private void Awake()
{
instance = this;
}
private void Start()
{
dialogueManager = DialogueManager.instance;
foeHPSliderBar = foeHPSlider.GetComponentInChildren<Image>();
allyHPSliderBar = allyHPSlider.GetComponentInChildren<Image>();
}
private void Update()
{
UpdateUI();
}
public void InitWildBattle()
{
foePokemon.InitPokemon();
UpdateUI();
StartBattle();
}
public void UpdateUI()
{
//FOE
foeHPSlider.minValue = 0;
foeHPSlider.maxValue = foePokemon.HP;
//foeHPSlider.value = foePokemon.currentHP;
if(foeHPSlider.value != foePokemon.currentHP)
{
foeHPSlider.value = Mathf.RoundToInt(foeHPSlider.value + Mathf.Sign(foePokemon.currentHP - foeHPSlider.value));
if (Mathf.Abs(foePokemon.currentHP - foeHPSlider.value) < 3)
{
foeHPSlider.value = foePokemon.currentHP;
}
}
float foeHPRatio = foeHPSlider.value / foePokemon.HP;
if (foeHPRatio > .5f)
{
foeHPSliderBar.color = HPSliderBarColors[0];
}
else if (foeHPRatio > .2f)
{
foeHPSliderBar.color = HPSliderBarColors[1];
}
else
{
foeHPSliderBar.color = HPSliderBarColors[2];
}
if (!foePokemon.CheckForDeath())
{
foeNameText.text = foePokemon.GetName();
foeLevelText.text = "Lv" + foePokemon.level;
foeSprite.sprite = foePokemon.GetFrontSprite();
if (!foePokemon.gender.Equals(Gender.NONE))
{ foeGenderSprite.enabled = true; foeGenderSprite.sprite = genderSprites[(int)foePokemon.gender]; }
else { foeGenderSprite.enabled = false; }
if (!foePokemon.status.Equals(Status.NONE))
{ foeStatusSprite.enabled = true; foeStatusSprite.sprite = statusSprites[(int)foePokemon.status]; }
else { foeStatusSprite.enabled = false; }
}
//ALLY
allyHealthText.text = allyPokemon.currentHP + "/" + allyPokemon.HP;
allyHPSlider.minValue = 0;
allyHPSlider.maxValue = allyPokemon.HP;
//allyHPSlider.value = allyPokemon.currentHP;
if (allyHPSlider.value != allyPokemon.currentHP)
{
allyHPSlider.value = allyHPSlider.value + Mathf.Sign(allyPokemon.currentHP - allyHPSlider.value);
if(Mathf.Abs(allyPokemon.currentHP - allyHPSlider.value) < 3)
{
allyHPSlider.value = allyPokemon.currentHP;
}
}
float allyHPRatio = allyHPSlider.value / allyPokemon.HP;
if (allyHPRatio > .5f)
{
allyHPSliderBar.color = HPSliderBarColors[0];
}
else if (allyHPRatio > .2f)
{
allyHPSliderBar.color = HPSliderBarColors[1];
}
else
{
allyHPSliderBar.color = HPSliderBarColors[2];
}
if (!allyPokemon.CheckForDeath())
{
allyNameText.text = allyPokemon.GetName();
allyLevelText.text = "Lv" + allyPokemon.level;
allySprite.sprite = allyPokemon.GetBackSprite();
if (!allyPokemon.gender.Equals(Gender.NONE))
{ allyGenderSprite.enabled = true; allyGenderSprite.sprite = genderSprites[(int)allyPokemon.gender]; }
else { allyGenderSprite.enabled = false; }
if (!allyPokemon.status.Equals(Status.NONE))
{ allyStatusSprite.enabled = true; allyStatusSprite.sprite = statusSprites[(int)allyPokemon.status]; }
else { allyStatusSprite.enabled = false; }
allyXPSlider.minValue = allyPokemon.GetXPMin();
allyXPSlider.maxValue = allyPokemon.GetXPMax();
allyXPSlider.value = allyPokemon.XP;
}
}
public IEnumerator SingleAttack(Pokemon attacker, Pokemon defender, int moveIndex)
{
MoveInSet moveInSet = attacker.moveset[moveIndex];
yield return StartCoroutine(SingleAttack(attacker, defender, moveInSet));
}
public IEnumerator SingleAttack(Pokemon attacker, Pokemon defender, MoveInSet moveInSet)
{
float accuracyCheck = Random.Range(0,100f);
MoveData move = moveInSet.move;
dialogueManager.AddDialogue(attacker.GetName() + " used " + move.name + "!");
yield return StartCoroutine(dialogueManager.WaitForCaughtUpText());
if (move.accuracy > 0 && accuracyCheck > move.accuracy)
{
yield return StartCoroutine(dialogueManager.WaitForCaughtUpTextAndInput());
dialogueManager.AddDialogue("But it missed!");
yield break;
}
float level = attacker.level;
float power = move.basePower;
float ratingMultiplier;
float burn;
if(move.isSpecial)
{
burn = 1.0f;
ratingMultiplier = (float)attacker.specialAttack / defender.specialDefense;
} else
{
burn = attacker.status.Equals(Status.BURN) ? .5f : 1.0f;
ratingMultiplier = (float)attacker.attack / defender.defense;
}
float targets = 1.0f;
float weather = 1.0f;
float badge = 1.0f;
float criticalChance = 1f / 16.0f;
bool criticalHappened = Random.Range(0f, 1f) < criticalChance;
float critical = (criticalHappened? 2.0f : 1.0f);
float randomVariation = Random.Range(.85f, 1.0f);
float STAB = (attacker.IsType(move.type) ? 1.5f : 1.0f);
float typeEffectiveness = PokemonTypeData.Effectiveness(move.type, defender);
float other = 1.0f;
float modifier = targets * weather * badge * critical * randomVariation * STAB * typeEffectiveness * burn * other;
int damage = Mathf.CeilToInt((2f + ((2f + (2f * level) / 5f) * power * ratingMultiplier)/50f) * modifier);
if(damage <= 0)
{
yield return StartCoroutine(dialogueManager.WaitForCaughtUpTextAndInput());
dialogueManager.AddDialogue("It didn't effect " + defender.GetName() + "...");
yield break;
}
defender.ModHP(-damage);
yield return StartCoroutine(WaitForBarsToLoad());
if (criticalHappened) { yield return StartCoroutine(dialogueManager.WaitForCaughtUpTextAndInput()); dialogueManager.AddDialogue("Critical hit!"); }
if (typeEffectiveness > 1.0f) { yield return StartCoroutine(dialogueManager.WaitForCaughtUpTextAndInput()); dialogueManager.AddDialogue("It was super effective!"); }
if (typeEffectiveness < 1.0f) { yield return StartCoroutine(dialogueManager.WaitForCaughtUpTextAndInput()); dialogueManager.AddDialogue("It wasn't very effective..."); }
dialogueManager.DisplayNextSentence();
}
private IEnumerator WaitForBarsToLoad()
{
while(
Mathf.Abs(allyHPSlider.value - allyPokemon.currentHP) > 1 ||
Mathf.Abs(allyXPSlider.value - allyPokemon.XP) > 1 ||
Mathf.Abs(foeHPSlider.value - foePokemon.currentHP) > 1)
{
Debug.Log("HP@" + allyHPSlider.value + " " + allyPokemon.currentHP);
Debug.Log("XP@" + allyXPSlider.value + " " + allyPokemon.XP);
Debug.Log("ENEMY HP@" + foeHPSlider.value + " " + foePokemon.currentHP);
yield return null;
}
}
public void StartBattle()
{
StartCoroutine(BattleHandler());
}
private int ExperienceCalculation(Pokemon victor, Pokemon loser, bool trainerBattle = false)
{
float a = trainerBattle ? 1.5f : 1.0f; //Trainer battle or not
float b = loser.pokemonData.baseEXP; //Base
float e = (victor.heldItem != null && victor.heldItem.internalName.Equals("LUCKYEGG")) ? 1.5f : 1.0f; //Lucky egg held?
float l = loser.level; //Opponent level
float s = 1f; //Participants
float exp = (a * b * e * l) / (7 * s);
return Mathf.RoundToInt(exp);
}
IEnumerator BattleHandler()
{
allyPokemon = Player.instance.party.GetFirstNonFaintedPokemon();
allyHPSlider.value = allyPokemon.HP;
dialogueManager.ClearDialogue();
dialogueManager.AddDialogue("Foe " + foePokemon.GetName() + " wants to battle!");
allyParent.transform.localPosition = new Vector3(600, -32, 0);
dialogueManager.DisplayNextSentence();
foePokemonParent.transform.localPosition = Vector3.zero;
for (int i = 600; i >= 0; i-=10) {
foeParent.transform.localPosition = new Vector3(-i, 96, 0);
yield return null;
}
bool partyDead = false;
while (Player.instance.party.HasUsablePokemon() && !foePokemon.CheckForDeath())
{
bool allyDied = false;
bool foeDied = false;
allyParent.transform.localPosition = new Vector3(600, -32, 0);
allyPokemon = Player.instance.party.GetFirstNonFaintedPokemon();
dialogueManager.AddDialogue("Go, " + allyPokemon.GetName() + "!");
yield return dialogueManager.WaitForCaughtUpText();
allyPokemonParent.transform.localPosition = Vector3.zero;
for (int i = 500; i >= 0; i -= 10)
{
allyParent.transform.localPosition = new Vector3(i, -32, 0);
yield return null;
}
while (!allyPokemon.CheckForDeath() && !foePokemon.CheckForDeath())
{
int foeRand = Random.Range(0, foePokemon.GetNumberOfMoves());
int allyRand = Random.Range(0, allyPokemon.GetNumberOfMoves());
Pokemon fasterPokemon;
Pokemon slowerPokemon;
if (allyPokemon.speed > foePokemon.speed)
{
fasterPokemon = allyPokemon;
slowerPokemon = foePokemon;
}
else
{
fasterPokemon = foePokemon;
slowerPokemon = allyPokemon;
}
yield return StartCoroutine(SingleAttack(fasterPokemon, slowerPokemon, foeRand));
int check = CheckIfEitherPokemonDied();
if (check != 0)
{
allyDied = (check == 1);
foeDied = (check == 2);
break;
}
yield return StartCoroutine(SingleAttack(slowerPokemon, fasterPokemon, allyRand));
check = CheckIfEitherPokemonDied();
if (check != 0)
{
allyDied = (check == 1);
foeDied = (check == 2);
break;
}
}
if (foeDied)
{
int exp = ExperienceCalculation(allyPokemon, foePokemon);
yield return StartCoroutine(dialogueManager.WaitForCaughtUpTextAndInput());
for (int i = 0; i < 150; i += 10)
{
foePokemonParent.transform.localPosition = new Vector3(0, -i, 0);
yield return null;
}
dialogueManager.AddDialogue(foePokemon.GetName() + " fainted!");
yield return StartCoroutine(dialogueManager.WaitForCaughtUpTextAndInput());
dialogueManager.AddDialogue(allyPokemon.GetName() + " gained " + exp + " experience points!");
yield return StartCoroutine(dialogueManager.WaitForCaughtUpTextAndInput());
allyPokemon.ModXP(exp);
yield return StartCoroutine(WaitForBarsToLoad());
break;
}
if (allyDied)
{
yield return StartCoroutine(dialogueManager.WaitForCaughtUpTextAndInput());
for (int i = 0; i < 150; i += 10)
{
allyPokemonParent.transform.localPosition = new Vector3(0, -i, 0);
yield return null;
}
dialogueManager.AddDialogue(allyPokemon.GetName() + " fainted!");
yield return StartCoroutine(dialogueManager.WaitForCaughtUpTextAndInput());
if(!Player.instance.party.HasUsablePokemon())
{
partyDead = true;
}
}
}
if(partyDead)
{
dialogueManager.AddDialogue(Player.instance.name + " is out of usable Pokemon!");
dialogueManager.AddDialogue(Player.instance.name + " blacked out!");
yield return StartCoroutine(dialogueManager.WaitForCaughtUpTextAndInput());
}
//dialogueManager.AddDialogue("BATTLE OVER");
PokemonGameManager.instance.EndBattle();
}
/// <summary>
/// Returns 2 for foe death, 1 for player death, 0 for neither
/// </summary>
/// <returns></returns>
private int CheckIfEitherPokemonDied()
{
if(foePokemon.CheckForDeath())
{
return 2;
}
if (allyPokemon.CheckForDeath())
{
return 1;
}
return 0;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum Direction
{
NORTH,
SOUTH,
EAST,
WEST,
NONE
}
[RequireComponent(typeof(SpriteRenderer))]
[RequireComponent(typeof(SpriteRenderer))]
public class Entity : MonoBehaviour
{
public enum EntityCommand
{
FACEDOWN,
FACELEFT,
FACERIGHT,
FACEUP,
FACEPLAYER,
MOVEDOWN,
MOVELEFT,
MOVERIGHT,
MOVEUP,
MOVEFORWARD,
MOVETOWARDSPLAYER
}
protected Direction direction;
int index = 0;
public int movespeed = 1;
public bool setSortOrder = false;
bool stopped = false;
protected bool isMoving = false;
protected bool isAirborne = false;
protected bool collisionEnabled = true;
[Header("If stopped, don't increment movement to next.")]
public bool deterministicMovement = true;
bool leftFoot = false;
public EntitySpriteData entitySpriteData;
public SpriteRenderer dropShadowRenderer;
private Sprite[] spritesInUse;
SpriteRenderer spriteRenderer;
BoxCollider2D boxCollider;
public LayerMask collidableLayerMask;
public LayerMask nonCollidableLayerMask;
protected PokemonGameManager pokemonGameManager;
public virtual void Start()
{
if(dropShadowRenderer!=null) { dropShadowRenderer.enabled = false; }
spriteRenderer = GetComponent<SpriteRenderer>();
boxCollider = GetComponent<BoxCollider2D>();
pokemonGameManager = PokemonGameManager.instance;
FaceDown();
}
public virtual void Update()
{
Animation();
}
public void ExecuteCommand(EntityCommand command, int value = 1)
{
switch(command)
{
case EntityCommand.FACEDOWN:
FaceDown(); break;
case EntityCommand.FACELEFT:
FaceLeft(); break;
case EntityCommand.FACERIGHT:
FaceRight(); break;
case EntityCommand.FACEUP:
FaceUp(); break;
case EntityCommand.FACEPLAYER:
FacePlayer(); break;
case EntityCommand.MOVEDOWN:
MoveDown(value); break;
case EntityCommand.MOVELEFT:
MoveLeft(value); break;
case EntityCommand.MOVERIGHT:
MoveRight(value); break;
case EntityCommand.MOVEUP:
MoveUp(value); break;
case EntityCommand.MOVEFORWARD:
MoveForward(value); break;
case EntityCommand.MOVETOWARDSPLAYER:
MoveTowardsPlayer(value); break;
default:
break;
}
}
public void FaceUp() { FaceDirection(Direction.NORTH); }
public void FaceDown() { FaceDirection(Direction.SOUTH); }
public void FaceLeft() { FaceDirection(Direction.WEST); }
public void FaceRight() { FaceDirection(Direction.EAST); }
public void FacePlayer()
{
Vector3 difference = PlayerController.instance.transform.position - transform.position;
bool x = Mathf.Abs(difference.x) > Mathf.Abs(difference.y);
bool negative = (x ? Mathf.Sign(difference.x) : Mathf.Sign(difference.y)) < 0;
if(x)
{
if(negative) {
FaceLeft();
} else {
FaceRight();
}
} else
{
if (negative) {
FaceDown();
} else {
FaceUp();
}
}
}
public void MoveUp(int times = 1, bool jump = false) { MoveInDirection(Direction.NORTH, times, jump); }
public void MoveDown(int times = 1, bool jump = false) { MoveInDirection(Direction.SOUTH, times, jump); }
public void MoveLeft(int times = 1, bool jump = false) { MoveInDirection(Direction.WEST, times, jump); }
public void MoveRight(int times = 1, bool jump = false) { MoveInDirection(Direction.EAST, times, jump); }
public void MoveForward(int times = 1, bool jump = false) { MoveInDirection(direction, times, jump); }
public void MoveTowardsPlayer(int times = 1, bool jump = false) { FacePlayer(); MoveForward(times, jump); }
public void StopMovement()
{
stopped = true;
}
public void StartMovement()
{
stopped = false;
}
public void SetCollision(bool c)
{
collisionEnabled = c;
}
public void FaceDirection(Direction d)
{
if (!stopped)
{
direction = d;
index = 0;
switch (direction)
{
case Direction.NORTH:
spritesInUse = entitySpriteData.northSprites;
break;
case Direction.SOUTH:
spritesInUse = entitySpriteData.southSprites;
break;
case Direction.EAST:
spriteRenderer.flipX = false;
spritesInUse = entitySpriteData.eastSprites;
break;
case Direction.WEST:
spriteRenderer.flipX = true;
spritesInUse = entitySpriteData.eastSprites;
break;
default:
break;
}
}
}
public void InitSprites()
{ FaceDirection(direction); }
public void MoveInDirection(Direction d, int times = 1, bool jump = false)
{
//StopAllCoroutines();
StartCoroutine(MoveInDirectionCoroutine(d, times, jump));
}
public IEnumerator MoveInDirectionCoroutine(Direction d, int times = 1, bool jump = false)
{
isMoving = true;
if (jump) {
isAirborne = true;
if(dropShadowRenderer != null) { dropShadowRenderer.enabled = true; }
}
FaceDirection(d);
int t = 0;
bool upJump = false;
int macroIndex = 0;
int totalHalfLife = times * 8;
int height = 16;
while (t < times)
{
upJump = !upJump;
if (deterministicMovement)
{
while (CheckForthTile() || stopped)
{
yield return null;
}
} else
{
if (CheckForthTile() || stopped)
{
break;
}
}
leftFoot = !leftFoot;
Vector3 startingPosition = transform.position;
Vector3 targetPositionOffset = Direction2Vector(direction);
for (int i = 0; i < 16; i+=movespeed)
{
macroIndex++;
if(i>4 && i<12)
{
index = leftFoot ? 1 : 2;
} else
{
index = 0;
}
Vector3 offset = Vector3.Lerp(Vector3.zero, targetPositionOffset, i / 16f);
Vector3 inverseOffset = Vector3.Lerp(targetPositionOffset, Vector3.zero, i / 16f);
//JUMP
//int jumpY = 8-Mathf.Abs(i-8);//upJump ? i : 16 - i;
int jumpLerpFactor = totalHalfLife-Mathf.Abs(macroIndex - totalHalfLife);
int jumpY = (int) Mathf.Lerp(0, height, jumpLerpFactor / (totalHalfLife * 2f));
Vector3 jumpVector = (jump ? Vector3.down * jumpY / 16f : Vector3.zero);
transform.position = startingPosition + offset + (jump? Vector3.up * jumpY/16f : Vector3.zero);
boxCollider.offset = inverseOffset + jumpVector;
if (dropShadowRenderer != null) { dropShadowRenderer.transform.localPosition = jumpVector; }
yield return new WaitForEndOfFrame();
}
transform.position = startingPosition + targetPositionOffset;
boxCollider.offset = Vector2.zero;
CheckCurrentTile();
t++;
yield return null;
}
isMoving = false;
isAirborne = false;
if (dropShadowRenderer != null) { dropShadowRenderer.enabled = false; }
}
public virtual bool CheckCurrentTile()
{
Collider2D collider = Physics2D.OverlapBox(transform.position, new Vector2(.1f, .1f), 0, nonCollidableLayerMask.value);
if (collider != null)
{
if(collider.CompareTag("Grass"))
{
ParticleSystemPooler.instance.SpawnParticleSystem("ShakingGrass", transform.position);
return true;
}
}
return false;
}
public virtual Collider2D CheckForthTile()
{
if(!collisionEnabled) { return null; }
RaycastHit2D hit = Physics2D.Raycast(transform.position, Direction2Vector(direction), 1.0f, collidableLayerMask.value);
Collider2D collider = hit.collider;
if (collider != null)
{
if (hit.distance < 1.0f)
{
return collider;
}
}
return null;
}
protected void Animation()
{
spriteRenderer.sprite = spritesInUse[index];
if (!setSortOrder) {
spriteRenderer.sortingOrder = -Mathf.RoundToInt(transform.position.y);
}
}
public static Vector3 Direction2Vector(Direction d)
{
switch (d)
{
case Direction.NORTH:
return Vector3.up;
case Direction.SOUTH:
return Vector3.down;
case Direction.EAST:
return Vector3.right;
case Direction.WEST:
return Vector3.left;
default:
return Vector3.zero;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InspectableObject : MonoBehaviour, IInteractable
{
public Dialogue dialogue;
public void OnInteract()
{
PokemonGameManager.instance.StartDialogue(dialogue);
}
}
<file_sep>using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(ItemData))]
public class ItemDataEditor : Editor
{
ItemData comp;
private void OnEnable()
{
comp = (ItemData)target;
}
public override void OnInspectorGUI()
{
//base.OnInspectorGUI();
GUIStyle headerStyle = new GUIStyle(EditorStyles.boldLabel)
{
font = (Font)Resources.Load("Fonts/pkmnrs"),
fontSize = 24,
alignment = TextAnchor.MiddleLeft
};
GUIStyle captionStyle = new GUIStyle(EditorStyles.wordWrappedLabel)
{
fontSize = 14,
richText = true,
alignment = TextAnchor.MiddleLeft
};
EditorGUILayout.BeginHorizontal();
GUILayout.Label(comp.sprite.texture, captionStyle, GUILayout.Height(64), GUILayout.Width(64));
EditorGUILayout.LabelField(comp.ID + ": " + comp.name, headerStyle, GUILayout.Height(64));
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField("", EditorStyles.helpBox);
EditorGUILayout.Separator();
EditorGUILayout.LabelField("<color=blue>" + comp.itemType.ToString() + "</color>", captionStyle);
EditorGUILayout.LabelField("<color=blue>$" + comp.price + ".00</color>", captionStyle);
EditorGUILayout.Separator();
EditorGUILayout.LabelField("Use in overworld: <color=blue>" + comp.overworldUsabilityID.ToString() + "</color>", captionStyle);
EditorGUILayout.LabelField("Use in battle: <color=blue>" + comp.battleUsabilityID.ToString() + "</color>", captionStyle);
if (!comp.specialItemID.Equals(ItemData.SpecialItemType.NONE))
{
EditorGUILayout.LabelField("Special item: <color=blue>" + comp.specialItemID.ToString() + "</color>", captionStyle);
}
if (comp.TMmoveToLearn != null)
{
EditorGUILayout.LabelField("Teaches move <color=blue>" + comp.TMmoveToLearn.name + "</color>", captionStyle);
}
EditorGUILayout.LabelField("\"" + comp.description + "\"", captionStyle, GUILayout.Height(64f));
}
}
<file_sep>using UnityEditor;
using UnityEngine;
public class TXTFileAccessor {
private static string path;
private static TextAsset textAsset;
private static string[] textAssetSplitLine;
public static void SetPath(string _path)
{
path = _path;
textAsset = (TextAsset) AssetDatabase.LoadAssetAtPath(path, typeof(TextAsset));
textAssetSplitLine = textAsset.text.Split('\n');
}
public static string GetPath()
{
return path;
}
public static string ReadValue()
{
return textAsset.text;
}
public static string ReadValue(int line)
{
return textAssetSplitLine[line];
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DialogueManager : MonoBehaviour
{
public Camera dialogueCamera;
public Text dialogueText;
[Space(3f)]
[Range(.01f, .1f)]
public float timeBetweenCharacters = .05f;
private Queue<string> sentences;
private bool currentlyReadingDialogue = false;
public static DialogueManager instance;
private string colorString = "black";
public Text[] choiceTexts;
public Image choicer;
private int choice = 0;
private void Awake()
{
instance = this;
}
private void Start()
{
SetDisplay(false);
sentences = new Queue<string>();
dialogueText.text = "";
}
public void SetColor(string cs)
{
if (cs == "")
{ colorString = "black"; }
else
{
colorString = cs;
}
}
public void SetDisplay(bool on = true)
{
dialogueCamera.enabled = on;
}
public bool IsDialogueDisplayed()
{
return dialogueCamera.enabled;
}
public void Update()
{
if (sentences != null && sentences.Count > -1)
{
if (Input.GetButtonDown("Fire1"))
{
if (!currentlyReadingDialogue)
{
DisplayNextSentence();
}
}
}
}
private string StringReplacement(string s)
{
string ret = s;
//Player name
if (s.Contains("/pn"))
{
ret = s.Replace("/pn", Player.instance.name);
}
return ret;
}
public void AddDialogue(string[] s)
{
AddDialogue(new Dialogue(s));
}
public void AddDialogue(string s)
{
AddDialogue(new Dialogue(s));
}
public void AddDialogue(Dialogue d)
{
SetDisplay();
foreach (string sentence in d.sentences)
{
sentences.Enqueue(StringReplacement(sentence));
}
}
public void ClearDialogue()
{
sentences.Clear();
dialogueText.text = "";
}
public void DisplayNextSentence()
{
if (sentences.Count == 0)
{
EndDialogue();
return;
}
string sentence = sentences.Dequeue();
Debug.Log(sentence);
StopCoroutine("DialogueRead");
StartCoroutine(DialogueRead(sentence));
}
IEnumerator DialogueRead(string target)
{
currentlyReadingDialogue = true;
for (int i = 0; i < target.Length+1; i++)
{
dialogueText.text = "<color=" + colorString + ">" + target.Substring(0, i) + "</color><color=clear>" + target.Substring(i) + "</color>";
yield return new WaitForSeconds(timeBetweenCharacters);
}
currentlyReadingDialogue = false;
}
public void EndDialogue()
{
sentences = new Queue<string>();
}
public bool CurrentlyReadingDialogue()
{ return currentlyReadingDialogue; }
public bool AllCaughtUp()
{
return (sentences.Count <= 0 && !CurrentlyReadingDialogue());
}
public IEnumerator WaitForCaughtUpText()
{
while (!AllCaughtUp())
yield return null;
}
public IEnumerator WaitForCaughtUpTextAndInput()
{
while (!Input.GetButtonDown("Fire1") || !AllCaughtUp())
yield return null;
}
//CHOICE
public int StartChoice()
{
StartCoroutine(ChoiceEnumerator());
return choice;
}
public IEnumerator ChoiceEnumerator()
{
if(Input.GetKeyDown(KeyCode.UpArrow))
{
choice++;
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
choice--;
}
choice = Mathf.Clamp(choice, 0, 4);
choicer.transform.localPosition = new Vector3(48, 64 + (32 * choice), 0);
while (!Input.GetButtonDown("Fire1"))
yield return null;
}
}<file_sep># PokemonInUnity
Pokemon in Unity3D
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : Entity
{
bool swimming = false;
bool running = false;
public static PlayerController instance;
public EntitySpriteData walkingSpriteData;
public EntitySpriteData runningSpriteData;
public EntitySpriteData swimmingSpriteData;
public Entity swimmingEntity;
public LayerMask normalCollidableLayerMask;
public LayerMask swimmingCollidableLayerMask;
private void Awake()
{
instance = this;
}
public override void Start()
{
base.Start();
swimmingEntity.SetCollision(false);
swimmingEntity.gameObject.SetActive(false);
collidableLayerMask = normalCollidableLayerMask;
}
public override void Update()
{
base.Update();
if (!isMoving && pokemonGameManager.gameState.Equals(PokemonGameManager.GameState.OVERWORLD))
{
GatherInput();
}
Tick();
}
public void SetRunning(bool r)
{
running = r;
}
private void GatherInput()
{
float x = Input.GetAxisRaw("Horizontal");
float y = Input.GetAxisRaw("Vertical");
running = Input.GetButton("Run");
if (x > 0)
{ MoveRight(); }
else if (x < 0)
{ MoveLeft(); }
else if (y > 0)
{ MoveUp(); }
else if (y < 0)
{ MoveDown(); }
if(Input.GetButtonDown("Fire1"))
{
Interact();
} else if(Mathf.Abs(x) > .1f || Mathf.Abs(y) > .1f)
{
InteractCollision();
}
}
private void Tick()
{
if (swimming)
{
entitySpriteData = swimmingSpriteData;
movespeed = 2;
swimmingEntity.FaceDirection(direction);
InitSprites();
} else if (running && isMoving)
{
entitySpriteData = runningSpriteData;
movespeed = 2;
InitSprites();
}
else
{
entitySpriteData = walkingSpriteData;
movespeed = 1;
InitSprites();
}
}
public override bool CheckCurrentTile()
{
base.CheckCurrentTile();
Collider2D collider = Physics2D.OverlapBox(transform.position, new Vector2(.1f, .1f), 0, nonCollidableLayerMask.value);
if (collider != null)
{
//Check for grass encounter
if (collider.CompareTag("Grass"))
{
if (MapSettings.instance.TryGrassEncounter())
{
StopMovement();
}
return true;
}
Portal p = collider.GetComponent<Portal>();
if(p != null)
{
pokemonGameManager.TraversePortal(p);
return true;
}
}
//Check for water encounter
if(swimming)
{
if(MapSettings.instance.TryWaterEncounter())
{
StopMovement();
return true;
}
}
//Check for random encounter
if(MapSettings.instance.TryRandomEncounter())
{
StopMovement();
return true;
}
return false;
}
private void Interact()
{
Collider2D c = CheckForthTile();
if (c != null)
{
IInteractable interactable = c.GetComponent<IInteractable>();
if (interactable != null)
{
interactable.OnInteract();
}
if (c.CompareTag("Water"))
{
StartCoroutine(StartSwimming());
}
}
}
private void InteractCollision()
{
Collider2D c = CheckForthTile();
if(c != null)
{
if (c.CompareTag("ReEnterLand"))
{
StartCoroutine(StopSwimming());
}
if (c.CompareTag("JumpableCliffSouth") && direction.Equals(Direction.SOUTH))
{
StartCoroutine(HopJumpableCliff());
}
}
}
IEnumerator HopJumpableCliff()
{
SetCollision(false);
pokemonGameManager.gameState = PokemonGameManager.GameState.CUTSCENE;
running = false;
yield return new WaitForSeconds(.1f);
MoveForward(2, true);
while (isMoving)
{
yield return null;
}
SetCollision(true);
pokemonGameManager.gameState = PokemonGameManager.GameState.OVERWORLD;
}
IEnumerator StartSwimming()
{
pokemonGameManager.gameState = PokemonGameManager.GameState.CUTSCENE;
SetCollision(false);
running = false;
pokemonGameManager.StartDialogue(new Dialogue("The water is a deep blue. Would you like to swim?"));
while (DialogueManager.instance.IsDialogueDisplayed())
{
yield return null;
}
MoveForward(1,true);
while(isMoving)
{
yield return null;
}
swimmingEntity.gameObject.SetActive(true);
SetCollision(true);
collidableLayerMask = swimmingCollidableLayerMask;
swimming = true;
InitSprites();
pokemonGameManager.gameState = PokemonGameManager.GameState.OVERWORLD;
}
IEnumerator StopSwimming()
{
SetCollision(false);
pokemonGameManager.gameState = PokemonGameManager.GameState.CUTSCENE;
running = false;
yield return new WaitForSeconds(.1f);
swimmingEntity.gameObject.SetActive(false);
collidableLayerMask = normalCollidableLayerMask;
swimming = false;
MoveForward(1, true);
while (isMoving)
{
yield return null;
}
SetCollision(true);
pokemonGameManager.gameState = PokemonGameManager.GameState.OVERWORLD;
}
}
<file_sep>
using System.Collections;
using UnityEngine;
public enum Status
{
NONE,
SLEEP,
POISON,
BURN,
PARALYSIS,
FREEZE,
FAINTED
}
public enum Gender
{
NONE,
MALE,
FEMALE
}
public enum Nature
{
HARDY,
LONELY,
BRAVE,
ADAMANT,
NAUGHTY,
BOLD,
DOCILE,
RELAXED,
IMPISH,
LAX,
TIMID,
HASTY,
SERIOUS,
JOLLY,
NAIVE,
MODEST,
MILD,
QUIET,
BASHFUL,
RASH,
CALM,
GENTLE,
SASSY,
CAREFUL,
QUIRKY
}
[System.Serializable]
public class MoveInSet
{
public MoveData move;
public int PP;
public MoveInSet(MoveData _move)
{
move = _move;
PP = move.totalPP;
}
}
[System.Serializable]
public class NatureData
{
public string name;
public float ATK, DEF, SPE, SPA, SPD;
public NatureData(string _name, float _ATK, float _DEF, float _SPA, float _SPD, float _SPE)
{
name = _name;
ATK = _ATK;
DEF = _DEF;
SPA = _SPA;
SPD = _SPD;
SPE = _SPE;
}
public static NatureData[] natures = new NatureData[]
{
new NatureData("HARDY", 1, 1, 1, 1, 1),
new NatureData("LONELY", 1.1f, 0.9f, 1, 1, 1),
new NatureData("BRAVE", 1.1f, 1, 1, 1, 0.9f),
new NatureData("ADAMANT", 1.1f, 1, 0.9f, 1, 1),
new NatureData("NAUGHTY", 1.1f, 1, 1, 0.9f, 1),
new NatureData("BOLD", 0.9f, 1.1f, 1, 1, 1),
new NatureData("DOCILE", 1, 1, 1, 1, 1),
new NatureData("RELAXED", 1, 1.1f, 1, 1, 0.9f),
new NatureData("IMPISH", 1, 1.1f, 0.9f, 1, 1),
new NatureData("LAX", 1, 1.1f, 1, 0.9f, 1),
new NatureData("TIMID", 0.9f, 1, 1, 1, 1.1f),
new NatureData("HASTY", 1, 0.9f, 1, 1, 1.1f),
new NatureData("SERIOUS", 1, 1, 1, 1, 1),
new NatureData("JOLLY", 1, 1, 0.9f, 1, 1.1f),
new NatureData("NAIVE", 1, 1, 1, 0.9f, 1.1f),
new NatureData("MODEST", 0.9f, 1, 1.1f, 1, 1),
new NatureData("MILD", 1, 0.9f, 1.1f, 1, 1),
new NatureData("QUIET", 1, 1, 1.1f, 1, 0.9f),
new NatureData("BASHFUL", 1, 1, 1, 1, 1),
new NatureData("RASH", 1, 1, 1.1f, 0.9f, 1),
new NatureData("CALM", 0.9f, 1, 1, 1.1f, 1),
new NatureData("GENTLE", 1, 0.9f, 1, 1.1f, 1),
new NatureData("SASSY", 1, 1, 1, 1.1f, 0.9f),
new NatureData("CAREFUL", 1, 1, 0.9f, 1.1f, 1),
new NatureData("QUIRKY", 1, 1, 1, 1, 1)
};
}
[System.Serializable]
public class Pokemon {
public PokemonData pokemonData;
public string nickname;
//public int form;
public Gender gender;
public int level;
public int XP;
private int nextLevelXP;
private int previousLevelXP;
public int happiness;
public bool pokerus;
public bool shiny;
public Status status;
public int sleepTurns;
public ItemData caughtBall;
public ItemData heldItem;
public string metDate;
public string metMap;
public int metLevel;
public string OT;
public int ID;
public static int count;
public int IV_HP, IV_Attack, IV_Defense, IV_Speed, IV_SpecialAttack, IV_SpecialDefense;
public int EV_HP, EV_Attack, EV_Defense, EV_Speed, EV_SpecialAttack, EV_SpecialDefense;
public Nature nature;
public int HP;
public int currentHP;
public int attack;
public int defense;
public int speed;
public int specialAttack;
public int specialDefense;
public AbilityData ability;
public MoveInSet[] moveset = new MoveInSet[4];
public static int SHINY_CHANCE = 8192;
public static int POKERUS_CHANCE = 21845;
/// <summary>
/// General initiator for Pokemon. All details. Use for special cases.
/// </summary>
public void InitPokemon(PokemonData _pokemonData, string _nickname, Gender _gender, int _level,
bool _shiny, ItemData _caughtBall, ItemData _heldItem, string _OT,
int _IV_HP, int _IV_Attack, int _IV_Defense, int _IV_Speed, int _IV_SpecialAttack, int _IV_SpecialDefense,
int _EV_HP, int _EV_Attack, int _EV_Defense, int _EV_Speed, int _EV_SpecialAttack, int _EV_SpecialDefense,
Nature _nature, AbilityData _ability, MoveData[] _moveset, Status _status, int _sleepTurns)
{
ID = count;
count++;
pokemonData = _pokemonData;
nickname = _nickname;
gender = _gender;
shiny = _shiny;
caughtBall = _caughtBall;
heldItem = _heldItem;
OT = _OT;
IV_HP = _IV_HP;
IV_Attack = _IV_Attack;
IV_Defense = _IV_Defense;
IV_Speed = _IV_Speed;
IV_SpecialAttack = _IV_SpecialAttack;
IV_SpecialDefense = _IV_SpecialDefense;
EV_HP = _EV_HP;
EV_Attack = _EV_Attack;
EV_Defense = _EV_Defense;
EV_Speed = _EV_Speed;
EV_SpecialAttack = _EV_SpecialAttack;
EV_SpecialDefense = _EV_SpecialDefense;
nature = _nature;
ability = _ability;
level = _level;
XP = PokemonData.GetLevelXP(pokemonData.growthRate, level);
UpdateStats();
currentHP = HP;
happiness = pokemonData.baseHappiness;
status = _status;
sleepTurns = _sleepTurns;
metLevel = level;
metMap = "Somewhere";
metDate = System.DateTime.Today.Month + "/" + System.DateTime.Today.Day + "/" + System.DateTime.Today.Year;
for (int i = 0; i < 4; i++)
{
if (_moveset[i] != null)
{
moveset[i] = new MoveInSet(_moveset[i]);
} else { moveset[i] = null; }
}
}
/// <summary>
/// Common initiator for Pokemon. Necessary details, rest to random generation. Use for wild pokemon and trainers.
/// </summary>
public void InitPokemon(PokemonData _pokemonData, string _nickname, int _level, ItemData _caughtBall, string _OT)
{
int[] pIV = new int[6] {
Random.Range(0,32),
Random.Range(0,32),
Random.Range(0,32),
Random.Range(0,32),
Random.Range(0,32),
Random.Range(0,32)
};
bool pShiny = (Random.Range(0, SHINY_CHANCE)) == 1;
Gender pGender;
if(_pokemonData.femaleRatio >= 0)
{
pGender = (Random.Range(0f, 1.0f) < _pokemonData.femaleRatio ? Gender.FEMALE : Gender.MALE);
} else { pGender = Gender.NONE; }
Nature pNature = (Nature)Random.Range(0, NatureData.natures.Length);
AbilityData pAbility = _pokemonData.standardAbilities[Random.Range(0, _pokemonData.standardAbilities.Count)];
MoveData[] pMoveset = _pokemonData.GetBestMovesAtLevel(_level);
InitPokemon(_pokemonData, _nickname, pGender, _level,
pShiny, _caughtBall, null, _OT,
pIV[0], pIV[1], pIV[2], pIV[3], pIV[4], pIV[5],
0, 0, 0, 0, 0, 0,
pNature, pAbility, pMoveset, Status.NONE, 0);
}
/// <summary>
/// Default initatior.
/// </summary>
public void InitPokemon()
{
InitPokemon(pokemonData, nickname, level, caughtBall, OT);
}
public void UpdateStats()
{
previousLevelXP = PokemonData.GetLevelXP(pokemonData.growthRate, level);
nextLevelXP = PokemonData.GetLevelXP(pokemonData.growthRate, level + 1);
//HP - Stat = floor((2 * B + I + E) * L / 100 + L + 10)
float hpRatio = GetHPRatio();
HP = Mathf.FloorToInt((2f * pokemonData.baseHP + IV_HP + EV_HP) * (level / 100f) + level + 10);
currentHP = Mathf.FloorToInt(HP * hpRatio);
//OTHERS - Stat = floor(floor((2 * B + I + E) * L / 100 + 5) * N)
attack = Mathf.FloorToInt(Mathf.Floor((2f * pokemonData.baseAttack + IV_Attack + EV_Attack) * (level / 100f) + 5) * NatureData.natures[(int)nature].ATK);
defense = Mathf.FloorToInt(Mathf.Floor((2f * pokemonData.baseDefense + IV_Defense + EV_Defense) * (level / 100f) + 5) * NatureData.natures[(int)nature].DEF);
speed = Mathf.FloorToInt(Mathf.Floor((2f * pokemonData.baseSpeed + IV_Speed + EV_Speed) * (level / 100f) + 5) * NatureData.natures[(int)nature].SPE);
specialAttack = Mathf.FloorToInt(Mathf.Floor((2f * pokemonData.baseSpecialAttack + IV_SpecialAttack + EV_SpecialAttack) * (level / 100f) + 5) * NatureData.natures[(int)nature].SPA);
specialDefense = Mathf.FloorToInt(Mathf.Floor((2f * pokemonData.baseSpecialDefense + IV_SpecialDefense + EV_SpecialDefense) * (level / 100f) + 5) * NatureData.natures[(int)nature].SPD);
}
public bool CheckForDeath()
{
if(currentHP <= 0)
{
status = Status.FAINTED;
return true;
}
return false;
}
public bool CheckForLevelUp()
{
int prevL = level;
while(level < 100 && XP > nextLevelXP)
{
level++;
UpdateStats();
}
return (level > prevL);
}
public string GetName() { if(nickname != "") { return nickname; } return pokemonData.name; }
public Sprite GetFrontSprite() { if (shiny) { return pokemonData.shinySprite; } return pokemonData.sprite; }
public Sprite GetBackSprite() { if (shiny) { return pokemonData.shinyBackSprite; } return pokemonData.backSprite; }
public float GetHPRatio() { return (float)currentHP / HP; }
public float GetXPRatio() { return (float)(XP - previousLevelXP) / (nextLevelXP - previousLevelXP); }
public float GetXPMin() { return (float)previousLevelXP; }
public float GetXPMax() { return (float)nextLevelXP; }
public int GetNumberOfMoves()
{
for(int i = 0; i < 4; i++)
{
if(moveset[i] == null || moveset[i].move == null)
{
return i;
}
}
return 4;
}
public bool IsType(PokemonTypeData type)
{
return (type.Equals(pokemonData.type1) || type.Equals(pokemonData.type2));
}
public void ModHP(int amount)
{
currentHP = Mathf.Clamp(currentHP + amount, 0, HP);
}
public void ModXP(int amount, bool instant = false)
{
amount = Mathf.Abs(amount);
XP += amount; CheckForLevelUp();
}
public void AfflictStatus(Status s)
{ status = s; }
public void AfflictStatus(string str)
{
status = (Status)System.Enum.Parse(typeof(Status), str, true);
}
}
<file_sep>using UnityEngine;
using UnityEditor;
using System.IO;
using UnityEditor.SceneManagement;
[CustomEditor(typeof(DataGenerator))]
public class DataGeneratorEditor : Editor {
DataGenerator comp;
public void OnEnable()
{
comp = (DataGenerator)target;
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
//Cleaners
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Clear Item Data"))
{
comp.ClearItemData();
AssetDatabase.DeleteAsset("Assets/Data/ScriptableObjects/Items");
}
if (GUILayout.Button("Clear Type Data"))
{
comp.ClearTypeData();
AssetDatabase.DeleteAsset("Assets/Data/ScriptableObjects/Types");
}
if (GUILayout.Button("Clear Ability Data"))
{
comp.ClearAbilityData();
AssetDatabase.DeleteAsset("Assets/Data/ScriptableObjects/Abilites");
}
if (GUILayout.Button("Clear Move Data"))
{
comp.ClearMoveData();
AssetDatabase.DeleteAsset("Assets/Data/ScriptableObjects/Moves");
}
if (GUILayout.Button("Clear Pokemon Data"))
{
comp.ClearPokemonData();
AssetDatabase.DeleteAsset("Assets/Data/ScriptableObjects/Pokemon");
}
EditorGUILayout.EndHorizontal();
if (GUILayout.Button("Clear ALL Data"))
{
comp.ClearPokemonData();
comp.ClearMoveData();
comp.ClearAbilityData();
comp.ClearTypeData();
comp.ClearItemData();
AssetDatabase.DeleteAsset("Assets/Data/ScriptableObjects/Pokemon");
AssetDatabase.DeleteAsset("Assets/Data/ScriptableObjects/Moves");
AssetDatabase.DeleteAsset("Assets/Data/ScriptableObjects/Abilites");
AssetDatabase.DeleteAsset("Assets/Data/ScriptableObjects/Types");
AssetDatabase.DeleteAsset("Assets/Data/ScriptableObjects/Items");
}
//Item, Move and Ability Generation
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Generate Type Data"))
{
GenerateTypeData();
}
if (GUILayout.Button("Generate Ability Data"))
{
GenerateAbilityData();
}
if (GUILayout.Button("Generate Move Data"))
{
GenerateMoveData();
}
if (GUILayout.Button("Generate Item Data"))
{
GenerateItemData();
}
if (GUILayout.Button("Generate Pokemon Data"))
{
GeneratePokemonData();
}
EditorGUILayout.EndHorizontal();
if(GUILayout.Button("Generate All Data"))
{
EditorGUI.BeginChangeCheck();
EditorUtility.SetDirty(this);
EditorSceneManager.MarkAllScenesDirty();
GenerateTypeData();
GenerateAbilityData();
GenerateMoveData();
GenerateItemData();
GeneratePokemonData();
AssetDatabase.SaveAssets();
if(EditorGUI.EndChangeCheck())
{
Undo.RecordObject(comp, "arrays");
}
}
EditorGUILayout.LabelField(
"Generate in this order: Type, Ability, Move, Item, Pokemon. Clear beforehand.",
EditorStyles.helpBox);
}
void GenerateItemData() {
Directory.CreateDirectory(Application.dataPath + "/Data/ScriptableObjects/Items");
int index = 0;
foreach (ItemData item in comp.GenerateItems())
{
if (EditorUtility.DisplayCancelableProgressBar(
"Item Generation Progress",
"Currently generating " + item.name + " ability data...",
((float)index) / DataGenerator.NUMBER_OF_ITEMS))
{
EditorUtility.ClearProgressBar();
return;
}
string paddedindexStr = index.ToString().PadLeft(3, '0'); // results in 009
AssetDatabase.CreateAsset(item, "Assets/Data/ScriptableObjects/Items/" + paddedindexStr + "-" + item.name + "ItemData.asset");
EditorUtility.SetDirty(item);
index++;
}
EditorUtility.ClearProgressBar();
}
void GenerateTypeData() {
Directory.CreateDirectory(Application.dataPath + "/Data/ScriptableObjects/Types");
int index = 0;
foreach (PokemonTypeData typeData in comp.GenerateTypes())
{
if (EditorUtility.DisplayCancelableProgressBar(
"Type Generation Progress",
"Currently generating " + typeData.name + " type data...",
((float)index) / DataGenerator.NUMBER_OF_TYPES))
{
EditorUtility.ClearProgressBar();
return;
}
string paddedindexStr = index.ToString().PadLeft(3, '0'); // results in 009
AssetDatabase.CreateAsset(typeData, "Assets/Data/ScriptableObjects/Types/" + paddedindexStr + "-" + typeData.name + "TypeData.asset");
EditorUtility.SetDirty(typeData);
index++;
}
EditorUtility.ClearProgressBar();
}
void GenerateAbilityData() {
Directory.CreateDirectory(Application.dataPath + "/Data/ScriptableObjects/Abilites");
int index = 0;
foreach (AbilityData ability in comp.GenerateAbilities())
{
if (EditorUtility.DisplayCancelableProgressBar(
"Ability Generation Progress",
"Currently generating " + ability.name + " ability data...",
((float)index) / DataGenerator.NUMBER_OF_ABILITIES))
{
EditorUtility.ClearProgressBar();
return;
}
string paddedindexStr = index.ToString().PadLeft(3, '0'); // results in 009
AssetDatabase.CreateAsset(ability, "Assets/Data/ScriptableObjects/Abilites/" + paddedindexStr + "-" + ability.name + "AbilityData.asset");
EditorUtility.SetDirty(ability);
index++;
}
EditorUtility.ClearProgressBar();
}
void GenerateMoveData() {
Directory.CreateDirectory(Application.dataPath + "/Data/ScriptableObjects/Moves");
int index = 0;
foreach (MoveData move in comp.GenerateMoves())
{
if (EditorUtility.DisplayCancelableProgressBar(
"Move Generation Progress",
"Currently generating " + move.name + " ability data...",
((float)index) / DataGenerator.NUMBER_OF_MOVES))
{
EditorUtility.ClearProgressBar();
return;
}
string paddedindexStr = index.ToString().PadLeft(3, '0'); // results in 009
AssetDatabase.CreateAsset(move, "Assets/Data/ScriptableObjects/Moves/" + paddedindexStr + "-" + move.name + "MoveData.asset");
EditorUtility.SetDirty(move);
index++;
}
EditorUtility.ClearProgressBar();
}
void GeneratePokemonData()
{
Directory.CreateDirectory(Application.dataPath + "/Data/ScriptableObjects/Pokemon");
int index = 0;
foreach (PokemonData pokemonData in comp.GeneratePokemon())
{
string paddedindexStr = index.ToString().PadLeft(3, '0'); // results in 009
if (EditorUtility.DisplayCancelableProgressBar(
"Pokemon Generation Progress",
"Currently generating " + pokemonData.name + " data...",
((float)index) / DataGenerator.NUMBER_OF_POKEMON))
{
EditorUtility.ClearProgressBar();
return;
}
AssetDatabase.CreateAsset(pokemonData, "Assets/Data/ScriptableObjects/Pokemon/" + paddedindexStr + "-" + pokemonData.name + "PokemonData.asset");
EditorUtility.SetDirty(pokemonData);
index++;
}
EditorUtility.ClearProgressBar();
}
void OnInspectorUpdate()
{
Repaint();
}
}
| 2afb177aba6f836c32eb05cb3157412cb510def8 | [
"Markdown",
"C#",
"INI"
] | 38 | C# | sinqz/PokemonInUnity-1 | 4eae99ccf52f637ab5ccc0d9a79dae3ff96ab91d | 2fc86d620252c1ce47f910f4d3ffa39dacbd0deb |
refs/heads/master | <file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "2e579ff99720a50ad0470d5d274f16a6",
"url": "/index.html"
},
{
"revision": "defa48da20dba649c3bf",
"url": "/static/css/main.fe49e6e2.chunk.css"
},
{
"revision": "c3523fed135cabb60e9b",
"url": "/static/js/2.c7f6580b.chunk.js"
},
{
"revision": "1c9a5c14c094f70c35a5a57a5770d494",
"url": "/static/js/2.c7f6580b.chunk.js.LICENSE.txt"
},
{
"revision": "defa48da20dba649c3bf",
"url": "/static/js/main.ec4522f6.chunk.js"
},
{
"revision": "86395acb2411a2a56149",
"url": "/static/js/runtime-main.3efb4427.js"
},
{
"revision": "026ce4fd4786722db550c0963588f39f",
"url": "/static/media/NotoSansCJKjp-Regular.026ce4fd.woff"
},
{
"revision": "417625d63533c603095cb10deefa413a",
"url": "/static/media/NotoSansCJKjp-Regular.417625d6.eot"
},
{
"revision": "2d9033bb035d529347e49aef86d4d0a4",
"url": "/static/media/iconfont.2d9033bb.svg"
},
{
"revision": "890b7b8d1ee6fcbe43bd90d5a420704c",
"url": "/static/media/iconfont.890b7b8d.eot"
},
{
"revision": "9dbcc49e00b3157ab57861c3751f4ea2",
"url": "/static/media/iconfont.9dbcc49e.ttf"
},
{
"revision": "cb652fe93ddfc056f9c63a140c77d96b",
"url": "/static/media/iconfont.cb652fe9.woff"
}
]);<file_sep># nri-static
# https://qv2ray.net/getting-started/
| 4eff91ca4efd096aa039376bff3270c165dbf104 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | NKStupid/nri-static | a1b07467f7d1380fe99f8cef4e6e1f28ac23b419 | f0d1fbf228138067239e6179b1e10270dfed8c3c |
refs/heads/master | <repo_name>akyao/namingcounter<file_sep>/src/namingcounter/CountAction.java
package namingcounter;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import namingcounter.dto.CountData;
import namingcounter.views.NamingCountView;
/**
* 「カウント」メニュー
*/
public class CountAction implements IObjectActionDelegate {
private ISelection selection;
@Override
public void run(IAction action) {
try {
// 計算
CountData ore = Counter.count(selection);
// 表示
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IViewPart viewPart = window.getActivePage().showView("namingcounter.views.NamingCountView", null, IWorkbenchPage.VIEW_VISIBLE);
if (viewPart instanceof NamingCountView) {
((NamingCountView) viewPart).render(ore);
}
} catch(Exception ex){
// TODO エラー処理
ex.printStackTrace();
}
}
@Override
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
// TODO なにこれ?
}
@Override
public void selectionChanged(IAction action, ISelection selection) {
this.selection = selection;
}
}
<file_sep>/src/namingcounter/Counter.java
package namingcounter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import namingcounter.dto.CountData;
/**
* カウントするやつ
* @author akyao
*/
public class Counter {
private CountData countData = new CountData();
private IStructuredSelection iSel;
public static CountData count(ISelection iSel) {
if (iSel != null && iSel instanceof IStructuredSelection) {
Counter c = new Counter((IStructuredSelection) iSel);
c.count();
return c.countData;
}
return new CountData();
}
private Counter(IStructuredSelection iSel){
this.iSel = iSel;
}
private void count() {
@SuppressWarnings("unchecked")
Iterator<Object> ite = iSel.iterator();
while (ite.hasNext()) {
Object obj = ite.next();
if (obj instanceof IContainer) {
// ディレクトリ
count((IContainer) obj);
} else if (obj instanceof IPackageFragment) {
// Javaパッケージ(JDT)
try{
IPackageFragment pkg = (IPackageFragment)obj;
for (ICompilationUnit cUnit : pkg.getCompilationUnits()) {
count(cUnit);
}
}catch(Exception e){
throw new RuntimeException(e);
}
} else if (obj instanceof IFile) {
// ファイル
count((IFile) obj);
} else if (obj instanceof ICompilationUnit) {
// Javaソース
count((ICompilationUnit) obj);
}
}
}
private void count(IContainer container) {
try {
for (IResource resource : container.members()) {
if (resource instanceof IContainer) {
count((IContainer) resource);
} else if (resource instanceof IFile) {
count((IFile) resource);
} else if (resource instanceof ICompilationUnit){
count((ICompilationUnit) resource);
}
}
}catch(Exception e){
throw new RuntimeException(e);
}
}
private void count(IFile file) {
IJavaElement jEle = JavaCore.create(file);
if (jEle != null) {
ICompilationUnit unit = (ICompilationUnit) jEle.getAncestor(IJavaElement.COMPILATION_UNIT);
count(unit);
}
}
private void count(ICompilationUnit unit) {
if(unit == null) {
return;
}
try{
Function<IMember, List<String>> convert = x -> toSmallCaracters(splitToWord(x.getElementName()));
for (IType iType : unit.getTypes()) {
// top level class
countData.add(convert.apply(iType), iType);
// inner class
for (IType iType2 : iType.getTypes()) {
// TODO 再帰させないと、2重にネストしたクラスをカウントできない。要修正
countData.add(convert.apply(iType2), iType2);
}
// methods
for (IMethod method : iType.getMethods()) {
countData.add(convert.apply(iType), method);
}
// fields
for (IField field : iType.getFields()) {
countData.add(convert.apply(iType), field);
}
}
}catch(Exception e){
throw new RuntimeException(e);
}
}
private List<String> splitToWord(String str) {
// thanks to -> http://akisute3.hatenablog.com/entry/20111217/1324109628
String[] strs = str.split("(?<=[A-Z])(?=[A-Z][a-z])|(?<=[a-z])(?=[A-Z])");
return Arrays.asList(strs);
}
private List<String> toSmallCaracters(List<String> strList){
return strList.stream().map(x -> x.toLowerCase()).collect(Collectors.toList());
}
}
<file_sep>/src/namingcounter/views/NamingCountView.java
package namingcounter.views;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.*;
import namingcounter.dto.CountData;
import namingcounter.dto.CountData.CountDataItem;
import namingcounter.dto.CountData.SortBy;
import java.util.List;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
/**
* Viewのところ
*
* @author akyao
*/
public class NamingCountView extends ViewPart {
private static final CountData.SortBy DEFAULT_SORT = CountData.SortBy.WORD;
public static final String ID = "namingcounter.views.NamingCountView";
private TableViewer viewer;
private Table table;
private CountData countData;
private String[] sumData;
// sort用 TODO 名前がなげえ
private String lastSortColumnHeaderText;
private boolean lastTimeSortIsDesc = false;
public NamingCountView() {
}
/**
* 与えられたデータをViewに表示します
* @param countData
*/
public void render(CountData countData) {
List<CountDataItem> dataItems = countData.getItems(DEFAULT_SORT, false);
this.countData = countData;
this.lastSortColumnHeaderText = "word";
this.sumData = new String[]{
"-",
String.valueOf(dataItems.stream().mapToInt(x -> x.countInClass).sum()),
String.valueOf(dataItems.stream().mapToInt(x -> x.countInMethod).sum()),
String.valueOf(dataItems.stream().mapToInt(x -> x.countInField).sum()),
String.valueOf(dataItems.stream().mapToInt(x -> x.total()).sum())
};
render(dataItems);
}
private void render(List<CountDataItem> dataItems) {
// 表示を初期化
table.removeAll();
for (CountDataItem dataItem : dataItems) {
// 行分のデータ
String[] data ={
dataItem.word,
Integer.toString(dataItem.countInClass),
Integer.toString(dataItem.countInMethod),
Integer.toString(dataItem.countInField),
Integer.toString(dataItem.total())
};
TableItem tableItem = new TableItem(table, SWT.NULL);
tableItem.setText(data);
if ("fuck".equals(dataItem.word)) {
tableItem.setBackground(new Color(table.getDisplay(), new RGB(255,0,0)));
}
}
// 合計
TableItem tableItem = new TableItem(table, SWT.NULL);
tableItem.setText(sumData);
}
@Override
public void createPartControl(Composite parent) {
Composite container = new Composite(parent, SWT.NONE);
container.setLayout(new FillLayout());
viewer = new TableViewer(container, SWT.FULL_SELECTION | SWT.BORDER);
viewer.setContentProvider(new ArrayContentProvider());
viewer.setInput(getViewSite());
initTable(viewer);
}
private void initTable(final TableViewer viewer) {
TableLayout layout = new TableLayout();
table = viewer.getTable();
table.setLayout(layout);
table.setHeaderVisible(true);
table.setLinesVisible(true);
// カラムをセット
initColumn(layout, new ColumnWeightData(3), "word", 0, false);
initColumn(layout, new ColumnWeightData(2), "class", 1, true);
initColumn(layout, new ColumnWeightData(2), "method", 2, true);
initColumn(layout, new ColumnWeightData(2), "field", 3, true);
initColumn(layout, new ColumnWeightData(2), "total", 4, true);
}
private void initColumn(TableLayout layout, ColumnLayoutData layoutData,
String header, int index, boolean paddingRight)
{
int padding = paddingRight ? SWT.RIGHT : SWT.LEFT;
layout.addColumnData(layoutData);
TableColumn tc = new TableColumn(table, padding, index);
tc.setText(header);
tc.addSelectionListener(new TableHeaderListener());
}
@Override
public void setFocus() {
viewer.getControl().setFocus();
}
/**
* テーブルのカラムをクリックされた時のソート処理
*/
private class TableHeaderListener extends SelectionAdapter {
@Override
public void widgetSelected(SelectionEvent e) {
// ソート方法を取得する
TableColumn column = (TableColumn) e.getSource();
SortBy sortBy = getSortBy(column.getText());
// descするのは、 (前と同じカラムをクリック)かつ(前のソートがdescじゃない)の場合
boolean isDesc = lastSortColumnHeaderText.equals(column.getText()) && !lastTimeSortIsDesc;
// データを再表示
render(countData.getItems(sortBy, isDesc));
// 次回descソートするために記録しておく
lastSortColumnHeaderText = column.getText();
lastTimeSortIsDesc = isDesc;
}
}
private static SortBy getSortBy(String colHeaderTxt) {
return SortBy.valueOf(colHeaderTxt.toUpperCase());
}
// SWG系のサブクラスを使おうとすると実行時エラーになる。これ豆知識な
// private class TableColumnWithSortBy extends TableColumn{
// private SortBy sortBy;
// public TableColumnWithSortBy(Table table, int style, int index, SortBy sortBy) {
// super(table, style, index);
// this.sortBy = sortBy;
// }
// }
}
<file_sep>/README.md
# なにこれ?
+ Eclipseのプラグインです。
+ Javaファイルを解析して、クラス名、メソッド名、フィールド名で使われている単語の数をカウントします。
+ こんな感じです。

# インストール方法
+ [こちら](https://github.com/akyao/namingcounter/releases) からjarファイルをダウンロードしてください。
+ ダウンロードしたjarファイルをeclipse/plugins下に置いてください
# 使い方
+ 数えたいファイル、フォルダで右クリック-> Naming counter -> count
| 9a3d33ce3b3d7083a8e5e68f601f96e18365fe4f | [
"Markdown",
"Java"
] | 4 | Java | akyao/namingcounter | 30de1ab720572687b45a77cb8650ecbd4c51deed | b9eb82e9146a6c448f5adeebb1abc7f7466a9dc3 |
refs/heads/master | <repo_name>MalonHolmes/FirstObjectsDemo<file_sep>/src/test/java/io/codedifferently/HumanTest.java
package io.codedifferently;
import org.junit.Assert;
import org.junit.Test;
public class HumanTest {
@Test
public void constructorTest() {
// Given
String first = "Mickey";
String last = "Mouse";
int energy = 50;
// When
Human testHuman = new Human(first, last);
String actualFirst = testHuman.getFirst();
String actualLast = testHuman.getLast();
int actualEnergy = testHuman.getEnergy();
// Then
Assert.assertEquals(first, actualFirst);
Assert.assertEquals(last, actualLast);
Assert.assertEquals(energy, actualEnergy);
}
@Test
public void eatTest(){
// Given
Fruit pineapple = new Fruit("Pineapple", 10);
int expectedEnergy = 60;
Human testHuman = new Human("Lonnie","Jackson");
// When
testHuman.eat(pineapple);
int actualEnergy = testHuman.getEnergy();
// Then
Assert.assertEquals(expectedEnergy, actualEnergy);
}
@Test
public void worktest(){
// Given
Human testHuman = new Human("Bob", "<NAME>");
int expectedEnergy = 30;
// When
testHuman.work(2);
int actualEnergy = testHuman.getEnergy();
// Then
Assert.assertEquals(expectedEnergy, actualEnergy);
}
@Test
public void energyMaxTest(){
// Given
Human testHuman = new Human("Milton", "O'Neil");
Fruit watermelon = new Fruit("Watermelon", 20);
Fruit raspberries = new Fruit("Raspberries", 15);
Fruit orange = new Fruit("Orange", 20);
Human.maxEnergy = 100;
// When
testHuman.eat(watermelon); // energy: 50 -> 70
testHuman.eat(orange); // energy: 70 -> 90
testHuman.eat(raspberries);// energy: 90 -> 105 (maxes out at 100)
int actualEnergy = testHuman.getEnergy();
// Then
Assert.assertEquals(100, actualEnergy);
}
@Test
public void workMinTest() {
// Given
Human testHuman = new Human("Miles", "Morales");
// When
testHuman.work(6);
int actualEnergy = testHuman.getEnergy();
// Then
Assert.assertEquals(50, actualEnergy);
}
@Test
public void maxEnergyChangeTest(){
// Given
Human Jharell = new Human("Jharell", "Giles");
// When
Human.maxEnergy = 150;
Fruit watermelon = new Fruit("Watermelon", 20);
Fruit raspberries = new Fruit("Raspberries", 15);
Fruit orange = new Fruit("Orange", 20);
//Fruit apple = new Fruit("Apple", 20);
//Fruit banana = new Fruit("Banana", 20);
//Fruit papaya = new Fruit("Papaya", 20);
Jharell.eat(watermelon);
Jharell.eat(raspberries);
Jharell.eat(orange);
int actualEnergy = Jharell.getEnergy();
// Then
Assert.assertEquals(105, actualEnergy);
}
} | e5a641ed24eb2f439f1d447ff52a80963b916d99 | [
"Java"
] | 1 | Java | MalonHolmes/FirstObjectsDemo | b20bc3f91864f2f32a4aa3fe0c48097b2c1c3f14 | c5754d7ab6522f4c63c635826f15c7c38a7fd51f |
refs/heads/master | <file_sep>import bpy
from bpy.props import StringProperty, EnumProperty, PointerProperty, CollectionProperty, BoolProperty, IntProperty, FloatProperty, BoolVectorProperty, IntVectorProperty, FloatVectorProperty
from bpy.types import Operator, Panel, PropertyGroup, AddonPreferences
import os
from bpy.app.handlers import persistent
from . import functions as imfc
from bpy_extras.io_utils import ImportHelper, ExportHelper
bl_info = {
"name": "Script To Button",
"author": "RivinHD",
"blender": (2, 83, 3),
"version": (2, 00, 0),
"location": "View3D",
"category": "System",
"doc_url": "https://github.com/RivinHD/ScriptToButton/wiki",
"tracker_url": "https://github.com/RivinHD/ScriptToButton/issues"
}
classes = []
SpaceTypes = ["VIEW_3D","IMAGE_EDITOR","NODE_EDITOR","SEQUENCE_EDITOR","CLIP_EDITOR","DOPESHEET_EDITOR","GRAPH_EDITOR","NLA_EDITOR","TEXT_EDITOR"]
# Functions ----------------------------------------------------
@persistent
def LoadSaves(dummy = None):
try:
bpy.app.timers.unregister(LoadSaves)
bpy.app.handlers.depsgraph_update_pre.remove(LoadSaves)
except:
print("Already Loaded")
return
print("------------------Load-----------------")
btnFails = imfc.Load()
mes = "'''"
for name, Fails in zip(btnFails[0], btnFails[1]) :
if len(Fails[0]) or len(Fails[1]):
mes += "\n %s: " %name
mes += imfc.CreatFailmessage(Fails)
if bpy.data.texts.find('STB Fail Message') == -1:
if mes != "'''":
bpy.data.texts.new('STB Fail Message')
else:
bpy.data.texts['STB Fail Message'].clear()
if mes != "'''":
bpy.data.texts['STB Fail Message'].write(mes + "'''")
imfc.NotOneStart[0] = True
# Panles -------------------------------------------------------
def panelfactory(spaceType):
class STB_PT_Controls(bpy.types.Panel):
bl_idname = "STB_PT_Controls_%s" %spaceType
bl_label = "Controls"
bl_space_type = spaceType
bl_region_type = "UI"
bl_category = "Script To Button"
def draw(self, context):
layout = self.layout
p_stb = context.preferences.addons[__name__].preferences
col = layout.column()
row = col.row(align= True)
row.operator(STB_OT_AddButton.bl_idname, text= "Add", icon= 'ADD')
row.operator(STB_OT_RemoveButton.bl_idname, text= "Remove", icon= 'REMOVE')
if p_stb.Autosave:
row = col.row()
row.operator(STB_OT_Load.bl_idname, text= "Load")
row2 = row.row(align= True)
row2.scale_x = 1.2
row2.operator(STB_OT_Reload.bl_idname, text= "", icon= 'FILE_REFRESH')
row2.operator(SBT_OT_Rename.bl_idname, text= "", icon= 'GREASEPENCIL')
else:
row = col.row(align= True)
row.operator(STB_OT_Load.bl_idname, text= "Load")
row.operator(STB_OT_Save.bl_idname, text= "Save")
row = col.row(align= True)
row.operator(STB_OT_Reload.bl_idname, text= "Reload", icon= 'FILE_REFRESH')
row.operator(SBT_OT_Rename.bl_idname, text= "Rename", icon= 'GREASEPENCIL')
row = col.row(align= True)
row.operator(STB_OT_Export.bl_idname, text= "Export", icon= 'EXPORT')
row.operator(STB_OT_Import.bl_idname, text= "Import", icon= 'IMPORT')
STB_PT_Controls.__name__ = "STB_PT_Controls_%s" %spaceType
classes.append(STB_PT_Controls)
class STB_PT_Buttons(bpy.types.Panel):
bl_idname = "STB_PT_Buttons_%s" %spaceType
bl_label = "Buttons"
bl_space_type = spaceType
bl_region_type = "UI"
bl_category = "Script To Button"
def draw(self, context):
p_stb = context.preferences.addons[__name__].preferences
layout = self.layout
for i in range(len(context.scene.b_stb)):
btn = context.scene.b_stb[i]
area = STB_PT_Buttons.bl_idname[15:]
for A in btn.Areas:
if area == A.area:
row = layout.row(align= True)
row.prop(p_stb.SelctedButtonEnum[i], 'selected', toggle= True, text= "", icon= 'RADIOBUT_ON' if p_stb.SelctedButtonEnum[i].selected else 'RADIOBUT_OFF')
row.operator(STB_OT_ScriptButton.bl_idname, text= btn.name).btn_name = btn.name
break
STB_PT_Buttons.__name__ = "STB_PT_Buttons_%s" %spaceType
classes.append(STB_PT_Buttons)
class STB_PT_Properties(bpy.types.Panel):
bl_idname = "STB_PT_Properties_%s" %spaceType
bl_label = "Properties"
bl_space_type = spaceType
bl_region_type = "UI"
bl_category = "Script To Button"
def draw(self, context):
empty = True
propdrawn = False
layout = self.layout
b_stb = context.scene.b_stb
p_stb = context.preferences.addons[__name__].preferences
if len(b_stb):
btn = b_stb[p_stb['SelectedButton']]
col = layout.column(align= True)
for prop in btn.StringProps:
if prop.space == 'Panel':
box = col.box()
box.prop(prop, 'prop', text= prop.pname)
empty = False
if len(btn.StringProps):
col = layout.column(align= True)
for prop in btn.IntProps:
if prop.space == 'Panel':
box = col.box()
box.prop(prop, 'prop', text= prop.pname)
empty = False
if len(btn.IntProps):
col = layout.column(align= True)
for prop in btn.FloatProps:
if prop.space == 'Panel':
box = col.box()
box.prop(prop, 'prop', text= prop.pname)
empty = False
if len(btn.FloatProps):
col = layout.column(align= True)
for prop in btn.BoolProps:
if prop.space == 'Panel':
box = col.box()
box.prop(prop, 'prop', text= prop.pname)
empty = False
if len(btn.BoolProps):
col = layout.column(align= True)
for prop in btn.EnumProps:
if prop.space == 'Panel':
box = col.box()
box.prop(prop, 'prop', text= prop.pname)
empty = False
if len(btn.EnumProps):
col = layout.column(align= True)
for prop in btn.IntVectorProps:
if prop.space == 'Panel':
box = col.box()
box.prop(eval(prop.address), 'prop', text= prop.pname)
empty = False
if len(btn.IntVectorProps):
col = layout.column(align= True)
for prop in btn.FloatVectorProps:
if prop.space == 'Panel':
box = col.box()
box.prop(eval(prop.address), 'prop', text= prop.pname)
empty = False
if len(btn.FloatVectorProps):
col = layout.column(align= True)
for prop in btn.BoolVectorProps:
if prop.space == 'Panel':
box = col.box()
box.prop(eval(prop.address), 'prop', text= prop.pname)
empty = False
for props in btn.ListProps:
if props.space == 'Panel':
box = col.box()
box.label(text= props.pname)
empty = False
for prop in props.prop:
if prop.ptype.endswith("vector"):
box.prop(eval(eval("prop." + prop.ptype + "prop")), 'prop', text= "")
elif prop.ptype == 'enum':
box.prop(eval("prop." + prop.ptype + "prop"), 'prop', text= "")
else:
box.prop(prop, prop.ptype + "prop", text= "")
if len(btn.ListProps):
col = layout.column(align= True)
for props in btn.ObjectProps:
if prop.space == 'Panel':
box = col.box()
box.prop_search(props, 'prop', bpy.data, "objects", text= prop.pname)
empty = False
if empty:
col.label(text= "No Properties")
STB_PT_Properties.__name__ = "STB_PT_Properties_%s" %spaceType
classes.append(STB_PT_Properties)
# Operators -----------------------------------------------------
def SkipTextList(self, context):
return [(self.Text, self.Text, "")]
class STB_OT_AddButton(bpy.types.Operator):
bl_idname = "stb.addbutton"
bl_label = "Add Button"
bl_description = 'Add a script as Button to the "Buttons" Panel'
bl_options = {"REGISTER", "UNDO"}
ShowSkip: BoolProperty(default= False, name= "Show Skip")
Mode: EnumProperty(items= [("add", "Add", ""),("skip", "Skip", "")], name= "Change Mode", default= "add")
AllNames = []
Name : StringProperty(name= "Name")
Text : StringProperty(name= "Text")
TextList : EnumProperty(name= "Text", items= SkipTextList)
def execute(self, context):
p_stb = context.preferences.addons[__name__].preferences
p_stb.ButtonName = self.Name
txt = p_stb.TextsList
if self.ShowSkip:
txt = self.Text
if self.Mode == 'add':
if self.Name == '':
self.report({'ERROR'}, "You need a name for the Button")
return {"FINISHED"}
elif self.Name in self.AllNames:
self.report({'INFO'}, txt + " has been overwritten")
elif p_stb.TextsList == '':
self.report({'ERROR'}, "You need to select a Text")
return {"FINISHED"}
Fails = imfc.AddButton(p_stb, self.Name, txt)
if len(Fails[0]) or len(Fails[1]):
self.report({'ERROR'}, "Not all Areas or Properties could be added because the Syntax is invailid: %s" % imfc.CreatFailmessage(Fails))
p_stb.SelectedButton # Update this Enum
bpy.context.area.tag_redraw()
return {"FINISHED"}
def invoke(self, context, event):
p_stb = context.preferences.addons[__name__].preferences
self.AllNames = imfc.GetAllButtonnames()
if self.ShowSkip:
self.Name = p_stb.ButtonName
self.Text = p_stb.TextsList
return context.window_manager.invoke_props_dialog(self)
def draw(self, context):
p_stb = context.preferences.addons[__name__].preferences
layout = self.layout
if self.ShowSkip:
layout.prop(self, 'Mode', expand= True)
if self.Mode == 'add':
if p_stb.ButtonName in self.AllNames:
box = layout.box()
box.alert = True
box.label(text= '"' + p_stb.ButtonName + '" will be overwritten', icon= 'ERROR')
col = layout.column()
col.prop(self, 'Name')
col = layout.column()
if self.ShowSkip:
col.enabled = False
col.prop(self, 'TextList')
else:
col.prop(p_stb, 'TextsList')
classes.append(STB_OT_AddButton)
class STB_OT_ScriptButton(bpy.types.Operator):
bl_idname = "stb.scriptbutton"
bl_label = "ScriptButton"
bl_options = {"UNDO","INTERNAL"}
btn_name: StringProperty()
def execute(self, context):
text = bpy.data.texts[self.btn_name]
ctx = bpy.context.copy()
ctx['edit_text'] = text
try:
bpy.ops.text.run_script(ctx)
except:
error = imfc.GetConsoleError()
if error:
self.report({'ERROR'}, "The linked Script is not working\n\n%s" % error)
return {'CANCELLED'}
return {"FINISHED"}
def draw(self, context):
empty = True
propdrawn = False
layout = self.layout
b_stb = context.scene.b_stb
p_stb = context.preferences.addons[__name__].preferences
if len(b_stb):
btn = b_stb[self.btn_name]
col = layout.column(align= True)
for prop in btn.StringProps:
if prop.space == 'Dialog':
box = col.box()
box.prop(prop, 'prop', text= prop.pname)
empty = False
if len(btn.StringProps):
col = layout.column(align= True)
for prop in btn.IntProps:
if prop.space == 'Dialog':
box = col.box()
box.prop(prop, 'prop', text= prop.pname)
empty = False
if len(btn.IntProps):
col = layout.column(align= True)
for prop in btn.FloatProps:
if prop.space == 'Dialog':
box = col.box()
box.prop(prop, 'prop', text= prop.pname)
empty = False
if len(btn.FloatProps):
col = layout.column(align= True)
for prop in btn.BoolProps:
if prop.space == 'Dialog':
box = col.box()
box.prop(prop, 'prop', text= prop.pname)
empty = False
if len(btn.BoolProps):
col = layout.column(align= True)
for prop in btn.EnumProps:
if prop.space == 'Dialog':
box = col.box()
box.prop(prop, 'prop', text= prop.pname)
empty = False
if len(btn.EnumProps):
col = layout.column(align= True)
for prop in btn.IntVectorProps:
if prop.space == 'Dialog':
box = col.box()
box.prop(eval(prop.address), 'prop', text= prop.pname)
empty = False
if len(btn.IntVectorProps):
col = layout.column(align= True)
for prop in btn.FloatVectorProps:
if prop.space == 'Dialog':
box = col.box()
box.prop(eval(prop.address), 'prop', text= prop.pname)
empty = False
if len(btn.FloatVectorProps):
col = layout.column(align= True)
for prop in btn.BoolVectorProps:
if prop.space == 'Dialog':
box = col.box()
box.prop(eval(prop.address), 'prop', text= prop.pname)
empty = False
for props in btn.ListProps:
if props.space == 'Dialog':
box = col.box()
box.label(text= props.pname)
empty = False
for prop in props.prop:
if prop.ptype.endswith("vector"):
box.prop(eval(eval("prop." + prop.ptype + "prop")), 'prop', text= "")
elif prop.ptype == 'enum':
box.prop(eval("prop." + prop.ptype + "prop"), 'prop', text= "")
else:
box.prop(prop, prop.ptype + "prop", text= "")
if empty:
col.label(text= "No Properties")
def invoke(self, context, event):
notempty = False
b_stb = context.scene.b_stb
p_stb = context.preferences.addons[__name__].preferences
if len(b_stb):
btn = b_stb[self.btn_name]
for prop in btn.StringProps:
if prop.space == 'Dialog':
notempty = True
break
if notempty:
return context.window_manager.invoke_props_dialog(self)
for prop in btn.IntProps:
if prop.space == 'Dialog':
notempty = True
break
if notempty:
return context.window_manager.invoke_props_dialog(self)
for prop in btn.FloatProps:
if prop.space == 'Dialog':
notempty = True
break
if notempty:
return context.window_manager.invoke_props_dialog(self)
for prop in btn.BoolProps:
if prop.space == 'Dialog':
notempty = True
break
if notempty:
return context.window_manager.invoke_props_dialog(self)
for prop in btn.EnumProps:
if prop.space == 'Dialog':
notempty = True
break
if notempty:
return context.window_manager.invoke_props_dialog(self)
for prop in btn.IntVectorProps:
if prop.space == 'Dialog':
notempty = True
break
if notempty:
return context.window_manager.invoke_props_dialog(self)
for prop in btn.FloatVectorProps:
if prop.space == 'Dialog':
notempty = True
break
if notempty:
return context.window_manager.invoke_props_dialog(self)
for prop in btn.BoolVectorProps:
if prop.space == 'Dialog':
notempty = True
break
if notempty:
return context.window_manager.invoke_props_dialog(self)
for props in btn.ListProps:
if props.space == 'Dialog':
notempty = True
break
if notempty:
return context.window_manager.invoke_props_dialog(self)
else:
return self.execute(context)
classes.append(STB_OT_ScriptButton)
class STB_OT_RemoveButton(bpy.types.Operator):
bl_idname = "stb.removebutton"
bl_label = "Remove"
bl_description = "Delete the selected Button"
bl_options = {"REGISTER", "UNDO"}
deleteFile : BoolProperty(default= True, name= "Delete File", description= "Deletes the saved .py in the Storage")
deleteText : BoolProperty(default= True, name= "Delete Text", description= "Deletes the linked Text in the Texteditor")
def execute(self, context):
p_stb = context.preferences.addons[__name__].preferences
imfc.RemoveButton(p_stb, self.deleteFile, self.deleteText)
bpy.context.area.tag_redraw()
p_stb.SelectedButton # Update this Enum
return {"FINISHED"}
def draw(self, context):
layout = self.layout
layout.prop(self, 'deleteFile', text= "Delete File")
layout.prop(self, 'deleteText', text= "Delete Text")
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
classes.append(STB_OT_RemoveButton)
class TextsProperty(PropertyGroup):
txt_name: StringProperty()
select: BoolProperty(default= False)
classes.append(TextsProperty)
class STB_OT_Load(bpy.types.Operator):
bl_idname = "stb.load"
bl_label = "Load"
bl_description = "Load all Buttons from File or Texteditor"
bl_options = {"REGISTER", "UNDO"}
Mode: EnumProperty(name= "Load from ", items=[("file", "Load from Disk", ""), ("texteditor", "Load from Texteditor", "")], description= "Change the Mode which to load")
All: BoolProperty(name= "Load all", default= False, description= "Load all Buttons from the Texteditor")
Texts: CollectionProperty(type= TextsProperty, name= "Texts in Texteditor")
def execute(self, context):
p_stb = context.preferences.addons[__name__].preferences
if self.Mode == "file":
btnFails = imfc.Load()
elif self.Mode == "texteditor":
btnFails = imfc.LoadFromTexteditor(self, p_stb)
mes = "\n"
for name, Fails in zip(btnFails[0], btnFails[1]):
if len(Fails[0]) or len(Fails[1]):
mes += "\n %s:" %name
mes += imfc.CreatFailmessage(Fails)
if mes != "\n":
self.report({'ERROR'}, "Not all Areas or Properties could be added because the Syntax is invailid: %s" % mes)
bpy.context.area.tag_redraw()
p_stb.SelectedButton # Update this Enum
return {"FINISHED"}
def draw(self, context):
layout = self.layout
layout.prop(self, 'Mode', expand= True)
if self.Mode == "file":
# File -------------------------------------------
box = layout.box()
col = box.column()
col.scale_y = 0.8
col.label(text= "It will delete all your current Buttons", icon= "INFO")
col.label(text= "and replace it with the Buttons from the Disk", icon= "BLANK1")
else:
# Texteditor -------------------------------------
box = layout.box()
box.prop(self, 'All', text= "Load All", toggle= True)
if self.All:
for txt in self.Texts:
box.label(text= txt.txt_name, icon= 'CHECKBOX_HLT')
else:
for txt in self.Texts:
box.prop(txt, 'select', text= txt.txt_name)
def invoke(self, context, event):
self.Texts.clear()
for txt in bpy.data.texts:
new = self.Texts.add()
new.txt_name = txt.name
return context.window_manager.invoke_props_dialog(self)
classes.append(STB_OT_Load)
class STB_OT_Reload(bpy.types.Operator):
bl_idname = "stb.reload"
bl_label = "Reload"
bl_description = "Reload the linked Text in the Texteditor of the selected Button"
bl_options = {"REGISTER"}
def execute(self, context):
p_stb = context.preferences.addons[__name__].preferences
b_stb = context.scene.b_stb
txt_index = bpy.data.texts.find(p_stb.SelectedButton)
if txt_index != -1:
if p_stb.Autosave:
imfc.SaveText(bpy.data.texts[txt_index], p_stb.SelectedButton)
Fails = imfc.ReloadButtonText(b_stb[p_stb.SelectedButton], bpy.data.texts[txt_index].as_string())
if len(Fails[0]) or len(Fails[1]):
self.report({'ERROR'}, "Not all Areas or Properties could be added because the Syntax is invailid: %s" % imfc.CreatFailmessage(Fails))
else:
self.report({'ERROR'}, p_stb.SelectedButton + " could not be reloaded, linked Text in Texteditor don't exist.\n\nINFO: The linked Text must have the same name as the Button")
bpy.context.area.tag_redraw()
return {"FINISHED"}
classes.append(STB_OT_Reload)
class STB_OT_Save(bpy.types.Operator):
bl_idname = "stb.save"
bl_label = "Save"
bl_description = "Save all buttons to the Storage"
def execute(self, context):
for btn in context.scene.b_stb:
imfc.Save(bpy.data.texts[btn.name], btn.btn_name)
return {"FINISHED"}
classes.append(STB_OT_Save)
def get_filename_ext(self):
if self.Mode == "zip":
return ".zip"
else:
return "."
def get_use_filter_folder(self):
return self.Mode == "py"
class STB_OT_Export(bpy.types.Operator, ExportHelper):
bl_idname = "stb.export"
bl_label = "Export"
bl_description = "Export the selected Buttons"
All : BoolProperty(name= "All", description= "Export all Buttons")
Mode : EnumProperty(name= "Mode", items= [("py", "Export as .py Files", ""), ("zip", "Export as .zip File", "")])
filter_glob: StringProperty( default='*.zip', options={'HIDDEN'})
filename_ext : StringProperty(default= ".", get= get_filename_ext)
use_filter_folder : BoolProperty(default= True, get= get_use_filter_folder)
filepath : StringProperty(name= "File Path", maxlen= 1024, default= "")
def execute(self, context):
p_stb = context.preferences.addons[__name__].preferences
if self.Mode == "py":
if not os.path.isdir(self.filepath):
self.report({'ERROR'}, "The given filepath is not a dirctory")
return {'CANCELLED'}
else:
if not self.filepath.endswith(".zip"):
self.report({'ERROR'}, "The given filepath is not a .zip file")
return {'CANCELLED'}
imfc.Export(self.Mode, p_stb.MultiButtonSelection, p_stb, context, self.filepath)
return {"FINISHED"}
def draw(self, context):
p_stb = context.preferences.addons[__name__].preferences
layout = self.layout
layout.prop(self, 'Mode', expand= True)
box = layout.box()
box.prop(self, 'All')
for btn in p_stb.MultiButtonSelection:
if self.All:
box.label(text= btn.btn_name, icon= 'CHECKBOX_HLT')
else:
box.prop(btn, 'selected', text= btn.btn_name)
def invoke(self, context, invoke):
p_stb = context.preferences.addons[__name__].preferences
p_stb.MultiButtonSelection.clear()
for btn in context.scene.b_stb:
new = p_stb.MultiButtonSelection.add()
new.name = btn.name
new.btn_name = btn.btn_name
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
classes.append(STB_OT_Export)
class STB_OT_Import(bpy.types.Operator, ImportHelper):
bl_idname = "stb.import"
bl_label = "Import"
bl_description = "Import the seleceted Files"
filter_glob: StringProperty( default='*.zip;*.py', options={'HIDDEN'} )
files : CollectionProperty(type= PropertyGroup)
def execute(self, context):
p_stb = context.preferences.addons[__name__].preferences
notaddedfile = []
btnFails = ([],[])
directory = os.path.dirname(self.filepath)
for filep in self.files:
if filep.name.endswith(".zip"):
zipfails = imfc.ImportZip(os.path.join(directory, filep.name), context, p_stb)
btnFails[0].extend(zipfails[0])
btnFails[1].extend(zipfails[1])
elif filep.name.endswith(".py"):
pyfail = imfc.ImportPy(os.path.join(directory, filep.name), context, p_stb)
btnFails[0].extend(pyfail[0])
btnFails[1].append(pyfail[1])
else:
notaddedfile.append(filep)
mes = "Not all Files could be added:\n"
for notf in notaddedfile:
mes += notf + "\n"
mesFail = "Not all Areas or Properties could be added because the Syntax is invailid:\n"
for name, Fails in zip(btnFails[0], btnFails[1]) :
if len(Fails[0]) or len(Fails[1]):
mesFail += "\n %s:" %name
mesFail += imfc.CreatFailmessage(Fails)
if mes != "Not all Files could be added:\n" and mesFail != "Not all Areas or Properties could be added because the Syntax is invailid:\n":
self.report({'ERROR'}, mes + "\n\n" + mesFail)
elif mes != "Not all Files could be added:\n":
self.report({'ERROR'}, mes)
elif mesFail != "Not all Areas or Properties could be added because the Syntax is invailid:\n":
self.report({'ERROR'}, mesFail)
bpy.context.area.tag_redraw()
return {"FINISHED"}
classes.append(STB_OT_Import)
class SBT_OT_Rename(bpy.types.Operator):
bl_idname = "stb.rename"
bl_label = "Rename"
bl_description = "Rename the seleccted Button"
bl_options = {"UNDO"}
Name : StringProperty(name= "Name")
def execute(self, context):
p_stb = context.preferences.addons[__name__].preferences
imfc.Rename(p_stb, self.Name)
bpy.context.area.tag_redraw()
p_stb.SelectedButton # Update this Enum
return {"FINISHED"}
def draw(self ,context):
layout = self.layout
layout.prop(self, 'Name', text= "Name")
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
classes.append(SBT_OT_Rename)
# PropertyGroup ----------------------------------------------
class PropString(PropertyGroup):
prop: StringProperty(update= imfc.StringPropUpdate)
space: StringProperty()
pname: StringProperty()
linename: StringProperty()
line: IntProperty()
classes.append(PropString)
class PropInt(PropertyGroup):
prop: IntProperty(update= imfc.IntPropUpdate)
space: StringProperty()
pname: StringProperty()
linename: StringProperty()
line: IntProperty()
classes.append(PropInt)
class PropFloat(PropertyGroup):
prop: FloatProperty(update= imfc.FloatPropUpdate)
space: StringProperty()
pname: StringProperty()
linename: StringProperty()
line: IntProperty()
classes.append(PropFloat)
class PropBool(PropertyGroup):
prop: BoolProperty(update= imfc.BoolPropUpdate)
space: StringProperty()
pname: StringProperty()
linename: StringProperty()
line: IntProperty()
classes.append(PropBool)
class EnumItem(PropertyGroup):
item : StringProperty()
classes.append(EnumItem)
def e_items(self, context):
return imfc.ListToEnumitems([item.item for item in self.items])
class PropEnum(PropertyGroup):
prop: EnumProperty(items=e_items, update= imfc.EnumPropUpdate)
space: StringProperty()
pname: StringProperty()
linename: StringProperty()
line: IntProperty()
items : CollectionProperty(type= EnumItem)
classes.append(PropEnum)
class PropIntVector(PropertyGroup):
address: StringProperty()
space: StringProperty()
pname: StringProperty()
linename: StringProperty()
line: IntProperty()
classes.append(PropIntVector)
class PropFloatVector(PropertyGroup):
address: StringProperty()
space: StringProperty()
pname: StringProperty()
linename: StringProperty()
line: IntProperty()
classes.append(PropFloatVector)
class PropBoolVector(PropertyGroup):
address: StringProperty()
space: StringProperty()
pname: StringProperty()
linename: StringProperty()
line: IntProperty()
classes.append(PropBoolVector)
class EnumProp(PropertyGroup):
prop : EnumProperty(items= e_items, update= imfc.ListPropUpdate)
items : CollectionProperty(type= EnumItem)
classes.append(EnumProp)
class PropListProp(PropertyGroup):
strprop: StringProperty(update= imfc.ListPropUpdate)
intprop: IntProperty(update= imfc.ListPropUpdate)
floatprop: FloatProperty(update= imfc.ListPropUpdate)
boolprop: BoolProperty(update= imfc.ListPropUpdate)
enumprop: PointerProperty(type= EnumProp)
intvectorprop: StringProperty()
floatvectorprop: StringProperty()
boolvectorprop: StringProperty()
ptype: StringProperty()
classes.append(PropListProp)
class PropList(PropertyGroup):
prop: CollectionProperty(type= PropListProp)
space: StringProperty()
pname: StringProperty()
linename: StringProperty()
line: IntProperty()
classes.append(PropList)
class PropObject(PropertyGroup):
prop: StringProperty(update= imfc.ObjectPropUpdate)
space: StringProperty()
pname: StringProperty()
linename: StringProperty()
line: IntProperty()
classes.append(PropObject)
class ButtonArea(PropertyGroup):
area: StringProperty()
classes.append(ButtonArea)
class ButtonPropertys(PropertyGroup):
btn_name: StringProperty()
StringProps: CollectionProperty(type=PropString)
IntProps: CollectionProperty(type=PropInt)
FloatProps: CollectionProperty(type=PropFloat)
BoolProps: CollectionProperty(type=PropBool)
EnumProps: CollectionProperty(type=PropEnum)
IntVectorProps: CollectionProperty(type=PropIntVector)
FloatVectorProps: CollectionProperty(type=PropFloatVector)
BoolVectorProps: CollectionProperty(type=PropBoolVector)
ListProps: CollectionProperty(type= PropList)
ObjectProps: CollectionProperty(type= PropObject)
Areas: CollectionProperty(type= ButtonArea)
classes.append(ButtonPropertys)
class ButtonSelection(PropertyGroup):
selected : BoolProperty()
btn_name : StringProperty()
classes.append(ButtonSelection)
Icurrentselected = [None]
Ilastselected = [0]
def Radiobutton(self, context):
p_stb = context.preferences.addons[__name__].preferences
if self.selected and self.Index != Icurrentselected[0]:
Icurrentselected[0] = self.Index
if Ilastselected[0] != self.Index:
p_stb.SelctedButtonEnum[Ilastselected[0]].selected = False
p_stb['SelectedButton'] = self.Index
Ilastselected[0] = self.Index
elif not self.selected and self.Index == Ilastselected[0] and self.Index == Icurrentselected[0]:
self.selected = True
class ButtonEnum(PropertyGroup):
Index : IntProperty()
selected : BoolProperty(update=Radiobutton)
classes.append(ButtonEnum)
def textlist(self, context):
l = []
for i in bpy.data.texts:
st1 = i.name
st2 = i.name
st3 = ""
l.append((st1,st2,st3))
return l
def buttonlist(self, context):
return imfc.ListToEnumitems(imfc.GetAllButtonnames())
class STB_Properties(AddonPreferences):
bl_idname = __name__
ButtonName: StringProperty(name="Name", description="Set the name of the Button", default="")
TextsList: EnumProperty(name="Text", description="Chose a Text to convert into a Button", items=textlist)
Autosave: BoolProperty(name="Autosave", description="Save your changes automatically to the files", default=True)
SelctedButtonEnum : CollectionProperty(type=ButtonEnum)
SelectedButton: EnumProperty(items=buttonlist, name="INTERNAL")
SelectedEnum: IntProperty(name="INTERNAL")
MultiButtonSelection : CollectionProperty(type= ButtonSelection)
def draw(self, context):
layout = self.layout
layout.prop(self, 'Autosave')
classes.append(STB_Properties)
# Registration ================================================================================================
for spaceType in SpaceTypes:
panelfactory(spaceType)
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.Scene.b_stb = CollectionProperty(type=ButtonPropertys)
bpy.app.handlers.depsgraph_update_pre.append(LoadSaves)
bpy.app.timers.register(LoadSaves, first_interval = 3)
def unregister():
for ele in bpy.context.scene.b_stb:
for intvec in ele.IntVectorProps:
exec("del bpy.types.Scene.%s" % intvec.address.split(".")[-1])
for floatvec in ele.FloatVectorProps:
exec("del bpy.types.Scene.%s" % floatvec.address.split(".")[-1])
for boolvec in ele.BoolVectorProps:
exec("del bpy.types.Scene.%s" % boolvec.address.split(".")[-1])
del bpy.types.Scene.b_stb
try:
bpy.app.handlers.depsgraph_update_pre.remove(LoadSaves)
except:
pass
for cls in classes:
bpy.utils.unregister_class(cls)<file_sep>import os
import time
import bpy
import sys
import traceback
import zipfile
import threading
from bpy.props import IntVectorProperty, FloatVectorProperty, BoolVectorProperty, PointerProperty, StringProperty
from bpy.types import PropertyGroup
classes = []
NotOneStart = [False]
AllAreas = ["3D_Viewport", "UV_Editor", "Compositor", "Video_Sequencer", "Movie_Clip_Editor", "Dope_Sheet", "Graph_Editor", "Nonlinear_Animation", "Text_Editor"]
def SaveText(ActiveText, ScriptName):
text = ActiveText.as_string()
destination = os.path.dirname(os.path.abspath(__file__)) + "/Storage/" + ScriptName + ".py"
with open(destination, 'w', encoding='utf8') as outfile:
outfile.write(text)
def GetText(ScriptName):
destination = os.path.dirname(os.path.abspath(__file__)) + "/Storage/" + ScriptName + ".py"
if bpy.data.texts.find(ScriptName) == -1:
bpy.data.texts.new(ScriptName)
else:
bpy.data.texts[ScriptName].clear()
with open(destination, 'r', encoding='utf8') as infile:
bpy.data.texts[ScriptName].write(infile.read())
def GetAllSavedScripts():
path = os.path.dirname(os.path.abspath(__file__)) + "/Storage"
if not os.path.exists(path):
os.mkdir(path)
l = []
for file in os.listdir(path):
l.append(file.replace(".py",""))
return l
def Load():
scene = bpy.context.scene
scene.b_stb.clear()
p_stb = bpy.context.preferences.addons[__package__].preferences
p_stb.SelctedButtonEnum.clear()
btnFails = ([],[])
scripts = GetAllSavedScripts()
for i in range(len(scripts)):
script = scripts[i]
new = scene.b_stb.add()
new.name = script
new.btn_name = script
item = p_stb.SelctedButtonEnum.add()
item.Index = i
GetText(script)
btnFails[0].append(script)
btnFails[1].append(Add_AreasANDProps(new, bpy.data.texts[script].as_string()))
if len(p_stb.SelctedButtonEnum):
p_stb.SelctedButtonEnum[0].selected = True
return btnFails
def GetAllButtonnames():
l = []
for btn in bpy.context.scene.b_stb:
l.append(btn.btn_name)
return l
def ListToEnumitems(datalist):
l = []
for i in range(len(datalist)):
l.append((datalist[i], datalist[i], "", "", i))
return l
def GetAreas(text):
lines = text.splitlines()
if len(lines):
if lines[0].strip().startswith("#STB-Area-"):
areas = lines[0].replace(" ", "").split("///")
l = []
for area in areas:
if area.startswith("#STB-Area-"):
l.append(area.split("-")[2])
return l
else:
return AllAreas
else:
return []
def AreaParser(stbArea):
AreaParsDict = {
"3D_Viewport": "VIEW_3D",
"UV_Editor": "IMAGE_EDITOR",
"Image_Editor": "IMAGE_EDITOR",
"Compositor": "NODE_EDITOR",
"Texture_Node_Editor": "NODE_EDITOR",
"Shader_Editor": "NODE_EDITOR",
"Video_Sequencer": "SEQUENCE_EDITOR",
"Movie_Clip_Editor": "CLIP_EDITOR",
"Dope_Sheet": "DOPESHEET_EDITOR",
"Timeline": "DOPESHEET_EDITOR",
"Graph_Editor": "GRAPH_EDITOR",
"Drivers": "GRAPH_EDITOR",
"Nonlinear_Animation": "NLA_EDITOR",
"Text_Editor": "TEXT_EDITOR"
}
try:
return AreaParsDict[stbArea]
except:
return False # Add to Failstack
def GetProps(text):
lines = text.splitlines()
props = []
for i in range(len(lines)):
currentline = lines[i]
if currentline.strip().startswith("#STB-Input-"):
nextline = lines[i + 1]
if not nextline.startswith("#"):
inputs = currentline.replace(" ", "").split("///")
linename = nextline.split("=")[0]
valuestring = nextline.split("=")[1].split("#")[0].replace(" ", "")
for inp in inputs:
props.append({
"name": linename.strip(),
"linename": linename,
"space": inp.split("-")[2],
"type": inp.split("-")[3],
"line": i + 1,
"value": valuestring
})
return props
def AddProp(btn, prop):
try:
value = eval(prop["value"])
valuetype = type(value)
proptype = prop["type"]
if proptype == 'String': # Check types
if not valuetype is str:
return False
elif proptype == 'Int':
if not valuetype is int:
return False
elif proptype == 'Float':
if not valuetype is float:
return False
elif proptype == 'Bool':
if not valuetype is bool:
return False
elif proptype == 'Enum':
if not((valuetype is list or valuetype is tuple) and (isinstance(value[1], list) or isinstance(value[1], tuple)) and isinstance(value[0], str) and all(map(lambda x: isinstance(x, str), value[1]))):
return False
elif proptype == 'IntVector':
if not((valuetype is list or valuetype is tuple) and all(map(lambda x: isinstance(x, int), value)) and len(value) <= 32):
return False
elif proptype == 'FloatVector':
if not((valuetype is list or valuetype is tuple) and all(map(lambda x: isinstance(x, float), value)) and len(value) <= 32):
return False
elif proptype == 'BoolVector':
if not((valuetype is list or valuetype is tuple) and all(map(lambda x: isinstance(x, bool), value)) and len(value) <= 32):
return False
elif proptype == 'List':
if not(valuetype is list or valuetype is tuple):
return False
elif proptype == 'Object':
if not (valuetype is str or valuetype is bpy.types.Object):
return False
coll = eval("btn." + proptype + "Props.add()") # Add element to the right Propcollection
except:
return False # Add to Failstack
name = prop["name"]
coll.name = name # parse data
coll.pname = name
coll.linename = prop["linename"]
coll.space = prop["space"]
coll.line = prop["line"]
if proptype == 'Enum':
coll.items.clear()
for v in value[1]:
item = coll.items.add()
item.name = v
item.item = v
try:
coll.prop = value[0]
except:
coll.prop = value[1][0]
elif proptype == 'IntVector' or proptype == 'FloatVector' or proptype == 'BoolVector':
coll.address = Creat_VectorProp(len(value), (btn.btn_name + "_"+ name + str(coll.line)).replace(" ", ""), proptype, "bpy.context.scene.b_stb['%s'].%sProps['%s']" % (btn.name, proptype, name), proptype)
exec("%s.prop = value" %coll.address)
elif proptype == 'List':
coll.prop.clear()
for i in value:
prop = coll.prop.add()
itype = type(i)
if itype is list or itype is tuple:
if (itype is list or itype is tuple) and (isinstance(i[1], list) or isinstance(i[1], tuple)) and isinstance(i[0], str) and all(map(lambda x: isinstance(x, str), i[1])):
prop.enumprop.items.clear() #Enum
prop.ptype = 'enum'
for v in i[1]:
item = prop.enumprop.items.add()
item.name = v
item.item = v
try:
prop.enumprop.prop = i[0]
except:
prop.enumprop.prop = i[1][0]
elif (itype is list or itype is tuple) and all(map(lambda x: isinstance(x, bool), i)) and len(i) <= 32: #BoolVector
prop.boolvectorprop = Creat_VectorProp(len(i), (btn.btn_name + "_"+ name + "_list_" + str(len(coll.prop))).replace(" ", ""), "BoolVector", "bpy.context.scene.b_stb['%s'].ListProps['%s']"% (btn.name, name), "List")
prop.ptype = 'boolvector'
exec("%s.prop = i" %prop.boolvectorprop)
elif (itype is list or itype is tuple) and all(map(lambda x: isinstance(x, int), i)) and len(i) <= 32: #IntVector
prop.intvectorprop = Creat_VectorProp(len(i), (btn.btn_name + "_"+ name + "_list_" + str(len(coll.prop))).replace(" ", ""), "IntVector", "bpy.context.scene.b_stb['%s'].ListProps['%s']"% (btn.name, name), "List")
prop.ptype = 'intvector'
exec("%s.prop = i" %prop.intvectorprop)
elif (itype is list or itype is tuple) and all(map(lambda x: isinstance(x, float), i)) and len(i) <= 32: # FloatVector
prop.floatvectorprop = Creat_VectorProp(len(i), (btn.btn_name + "_"+ name + "_list_" + str(len(coll.prop))).replace(" ", ""), "FloatVector", "bpy.context.scene.b_stb['%s'].ListProps['%s']"% (btn.name, name), "List")
prop.ptype = 'floatvector'
exec("%s.prop = i" %prop.floatvectorprop)
else:
prop.strprop = str(i)
prop.ptype = 'str'
else:
exec("prop." + str(itype.__name__)+ "prop = i")
prop.ptype = str(itype.__name__)
elif proptype == 'Object':
coll.prop = value.name
else:
coll.prop = value
def AddButton(p_stb, name, textname):
texts = bpy.data.texts
text = texts[textname].as_string() # Get selected Text
if p_stb.Autosave:
SaveText(texts[textname], name)
GetText(name) # do same as lower, but with File
else:
if texts.find(textname) == -1: # Creat new text if not exist
texts.new(textname)
else:
texts[textname].clear()
texts[textname].write(text) # Write to Text
index = bpy.context.scene.b_stb.find(name)
if index != -1:
bpy.context.scene.b_stb.remove(index)
new = bpy.context.scene.b_stb.add() # Create new Instance
new.name = name
new.btn_name = name
item = p_stb.SelctedButtonEnum.add()
item.Index = len(p_stb.SelctedButtonEnum) - 1
return Add_AreasANDProps(new, text)
def RemoveButton(p_stb, deleteFile, deleteText):
index = p_stb['SelectedButton']
b_stb = bpy.context.scene.b_stb
if deleteFile:
os.remove(os.path.dirname(__file__) + "/Storage/" + p_stb.SelectedButton + ".py")
if deleteText:
bpy.data.texts.remove(bpy.data.texts[p_stb.SelectedButton])
Delete_VectorProps(b_stb[p_stb.SelectedButton])
Delet_ListProp(b_stb[p_stb.SelectedButton])
b_stb.remove(b_stb.find(p_stb.SelectedButton))
if index - 1 >= 0:
p_stb.SelctedButtonEnum[index - 1].selected = index >= len(p_stb.SelctedButtonEnum) - 1
p_stb.SelctedButtonEnum.remove(len(p_stb.SelctedButtonEnum) - 1)
def CreatFailmessage(Fails):
mess = "\n"
if len(Fails[0]):
mess += " Areas: \n"
for fail in Fails[0]:
mess += " Line: 0 #STB-Area-%s \n" %fail
if len(Fails[1]):
mess += " Properties: \n"
for fail in Fails[1]:
mfail = "Line: " + str(fail['line']) + " #STB-Input-" + str(fail['space']) + "-" + str(fail['type'] + " " + str(fail['value']))
mess += " %s \n" %mfail
return mess
def LoadFromTexteditor(opt, p_stb):
btnFails = ([],[])
if opt.All:
for txt in opt.Texts: # All Texts from Buttons
btn_index = bpy.context.scene.b_stb.find(txt.txt_name)
if btn_index != -1:
btnFails[0].append(txt.txt_name)
btnFails[1].append(ReloadButtonText(bpy.context.scene.b_stb[btn_index], bpy.data.texts[txt.txt_name].as_string()))
if p_stb.Autosave:
SaveText(bpy.data.texts[txt.txt_name], txt.txt_name)
else:
LoadAddButton(p_stb, txt.txt_name)
else:
for txt in opt.Texts:
if txt.select: # selected Texts from Buttons
btn_index = bpy.context.scene.b_stb.find(txt.txt_name)
if btn_index != -1:
btnFails[0].append(txt.txt_name)
btnFails[1].append(ReloadButtonText(bpy.context.scene.b_stb[btn_index], bpy.data.texts[txt.txt_name].as_string()))
if p_stb.Autosave:
SaveText(bpy.data.texts[txt.txt_name], txt.txt_name)
else:
LoadAddButton(p_stb, txt.txt_name)
return btnFails
Propdatatyp = ["String", "Int", "Float", "Bool", "Enum", "IntVector", "FloatVector", "BoolVector", "List", "Object"]
def LoadAddButton(p_stb, name):
p_stb.ButtonName = name
p_stb.TextsList = name
end = bpy.ops.stb.addbutton('INVOKE_DEFAULT',ShowSkip=True)
def ReloadButtonText(btn,text):
Delete_VectorProps(btn)
Delet_ListProp(btn)
return Add_AreasANDProps(btn, text)
def Add_AreasANDProps(btn, text):
btn.Areas.clear() # Clear Area and Prop
for prop in Propdatatyp:
eval("btn." + prop + "Props.clear()")
AreaList = GetAreas(text)# Get Areas
FaildAreas = []
for ele in AreaList: # Add Areas
pars = AreaParser(ele)
if pars is False:
FaildAreas.append(ele)
else:
new = btn.Areas.add()
new.name = pars
new.area = pars
if len(AreaList) == len(FaildAreas):
for ele in AllAreas: # Add All Areas, when no writen rea has a vailid Syntax
pars = AreaParser(ele)
new = btn.Areas.add()
new.name = pars
new.area = pars
PropListDict = GetProps(text) # Get Props
FailedProps = []
for ele in PropListDict: # Add Props
if AddProp(btn, ele) is False:
FailedProps.append(ele)
return (FaildAreas, FailedProps)
def Creat_VectorProp(vsize, name, vectortyp, backaddress, update):
class VectorProp(PropertyGroup):
exec("prop : %sProperty(size= %d, update= %sPropUpdate)" % (vectortyp, vsize, update))
address : StringProperty(default= backaddress)
VectorProp.__name__ = "VectorProp_%s_%s" % (vectortyp, name)
bpy.utils.register_class(VectorProp)
exec("bpy.types.Scene.stb_%sproperty_%s = PointerProperty(type= VectorProp)" % (vectortyp.lower(), name))
return "bpy.context.scene.stb_%sproperty_%s" %(vectortyp.lower(), name)
def unregister_vector():
for cls in classes:
bpy.utils.unregister_class(cls)
def Delete_VectorProps(btn):
for intvec in btn.IntVectorProps:
name = intvec.address.split(".")[-1]
exec("del bpy.types.Scene.%s" % name)
exec("del bpy.context.scene['%s']" % name)
for floatvec in btn.FloatVectorProps:
name = floatvec.address.split(".")[-1]
exec("del bpy.types.Scene.%s" % name)
exec("del bpy.context.scene['%s']" % name)
for boolvec in btn.BoolVectorProps:
name = boolvec.address.split(".")[-1]
exec("del bpy.types.Scene.%s" % name)
exec("del bpy.context.scene['%s']" % name)
def Delet_ListProp(btn):
for l in btn.ListProps:
for prop in l.prop:
if prop.ptype == 'intvector':
name = prop.intvectorprop.split(".")[-1]
exec("del bpy.types.Scene.%s" % name)
exec("del bpy.context.scene['%s']" % name)
elif prop.ptype == 'floatvector':
name = prop.floatvectorprop.split(".")[-1]
exec("del bpy.types.Scene.%s" % name)
exec("del bpy.context.scene['%s']" % name)
elif prop.ptype == 'boolvector':
name = prop.boolvectorprop.split(".")[-1]
exec("del bpy.types.Scene.%s" % name)
exec("del bpy.context.scene['%s']" % name)
def StringPropUpdate(self, context):
txt = self.prop.replace('"', '\\"').replace("'", "\\'")
UpdateText(self.line, self.linename, '"%s"'% txt, eval("bpy.context.scene." + self.path_from_id().split(".")[0]))
def IntPropUpdate(self, context):
UpdateText(self.line, self.linename, self.prop, eval("bpy.context.scene." + self.path_from_id().split(".")[0]))
def FloatPropUpdate(self, context):
UpdateText(self.line, self.linename, self.prop, eval("bpy.context.scene." + self.path_from_id().split(".")[0]))
def BoolPropUpdate(self, context):
UpdateText(self.line, self.linename, self.prop, eval("bpy.context.scene." + self.path_from_id().split(".")[0]))
def EnumPropUpdate(self, context):
UpdateText(self.line, self.linename, [self.prop,[item.item for item in self.items]], eval("bpy.context.scene." + self.path_from_id().split(".")[0]))
def IntVectorPropUpdate(self, context):
Prop = eval(self.address)
UpdateText(Prop.line, Prop.linename, [ele for ele in self.prop], eval("bpy.context.scene." + Prop.path_from_id().split(".")[0]))
def FloatVectorPropUpdate(self, context):
Prop = eval(self.address)
UpdateText(Prop.line, Prop.linename, [ele for ele in self.prop], eval("bpy.context.scene." + Prop.path_from_id().split(".")[0]))
def BoolVectorPropUpdate(self, context):
Prop = eval(self.address)
UpdateText(Prop.line, Prop.linename, [ele for ele in self.prop], eval("bpy.context.scene." + Prop.path_from_id().split(".")[0]))
def ListPropUpdate(self, context):
split = self.path_from_id().split(".")
if len(split) > 1:
Prop = eval("bpy.context.scene." + ".".join(split[:2]))
else:
Prop = eval(self.address)
UpdateText(Prop.line, Prop.linename, [TypeGetter(ele, ele.ptype) for ele in Prop.prop], eval("bpy.context.scene." + Prop.path_from_id().split(".")[0]))
def ObjectPropUpdate(self, context):
UpdateText(self.line, self.linename, "bpy.data.objects['" + self.prop + "']" if self.prop != '' else "''" , eval("bpy.context.scene." + self.path_from_id().split(".")[0]))
def UpdateText(linepos, varname, message, btn):
if NotOneStart[0]:
text = bpy.data.texts[btn.name]
text.lines[linepos].body = varname + "= " + str(message)
txt = text.as_string()
text.clear()
text.write(txt)
def TypeGetter(value, vtype):
if vtype == 'str':
return value.strprop
elif vtype == 'int':
return value.intprop
elif vtype == 'float':
return value.floatprop
elif vtype == 'bool':
return value.boolprop
elif vtype == 'enum':
return [value.enumprop.prop, [item.item for item in value.enumprop.items]]
elif vtype == 'intvector':
return [i for i in eval(value.intvectorprop + "['prop']")]
elif vtype == 'floatvector':
return [i for i in eval(value.floatvectorprop + "['prop']")]
elif vtype == 'boolvector':
return [bool(i) for i in eval(value.boolvectorprop + "['prop']")]
def GetConsoleError():
lasttb = sys.last_traceback
if lasttb is None:
return False
error = ""
for tb in traceback.extract_tb(lasttb):
error += ' File "' + str(tb.filename) +'", line ' + str(tb.lineno) + ", in " + tb.name +"\n"
return 'Traceback (most recent call last):\n'+ error + str(sys.last_type.__name__) + ": " + str(sys.last_value)
def Export(mode, selections, p_stb, context, dir_filepath):
if mode == "py":
for selc in selections:
path = os.path.join(dir_filepath, selc.btn_name + ".py")
with open(path, 'w', encoding='utf8') as pyfile:
pyfile.write(bpy.data.texts[selc.name].as_string())
else:
folderpath = os.path.join(bpy.app.tempdir, "STB_Zip")
if not os.path.exists(folderpath):
os.mkdir(folderpath)
with zipfile.ZipFile(dir_filepath, 'w') as zip_it:
for selc in selections:
zip_path = folderpath + "/" + selc.btn_name + ".py"
with open(zip_path, 'w', encoding='utf8') as recfile:
recfile.write(bpy.data.texts[selc.name].as_string())
zip_it.write(zip_path, selc.btn_name + ".py")
os.remove(zip_path)
os.rmdir(folderpath)
def ImportZip(filepath, context, p_stb):
btnFails = ([],[])
with zipfile.ZipFile(filepath, 'r') as zip_out:
filepaths = []
for i in zip_out.namelist():
if i.endswith(".py"):
filepaths.append(i)
for filep in filepaths:
txt = str(zip_out.read(filep))
Fail = ImportButton(filep, context, p_stb, txt)
btnFails[0].extend(Fail[0])
btnFails[1].append(Fail[1])
return btnFails
def ImportPy(filepath, context, p_stb):
with open(filepath, 'r', encoding='utf8') as pyfile:
txt = pyfile.read()
return ImportButton(filepath, context, p_stb, txt)
def ImportButton(filepath, context, p_stb, txt):
name = CheckForDublicates([i.name for i in bpy.data.texts], os.path.splitext(os.path.basename(filepath))[0])
bpy.data.texts.new(name)
bpy.data.texts[name].write(txt)
btn = context.scene.b_stb.add()
btn.name = name
btn.btn_name = name
item = p_stb.SelctedButtonEnum.add()
item.Index = len(p_stb.SelctedButtonEnum) - 1
if p_stb.Autosave:
SaveText(bpy.data.texts[name], name)
Fails = Add_AreasANDProps(btn, txt)
return ([name],Fails)
def CheckForDublicates(l, name, num = 1): #Check for name dublicates and appen .001, .002 etc.
if name in l:
return CheckForDublicates(l, name.split("_")[0] +"_{0:03d}".format(num), num + 1)
return name
def Rename(p_stb, name):
btn = bpy.context.scene.b_stb[p_stb.SelectedButton]
text = bpy.data.texts[p_stb.SelectedButton]
os.remove(os.path.dirname(os.path.abspath(__file__)) + "/Storage/" + btn.btn_name + ".py")
if name != btn.btn_name:
name = CheckForDublicates(GetAllButtonnames(), name)
btn.name = name
btn.btn_name = name
text.name = name
if p_stb.Autosave:
SaveText(text, name) | 488feead6c9a0e862805f916bb3ddfa759d12a99 | [
"Python"
] | 2 | Python | DruidTin/ScriptToButton | 596d1acb8a84470861dcfc3ba160c4069b1c5540 | cf8952e8d25b7672b5295f51a1f5f9946421320c |
refs/heads/master | <file_sep># Unreleased
# 0.4.2 (2021-08-06)
- Pass UNIX path separators to `aapt` on non-UNIX systems, ensuring the resulting separator is compatible with the target device instead of the host platform.
# 0.4.1 (2021-08-02)
- Only the highest platform supported by the NDK is now selected as default platform.
# 0.4.0 (2021-07-06)
- Added `add_runtime_libs` function for including extra dynamic libraries in the APK.
# 0.3.0 (2021-05-10)
- New `ApkConfig` field `apk_name` is now used for APK file naming, instead of the application label.
- Renamed `cargo_apk` utility to `cargo_ndk`.
# 0.2.0 (2021-04-20)
- **Breaking:** refactored `Manifest` into a proper (de)serialization struct. `Manifest` now closely matches [`an android manifest file`](https://developer.android.com/guide/topics/manifest/manifest-element).
- **Breaking:** removed `Config` in favor of using the new `Manifest` struct directly. Instead of using `Config::from_config` to create a `Manifest`, now you instantiate `Manifest` directly using, almost all, the same values.
# 0.1.4 (2020-11-25)
- On Windows, fixed UNC path handling for resource folder.
# 0.1.3 (2020-11-21)
- `android:launchMode` is configurable.
# 0.1.2 (2020-09-15)
- `android:label` is configurable.
- Library search paths are much more intelligent.
- `android:screenOrientation` is configurable.
# 0.1.1 (2020-07-15)
- Added support for custom intent filters.
- On Windows, fixed UNC path handling.
- Fixed toolchain path handling when the NDK installation has no host arch suffix on its prebuilt LLVM directories.
# 0.1.0 (2020-04-22)
- Initial release! 🎉
<file_sep># Unreleased
- **Breaking:** Replace `add_fd_with_callback` `ident` with constant value `ALOOPER_POLL_CALLBACK`,
as per https://developer.android.com/ndk/reference/group/looper#alooper_addfd.
- **Breaking:** Accept unboxed closure in `add_fd_with_callback`.
- ndk/aaudio: Replace "Added in" comments with missing `#[cfg(feature)]`
- ndk/aaudio: Add missing `fn get_allowed_capture_policy()`
- ndk/configuration: Add missing `api-level-30` feature to `fn screen_round()`
# 0.4.0 (2021-08-02)
- **Breaking:** Model looper file descriptor events integer as `bitflags`.
# 0.3.0 (2021-01-30)
- **Breaking:** Looper `ident` not passed in `data` pointer anymore.
`attach_looper` now only sets the `ident` field when attaching an
`InputQueue` to a `ForeignLooper`.
If you are relying on `Poll::Event::data` to tell event fd and
input queue apart, please use `Poll::Event::ident` and the new
constants introduced in `ndk-glue`!
# 0.2.1 (2020-10-15)
- Fix documentation build on docs.rs
# 0.2.0 (2020-09-15)
- **Breaking:** Updated to use [ndk-sys 0.2.0](../ndk-sys/CHANGELOG.md#020-2020-09-15)
- Added `media` bindings
- Added `bitmap` and `hardware_buffer` bindings
- Added `aaudio` bindings
- Fixed assets directory path to be relative to the manifest
- Added `trace` feature for native tracing
# 0.1.0 (2020-04-22)
- Initial release! 🎉
<file_sep>use crate::error::NdkError;
use crate::manifest::AndroidManifest;
use crate::ndk::{Key, Ndk};
use crate::target::Target;
use std::ffi::OsStr;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
pub struct ApkConfig {
pub ndk: Ndk,
pub build_dir: PathBuf,
pub apk_name: String,
pub assets: Option<PathBuf>,
pub resources: Option<PathBuf>,
pub manifest: AndroidManifest,
}
impl ApkConfig {
fn build_tool(&self, tool: &'static str) -> Result<Command, NdkError> {
let mut cmd = self.ndk.build_tool(tool)?;
cmd.current_dir(&self.build_dir);
Ok(cmd)
}
fn unaligned_apk(&self) -> PathBuf {
self.build_dir
.join(format!("{}-unaligned.apk", self.apk_name))
}
fn apk(&self) -> PathBuf {
self.build_dir.join(format!("{}.apk", self.apk_name))
}
pub fn create_apk(&self) -> Result<UnalignedApk, NdkError> {
std::fs::create_dir_all(&self.build_dir)?;
self.manifest.write_to(&self.build_dir)?;
let target_sdk_version = self
.manifest
.sdk
.target_sdk_version
.unwrap_or_else(|| self.ndk.default_platform());
let mut aapt = self.build_tool(bin!("aapt"))?;
aapt.arg("package")
.arg("-f")
.arg("-F")
.arg(self.unaligned_apk())
.arg("-M")
.arg("AndroidManifest.xml")
.arg("-I")
.arg(self.ndk.android_jar(target_sdk_version)?);
if let Some(res) = &self.resources {
aapt.arg("-S").arg(res);
}
if let Some(assets) = &self.assets {
aapt.arg("-A").arg(assets);
}
if !aapt.status()?.success() {
return Err(NdkError::CmdFailed(aapt));
}
Ok(UnalignedApk(self))
}
}
pub struct UnalignedApk<'a>(&'a ApkConfig);
impl<'a> UnalignedApk<'a> {
pub fn config(&self) -> &ApkConfig {
self.0
}
pub fn add_lib(&self, path: &Path, target: Target) -> Result<(), NdkError> {
if !path.exists() {
return Err(NdkError::PathNotFound(path.into()));
}
let abi = target.android_abi();
let lib_path = Path::new("lib").join(abi).join(path.file_name().unwrap());
let out = self.0.build_dir.join(&lib_path);
std::fs::create_dir_all(out.parent().unwrap())?;
std::fs::copy(path, out)?;
// Pass UNIX path separators to `aapt` on non-UNIX systems, ensuring the resulting separator
// is compatible with the target device instead of the host platform.
// Otherwise, it results in a runtime error when loading the NativeActivity `.so` library.
let lib_path_unix = lib_path.to_str().unwrap().replace("\\", "/");
let mut aapt = self.0.build_tool(bin!("aapt"))?;
aapt.arg("add")
.arg(self.0.unaligned_apk())
.arg(lib_path_unix);
if !aapt.status()?.success() {
return Err(NdkError::CmdFailed(aapt));
}
Ok(())
}
pub fn add_runtime_libs(
&self,
path: &Path,
target: Target,
search_paths: &[&Path],
) -> Result<(), NdkError> {
let abi_dir = path.join(target.android_abi());
for entry in fs::read_dir(&abi_dir).map_err(|e| NdkError::IoPathError(e, abi_dir))? {
let entry = entry?;
let path = entry.path();
if path.extension() == Some(OsStr::new("so")) {
self.add_lib_recursively(&path, target, search_paths)?;
}
}
Ok(())
}
pub fn align(self) -> Result<UnsignedApk<'a>, NdkError> {
let mut zipalign = self.0.build_tool(bin!("zipalign"))?;
zipalign
.arg("-f")
.arg("-v")
.arg("4")
.arg(self.0.unaligned_apk())
.arg(self.0.apk());
if !zipalign.status()?.success() {
return Err(NdkError::CmdFailed(zipalign));
}
Ok(UnsignedApk(self.0))
}
}
pub struct UnsignedApk<'a>(&'a ApkConfig);
impl<'a> UnsignedApk<'a> {
pub fn sign(self, key: Key) -> Result<Apk, NdkError> {
let mut apksigner = self.0.build_tool(bat!("apksigner"))?;
apksigner
.arg("sign")
.arg("--ks")
.arg(&key.path)
.arg("--ks-pass")
.arg(format!("pass:{}", &key.password))
.arg(self.0.apk());
if !apksigner.status()?.success() {
return Err(NdkError::CmdFailed(apksigner));
}
Ok(Apk::from_config(self.0))
}
}
pub struct Apk {
path: PathBuf,
package_name: String,
ndk: Ndk,
}
impl Apk {
pub fn from_config(config: &ApkConfig) -> Self {
let ndk = config.ndk.clone();
Self {
path: config.apk(),
package_name: config.manifest.package.clone(),
ndk,
}
}
pub fn install(&self) -> Result<(), NdkError> {
let mut adb = self.ndk.platform_tool(bin!("adb"))?;
adb.arg("install").arg("-r").arg(&self.path);
if !adb.status()?.success() {
return Err(NdkError::CmdFailed(adb));
}
Ok(())
}
pub fn start(&self) -> Result<(), NdkError> {
let mut adb = self.ndk.platform_tool(bin!("adb"))?;
adb.arg("shell")
.arg("am")
.arg("start")
.arg("-a")
.arg("android.intent.action.MAIN")
.arg("-n")
.arg(format!("{}/android.app.NativeActivity", &self.package_name));
if !adb.status()?.success() {
return Err(NdkError::CmdFailed(adb));
}
Ok(())
}
}
<file_sep># Unreleased
- Document when to lock and unlock the window/input queue when certain events are received.
# 0.4.0 (2021-08-02)
- Looper is now created before returning from `ANativeActivity_onCreate`, solving
race conditions in `onInputQueueCreated`.
- Event pipe and looper are now notified of removal _before_ destroying `NativeWindow`
and `InputQueue`. This allows applications to unlock their read-locks of these instances
first (which they are supposed to hold on to during use) instead of deadlocking in
Android callbacks.
- Reexport `android_logger` and `log` from the crate root for `ndk-macro` to use.
- Use new `FdEvents` `bitflags` for looper file descriptor events.
- Update to `ndk` 0.4.0.
This minor dependency bump causes a minor bump for `ndk-glue` too.
# 0.3.0 (2021-01-30)
- **Breaking:** Looper `ident` not passed in `data` pointer anymore.
If you are relying on `Poll::Event::data` to tell event fd and
input queue apart, please use `Poll::Event::ident` and the new
constants introduced in `ndk-glue`!
# 0.2.1 (2020-10-15)
- Fix documentation build on docs.rs
# 0.2.0 (2020-09-15)
- **Breaking:** Removed `ndk_glue` macro in favor of new `main` attribute macro.
# 0.1.0 (2020-04-22)
- Initial release! 🎉
<file_sep># Unreleased
- Fixed the library name in case of multiple build artifacts in the Android manifest.
# 0.8.1 (2021-08-06)
- Updated to use [ndk-build 0.4.2](../ndk-build/CHANGELOG.md#042-2021-08-06)
# 0.8.0 (2021-07-06)
- Added `runtime_libs` path to android metadata for packaging extra dynamic libraries into the apk.
# 0.7.0 (2021-05-10)
- Added `cargo apk check`. Useful for compile-testing crates that contain C/C++ dependencies or
target-specific conditional compilation, but do not provide a cdylib target.
- Added `apk_name` field to android metadata for APK file naming (defaults to Rust library name if unspecified).
The application label is now no longer used for this purpose, and can contain a string resource ID from now on.
# 0.6.0 (2021-04-20)
- **Breaking:** uses `ndk-build`'s new (de)serialized `Manifest` struct to properly serialize a toml's `[package.metadata.android]` to an `AndroidManifest.xml`. The `[package.metadata.android]` now closely resembles the structure of [an android manifest file](https://developer.android.com/guide/topics/manifest/manifest-element). See [README](README.md) for an example of the new `[package.metadata.android]` structure and all manifest attributes that are currently supported.
# 0.5.6 (2020-11-25)
- Use `dunce::simplified` when extracting the manifest's assets and resource folder
- Updated to use [ndk-build 0.1.4](../ndk-build/CHANGELOG.md#014-2020-11-25)
# 0.5.5 (2020-11-21)
- Updated to use [ndk-build 0.1.3](../ndk-build/CHANGELOG.md#013-2020-11-21)
# 0.5.4 (2020-11-01)
- Added support for activity metadata entries.
- Fix glob member resolution in workspaces.
# 0.5.3 (2020-10-15)
- Fix `res` folder resolve.
# 0.5.2 (2020-09-15)
- Updated to use [ndk-build 0.1.2](../ndk-build/CHANGELOG.md#012-2020-09-15)
# 0.5.1 (2020-07-15)
- Updated to use [ndk-build 0.1.1](../ndk-build/CHANGELOG.md#011-2020-07-15)
# 0.5.0 (2020-04-22)
- Updated to use [ndk-build 0.1.0](../ndk-build/CHANGELOG.md#010-2020-04-22)
- First release in almost 3 years! 🎉
- **Breaking:** A ton of things changed!
| 8bc96709367360dbb3b793ed7389db5b579446fe | [
"Markdown",
"Rust"
] | 5 | Markdown | snow2flying/android-ndk-rs | e8f52d2a3bde47250b4e49563ae23a05ede272cd | f1413ae040b9abcfbf15ff15f67492b558965a9e |
refs/heads/main | <file_sep># This is a chat app built around sockets in python
import socket
import time
# parameters for connection
SERVER_HOST = "0.0.0.0"
SERVER_PORT = 80
BUFFER_SIZE = 1024
# create socket
s = socket.socket()
print(f"[*] Listening at {SERVER_HOST}:{SERVER_PORT}")
s.bind((SERVER_HOST, SERVER_PORT))
s.listen(5)
client_socket, client_addr = s.accept()
print(f"[+] Connected to {client_addr}! \nReady to chat on Encrypted Channel \n\n")
def msg():
def receive():
while True:
msgs = client_socket.recv(BUFFER_SIZE).decode()
if msgs != "r":
print(f"--> {msgs}")
elif msgs == "r":
send()
def send():
while True:
msgs = input("Type Message > ")
client_socket.send(msgs.encode())
if msgs == "end":
exit()
elif msgs == "r":
receive()
send()
send()
msg()
<file_sep># This is a chat app built around sockets in python
import socket
import time
# parameters for connection
SERVER_HOST = "192.168.43.150"
SERVER_PORT = 80
BUFFER_SIZE = 1024
# create socket
s = socket.socket()
print(f"[+] Connecting to {SERVER_HOST}:{SERVER_PORT}")
time.sleep(3)
s.connect((SERVER_HOST, SERVER_PORT))
print("Connected! Ready to Chat on Encrypted Channel \n\n")
def msg():
def receive():
while True:
msgs = s.recv(BUFFER_SIZE).decode()
if msgs != "r":
print(f"--> {msgs}")
elif msgs == "r":
send()
def send():
while True:
msgs = input("Type Message > ")
s.send(msgs.encode())
if msgs == "end":
exit()
elif msgs == "r":
receive()
send()
receive()
msg()
<file_sep># chat-app
Terminal-based Chat App built around Sockets in Python
| e571f723a3c95cde4e74b5a314c02172d82c85d6 | [
"Markdown",
"Python"
] | 3 | Python | uzowis/chat-app | 0f1f4d995bc863baccc01cdaf1c60ad13d262685 | c4c77f8f588926bc8d8724a10d7127a3f913d1d4 |
refs/heads/master | <file_sep>import math
import random
import numpy as np
def pixel_classifier_scan(sampleName):
"""
This function takes in the name of a sample and calls the pixel classification method that looks only at the values
of the pixel's mechanical properties.
Inputs: sampleName - a string of the sample's name, excluding filetype extension. Assumes .txt filetype
Outputs: pixel_identities - a 2D array of the classifications of the each pixel within the scan
*writes a 2D .txt file of the original data + the new classifications
"""
scan = np.loadtxt('../Data/AFM/AggregatedData/%s.txt'% (sampleName))
x2, z = scan.shape
x = y = int(math.sqrt(x2))
scan = scan.reshape((x, y, z))
pixel_identities = np.empty((x, y))
for i in range(x):
for j in range(y):
pixel_identities[i, j] = pixel_classifier_pixel(scan[i, j])
if z == 5:
scan = scan.reshape((x2, z))
pixel_identities_1d = pixel_identities.reshape((x2, 1))
scan_and_classif = np.append(scan, pixel_identities_1d, axis = 1)
np.savetxt('../Data/AFM/AggregatedData/%s.txt'%(sampleName), scan_and_classif)
else:
for i in range(x):
for j in range(y):
scan[i, j, 5] = pixel_identities[i, j]
scan = scan.reshape((x2, z))
np.savetxt('../Data/AFM/AggregatedData/%s.txt'%(sampleName), scan)
return pixel_identities
def pixel_classifier_pixel(pixel):
"""
This function takes in a 1D array of AFM data from a single scan. It iterates through each xy location and
classifies that pixel as either crystalline or amorphous, depending on its z values.
inputs: pixel - a 1D array of AFM data for each pixel
outputs: classified_pixel - an integer that contains the pixel's identity, 1 denotes crystalline, -1 denotes
amorphous.
"""
adh_cut = 0.033 #greater than 33 mV
def_cut = 0.0000000026 #less than 2.6 nm
dis_cut = 0.033 #greater than 33 mV
mod_cut = -0.03 #greater than -0.03 V
stif_cut = 0.01 #greater than 0.01 V
classified_pixel = 0
crystalline_count = 0
if pixel[0] >= adh_cut:
crystalline_count += 1
else:
pass
if pixel[1] <= def_cut:
crystalline_count += 1
else:
pass
if pixel[2] >= dis_cut:
crystalline_count += 1
else:
pass
if pixel[3] >= mod_cut:
crystalline_count += 1
else:
pass
if pixel[4] >= stif_cut:
crystalline_count += 1
else:
pass
if crystalline_count >= 3:
classified_pixel = 1
else:
classified_pixel = -1
return classified_pixel
def find_maxes(scan):
"""
This function takes in a 3D array of intensity values for pixels in an AFM micrograph and returns the maximum
value for each of the scan types as a vector
input: numpy ndarray of 3 dimensions containing AFM scan data
output: numpy array of 1 dimension containing the maximum value of each scan type
"""
x, y, _ = scan.shape
z = 5 #only want the scan features and not prior classifications
maxVec = np.empty(z)
#initialize the maxVec to contain the 1st pixel's values
for h in range(z):
maxVec[h] = scan[0, 0, h]
#look for the maximum value for each scan type
for i in range(z):
for j in range(x):
for k in range(y):
if maxVec[i] < scan[j, k, i]:
maxVec[i] = scan[j, k, i]
elif maxVec[i] > scan[j, k, i]:
pass
else:
pass
return maxVec
def euc_dist(maxVec, pixel1, pixel2):
"""
This function takes in a vector of maximum values for the sample's different data types and two pixels as
vectors of their features and calculates the Euclidean distance. It then normalizes these differences for
each scan type so there isn't uneven weighting for a given feature type. Finally, it returns the adjusted
Euclidean distance.
This function assumes that only numeric data is in the pixel features.
inputs: a 1D numpy array containing the maximum values of a given sample's scan types
a 1D numpy array containing the feature values of the pixel being examined
a 1D numpy array containing the feature values of the neighboring pixel
outputs: a numeric value describing the normalized euclidean distance between the pixel and its neighbor
"""
dist_sqrd = 0
#calculate the normalized square of the euclidean distance.
for i in range(5):
diff = (pixel1[i] - pixel2[i])/maxVec[i]
dist_sqrd += diff
dist = math.sqrt(abs(dist_sqrd))
return dist
def neighbor_locater(x, y):
"""
This function takes in the xy location of a pixel in a 3D array of information and locates its neighbors,
returning these locations as a 2D array of 8 different xy coordinates.
input: x - The row of pixels that contains the pixel in question
y - The column of pixels that contains the pixel in question
output: neighbors - a 2D array containing the xy location of the 8 nearest neighbors
"""
neighbors = np.empty([8, 2])
neighbors[0, 0] = x - 1
neighbors[0, 1] = y - 1
neighbors[1, 0] = x - 1
neighbors[1, 1] = y
neighbors[2, 0] = x - 1
neighbors[2, 1] = y + 1
neighbors[3, 0] = x
neighbors[3, 1] = y - 1
neighbors[4, 0] = x
neighbors[4, 1] = y + 1
neighbors[5, 0] = x + 1
neighbors[5, 1] = y - 1
neighbors[6, 0] = x + 1
neighbors[6, 1] = y
neighbors[7, 0] = x + 1
neighbors[7, 1] = y + 1
return neighbors
def neighbor_properties(scan, neighbors):
"""
This function takes in a 3D np.ndarray of AFM data and a 2D np.array of pixel xy locations. These pixels are the
8 neighbors of a given pixel. It returns a 3D np.ndarray of the 8 neighbors' AFM values
inputs: scan - a 3D np.ndarray with 5 mechanical properties and classifications (1 or more) of an xy array of
pixels.
neighbors - a 2D np.array of the xy locations of pixels surrounding a given pixel
outputs: neighbor_props - a 2D np.array of the mechanical properties and classifications of a given pixel's
8 neighboring pixels
"""
x, y, _ = scan.shape
z = 5
neighbor_props = np.empty([8, z])
for i in range(8):
xx, yy = neighbors[i]
xx = int(xx)
yy = int(yy)
for j in range(z):
neighbor_props[i, j] = scan[xx, yy, j]
return neighbor_props
def euclidean_classifier_pixel(pixel, neighbor_props, maxVec):
"""
This function takes in a pixel as a vector of the scan types of a nanomechanical mapping AFM micrograph.
Using a normalized euclidean distance, the similarity of the pixel in question with its neighboring pixels
is factored into its own classification. Positive values denotes crystalline identification, negative values
denote amorphous identification.
inputs: pixel - a 1D np.array containing its mechanical properties (0-4) and its own classification (5) and any
previous classifications (6+)
neighbors - a 2D np.array containing the mechanical properties of the 8 neighbors of the pixel in question
maxVec - a 1D np.array containing the maximum values for each scan type within the whole scan
outputs: euc_classified_pixel - a float variable containing the % aggreement between the pixel and its neighbors
"""
neighbor_distances = np.empty([8, 5])
for i in range(8):
for j in range(5):
neighbor_distances[i, j] = euc_dist(maxVec, pixel, neighbor_props[i])
similar_neighbor_classifications = 0
for i in range(8):
total_distance = 0
for j in range(5):
total_distance += neighbor_distances[i, j]
if (total_distance/5) <= 0.7: #assume that there can be an overall 70% fluctuation pixel-to-pixel
similar_neighbor_classifications += 1
neighbor_distances[i, 4] = 1 #flag the similar pixels to use in probability calculation
else:
neighbor_distances[i, 4] = 0
pixel_identity = pixel_classifier_pixel(pixel)
euc_classified_pixel = (similar_neighbor_classifications/8)*pixel_identity #negative = amorphous, positive = xtal
return euc_classified_pixel
def euclidean_classifier_scan(sampleName):
"""
This function takes in the name of the sample, retrieves the file, and then calls other functions to complete a
classification of each pixel in the scan that incorporates its 8 nearest neighbors' euclidean distance. The edge
pixels are excluded from classification, but included as neighbors, for increased accuracy.
inputs: sampleName - a string of the sample's name, excluding the filetype extension. It is assumed that all files
are .txt filetype
outputs: euc_classified_scan - a 3D np.ndarray that contains the aggregated AFM scans, any previous
classifications, and the euclidean classification.
*also writes a 2D .txt file containing all of the above information
"""
scan = np.loadtxt('../Data/AFM/AggregatedData/%s.txt'% (sampleName))
x2, z = scan.shape
x = y = int(math.sqrt(x2))
scan = scan.reshape((x, y, z))
euc_classified_scan = np.empty([x, y])
maxVec = find_maxes(scan)
for i in range(1, x-1):
for j in range(1, y-1):
neighbors = neighbor_locater(i, j)
neighbor_props = neighbor_properties(scan, neighbors)
euc_classified_scan[i, j] = euclidean_classifier_pixel(scan[i, j], neighbor_props, maxVec)
if z <= 6:
scan = scan.reshape((x2, z))
euc_classified_scan_1d = euc_classified_scan.reshape((x2, 1))
scan_and_classif = np.append(scan, euc_classified_scan_1d, axis = 1)
np.savetxt('../Data/AFM/AggregatedData/%s.txt'%(sampleName), scan_and_classif)
else:
for i in range(x):
for j in range(y):
scan[i, j] = euc_classified_scan[i, j]
scan = scan.reshape((x2, z))
np.savetxt('../Data/AFM/AggregatedData/%s.txt'%(sampleName), scan)
return euc_classified_scan
def iterative_classifier_wrapper(sampleName):
"""
This function starts with the PixelClassifier model's classifications, then randomly walks from pixel-to-pixel to
compare each pixel to its neighbors, using that to update the classification. It then compares the new set of
classifications to the old classifications. If they differ by more than a negligible amount, the process starts
again until the differences are within a tolerance.
inputs: sampleName - a string with the name of the sample, excluding the filetype extension, which is assumed to
be .txt
outputs: new_classifications - a 2D array with the final identities of the pixels
*writes a new file to computer harddrive
"""
scan = np.loadtxt('../Data/AFM/AggregatedData/%s.txt'% (sampleName))
x2, z = scan.shape
x = y = int(math.sqrt(x2))
scan = scan.reshape((x, y, z))
classifications = np.empty([x, y])
new_classifications = np.empty([x, y])
if z == 5: #If there has been no prior single pixel classifications, this initializes those values
for i in range(x):
for j in range(y):
classifications[i, j] = pixel_classifier_pixel(scan[i, j, 5])
else:
for i in range(x): #initialize the classifications to the PixelClassifier identities
for j in range(y):
classifications[i, j] = scan[i, j, 5]
coords = [(xx,yy) for xx in range(1, x-1) for yy in range(1, y-1)] #generate a list of all coordinate pairs
pcnt_diff = 1
while True: #while there is more than a 20% difference b/w old & new classifications, keep iterating
new_classifications, pcnt_diff = iterative_classifier_comparison(classifications, coords)
print ('Percent Difference: ', pcnt_diff)
for i in range(1, x-1):
for j in range(1, y-1):
classifications[i, j] = new_classifications[i, j]
if pcnt_diff <= 0.1:
break
if z <= 6:
scan = scan.reshape((x2, z))
pixel_identities_1d = pixel_identities.reshape((x2, 1))
scan_and_classif = np.append(scan, pixel_identities_1d, axis = 1)
np.savetxt('../Data/AFM/AggregatedData/%s.txt'%(sampleName), scan_and_classif)
else:
for i in range(x):
for j in range(y):
scan[i, j, 6] = classifications[i, j]
scan = scan.reshape((x2, z))
np.savetxt('../Data/AFM/AggregatedData/%s.txt'%(sampleName), scan)
return new_classifications
def iterative_classifier_comparison(classifications, coords):
"""
This function takes in two 2D arrays of classifications for a given AFM scan. It iterates through classifications,
populates new_classifications based on the neighbor identities and compares the two arrays.
inputs: classifications - a 2D np.array of the existing classifications (-1/1 = amorphous/xtal) for each pixel
coords - a list of all of the possible coordinate pairs
outputs: new_classifications - a 2D np.array of the new classifications for each pixel
pcnt_diff - the percentage of pixels in the scan that have different classifications between the old
classifications and the new classifications
"""
random.shuffle(coords) #randomly mix up the pairs of coordinates
x, y = classifications.shape
coord_iterator = 0
coord_array = np.empty([x-2, y-2, 2])
for i in range(x-2): #put the newly randomized coordinate pairs into 2D array
for j in range(y-2):
xcoord, ycoord = coords[coord_iterator]
coord_iterator += 1
coord_array[i, j, 0] = xcoord
coord_array[i, j, 1] = ycoord
new_classifications = np.empty([x, y])
neighbor_classes = np.empty([8])
for i in range(x-2): #store neighbor locations of the randomly selected pixel. Initialize pixel class.
for j in range(y-2):
neighbors = neighbor_locater(coord_array[i, j, 0], coord_array[i, j, 1])
pixel_class = classifications[i+1, j+1]
for k in range(8): #retrieve and store the classifications of the neighboring pixels
neighborx, neighbory = neighbors[k]
neighborx = int(neighborx)
neighbory = int(neighbory)
neighbor_classes[k] = classifications[neighborx, neighbory]
new_classifications[i+1, j+1] = iterative_classifier_assignment(pixel_class, neighbor_classes)
num_diff_pixels = 0
for i in range(x-2):
for j in range(y-2):
if new_classifications[i+1, j+1] == classifications[i+1, j+1]:
pass
else:
num_diff_pixels += 1
pcnt_diff = num_diff_pixels / (x * y)
return new_classifications, pcnt_diff
def iterative_classifier_assignment(pixel_class, neighbor_classes):
"""
This function takes in the classifications of a pixel and its neighbors, then reclassifies the pixel taking into
account the classes of its neighbors.
inputs: pixel_class - an int that holds the initial identity of the pixel
neighbor_classes - a 1D array that holds the identities of the pixel's neighbors
outputs: new_pixel_class - the new identity of the pixel
"""
amorphous = 0
crystalline = 0
for i in range(8):
if neighbor_classes[i] == 1:
crystalline += 1
else:
amorphous += 1
if crystalline > 5:
new_pixel_class = 1
elif amorphous > 5:
new_pixel_class = -1
else:
new_pixel_class = pixel_class
return new_pixel_class
| 9d1daa810cdfee1dc858697d4e4aec6570ff34bc | [
"Python"
] | 1 | Python | wesleyktatum/MANA-T | b876fa0fe55aa80caedeb970437d6dac6a8a3a49 | e130a443a3f3545e5035557838a298e086ac78b6 |
refs/heads/main | <file_sep>class Module:
_validStartCharacterOfCode = ['B', 'E', 'I', 'S']
def __init__(self, code, level):
self._code = code
self._list = Module._validStartCharacterOfCode
if self._code[0] not in Module._validStartCharacterOfCode:
self._code[0] = Module._validStartCharacterOfCode[0]
self._level = level
@property
def code(self):
return self._code
@property
def level(self):
return self._level
@level.setter
def level(self, newLevel):
self._level = newLevel
def changeLevelBy(self, changeByLevel):
self._level = changeByLevel
if changeByLevel > 0:
if changeByLevel > 5:
changeByLevel = 5
else:
return changeByLevel
else:
changeByLevel = 1
def getDiffereceInLevels(self, module):
difference = self._level - self._module
return difference
@classmethod
def addValidStartCharacter(cls, startCharacter):
cls._validStartCharacterCode.append(startCharacter)
@classmethod
def removeValidStartCharacter(cls, startCharacter):
cls._validStartCharacterCode.remove(startCharacter)
def __str__(self):
f'Code: {self._code} Level: {self._level}'
def m():
m1 = Module('S123', '3')
print(m1)
m2 = Module('B231', '2')
print(m2)
m1.changeLevelBy(2)
m2.changeLevelBy(1)
print(m1.getDiffereceInLevels(m2.level)
Module.addValidStartCharacter('T')
#2b
class Staff:
_nextStaffId = 1
def __init__(self, name):
self.staffId = Staff._nextStaffId
Staff._nextStaffId +=1
self._name = name
self._modules = []
def numberOfModule(self):
return len(self._modules)
def searchModule(self, code):
pass
def removeModule(self, code):
pass
class PartTimeStaff(Staff):
_datejoin = datetime.today()
def init(self, name, dateJoined, module):
super().__init__(name, modules)
self._dateJoined = PartTimeStaff._datejoin.year - dateJoined.year
def removeModule(self, code):
search = self.searchModule(code)
if search is None:
return False
else:
if len(self._modules) < self._dateJoined:
return False
else:
self._modules.remove(search)
return True
def main():
p1 = PartTimeStaff('John','01/06/2020',m1)
print(p.removeModule('B231'))
main()
from abc import ABC, abstractmethod
class StaffManagmentException(Exception):
pass
class Staff(ABC):
def _init_(self, staffId, name, salary):
self._staffId = staffId
self._name = name
self._salary = salary
@property
def salary(self):
return self._salary
@salary.setter
def salary(self, newSalary):
if newSalary <= 0:
raise StaffManagmentException('Salary cannot be zero or negative')
self._salary = newSalary
@abstractmethod
def allowance(self):
pass
def grossSalary(self):
pass
class SupportStaff(Staff):
_baseAllowance = 200
@property
def allowance(self):
return self._baseAllowance * 1.02
def _str_(self):
return f'{self._baseAllowance}'
class Department:
_staffList = []
def _init_(self, budget, manager):
self._budget = budget
self._manager = manager
def addStaff(self, staff):
if self.grossSalary >= self._budget:
raise StaffManagmentException('Cannot add staff as budget will be exceeded')
if self.grossSalary > self._manager.salary:
raise StaffManagmentException('Staff has more salary than manager')
return self._staff
def manager(self):
self._manager = self._staffList
def main():
m = SupportStaff(1, 'Peter', 6000)
d = Department(15000)
s = SupportStaff(2, 'John', 2000)
try:
s.salary = 0
print(s)
d.addStaff() = 100
except StaffManagmentException as e:
print(e)
main()
import tkinter as tk
from tkinter import ttk
from tkinter.scrolledtext import ScrolledText
class StatsGui:
def __init__(self):
self._numbers = []
self.win = tk.Tk()
self.win.resizable(False, False)
#setting a window title
self.win.title("Statistics")
self.create_widgets()
self.win.mainloop()
def create_widgets(self):
#Making a frame of a window for the GUI
dataFrame = ttk.Frame(self.win)
dataFrame.grid(column=0, row=0)
inputDataFrame = ttk.Frame(dataFrame)
#To make a label that says 'Number'
p1_lbl = ttk.Label(inputDataFrame, text="Number:")
#Shift to the left
p1_lbl.pack(side=tk.LEFT)
#Making a input variable for the widget
self.numValue = tk.StringVar()
self.numValue_Ety = ttk.Entry(inputDataFrame, width=18,\
textvariable=self.numValue)
#Shift entry box to align to the left
self.numValue_Ety.pack(side=tk.LEFT)
inputDataFrame.grid(column = 0, row = 0)
actionFrame = ttk.Frame(dataFrame)
actionFrame.grid(column=0, row=1)
self.add_btn = ttk.Button(actionFrame, text="Add A Number") #Add a button that says 'Add a number'
#Shift to the left
self.add_btn.pack(side = tk.LEFT)
self.statistics_btn = ttk.Button(actionFrame, text="Get Statistics")
#Shift to the left
self.statistics_btn.pack(side = tk.LEFT)
outputFrame = ttk.Frame(self.win)
outputFrame.grid(column=0, row=2, columnspan=2)
self.output = ScrolledText(outputFrame, width=40, height=10, \
wrap=tk.WORD)
self.output.grid(column=0, row=0, sticky='WE', columnspan=2)
'''
Created on 21 May 2020
@author: Lester
'''
| 1f74a9356241bbabd607096a015c1705931c19d2 | [
"Python"
] | 1 | Python | EuyizL/PythonProjects | d5c199eb5c0e434fe1c4b8c08d745b355730f42e | a8a18ff3c987501eacbdac5a97e5fc4fa6bdca7c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.