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/master
<repo_name>nna0702/edx_python<file_sep>/README.md # edx_python Assignments for a Python course on edX <file_sep>/week 1/problem_1_1.py if __name__ == '__main__': # Create a list of vowels vowels = ['a', 'e', 'i', 'o', 'u'] # Define string s = 'renuoghfcgij' # Separate characters of s into a list string = list(s) # List the vowels in string output = [] for i in range(0, len(string)): if string[i] in vowels: output.append(string[i]) print(output) # Number of vowels in the s num = len(output) # Turn num into a string to print num = str(num) # Print output print("Number of vowels: " + num)<file_sep>/week 3/how_many.py # We want to write some simple procedures that work on dictionaries to return information. # # First, write a procedure, called how_many, which returns the sum of the number of values associated with a dictionary. def how_many(aDict): ''' aDict: A dictionary, where all the values are lists. returns: int, how many values are in the dictionary. ''' total = 0 for i in aDict.keys(): total = total + len(aDict[i]) return total if __name__ == '__main__': # Defne dictionary animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} animals['d'] = ['donkey'] animals['d'].append('dog') animals['d'].append('dingo') print(how_many(animals))<file_sep>/week 1/problem_1_2.py import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('s', help='special string') args = parser.parse_args() # Define special string special = 'bob' # Split string into list string = list(args.s) # List the starting point of 'bob' in string output = [] for i in range(0, len(string)-2): concat = string[i] + string[i+1] + string[i+2] if concat == special: output.append(i) # Count number of times 'bob' occurs num = len(output) # Turn num into string to print num = str(num) # Print output print("Number of times bob occurs is: " + num)
fc4b5b7d6d70b799f8a510541e79dcb1cef8ca92
[ "Markdown", "Python" ]
4
Markdown
nna0702/edx_python
b767618842097c8cfba3a393e82b4fd81a5a43b7
c10706bbee10eff052303c02c8a2fcda318e2ade
refs/heads/master
<repo_name>sansonex/DatabasePerTenant<file_sep>/DatabasePerTenant/Data/ApplicationDbContext.cs using Microsoft.EntityFrameworkCore; using System; using System.Linq; namespace DatabasePerTenant { public class ApplicationDbContext : DbContext { private readonly ITenantProvider tenantProvider; public ApplicationDbContext(ITenantProvider tenantProvider) { this.tenantProvider = tenantProvider; } public DbSet<User> Users { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var tenant = this.tenantProvider.GetTenantAsync().GetAwaiter().GetResult(); //if (tenant != null) //{ // optionsBuilder.UseSqlServer(tenant.ConnectionStringDb); //} optionsBuilder.UseInMemoryDatabase(Guid.NewGuid().ToString()); base.OnConfiguring(optionsBuilder); } } } <file_sep>/DatabasePerTenant/Data/TenantsDbContext.cs using Microsoft.EntityFrameworkCore; namespace DatabasePerTenant { public class TenantsDbContext : DbContext { public DbSet<Tenant> Tenants { get; set; } } } <file_sep>/DatabasePerTenant/Services/TenantProvider.cs using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace DatabasePerTenant { public class TenantProvider : ITenantProvider { private readonly IHttpContextAccessor httpContextAccessor; private readonly TenantsDbContext tenantsDbContext; private readonly ICurrentUserService currentUserService; private Tenant Tenant; private List<Tenant> Tenants; public TenantProvider(IHttpContextAccessor httpContextAccessor, TenantsDbContext tenantsDbContext, ICurrentUserService currentUserService) { this.httpContextAccessor = httpContextAccessor; this.tenantsDbContext = tenantsDbContext; this.currentUserService = currentUserService; } public async Task<Tenant> GetTenantAsync() { if (Tenant == null) { await SetTenant(); } return Tenant; } public async Task LoadTenats() { this.Tenants = await this.tenantsDbContext.Tenants.ToListAsync(); } private async Task SetTenant() { if (!Tenants.Any()) { await this.LoadTenats(); } if (this.TrySetTenantFromRoute() || this.TrySetTenantFromUser()) { return; } throw new TenantNotFoundException(); } private bool TrySetTenantFromRoute() { // Sample Code. return this.Tenant != null; } private bool TrySetTenantFromUser() { // Sample Code. this.Tenant = this.Tenants.FirstOrDefault(x => x.Id == Guid.Parse(this.currentUserService.GetUserTenantId())); return this.Tenant != null; } } } <file_sep>/DatabasePerTenant/Services/ITenantProvider.cs using System.Threading.Tasks; namespace DatabasePerTenant { public interface ITenantProvider { Task<Tenant> GetTenantAsync(); } } <file_sep>/DatabasePerTenant/Middlewares/ErrorHandlingMiddleware.cs using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; namespace DatabasePerTenant.Midlewares { /// <summary> /// Error Handling middleware class. /// </summary> public class ErrorHandlingMiddleware { private readonly RequestDelegate next; /// <summary> /// Constructor. /// </summary> /// <param name="next">The next request delegate.</param> public ErrorHandlingMiddleware(RequestDelegate next) { this.next = next; } /// <summary> /// Asynchronous Invoke. /// </summary> /// <param name="context">The HttpContext.</param> /// <returns>The asynchronous operation.</returns> public async Task InvokeAsync(HttpContext context) { try { await this.next(context); } catch (Exception exception) { if (context.Response.HasStarted) { throw; } await HandleExceptionAsync(context, exception); } } private static async Task HandleExceptionAsync(HttpContext context, Exception exception) { string responseBody; context.Response.Clear(); context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Response.ContentType = "application/json"; responseBody = exception.Message; await context.Response.WriteAsync(responseBody); } } } <file_sep>/README.md # DatabasePerTenant Tenant per database approach .NET sample code. <file_sep>/DatabasePerTenant/Services/CurrentUserService.cs using System; namespace DatabasePerTenant { public class CurrentUserService : ICurrentUserService { public string GetUserId() { return Guid.NewGuid().ToString(); } public string GetUserTenantId() { return Guid.NewGuid().ToString(); } } } <file_sep>/DatabasePerTenant/Models/Tenant.cs using System; namespace DatabasePerTenant { public class Tenant { public Guid Id { get; set; } public string Name { get; set; } public string ConnectionStringDb { get; set; } } } <file_sep>/DatabasePerTenant/Middlewares/MissingTenantMiddleware.cs using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DatabasePerTenant.Midlewares { /// <summary> /// Missing Tenant Middleware class. /// </summary> public class MissingTenantMiddleware { private readonly RequestDelegate next; /// <summary> /// Initializes a new instance of the <see cref="MissingTenantMiddleware"/> class. /// Missing Tenant constructor. /// </summary> /// <param name="next">Request Delegate.</param> public MissingTenantMiddleware(RequestDelegate next) { this.next = next; } /// <summary> /// Invoke method. /// </summary> /// <param name="httpContext">http context.</param> /// <param name="provider">provider.</param> /// <returns>nothing at all.</returns> public async Task Invoke(HttpContext httpContext, ITenantProvider provider) { if (await provider.GetTenantAsync() == null) { throw new TenantNotFoundException(); } await this.next.Invoke(httpContext); } } } <file_sep>/DatabasePerTenant/Exceptions/TenantNotFoundException.cs using System; namespace DatabasePerTenant { public class TenantNotFoundException : Exception { public TenantNotFoundException() : base("Tenant Not Found") { } } }
0b3803c521f62cc70b8ab1183b60dc8fd7fdbd2b
[ "Markdown", "C#" ]
10
C#
sansonex/DatabasePerTenant
9306df6047ef6bd48f365b9222d47b51f69b4c05
f6fa059a4444554278ef244218524cb06713bd22
refs/heads/master
<repo_name>Rowayda-Khayri/cryptanalysis<file_sep>/decryption.py # ###Decryption### # import math # take ciphertext input ciphertext = raw_input("Enter a ciphertext to be decrypted : ") # letters array letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] # ciphertext without special characters, numbers and spaces lettersOnlyCiphertext = '' # to be the input to count each letter frequency for character in ciphertext: if character in letters: lettersOnlyCiphertext += character # define function to calculate each letter's frequency percentage def percentage(count, total): return 100 * float(count) / total lettersFrequencyPercentages = [] # to store each letter's frequency percentage # calculate each letter's frequency percentage numberOfLettersInCiphertext = len(lettersOnlyCiphertext) for letter in letters: lettersFrequencyPercentages.append(percentage(lettersOnlyCiphertext.count(letter), numberOfLettersInCiphertext)) # The standard frequencies and percentages of English letters standardEnglishLettersFrequenciesPercentages = [7.487792, 1.295442, 3.544945, 3.621812, 13.99891, 2.183939, 1.73856, 4.225448, 6.653554, 0.269036, 0.465726, 3.569814, 3.39121, 6.741725, 7.372491, 2.428106, 0.262254, 6.140351, 6.945198, 9.852595, 3.004612, 1.157533, 1.691083, 0.278079, 1.643606, 0.036173] # calculate correlation coefficient for each possible shift key shiftsCorrelationCoefficients = [] # to store the co-eff of each shift key for shift in range(0,26): # 26 shifts .. ( 26 in range will be ignored ) r = ( 26 * ( sum([ (x * y) for (x, y) in zip(standardEnglishLettersFrequenciesPercentages, lettersFrequencyPercentages[shift:]) # #get y from the index as the shift to the last index ]) + sum([ (x * y) for (x, y) in zip(standardEnglishLettersFrequenciesPercentages, lettersFrequencyPercentages[0:shift]) # #get y from the first index to the index before the index as the shift ]) ) - sum([x for x in standardEnglishLettersFrequenciesPercentages]) * ( sum([y for y in lettersFrequencyPercentages[shift:]]) + sum([y for y in lettersFrequencyPercentages[0:shift]]) ))/( math.sqrt( 26 * sum([math.pow(x, 2) for x in standardEnglishLettersFrequenciesPercentages]) - math.pow(sum([x for x in standardEnglishLettersFrequenciesPercentages]), 2) ) * math.sqrt( 26 * ( sum([math.pow(y, 2) for y in lettersFrequencyPercentages[shift:]]) + sum([math.pow(y, 2) for y in lettersFrequencyPercentages[0:shift]]) ) - math.pow( ( sum([y for y in lettersFrequencyPercentages[shift:]]) + sum([y for y in lettersFrequencyPercentages[0:shift]]) ), 2 ) ) ) # add this shift's correlation coefficient to the list shiftsCorrelationCoefficients.append(r) # the shift key is the key with the max value shiftKey = shiftsCorrelationCoefficients.index(max(shiftsCorrelationCoefficients)) print " \nshiftKey : " + str(shiftKey) # Deciphering plaintext = "" for i in range(0, len(ciphertext)): # loop over all ciphertext characters if ciphertext[i] == ' ': # space plaintext += ' ' elif ciphertext[i] not in letters: # any character other than letters and spaces # print the same character plaintext += ciphertext[i] else: # letter index = letters.index(ciphertext[i]) # get index of character in letters plaintext += letters[index - int(shiftKey)] # print the result print " \nplaintext : " + plaintext <file_sep>/encryption.py # ### Encryption ### # # take msg input msg = raw_input("Enter a msg to be encrypted : ") # take shift input shift = raw_input("Enter a shift key : ") # letters array letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] ciphertext = "" # encryption for i in range(0, len(msg)): # loop over all msg characters if msg[i] == ' ': ciphertext += ' ' elif msg[i] not in letters: # any other character # print the same character ciphertext += msg[i] else: # letter index = letters.index(msg[i]) # get index of character in letters ciphertext += letters[(index + int(shift)) % 26] print "\nciphertext is : " + ciphertext <file_sep>/README.md # cryptanalysis A cryptanalysis application that's based on Caesar cipher algorithm. The app does the following: =========================== 1- Encryption: -------------- - Accept a plaintext and convert it to enciphered text according to a given (key) following Caesar cipher. 2- Decryption: -------------- - Accept an enciphered text, following Caesar cipher and automatically analyze the letters in the enciphered text to determine their frequencies. - Compare the frequencies with the standard English but shifted with 1, 2, 3, ... or more as expected by Caesar cipher. - Determine the highest correlation coefficient and then the key length and automatically deciphers the message accordingly.
d85f7506d72e609f7f6f58faf01e30a3cf3f4aae
[ "Markdown", "Python" ]
3
Python
Rowayda-Khayri/cryptanalysis
693d52ae1fce45ac5ab648aa55976ffea3f9e9d9
75659d8b85015f3113a87daea9275d2d79175d9e
refs/heads/master
<repo_name>ZunoRick/ProyectoCasa<file_sep>/ProyectoFinal/ProyectoFinal.cpp #include "texture.h" #include "figuras.h" #include "Camera.h" //#include "Main.h" #include <string.h> #include "cmodel/CModel.h" #define MAX_FRAMES 50 //Solo para Visual Studio 2015 #if (_MSC_VER >= 1900) # pragma comment( lib, "legacy_stdio_definitions.lib" ) #endif CCamera objCamera; GLfloat g_lookupdown = 0.0f; float rotX = 0.0, rotY = 0.0, rotZ = 0.0, movX = 0.0, movY = 0.0, movZ = 0.0; bool dia = true; bool g_fanimacion = false; int i_max_steps = 20; int i_curr_steps = 0; int frames = 0; //Luz Ambiente (Cielo) GLfloat LightAmbient[] = { 1.0f, 1.0f, 1.0f, 1.0f }; GLfloat LightDiffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f }; GLfloat LightSpecular[] = { 0.5, 0.5, 0.5, 1.0 }; //GLfloat LightPosition[] = { -80.0, 145.0, 0.0, 1.0f }; GLfloat LightPosition[] = { 0.0, 200.0, 100.0, 1.0f }; GLfloat LightAmbient2[] = { 0.0f, 0.0, 0.0f, 1.0f }; GLfloat LightDiffuse2[] = { 0.25f, 0.25f, 0.5f, 1.0f }; GLfloat LightSpecular2[] = { 0.25, 0.25, 0.5, 0.0 }; //GLfloat mat_ambient[] = { 0.329412f, 0.223529f, 0.027451f,1.0f }; GLfloat mat_diffuse[] = { 1.0f, 0.0f, 0.0f, 1.0f }; GLfloat mat_specular[] = { 0.909f, 0.333f, 0.047f, 1.0 }; GLfloat mat_shines[] = { 100.0f }; CTexture text1; CTexture pasto; CTexture ventana; CTexture ladrillos; CTexture pared_ext; CTexture carretera; CTexture textSuelo1; CTexture puertaPrincip; CTexture puertaPrincip2; CFiguras escenario; CFiguras Cilindro; CFiguras suelo; CFiguras figura; //Figuras de 3D Studio CModel kit; CModel llanta; void InitGL(GLvoid) // Inicializamos parametros { glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Negro de fondo glShadeModel(GL_SMOOTH); glLightfv(GL_LIGHT0, GL_POSITION, LightPosition); glLightfv(GL_LIGHT0, GL_POINT, LightAmbient); glLightfv(GL_LIGHT0, GL_DIFFUSE, LightDiffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, LightSpecular); glLightfv(GL_LIGHT1, GL_POSITION, LightPosition); glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient2); glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse2); glLightfv(GL_LIGHT1, GL_SPECULAR, LightSpecular2); glEnable(GL_LIGHTING); glEnable(GL_LIGHT1); glEnable(GL_LIGHT0); glClearDepth(1.0f); // Configuramos Depth Buffer glEnable(GL_DEPTH_TEST); // Habilitamos Depth Testing glDepthFunc(GL_LEQUAL); // Tipo de Depth Testing a realizar glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glEnable(GL_TEXTURE_2D); glEnable(GL_COLOR_MATERIAL); glEnable(GL_AUTO_NORMAL); glEnable(GL_NORMALIZE); /* setup blending */ glEnable(GL_BLEND); // Turn Blending On text1.LoadBMP("01.bmp"); text1.BuildGLTexture(); text1.ReleaseImage(); pasto.LoadTGA("texturas/pasto01.tga"); pasto.BuildGLTexture(); pasto.ReleaseImage(); ventana.LoadTGA("texturas/ventana.tga"); ventana.BuildGLTexture(); ventana.ReleaseImage(); ladrillos.LoadTGA("texturas/ladrillos.tga"); ladrillos.BuildGLTexture(); ladrillos.ReleaseImage(); pared_ext.LoadTGA("texturas/pared.tga"); pared_ext.BuildGLTexture(); pared_ext.ReleaseImage(); carretera.LoadTGA("texturas/way.tga"); carretera.BuildGLTexture(); carretera.ReleaseImage(); textSuelo1.LoadTGA("texturas/suelo1.tga"); textSuelo1.BuildGLTexture(); textSuelo1.ReleaseImage(); puertaPrincip.LoadTGA("texturas/puertaprincip.tga"); puertaPrincip.BuildGLTexture(); puertaPrincip.ReleaseImage(); puertaPrincip2.LoadTGA("texturas/puertaprincip2.tga"); puertaPrincip2.BuildGLTexture(); puertaPrincip2.ReleaseImage(); //Carga de Figuras kit._3dsLoad("modelos/kitt.3ds"); llanta._3dsLoad("modelos/k_rueda.3ds"); objCamera.Position_Camera(0, 2.5f, 1, 0, 2.5f, 0, 0, 1, 0); objCamera.mPos.y = -127; objCamera.mView.y = -118; objCamera.mPos.z = -150; } void ambiente() { //Pasto: glPushMatrix(); glTranslatef(0.0, -180.0, 155.0); glScalef(400, 0.01, 90); suelo.prisma2(pasto.GLindex, 0); glPopMatrix(); glPushMatrix(); glTranslatef(0.0, -180.0, -150.0); glScalef(400, 0.01, 80); suelo.prisma2(carretera.GLindex, 0); glPopMatrix(); glPushMatrix(); glTranslatef(-175.0, -180.0, 0.0); glScalef(50, 0.01, 220); suelo.prisma2(pasto.GLindex, 0); glPopMatrix(); glPushMatrix(); glTranslatef(175.0, -180.0, 0.0); glScalef(50, 0.01, 220); suelo.prisma2(pasto.GLindex, 0); glPopMatrix(); glPushMatrix(); glTranslatef(86, -180.0, -80); glScalef(128, 0.01, 60); suelo.prisma2(pasto.GLindex, 0); glPopMatrix(); glPushMatrix(); glTranslatef(-74, -180.0, -80); glScalef(152, 0.01, 60); suelo.prisma2(pasto.GLindex, 0); glPopMatrix(); //Pavimento y ladrillos: glPushMatrix(); glTranslatef(12, -180.0, -80.5); glScalef(20, 0.01, 59); suelo.prisma2(ladrillos.GLindex, 1); glPopMatrix(); glPushMatrix(); glTranslatef(12, -177.5, -53.6); glPushMatrix(); suelo.prisma(5.0, 20.0, 7.0, ladrillos.GLindex); glPopMatrix(); glTranslatef(0.0, -1.2, -7.0); glPushMatrix(); suelo.prisma(2.5, 20.0, 7.0, ladrillos.GLindex); glPopMatrix(); glPopMatrix(); } void coche1() { glPushMatrix(); glDisable(GL_COLOR_MATERIAL); glScalef(2.0, 2.0, 2.0); //glTranslatef(movX+63.5, movY-71.6, movZ-42.4); glTranslatef(-42.0, -71.6, -37.0); //Pongo aquí la carroceria del carro kit.GLrender(NULL, _SHADED, 1.0); glPushMatrix(); glTranslatef(-6.0, -1.0, 7.5); glRotatef(0.0, 1, 0, 0); llanta.GLrender(NULL, _SHADED, 1.0); glPopMatrix(); glPushMatrix(); glTranslatef(6.0, -1.0, 7.5); glRotatef(180, 0, 1, 0); glRotatef(-0.0, 1, 0, 0); llanta.GLrender(NULL, _SHADED, 1.0); glPopMatrix(); glPushMatrix(); glTranslatef(-6.0, -1.0, -9.5); glRotatef(0.0, 1, 0, 0); llanta.GLrender(NULL, _SHADED, 1.0); //Trasera Der glPopMatrix(); glPushMatrix(); glTranslatef(6.0, -1.0, -9.5); glRotatef(180, 0, 1, 0); glRotatef(-0.0, 1, 0, 0); llanta.GLrender(NULL, _SHADED, 1.0); //Trasera Izq glPopMatrix(); glPopMatrix(); } void coche2() { glPushMatrix(); //Para que el coche conserve sus colores glDisable(GL_COLOR_MATERIAL); //glRotatef(90, 0, 1, 0); glScalef(2.0, 2.0, 2.0); //glTranslatef(movX+63.5, movY-71.6, movZ-42.4); glTranslatef(-59.7, -71.6, -36.0); //Pongo aquí la carroceria del carro glColor3f(1.0, 0.0, 0.0); kit.GLrender(NULL, _SHADED, 1.0); //_WIRED O _POINTS glPushMatrix(); glTranslatef(-6.0, -1.0, 7.5); glRotatef(0.0, 1, 0, 0); llanta.GLrender(NULL, _SHADED, 1.0); //Delantera Izq glPopMatrix(); glPushMatrix(); glTranslatef(6.0, -1.0, 7.5); glRotatef(180, 0, 1, 0); glRotatef(-0.0, 1, 0, 0); llanta.GLrender(NULL, _SHADED, 1.0); //<NAME> glPopMatrix(); glPushMatrix(); glTranslatef(-6.0, -1.0, -9.5); glRotatef(0.0, 1, 0, 0); llanta.GLrender(NULL, _SHADED, 1.0); //<NAME> glPopMatrix(); glPushMatrix(); glTranslatef(6.0, -1.0, -9.5); glRotatef(180, 0, 1, 0); glRotatef(-0.0, 1, 0, 0); llanta.GLrender(NULL, _SHADED, 1.0); //Trasera Izq glPopMatrix(); glPopMatrix(); } void casa() { glPushMatrix(); //pared frontal glPushMatrix(); glColor3f(0.960, 0.564, 0.447); glTranslatef(86, -65, -50); glRotatef(-90.0, 1, 0, 0); glScalef(128.0, 2.0, 170.0); figura.prisma2(pared_ext.GLindex, 0); glPopMatrix(); glPushMatrix(); glTranslatef(-33, -65, -50); glRotatef(-90.0, 1, 0, 0); glScalef(70.0, 2.0, 170.0); figura.prisma2(pared_ext.GLindex, 0); glPopMatrix(); glPushMatrix(); glTranslatef(12, -34.3, -50); glRotatef(-90.0, 1, 0, 0); glScalef(20.0, 2.0, 108.5); figura.prisma2(pared_ext.GLindex, 0); glPopMatrix(); //pared izquierda glPushMatrix(); glTranslatef(149.1, -65, 29.6); glRotatef(-90.0, 0, 0, 1); glScalef(170, 2.0, 161.0); figura.prisma2(pared_ext.GLindex, 0); glPopMatrix(); //<NAME> glPushMatrix(); glTranslatef(0.0, -65.0, 109.0); glRotatef(90.0, 1, 0, 0); glScalef(161.0, 2.0, 170); figura.prisma2(pared_ext.GLindex, 0); glPopMatrix(); //Paredes Internas glPushMatrix(); glTranslatef(-50.0, -65.0, 28.7); glRotatef(90.0, 0, 0, 1); glScalef(170, 2.0, 161.0); figura.prisma2(pared_ext.GLindex, 0); glPopMatrix(); //Ventanas planta baja glPushMatrix(); glTranslatef(58.7, -100, -51.1); glPushMatrix(); glColor3f(1.0, 1.0, 1.0); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.1f); figura.plano(55.0, 40.0, ventana.GLindex); glDisable(GL_ALPHA_TEST); glPopMatrix(); glTranslatef(57.0, 0.0, 0.0); glPushMatrix(); glColor3f(1.0, 1.0, 1.0); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.1f); figura.plano(55.0, 40.0, ventana.GLindex); glDisable(GL_ALPHA_TEST); glPopMatrix(); glPopMatrix(); //Puerta Entrada Principal glPushMatrix(); glTranslatef(11.8, -116.2, -50.8); glPushMatrix(); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.1f); figura.plano(60.0, 22.0, puertaPrincip.GLindex); glDisable(GL_ALPHA_TEST); glPopMatrix(); glTranslatef(0.0, 0.0, 1.7); glPushMatrix(); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.1f); figura.plano(60.0, 22.0, puertaPrincip.GLindex); glDisable(GL_ALPHA_TEST); glPopMatrix(); glTranslatef(-8.3, -2.4, -0.9); glPushMatrix(); glRotatef(-90.0, 0, 1, 0); glBindTexture(GL_TEXTURE_2D, 0); glTranslatef(6.5, 0.7, 0.0); figura.prismaColor(54.0, 13.0, 1.3, 0.450, 0.192, 0.062); glColor3f(1.0, 1.0, 1.0); glPushMatrix(); glTranslatef(1.8, 1.5, -0.7); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.1f); glBindTexture(GL_TEXTURE_2D, puertaPrincip2.GLindex); figura.plano(60.0, 22.0, puertaPrincip2.GLindex); glDisable(GL_ALPHA_TEST); glPopMatrix(); glPushMatrix(); glTranslatef(1.8, 1.5, 0.7); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.1f); glBindTexture(GL_TEXTURE_2D, puertaPrincip2.GLindex); figura.plano(60.0, 22.0, puertaPrincip2.GLindex); glDisable(GL_ALPHA_TEST); glPopMatrix(); glPopMatrix(); glPopMatrix(); //Piso Planta Baja glColor3f(1.0, 1.0, 1.0); glPushMatrix(); glTranslatef(49.5, -146.2, 29.1); glScalef(197.3, 2.0, 158.4); figura.prisma2(textSuelo1.GLindex, 0); glPopMatrix(); glPopMatrix(); glPushMatrix(); glDisable(GL_COLOR_MATERIAL); glBindTexture(GL_TEXTURE_2D, 0); //glColor3f(1.0f, 1.0f, 1.0f); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shines); Cilindro.esfera(5.0,20.0, 20.0, 0); glTranslatef(0.0, 0.0, 0.0); glutSolidSphere(1.5, 25, 25); glEnable(GL_COLOR_MATERIAL); glPopMatrix(); } void display(void) // Creamos la funcion donde se dibuja { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glLightfv(GL_LIGHT0, GL_POSITION, LightPosition); glLightfv(GL_LIGHT1, GL_POSITION, LightPosition); glEnable(GL_LIGHTING); glPushMatrix(); glRotatef(g_lookupdown, 1.0f, 0, 0); gluLookAt(objCamera.mPos.x, objCamera.mPos.y, objCamera.mPos.z, objCamera.mView.x, objCamera.mView.y, objCamera.mView.z, objCamera.mUp.x, objCamera.mUp.y, objCamera.mUp.z); if (dia) { glDisable(GL_LIGHT1); glEnable(GL_LIGHT0); } else { glDisable(GL_LIGHT0); glEnable(GL_LIGHT1); } coche1(); coche2(); glEnable(GL_COLOR_MATERIAL); casa(); glColor3f(1.0, 1.0, 1.0); glPushMatrix(); //Creamos cielo glTranslatef(0, 30, 0); escenario.skybox(400.0, 400.0, 400.0, text1.GLindex); ambiente(); glPopMatrix(); glPopMatrix(); glutSwapBuffers(); } void reshape(int width, int height) // Creamos funcion Reshape { if (height == 0) // Prevenir division entre cero { height = 1; } glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); // Seleccionamos Projection Matrix glLoadIdentity(); // Tipo de Vista glFrustum(-0.5, 0.5, -0.5, 0.5, 0.5, 670.0); glMatrixMode(GL_MODELVIEW); // Seleccionamos Modelview Matrix //glLoadIdentity(); } void keyboard(unsigned char key, int x, int y) // Create Keyboard Function { switch (key) { case 'w': //Movimientos de camara case 'W': //if( objCamera.Move_Camera(CAMERASPEED) <= 200.0) objCamera.Move_Camera(CAMERASPEED + 0.001); break; case 's': case 'S': objCamera.Move_Camera(-(CAMERASPEED + 0.001)); break; case 'a': case 'A': objCamera.Strafe_Camera(-(CAMERASPEED + 0.001)); break; case 'd': case 'D': objCamera.Strafe_Camera(CAMERASPEED + 0.001); break; case 'j': rotX += 0.1; //printf("rotX = %f\n", rotX); break; case 'J': rotX -= 0.1; //printf("rotX = %f\n", rotX); break; case 'k': rotY += 0.1; //printf("rotY = %f\n", rotY); break; case 'K': rotY -= 0.1; //printf("rotY = %f\n", rotY); break; case 'l': rotZ += 0.1; //printf("rotZ = %f\n", rotZ); break; case 'L': rotZ -= 0.1; //printf("rotZ = %f\n", rotZ); break; case 'i': movX += 0.1; //printf("movX = %f\n", movX); break; case 'I': movX -= 0.1; //printf("movX = %f\n", movX); break; case 'o': movY += 0.1; //printf("movY = %f\n", movY); break; case 'O': movY -= 0.1; //printf("movY = %f\n", movY); break; case 'p': movZ += 0.1; //("movZ = %f\n", movZ); break; case 'P': movZ -= 0.1; //printf("movZ = %f\n", movZ); break; case ' ': printf("movX = %2.2f, movY = %2.2f, movZ = %2.2f\n", movX, movY, movZ); printf("rotX = %2.2f, rotY = %2.2f, rotZ = %2.2f\n", rotX, rotY, rotZ); break; case 'f': dia = true; break; case 'F': dia = false; break; case 27: // Cuando Esc es presionado... exit(0); // Salimos del programa break; default: // Cualquier otra break; } glutPostRedisplay(); } void arrow_keys(int a_keys, int x, int y) // Funcion para manejo de teclas especiales (arrow keys) { switch (a_keys) { case GLUT_KEY_PAGE_UP: objCamera.UpDown_Camera(CAMERASPEED); break; case GLUT_KEY_PAGE_DOWN: objCamera.UpDown_Camera(-CAMERASPEED); break; case GLUT_KEY_UP: // Presionamos tecla ARRIBA... g_lookupdown -= 1.0f; break; case GLUT_KEY_DOWN: // Presionamos tecla ABAJO... g_lookupdown += 1.0f; break; case GLUT_KEY_LEFT: objCamera.Rotate_View(-CAMERASPEED); break; case GLUT_KEY_RIGHT: objCamera.Rotate_View(CAMERASPEED); break; default: break; } glutPostRedisplay(); } int main(int argc, char** argv) // Main Function { glutInit(&argc, argv); // Inicializamos OpenGL glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); // Display Mode (Clores RGB y alpha | Buffer Doble ) glutInitWindowSize(1700, 940); // Tamaño de la Ventana glutInitWindowPosition(0, 0); //Posicion de la Ventana glutCreateWindow("Proyecto Final"); // Nombre de la Ventana //glutFullScreen ( ); // Full Screen InitGL(); // Parametros iniciales de la aplicacion glutDisplayFunc(display); //Indicamos a Glut función de dibujo glutReshapeFunc(reshape); //Indicamos a Glut función en caso de cambio de tamano glutKeyboardFunc(keyboard); //Indicamos a Glut función de manejo de teclado glutSpecialFunc(arrow_keys); //Otras //glutIdleFunc(animacion); glutMainLoop(); // return 0; }
e89d7209e6d9e92a4fdf5234df54ed2fa173799f
[ "C++" ]
1
C++
ZunoRick/ProyectoCasa
03089d55a77b02ba036ffd1b92689870acacd248
63fddfc1b9d0ac79897b845d69615ab8362f4616
refs/heads/main
<repo_name>Gabrielfernandes87f/adonis<file_sep>/.env.example PORT=3333 HOST=0.0.0.0 NODE_ENV=development APP_KEY=<KEY> SESSION_DRIVER=cookie CACHE_VIEWS=false
0beaa390672dcbae06be812ab32f54d38bee3862
[ "Shell" ]
1
Shell
Gabrielfernandes87f/adonis
35e4a45804f06129ac1fb34003916ece37c15fc2
e8df5bc2a2942ecbfc3c9295df6b6f997dd2f569
refs/heads/master
<file_sep>module.exports = { MongoURI: 'mongodb+srv://okeycj:okey1234@cluster0-edwzc.mongodb.net/test?retryWrites=true&w=majority' }
84e8c3504716d14b1ee60f1e2946d0f09324bc2b
[ "JavaScript" ]
1
JavaScript
okeycj/authentication_node_passport
aee6eecbde875928a7f898e5e02f0f9a32f53f0b
281c3066e3ece278a66921b29c2fbd93de6f2ee6
refs/heads/master
<repo_name>melvinwevers/detecting_faces-medium-types-gender<file_sep>/README.md # Detecting Faces, Medium Types,and Gender in Historical Advertisements This repo belongs to paper presented at VISART V workshop at ECCV2020. ## Abstract Libraries, museums, and other heritage institutions are digitizing large parts of their archives. Computer vision techniques enable scholars to query, analyze, and enrich the visual sources in these archives. However, it remains unclear how well algorithms trained on modern photographs perform on historical material. This study evaluates and adapts existing algorithms. We show that we can detect faces, visual media types, and gender with high accuracy in historical advertisements. It remains difficult to detect gender when faces are either of low quality or relatively small or large. Further optimization of scaling might solve the latter issue, while the former might be ameliorated using upscaling. We show how computer vision can produce meta-data information, which can enrich historical collections. This information can be used for further analysis of the historical representation of gender. ## Instructions Take files from Zenodo 10.5281/zenodo.4008991 - Place `annotations.tar.gz` in `data/raw` - Place `ads_meta.csv.zip` (metadata information) in `data/processed` - place `gt_faces.zip` (ground-truth) in `data/processed` - Place `dnn_detections.zip` (openCV face detection output) in `data/processed` - Place `medium classifier_training.zip` files in `data/processed` - Place `gender_faces.zip` in `data/processed` - Place `models.zip` in `models` Also place SIAMESET collection of ads in this folder. This set can be acquired from the National Library of the Netherlands. ## Project Organization ### Data This folder contains the annotations and training material for the classifiers ### Detecting Gender This folder contains contains the code for the training of the gender classifier `fine_tune_2step.py` is the script to finetune the model for classes `male` and `female` `fine_tune_multiclass.py` allows for for training of gender and medium type classes ### FaceDetection-DSFD Contains the adapted DSFD repo ### Models Outputted models for gender and medium type detection ### Notebooks `0-mw-preparing_meta_data.ipynb` describes the preparation of the meta data info and the training files `1-mw-analysis_meta_data.ipynb` analyses metadata `2-mw-make_gt_dt_dnn.ipynb` shows how to produce ground truth from annotations `3-mw-separatephoto.ipynb` training of the medium classifier `4-mw-inspecting_gender_prediction_model.ipynb` inspecting of the gender classifier training in `detecting_gender` folder ### Pytorch_Retinaface contains the adapted retinaface repo ### Reports Contains results of face detection, figures used in paper, and data underlying figures. ### src helper scripts for cropping, sampling, erasing, etc.. <file_sep>/detecting_gender/predict.py from adabound import AdaBound from keras.models import load_model from keras.preprocessing.image import ImageDataGenerator from keras.utils import CustomObjectScope import os.path import tensorflow as tf import keras.backend as K import numpy as np import argparse from sklearn.metrics import classification_report def make_generators(args): testPath = os.path.join(args.dataset, "test/1990") testAug = ImageDataGenerator( rescale=1.0 / 255 ) mean = np.array([123.68, 116.779, 103.939], dtype="float32") testAug.mean = mean # initialize the testing generator testGen = testAug.flow_from_directory( testPath, class_mode="binary", target_size=(args.image_size, args.image_size), color_mode="rgb", shuffle=False, batch_size=args.batch_size) print(testGen.class_indices.keys()) return testGen def get_args(): parser = argparse.ArgumentParser(description="Fine-tuning vgg16 for gender estimation in historical adverts.", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--batch_size", type=int, default=64, help="batch size") parser.add_argument("--n_epochs", type=int, default=50, help="number of epochs") parser.add_argument("--lr", type=float, default=1e-3, help="initial learning rate") parser.add_argument("--opt", type=str, default="adabound", help="optimizer name; 'sgd' or 'adam'") parser.add_argument("--patience", type=int, default=6, help="Patience for callbacks") parser.add_argument("--image_size", type=int, default=224, help="Input size of images") parser.add_argument("--eraser", action="store_true") parser.add_argument("--dataset", type=str, default="../data/gender_3") parser.add_argument("--aug", action="store_true", help="use data augmentation if set true") parser.add_argument("--output_path", type=str, default="checkpoints", help="checkpoint dir") parser.add_argument("--figures_path", type=str, default="figures", help="path for figures") parser.add_argument("--model_path", type=str, default="model.h5", help="model dir") args = parser.parse_args() return args def evaluate(args): testGen = make_generators(args) with CustomObjectScope({'AdaBound': AdaBound()}): model = load_model('binary_model.h5') # print(testGen.classes) predIdxs = model.predict_generator(testGen, steps=( testGen.samples // args.batch_size) + 1, verbose=1) predIdxs = predIdxs > 0.5 # print(predIdxs) print(classification_report(testGen.classes, predIdxs, target_names=testGen.class_indices.keys())) if __name__ == '__main__': os.environ['KERAS_BACKEND'] = 'tensorflow' config = tf.ConfigProto() config.gpu_options.per_process_gpu_memory_fraction = 0.95 config.gpu_options.allow_growth = True sess = tf.Session(config=config) K.set_session(sess) args = get_args() evaluate(args) <file_sep>/src/crop_gender.py import glob import cv2 import os import numpy as np import xml.etree.ElementTree as ET import random from tqdm import tqdm import argparse from utils import find_bb, to_parseable ''' Script to crop faces from images to generate training data for gender detection algorithm ''' parser = argparse.ArgumentParser(description='Create Gender Training Data') parser.add_argument('--annotation_dir', default='./data/raw/annotations/', type=str, help='dir that holds annotations') parser.add_argument('--images_dir', default='./data/processed/KB_FACES/', type=str, help='dir with images') parser.add_argument('--output_dir', default='./data/processed/gender_4/', type=str, help='output for cropped images') args = parser.parse_args() def crop_gender(): annotation_dir = args.annotation_dir images_dir = args.images_dir #types_ = ['train', 'test', 'validation'] types_ = ['test'] for type_ in types_: os.makedirs(os.path.join(args.output_dir, type_, 'f'), exist_ok=True) os.makedirs(os.path.join(args.output_dir, type_, 'm'), exist_ok=True) annotations = glob.glob(annotation_dir + '*') annotations.sort() test_annotations = annotations for index, type_ in enumerate(types_): print("processing: {}".format(index)) male_counter = 0 female_counter = 0 for xml in tqdm([test_annotations][index]): try: tree = ET.parse(xml).getroot() tree = to_parseable(tree) folder = tree.find("folder").text filename = tree.find("filename").text file_path = images_dir + '{}/{}'.format(folder, filename) img = cv2.imread(file_path) padding = 25 objects = tree.findall('.//object') for object in objects: if object.find("name").text in ['f']: xmin, ymin, xmax, ymax = find_bb(object) if (ymax - ymin) >= 100 and (xmax - xmin) >= 100: # TODO: check if this is necessary # if ymin > 25: # ymin -= 25 # if xmin > 25: # xmin -= 25 crop = np.copy(img[ymin:(ymax + padding), xmin:(xmax + padding)]) if 0 not in crop.shape[:2]: # check if crop != empty cv2.imwrite(args.output_dir + '/{}/{}_{}_f.jpg'.format(type_, folder, female_counter), crop) female_counter += 1 else: pass else: pass elif object.find("name").text in ['m']: xmin, ymin, xmax, ymax = find_bb(object) if (ymax - ymin) >= 100 and (xmax - xmin) >= 100: crop = np.copy(img[(ymin - padding):(ymax + padding), (xmin - padding):(xmax + padding)]) if 0 not in crop.shape[:2]: cv2.imwrite( args.output_dir + '/{}/{}_{}_m.jpg'.format(type_, folder, male_counter), crop) male_counter += 1 else: pass else: pass except Exception: pass if __name__ == '__main__': crop_gender() <file_sep>/src/make_samples.py import glob import numpy as np import os import tarfile ''' Script to make sample selection of original images ''' def make_samples(zipped_archives, n_samples): for archive in zipped_archives: year = os.path.basename(archive)[:4] tar = tarfile.open(archive) tar.extractall() # need to add proper directory to write to images = glob.glob(year + '/*.jpg') try: samples = np.random.choice(images, n_samples, replace=False) except Exception: pass # some years do not have enough images for image in images: if image not in samples: os.remove(image) if __name__ == '__main__': DATA_PATH = '../../datasets/ffads/' zipped_archives = glob.glob(DATA_PATH + '/*.gz') make_samples(zipped_archives, 1000) <file_sep>/src/utils.py from pathlib import Path import xml.etree.ElementTree as ET import os import cv2 import io from PIL import Image import pickle from torchvision import transforms, models from torch.autograd import Variable import random import numpy as np import torch from scipy.spatial import distance as dist datapath = '../data/processed/KB_FACES' vgg16 = models.vgg16(pretrained=True) newmodel = torch.nn.Sequential(*(list(vgg16.features[:24]))) def get_project_root() -> Path: """Returns project root folder.""" return Path(__file__).parent.parent def to_parseable(tree): t = ET.tostring(tree) t = t.lower() return ET.fromstring(t) def calculate_mean(files_, sample_size=1000, means=[]): ''' take a sample of the list of images and calculate the mean R,G,B value ''' sample_list = random.sample(files_, sample_size) for file_ in sample_list: img = cv2.imread(file_) means.append((cv2.mean(img))) print(np.mean(means, axis=0)) print(np.std(means, axis=0)) def find_bb(object): xmax = int(object.find('.//xmax').text) xmin = int(object.find('.//xmin').text) ymax = int(object.find('.//ymax').text) ymin = int(object.find('.//ymin').text) return xmin, ymin, xmax, ymax def detect_dnn(file_, net): # TO DO Change averages use default or based on dataset??? ''' detecting faces using openCV's deep neural network face detector The output is a dictionary with confidence scores and x,y,w,h ''' img = cv2.imread(file_) (h, w) = img.shape[:2] blob = cv2.dnn.blobFromImage(cv2.resize(img, (300, 300)), 1.0, (300, 300), (150.23, 170.07, 181.21)) # (300, 300), (104, 177, 123)) net.setInput(blob) detections = net.forward() pred_box = {} pred_box['boxes'] = [] pred_box['scores'] = [] for i in range(0, detections.shape[2]): confidence = detections[0, 0, i, 2] if confidence > 0: locations = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) # (startX, startY, endX, endY) = locations.astype("int") pred_box['boxes'].append([int(locations[0]), int(locations[1]), int(locations[2]), int(locations[3]) ]) pred_box['scores'].append(float('{:.3f}'.format(confidence))) return pred_box def generate_dt(file_, object_, file_base, DT_PATH, net): ''' function to detect faces in annotated images using open cv's dnn ''' pred_boxes = {} pred_box = detect_dnn(file_, net) pred_boxes[file_base] = pred_box os.makedirs(DT_PATH, exist_ok=True) with open(DT_PATH+'/{}.txt'.format(file_base), 'w') as f: scores = np.array(pred_box['scores']).tolist() boxes = np.array(pred_box['boxes']).tolist() if not scores: f.write(str(object_)+" "+str(0)+" "+str(0) + " "+str(0)+" "+str(0)+" "+str(0)) else: for box, score in zip(boxes, scores): f.write(str(object_) + " "+str(float('{:.3f}'.format(score)))+" "+str( box[0])+" "+str(box[1])+" "+str(box[2])+" "+str(box[3])+"\n") def generate_gt(xml, object_, file_base, GT_PATH): ''' function to extract gt (ground-truth) files from annotations xml ''' gt_boxes = {} gt_box = get_annotations(xml) if not any(gt_box): # check if there are face annotations pass else: gt_boxes[file_base] = gt_box os.makedirs(GT_PATH, exist_ok=True) with open(GT_PATH+'/{}.txt'.format(file_base), 'w') as f: for gt in gt_box: # left_xmin, top_ymin, right_xmax, bottom_ymax f.write( str(object_)+" "+str(gt[1])+" "+str(gt[0])+" "+str(gt[3])+" "+str(gt[2])+"\n") def generate_gt_WIDER(xml, object_, file_base, GT_PATH): ''' function to extract gt (ground-truth) files from annotations xml ''' gt_boxes = {} gt_box = get_annotations(xml) if not any(gt_box): # check if there are face annotations pass else: gt_boxes[file_base] = gt_box os.makedirs(GT_PATH, exist_ok=True) with open(GT_PATH+'/{}.txt'.format(file_base), 'w') as f: for gt in gt_box: # left, top, width, height left = gt[0] top = gt[1] width = gt[2] - gt[0] height = gt[4] - gt[1] f.write( str(left)+" "+str(gt[0])+" "+str(gt[3])+" "+str(gt[2])+"\n") def get_annotations(xml): img_data = [] tree = ET.parse(xml).getroot() tree = to_parseable(tree) objects = tree.findall('.//object') # folder = tree.find("folder").text for object in objects: if object.find("name").text in ['m', 'b', 'g', 'woman', 'man', 'f']: class_name = object.find("name").text if class_name == 'woman' or class_name == 'g': class_name = 'f' elif class_name == 'man' or class_name == 'b': class_name = 'm' x1, x2, y1, y2 = find_bb(object) img_data.append([int(x1), int(y1), int(x2), int(y2)]) # str(class_name)]) return img_data preprocess_img = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) def classify_single_image(img, newmodel=newmodel): filename = "../notebooks/finalized_model.sav" clf = pickle.load(open(filename, 'rb')) img_tensor = preprocess_img(img) img_tensor.unsqueeze_(0) images = Variable(img_tensor) encoding = newmodel(images) encoding = encoding.detach().numpy().flatten() prediction = clf.predict((np.asarray(encoding).reshape(1, -1))) return prediction def enrich_annotations(xml): img_data = [] tree = ET.parse(xml).getroot() tree = to_parseable(tree) objects = tree.findall('.//object') filename = tree.find("filename").text folder = tree.find("folder").text for object in objects: if object.find("name").text in ['m', 'b', 'g', 'woman', 'man', 'f']: class_name = object.find("name").text if class_name == 'woman' or class_name == 'g': class_name = 'f' elif class_name == 'man' or class_name == 'b': class_name = 'm' x1, x2, y1, y2 = find_bb(object) img_data.append([int(x1), int(y1), int(x2), int(y2)]) img_path = datapath + '/' + folder + '/' + filename img = Image.open(img_path) img_crop = img.crop((x1, y1, x2, y2)) prediction = classify_single_image(img_crop) print(prediction) # str(class_name)]) return img_data # TO DO: MOVE THIS TO FUNCTION for other project def get_men_women_annotations(xml, prediction=False): ''' This function extracts the males and females from the annotations. We also calculate the relative area of these annotated faces, and the distance of males and females from the center of the image. TODO: CLEAN THIS UP AS A CLASS ''' men = 0 areas_m = [] areas_f = [] distances_m = [] type_m = [] type_f = [] distances_f = [] object_m = [] object_f = [] position_m = [] position_f = [] women = 0 tree = ET.parse(xml).getroot() tree = to_parseable(tree) filename = tree.find("filename").text folder = tree.find("folder").text height = int(tree.findall('.//height')[0].text) width = int(tree.findall('.//width')[0].text) total_area = height * width objects = tree.findall('.//object') img_path = datapath + '/' + folder + '/' + filename for object_ in objects: if object_.find("name").text in ['m', 'man', 'b']: xmin, ymin, xmax, ymax = find_bb(object_) area = (ymax-ymin) * (xmax-xmin) img = Image.open(img_path) img_crop = img.crop((xmin, ymin, xmax, ymax)) if prediction: pred = classify_single_image(img_crop) type_m.append(int(prediction)) rel_area = area/total_area areas_m.append(rel_area) D, position, object_center = distance_from_center(width, height, object_) position_m.append(position) distances_m.append(D) object_m.append(object_center) men += 1 if object_.find("name").text in ['f', 'woman', 'g']: xmin, ymin, xmax, ymax = find_bb(object_) area = (ymax-ymin) * (xmax-xmin) img = Image.open(img_path) img_crop = img.crop((xmin, ymin, xmax, ymax)) if prediction: pred = classify_single_image(img_crop) type_f.append(int(prediction)) rel_area = area/total_area areas_f.append(rel_area) D, position, object_center = distance_from_center(width, height, object_) position_f.append(position) distances_f.append(D) object_f.append(object_center) women += 1 return men, women, areas_m, areas_f, total_area def distance_from_center(width, height, object_): ymin, ymax, xmin, xmax = find_bb(object_) image_center = ((height / 2), (width / 2)) #object_height = ymax-ymin #object_width = xmax-xmin object_center = (((xmax+xmin)/2)/width), ((ymax+ymin)/2/height) #print(object_center) if object_center[0] > 0.5 and object_center[1] > 0.5: position = 'UR' elif object_center[0] > 0.5 and object_center[1] <= 0.5: position = 'LR' elif object_center[0] <= 0.5 and object_center[1] <= 0.5: position = 'LL' else: position = 'UL' D = dist.euclidean((0.5, 0.5), object_center) #rel_position = np.subtract(object_center, (0.5, 0.5)) return D, position, object_center def get_random_eraser(p=0.5, s_l=0.02, s_h=0.4, r_1=0.3, r_2=1/0.3, v_l=0, v_h=255, pixel_level=False): def eraser(input_img): img_h, img_w, img_c = input_img.shape p_1 = np.random.rand() if p_1 > p: return input_img while True: s = np.random.uniform(s_l, s_h) * img_h * img_w r = np.random.uniform(r_1, r_2) w = int(np.sqrt(s / r)) h = int(np.sqrt(s * r)) left = np.random.randint(0, img_w) top = np.random.randint(0, img_h) if left + w <= img_w and top + h <= img_h: break if pixel_level: c = np.random.uniform(v_l, v_h, (h, w, img_c)) else: c = np.random.uniform(v_l, v_h) input_img[top:top + h, left:left + w, :] = c return input_img return eraser <file_sep>/detecting_gender/fine_tune_multiclass.py from keras.layers import Activation, Flatten, MaxPooling2D, Dropout from keras.layers import Convolution2D, ZeroPadding2D, Dense import keras.backend as K import tensorflow as tf from imutils import paths from sklearn.metrics import classification_report import matplotlib.pyplot as plt import matplotlib from keras.optimizers import SGD, Adam from keras.preprocessing.image import ImageDataGenerator from keras.models import Model from keras.models import Sequential from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau from utils import get_random_eraser import os.path import argparse from adabound import AdaBound import numpy as np import pandas as pd from keras_vggface.vggface import VGGFace matplotlib.use('agg') def get_optimizer(opt_name, lr, epochs): ''' set optimizer ''' if opt_name == 'sgd': return SGD(lr=lr, momentum=0.9, nesterov=False) elif opt_name == 'adam': return Adam(lr=lr) elif opt_name == 'adabound': return AdaBound(lr=1e-03, final_lr=0.1, gamma=1e-03, weight_decay=0., amsbound=False) else: raise ValueError("optimizer name should be 'sgd' or 'adam") def vgg_face(weights_path=None): ''' TODO replace with default function in keras (if model is the same) ''' model = Sequential() model.add(ZeroPadding2D((1, 1), input_shape=(224, 224, 3))) model.add(Convolution2D(64, (3, 3), activation='relu')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(128, (3, 3), activation='relu')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(128, (3, 3), activation='relu')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, (3, 3), activation='relu')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, (3, 3), activation='relu')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, (3, 3), activation='relu')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, (3, 3), activation='relu')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, (3, 3), activation='relu')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, (3, 3), activation='relu')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, (3, 3), activation='relu')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, (3, 3), activation='relu')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, (3, 3), activation='relu')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(Convolution2D(4096, (7, 7), activation='relu')) model.add(Dropout(0.5)) model.add(Convolution2D(4096, (1, 1), activation='relu')) # model.add(Dropout(0.5)) model.add(Convolution2D(2622, (1, 1))) model.add(Flatten()) model.add(Activation('softmax')) if weights_path: model.load_weights(weights_path) return model def get_callbacks(args): early_stop = EarlyStopping('val_loss', patience=args.patience, mode='max', verbose=1) reduce_lr = ReduceLROnPlateau( 'val_loss', factor=0.2, patience=int(args.patience/4), min_lr=0.000001, verbose=1) model_names = os.path.join( args.output_path, 'checkpoint-{epoch:02d}-{val_acc:2f}.hdf5') model_checkpoint = ModelCheckpoint(model_names, monitor='val_loss', verbose=1, save_best_only=True, mode='auto' ) return [early_stop, reduce_lr, model_checkpoint] def plot_training(H, plotPath): plt.style.use("ggplot") N = len(H.history["loss"]) plt.figure() plt.plot(np.arange(0, N), H.history["loss"], label="train_loss") plt.plot(np.arange(0, N), H.history["val_loss"], label="val_loss") plt.plot(np.arange(0, N), H.history["acc"], label="train_acc") plt.plot(np.arange(0, N), H.history["val_acc"], label="val_acc") plt.title("Training Loss and Accuracy") plt.xlabel("Epoch #") plt.ylabel("Loss/Accuracy") plt.legend(loc="lower left") plt.savefig(plotPath) def make_generators(args): trainPath = os.path.join(args.dataset, "train") valPath = os.path.join(args.dataset, "validation") testPath = os.path.join(args.dataset, "test") if args.eraser: preprocessing_function = get_random_eraser(pixel_level=True) else: preprocessing_function = None # initialize the training data augmentation objects trainAug = ImageDataGenerator( rescale=1.0 / 255, rotation_range=30, #zoom_range=[0, 0.2], width_shift_range=0.1, height_shift_range=0.1, shear_range=0.15, horizontal_flip=True, preprocessing_function=preprocessing_function, fill_mode="nearest" ) valAug = ImageDataGenerator( rescale=1.0 / 255 ) testAug = ImageDataGenerator( rescale=1.0 / 255 ) mean = np.array([123.68, 116.779, 103.939], dtype="float32") trainAug.mean = mean valAug.mean = mean testAug.mean = mean # initialize the training generator objects trainGen = trainAug.flow_from_directory( trainPath, class_mode="categorical", target_size=(args.image_size, args.image_size), color_mode="rgb", shuffle=True, batch_size=args.batch_size) # initialize the validation generator valGen = valAug.flow_from_directory( valPath, class_mode="categorical", target_size=(args.image_size, args.image_size), color_mode="rgb", shuffle=False, batch_size=args.batch_size) # initialize the testing generator testGen = testAug.flow_from_directory( testPath, class_mode="categorical", target_size=(args.image_size, args.image_size), color_mode="rgb", shuffle=False, batch_size=args.batch_size) print(testGen.class_indices.keys()) return trainGen, valGen, testGen def fine_tune(args): trainGen, valGen, testGen = make_generators(args) trainPath = os.path.join(args.dataset, "train") valPath = os.path.join(args.dataset, "validation") testPath = os.path.join(args.dataset, "test") totalTrain = len(list(paths.list_images(trainPath))) totalVal = len(list(paths.list_images(valPath))) totalTest = len(list(paths.list_images(testPath))) if not args.figures_path: os.makedir(args.figures_path) unfrozen_plot = os.path.join(args.figures_path, "unfrozen.png") warmup_plot = os.path.join(args.figures_path, "warmup.png") N_CATEGORIES = 4 ######################### print("[INFO] compiling model...") hidden_dim = 512 vgg_model = VGGFace(include_top=False, input_shape=(224, 224, 3)) last_layer = vgg_model.get_layer('pool5').output x = Flatten(name='flatten')(last_layer) x = Dense(hidden_dim, activation='relu', name='fc6')(x) x = Dense(hidden_dim, activation='relu', name='fc7')(x) x = Dropout(0.5, name='dropout')(x) out = Dense(N_CATEGORIES, activation='softmax', name='fc8')(x) gender_model = Model(vgg_model.input, out) for layer in vgg_model.layers: layer.trainable = False #model = vgg_face('models/vgg_face_weights.h5') opt = get_optimizer(args.opt, args.lr, args.n_epochs) gender_model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"]) callbacks = get_callbacks(args) # for layer in model.layers[:-7]: # layer.trainable = False ################################# print("[INFO] training head...") H = gender_model.fit_generator( trainGen, verbose=1, steps_per_epoch=totalTrain // args.batch_size, validation_data=valGen, callbacks=callbacks, validation_steps=totalVal // args.batch_size, epochs=args.n_epochs) ################################## print("[INFO] evaluating after fine-tuning network head...") testGen.reset() predIdxs = gender_model.predict_generator(testGen, steps=(totalTest // args.batch_size) + 1) predIdxs = np.argmax(predIdxs, axis=1) print(classification_report(testGen.classes, predIdxs, target_names=testGen.class_indices.keys())) plot_training(H, warmup_plot) trainGen.reset() valGen.reset() for layer in vgg_model.layers[15:]: layer.trainable = True for layer in vgg_model.layers: print("{}: {}".format(layer, layer.trainable)) print('re-compiling model') gender_model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"]) H = gender_model.fit_generator( trainGen, verbose=1, steps_per_epoch=totalTrain // args.batch_size, validation_data=valGen, callbacks=callbacks, validation_steps=totalVal // args.batch_size, epochs=20) print("[INFO] evaluating after fine-tuning network head...") testGen.reset() predIdxs = gender_model.predict_generator(testGen, steps=(totalTest // args.batch_size) + 1) predIdxs = np.argmax(predIdxs, axis=1) print(classification_report(testGen.classes, predIdxs, target_names=testGen.class_indices.keys())) plot_training(H, unfrozen_plot) print('saving model') pd.DataFrame(H.history).to_hdf(os.path.join("history.h5"), "history") gender_model.save(args.model_path) # # serialize the model to disk # print("[INFO] serializing network...") # pd.DataFrame(H.history).to_hdf("history.h5") # gender_model.save(args.model_path) def get_args(): parser = argparse.ArgumentParser(description="Fine-tuning vgg16 for gender estimation in historical adverts.", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--batch_size", type=int, default=64, help="batch size") parser.add_argument("--n_epochs", type=int, default=50, help="number of epochs") parser.add_argument("--lr", type=float, default=1e-3, help="initial learning rate") parser.add_argument("--opt", type=str, default="adabound", help="optimizer name; 'sgd' or 'adam'") parser.add_argument("--patience", type=int, default=6, help="Patience for callbacks") parser.add_argument("--image_size", type=int, default=224, help="Input size of images") parser.add_argument("--eraser", action="store_true") parser.add_argument("--dataset", type=str, default="../data/gender_2") parser.add_argument("--aug", action="store_true", help="use data augmentation if set true") parser.add_argument("--output_path", type=str, default="checkpoints", help="checkpoint dir") parser.add_argument("--figures_path", type=str, default="figures", help="path for figures") parser.add_argument("--model_path", type=str, default="multi_model.h5", help="model dir") args = parser.parse_args() return args if __name__ == '__main__': os.environ['KERAS_BACKEND'] = 'tensorflow' config = tf.ConfigProto() config.gpu_options.per_process_gpu_memory_fraction = 0.95 config.gpu_options.allow_growth = True sess = tf.Session(config=config) K.set_session(sess) args = get_args() fine_tune(args)
72358660720d45233b796f695327e1bc2032788d
[ "Markdown", "Python" ]
6
Markdown
melvinwevers/detecting_faces-medium-types-gender
eac51acdcc19b073b6a3a46275e3d47abdbc3b6f
3491a9154563f99e8b9111d1d4b4ba38fda4efc7
refs/heads/master
<file_sep>let p = {}; const e = { name: 'Ethan', age: '11', color: 'orange' }; let n = null; let userInput = null; let loop = 0; cTime = null; $('#info').submit(function (e) { e.preventDefault(); userInput = $('#input').val(); cb(); }); $('#fastforward').submit(function (e) { e.preventDefault(); clearTimeout(p.timeout.id); clearInterval(p.timeout.timeID); p.timeout = null; time(cTime); cb(); }); r('What is your name?'); function cb() { if (loop === 0) { if (userInput == 'gasp') { r('Welcome to the Byron easter egg.'); w(r, 'Unfortunately, he has requested a space paradox and everything we know is now lost.'); w(r, 'Goodbye, spaced out world.', 2); w(reset, 'https://media1.tenor.com/images/5ff9790dc2a52e2d61239c1eeda56255/tenor.gif', 4); } else { if (userInput == 'gaeCooper') { r('Welcome to the Cooper easter egg.'); w(r, 'Unfortunately, he has requested a picture of the worst football team ever.'); w(r, 'Goodbye, football-ly world.', 2); w(reset, 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgkLoFg5CIjBGQytTw-fIs0rCfjZ0wS3TBYnGq59oSiN2E1XU6Rg:https://txcityservices.com/wp-content/uploads/2018/04/Dallas-Cowboys-Logo.jpg', 4); } else { p.name = userInput; r('Hello ' + p.name + '!'); w(r, 'My name is ' + e.name + '!'); w(r, 'How old are you?', 2); $('#input').attr({type: 'number', min: 1, max: 122}); w(s, null, 2); } } } if (loop == 1) { p.age = Math.floor(userInput); r('Being ' + p.age + ' is awesome!'); w(r, 'I\'m ' + e.age + ' years old' + (p.age == e.age ? ' too!' : '!')); w(r, 'What\'s your favorite color?', 2); $('#input').attr({type: 'color'}); w(s, null, 2); } if (loop == 2) { p.color = userInput; document.body.style.background = p.color; r('There we go.'); w(r, 'This is my favorite color.', 1); w(function () { $('div').css('backgroundColor', e.color); }, null, 2); w(r, 'Oh, wait. I need to go to basketball practice now.', 3); w(r, 'Be back in an hour.', 4); p.timeout = { id: setTimeout(timef, 1000 * 60 * 60), timeID: setInterval(time, 1000 * 60) }; cTime = { h: 5, m: 59 }; w(s, !0, 5); } if (loop == 3) { if (p.timeout) { r('You actually waited a hour?'); w(r, 'Nice!'); p.timeout = null; } else { r('Puny human using puny button...'); w(r, 'Also, be warned that pressing Fast Forward 3 times will cause a time paradox.'); } h(); w(r, 'Anyway, let\'s play a game.', 2); w(r, 'I bet you can\'t guess what number I\'m thinking of!', 3); w(r, 'Rules: Ethan will think of a number between 1 and 10. You have to try and guess the number. Every time you are incorrect, ' + 'Ethan will tell you if it is too high or too low.', 4); w(function() { $('#fastforward').attr({ value: 'Start' }); w(s, true, 4); $('#input').attr({type: 'number', min: 1, max: 10 }, null, 4); }); } loop++; h(); h(!0); time(); } function time(e = null) { if (e) { timeE.innerHTML = e.h + ':' + e.m; } else { timeE = $('#time'); timeT = timeE.html().split(':'); timeT[1]++; if (timeT[1] == 60) { timeT[1] = 0; timeT[0]++; } if (timeT[0] == 12) { timeT[0] = 1; } timeE.html(timeT.join(':' + ((timeT[1] < 10) ? '0' : ''))); } } function r(text) { response = $('<p>' + htmlentities(text) + '</p>'); $('#text').append(response); } function w(f, p = null, m = 1) { if (p) { setTimeout(f, 1000 * m, p); } else { setTimeout(f, 1000 * m); } } function s(f = !1) { if (f) { $('#fastforward').css('display', 'initial'); } else { $('#info').css('display', 'initial'); } } function h(f = !1) { if (f) { $('#fastforward').hide(); } else { $('#info').hide(); } } function timef() { cb(); clearInterval(p.timeout.timeID); time(cTime); } function htmlentities(str) { return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); } function reset(url) { $('div').css('display', 'none'); $('body').css('background', 'url(' + url + ') no-repeat center center fixed'); $('body').css('backgroundSize', 'cover'); }
a6a56d9af950804410fdf282989a0e7171772dde
[ "JavaScript" ]
1
JavaScript
z331it3cod3r/ethan
afc2f730c89c78e1f84e1d76f974f39f46bc8eae
dcb53eb7e123b3a547a8f32d3ef67ec39c515717
refs/heads/master
<file_sep>export const getAll = model => async (req, res) => { try { const docs = await model .find({}) .lean() .exec(); res.status(200).json({ data: docs }); } catch (e) { console.error(e); res.status(400).end(); } }; export const createOne = model => async (req, res) => { try { const doc = await model.create({ ...req.body }); res.status(201).json({ data: doc }); } catch (e) { console.error(e); res .status(400) .send({ error: e }) .end(); } }; export const removeOne = model => async (req, res) => { try { const removed = await model.findOneAndRemove({ _id: req.params.id }); if (!removed) { return res.status(400).end(); } return res.status(200).json({ data: removed }); } catch (e) { console.error(e); res.status(400).end(); } }; export const findById = model => async (req, res) => { try { const docs = await model .find({ _id: req.params.id }) .lean() .exec(); res.status(200).json({ data: docs }); } catch (e) { console.error(e); res.status(400).end(); } }; export const crudControllers = model => ({ getAll: getAll(model), removeOne: removeOne(model), createOne: createOne(model), findById: findById(model) }); <file_sep>import { crudControllers } from "../../utils/crud"; import { Product } from "./product.model"; export const searchByBrand = async (req, res) => { try { if (req.body.brand === "all" || !req.body.brand) { const products = await Product.find({}) .lean() .exec(); res.status(200).json({ data: products }); } else { const products = await Product.find({ brand: req.body.brand.trim().toLowerCase() }) .lean() .exec(); res.status(200).json({ data: products }); } } catch (e) { console.error(e); res.status(400).end(); } }; export default crudControllers(Product); <file_sep>import mongoose from "mongoose"; const orderScheema = new mongoose.Schema( { orderName: { type: String, required: true, trim: true, default: "Pedido Não Nomeado" }, products: { type: [mongoose.SchemaTypes.ObjectId], ref: "product", required: true } }, { timestamps: true } ); export const Order = mongoose.model("order", orderScheema); <file_sep>import { Router } from "express"; import controller from "./order.controller"; const router = Router(); router .route("/") .get(controller.getAll) .post(controller.createOne); export default router; <file_sep>import { Router } from "express"; import controller, { searchByBrand } from "./product.controller"; const router = Router(); router.route("/").post(controller.createOne); router.route("/marca").post(searchByBrand); router.route("/:id").get(controller.findById); export default router; <file_sep>import express from "express"; import { json } from "body-parser"; import config from "./config"; import cors from "cors"; import { connect } from "./utils/db"; import productRouter from "./resources/product/product.router"; import orderRouter from "./resources/order/order.router"; export const app = express(); const router = express.Router(); app.disable("x-powered-by"); app.use(cors()); app.use(json()); app.use("/", router); app.use("/produtos", productRouter); app.use("/pedidos", orderRouter); export const start = async () => { try { await connect(); app.listen(config.port, () => { console.log(`REST API on http://localhost:${config.port}`); }); } catch (e) { console.error(e); } }; <file_sep>import mongoose from "mongoose"; const productSchema = new mongoose.Schema( { name: { type: String, required: true, trim: true }, imageUrl: { type: String, required: true }, brand: { type: String, required: true, trim: true } }, { timestamps: true } ); export const Product = mongoose.model("product", productSchema);
b3ec359c1de44e6bcff83b371c25b433ca12d70b
[ "JavaScript" ]
7
JavaScript
GabrielGalatti/Ziro.api
73f970bc407d6324461e4879681faeba7af625b4
acaad6a3c7f3bb08f0742c8298d393ecd4857c05
refs/heads/main
<file_sep>''' Game runs from this file. ''' import board import players game_logo = """ ================================================================================== ████████ ██ ██████ ████████ █████ ██████ ████████ ██████ ███████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ █████ ██ ███████ ██ █████ ██ ██ ██ █████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██████ ██ ██ ██ ██████ ██ ██████ ███████ ================================================================================== """ print(f"{game_logo}\nHello, this is a classic Tic-Tac-Toe game. You are going to play against a computer.\nEach cell has a number from 1 to 9. Like this:\n") print(''' [1][2][3] [4][5][6] [7][8][9] ''') while True: 'Game loop. Runs until user quits the game.' while True: 'Input validation loop. Runs until a valid symbol is chosen.' print("\n> Choose 'X' or '0' to start the game: ", end="") try: player_choice = input() assert player_choice in ["X", "0"] # Throw exception if this condition is not met print(f"\nYou are playing as {player_choice}") break except: print("\nTry again! You can only choose 'X' or '0'\n") continue # restart the inner loop ## Instantiate players and the game board human = players.Human(player_choice) b1 = board.Board(human.symbol,human.computer.symbol) b1.show_board() while b1.end_game() == False: 'Loop for taking turns. Runs until game ends in a win or a draw.' print("\n> It's your turn. Choose a valid cell: ", end="") try: 'Move validation' player_move = int(input()) if b1.end_game() != False: 'If the game ends, break the loop' break assert b1.make_move(player_move, "Human") == True # throw an exception is the move is not valid print(f"\nYou moved to cell {player_move}") b1.show_board() if b1.end_game() != False: break b1.make_move(b1.calculate_move(), "Computer") print("\nComputer made the move") b1.show_board() except: 'Move is not valid' print("\nThat's not a valid move. Try again!") pass print("\n",b1.end_game(), end="\n") user_replay = input("\n> Press any key to restart the game. Type 'Q' to quit.") if user_replay == "Q": break print("\nGoodbye!\n")<file_sep># Tic-Tac-Toe - Python Console Game ## How to play Simply run ```main.py``` and follow in-game directions ## Screenshot <img src="https://user-images.githubusercontent.com/72061626/162598001-02c8ff8a-058b-4afa-9b2f-2f82d42d8f66.png" width="600"> ## Computer algorithm Computer is focused on winning in least possible moves. Its decision making follows 4 steps (decreasing priority): 1. (Attack) Try to win in 1 move 2. (Defend) Prevent opponent from winning in 1 move 3. (Neutral move) If 2 and 3 don't work, move to a neutral cell and start building a winning combo -> random move 4. (Draw) If there is no way to build a winning combo, make it a draw -> random move To make the game more interesting, there is a possibilty that computer makes mistakes for 2 reasons: 1. There are ways to win Tic-Tac-Toe 100% percent but the computer is not going to block such moves -> the computer does not plan moves ahead 2. Neutral moves (that don't lead to win or loss in 1 move) are random ## Why I made this My main goal was to practice the following Python concepts: - @property decorators - OOP (Inheritance) - List/Set/Dictionary comprehension - Map and Filter functions - Lambdas - Random library - Set operations <img src="https://user-images.githubusercontent.com/72061626/162598075-08cbfbf0-0c87-4bab-9e9b-16b97fc942df.jpg" width="300"> ## License [MIT](https://choosealicense.com/licenses/mit/) <file_sep>''' Player parent class is responsible for instantiating humans and computers ''' class Player: 'Right now this parent class is empty but this OOP structure makes it easier to add more variables down the line if needed' def __init__(self): pass class Human(Player): 'This is a class controller by the human player. Computer child class is created automatically' def __init__(self, symbol): super().__init__() self.symbol = symbol if self.symbol == "X": self.computer = Computer("0") else: self.computer = Computer("X") class Computer(Player): def __init__(self, symbol): super().__init__() self.symbol = symbol <file_sep>''' board class is responsible for creating and showing 3x3x3 board, validating moves, computer AI moves and deciding when the game ends and how ''' import random class Board: def __init__(self, human_symbol, computer_symbol): self.cells = {1:" ", 2:" ", 3:" ", 4:" ", 5:" ", 6:" ", 7:" ", 8:" ",9:" "} # this dictionary shows the current state of the game self.symbols = {"Human":human_symbol, "Computer":computer_symbol} self.win_combos = [{1,2,3}, {4,5,6}, {7,8,9}, # these are all possible ways you can win at Tic-Tac-Toe {1,4,7}, {2,5,8}, {3,6,9}, {1,5,9}, {3,5,7}] @property def computer_positions(self): 'Returns A SET of all cells where the computer has made moves' return {cell[0] for cell in list(filter(lambda cell: cell[1] == self.symbols["Computer"], self.cells.items()))} @property def human_positions (self): 'Returns A SET of all cells where the human player has made moves' return {cell[0] for cell in list(filter(lambda cell: cell[1] == self.symbols["Human"], self.cells.items()))} @property def empty_positions (self): 'Returns A SET of all cells that are empty' return {cell[0] for cell in list(filter(lambda cell: cell[1] == " ", self.cells.items()))} def show_board(self): 'Displayes 3x3x3 board in its current state' print("\n") for key, value in self.cells.items(): row = "" row += f"[{value}]" if key % 3 == 0: row += "\n" print(row, end="") def end_game(self): 'Returns False if the game has not yet ended' if len(self.empty_positions) == 0: return "It's a draw!" for i in self.win_combos: if len(i.intersection(self.computer_positions)) == 3: return "You lost!" elif len(i.intersection(self.human_positions)) == 3: return "You won!" return False def make_move(self, cell, controller): 'Validates the move that the computer or human is trying to make and updates a corresponding cell' if cell in self.cells.keys() and self.cells[cell] == " ": self.cells[cell] = self.symbols[controller] return True return False def calculate_move(self): ''' Main algorithm that decides how computer should make the move. Computer is focused on winning in least possible moves. The decision making follows 4 steps: 1. Try to win in 1 move 2. Prevent opponent from winning in 1 move 3. If 2 and 3 don't work, move to a neutral cell and start building a winning combo -> random move 4. If there is no way to build a winning combo, make it a draw -> random move To make the game more interesting, there is a possibilty that computer makes mistakes for 2 reasons: 1. There are ways to win Tic-Tac-Toe 100% percent but the computer is not going to block such moves -> the computer does not plan moves ahead 2. Neutral moves (that don't lead to win or loss in 1 move) are random ''' win_combos = self.win_combos neutral_options_all = [row for row in win_combos if not row.intersection(self.human_positions)] neutral_options = [row.difference(self.computer_positions) for row in neutral_options_all if len(row.difference(self.computer_positions))>1] defense_options = [row.difference(self.human_positions) for row in win_combos if len(row.difference(self.human_positions)) == 1 and row.difference(self.human_positions).difference(self.computer_positions)] attack_options = [row.difference(self.computer_positions) for row in neutral_options_all if len(row.difference(self.computer_positions))==1] if len(attack_options) != 0: 'There is an opportunity to win in 1 move' return random.choice(list(map(lambda x: x.pop() if (len(x) == 1) else None, attack_options))) elif len(defense_options) != 0: 'Defense is needed otherwise opponent wins' return random.choice(list(map(lambda x: x.pop() if (len(x) == 1) else None, defense_options))) elif len(neutral_options) != 0: 'Move to an empty cell which has a chance to build a winning combo' return random.choice(list(random.choice(neutral_options))) else: 'Move to a random empty cell -> leads to a draw' return random.choice(list(self.empty_positions))
68d53e03ddec39ad03093e8bf5fc451997cbb1a2
[ "Markdown", "Python" ]
4
Python
georgeberidze/tic-tac-toe
6b9417ab3a38716153ee5c0c205191c9ca48c4e0
55e9406cfbed03a1722873134f3caab34f809298
refs/heads/main
<repo_name>viniciuss19/avaliacao-senai<file_sep>/README.md # avaliacao-senai Avaliação dos alunos Vinícius e Henzo <file_sep>/Avaliação/Avaliação/GerenciarPlanos.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace Avaliação { public partial class GerenciarPlanos : Form { public GerenciarPlanos() { InitializeComponent(); } private void GerenciarPlanos_Load(object sender, EventArgs e) { AtualizarClientes(); AtualizarPlanos(); AtualizarLinhas(); } public void AtualizarLinhas() { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; sql.CommandText = $"Select * FROM Linhas"; try { conexao.Open(); int i = sql.ExecuteNonQuery(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } finally { SqlDataAdapter adaptador = new SqlDataAdapter(sql.CommandText, conexao); DataTable tabela = new DataTable(); adaptador.Fill(tabela); dgvLinhas.DataSource = tabela; dgvLinhas.ClearSelection(); conexao.Close(); } } public void AtualizarClientes() { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; sql.CommandText = $"Select * FROM Clientes"; try { conexao.Open(); int i = sql.ExecuteNonQuery(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } finally { SqlDataAdapter adaptador = new SqlDataAdapter(sql.CommandText, conexao); DataTable tabela = new DataTable(); adaptador.Fill(tabela); dgvClientes.DataSource = tabela; dgvClientes.ClearSelection(); conexao.Close(); } } public void AtualizarPlanos() { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; sql.CommandText = $"Select * FROM Planos"; try { conexao.Open(); int i = sql.ExecuteNonQuery(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } finally { SqlDataAdapter adaptador = new SqlDataAdapter(sql.CommandText, conexao); DataTable tabela = new DataTable(); adaptador.Fill(tabela); dgvPlanos.DataSource = tabela; dgvPlanos.ClearSelection(); conexao.Close(); } } private void dgvClientes_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { DataGridViewRow row = this.dgvClientes.Rows[e.RowIndex]; tbIDCliente.Text = row.Cells["ID"].Value.ToString(); tbCPF.Text = row.Cells["CPF"].Value.ToString(); tbTelefone.Text = row.Cells["Telefone"].Value.ToString(); tbNomeCliente.Text = row.Cells["Nome"].Value.ToString(); } } private void dgvPlanos_CellContentClick(object sender, DataGridViewCellEventArgs e) { DataGridViewRow row = this.dgvPlanos.Rows[e.RowIndex]; tbNomePlano.Text = row.Cells["Nome_Plano"].Value.ToString(); tbIDPlano.Text = row.Cells["ID"].Value.ToString(); tbFranquia.Text = row.Cells["Franquia"].Value.ToString(); tbMensalidade.Text = row.Cells["Mensalidade"].Value.ToString(); } private void button1_Click(object sender, EventArgs e) { ModificarPlanoCliente(); } public void ModificarPlanoCliente() { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; try { conexao.Open(); sql.CommandText = $"UPDATE Linhas SET IDPlano = @idplano WHERE ID = @idlinhas AND IDCliente = @idcliente"; sql.Parameters.AddWithValue("@idplano", tbIDPlano.Text); sql.Parameters.AddWithValue("@idlinhas", tbIDLinhas.Text); sql.Parameters.AddWithValue("@idcliente", tbIDCliente.Text); int i = sql.ExecuteNonQuery(); } catch(Exception e) { MessageBox.Show(e.ToString()); } finally { MessageBox.Show($"O plano do cliente foi alterado para o plano com o ID {tbIDPlano.Text}"); conexao.Close(); tbCPF.Clear(); tbFranquia.Clear(); tbNomeCliente.Clear(); tbIDCliente.Clear(); tbIDPlano.Clear(); tbTelefone.Clear(); tbMensalidade.Clear(); } } private void label13_Click(object sender, EventArgs e) { new MenuPrincipal().Show(); this.Hide(); } private void dgvLinhas_CellContentClick(object sender, DataGridViewCellEventArgs e) { if(e.RowIndex >= 0) { DataGridViewRow row = this.dgvLinhas.Rows[e.RowIndex]; tbIDLinhas.Text = row.Cells["ID"].Value.ToString(); } } } } <file_sep>/Avaliação/Avaliação/Linha.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Avaliação { class Linha { private int _id; private int _idcliente; private int _idplano; private int _numero; private DateTime _datacompra; private string _ativo; public int ID { get => _id; set => _id = value; } public int IDCliente { get => _idcliente; set => _idcliente = value; } public int IDPlano { get => _idplano; set => _idplano = value; } public int Número { get => _numero; set => _numero = value; } public DateTime DataCompra { get => _datacompra; set => _datacompra = value; } public string Ativo { get => _ativo; set => _ativo = value; } } } <file_sep>/Avaliação/Avaliação/BD.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace Avaliação { class BD { static SqlConnection conexao = new SqlConnection(); static SqlCommand sql = new SqlCommand(); public static SqlDataAdapter Inicializar() { SqlCommand sql = new SqlCommand(); SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; sql.Connection = conexao; SqlDataAdapter adaptador = new SqlDataAdapter(sql.CommandText, conexao); return adaptador; } public static int Executar(out SqlDataAdapter adaptador) { conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; sql.Connection = conexao; adaptador = Inicializar(); int i = 0; conexao.Open(); i = sql.ExecuteNonQuery(); conexao.Close(); return i; } public static int Executar() { return Executar(out SqlDataAdapter adaptador); } public static int EditarCliente(int id, Cliente c) { SqlCommand sql = new SqlCommand(); sql.CommandText = $"UPDATE Clientes SET Nome = @nome, Telefone = @telefone, Rua = @rua WHERE ID = @id"; sql.Parameters.AddWithValue("@nome", c.Nome); sql.Parameters.AddWithValue("@telefone", c.Telefone); sql.Parameters.AddWithValue("@rua", c.Rua); sql.Parameters.AddWithValue("@id", id); int linhas = Executar(); return linhas; } } } <file_sep>/Avaliação/Avaliação/MenuPrincipal.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace Avaliação { public partial class MenuPrincipal : Form { public MenuPrincipal() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { new InserirCliente().Show(); this.Hide(); } private void label3_Click(object sender, EventArgs e) { } private void pictureBox2_Click(object sender, EventArgs e) { PesquisarNomeCliente(); lbltabela.Text = "Busca por nome..."; } private void MenuPrincipal_Load(object sender, EventArgs e) { AtualizarDGVClientes(); } public void AtualizarDGVClientes() { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; sql.CommandText = $"Select * FROM Clientes"; try { conexao.Open(); int i = sql.ExecuteNonQuery(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } finally { SqlDataAdapter adaptador = new SqlDataAdapter(sql.CommandText, conexao); DataTable tabela = new DataTable(); adaptador.Fill(tabela); dgvClientes.DataSource = tabela; dgvClientes.ClearSelection(); conexao.Close(); } } public void PesquisarNomeCliente() { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; sql.CommandText = $"SELECT * FROM Clientes WHERE Nome LIKE '%{tbNomePesquisar.Text}%'"; try { conexao.Open(); int i = sql.ExecuteNonQuery(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } finally { SqlDataAdapter adaptador = new SqlDataAdapter(sql.CommandText, conexao); DataTable tabela = new DataTable(); adaptador.Fill(tabela); dgvClientes.DataSource = tabela; dgvClientes.ClearSelection(); conexao.Close(); } } public void PesquisarCPFCliente() { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; sql.CommandText = $"SELECT * FROM Clientes WHERE CPF LIKE '%{tbCPFPesquisar.Text}%'"; try { conexao.Open(); int i = sql.ExecuteNonQuery(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } finally { SqlDataAdapter adaptador = new SqlDataAdapter(sql.CommandText, conexao); DataTable tabela = new DataTable(); adaptador.Fill(tabela); dgvClientes.DataSource = tabela; dgvClientes.ClearSelection(); conexao.Close(); } } public void PesquisarTelefoneCliente() { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; try { conexao.Open(); sql.CommandText = $"SELECT * FROM Clientes WHERE Telefone LIKE '%{tbTelefonePesquisar.Text}%'"; int i = sql.ExecuteNonQuery(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } finally { SqlDataAdapter adaptador = new SqlDataAdapter(sql.CommandText, conexao); DataTable tabela = new DataTable(); adaptador.Fill(tabela); dgvClientes.DataSource = tabela; dgvClientes.ClearSelection(); conexao.Close(); } } private void pbPesquisarCPF_Click(object sender, EventArgs e) { PesquisarCPFCliente(); lbltabela.Text = "Busca por CPF"; } private void pbPesquisarTelefone_Click(object sender, EventArgs e) { PesquisarTelefoneCliente(); lbltabela.Text = "Busca por telefone"; } private void button2_Click(object sender, EventArgs e) { AtualizarDGVClientes(); lbltabela.Text = "Tabela de Clientes..."; } private void label1_Click(object sender, EventArgs e) { } private void button3_Click(object sender, EventArgs e) { new GerenciarCliente().Show(); this.Hide(); } private void button4_Click(object sender, EventArgs e) { new AdicionarLinhas().Show(); this.Hide(); } public void AtualizarLinha() { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; try { conexao.Open(); sql.CommandText = $"SELECT * FROM Linhas"; int i = sql.ExecuteNonQuery(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } finally { SqlDataAdapter adaptador = new SqlDataAdapter(sql.CommandText, conexao); DataTable tabela = new DataTable(); adaptador.Fill(tabela); dgvLinhas.DataSource = tabela; dgvLinhas.ClearSelection(); conexao.Close(); } } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void dgvClientes_CellContentClick(object sender, DataGridViewCellEventArgs e) { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; int linhaselecionada = dgvClientes.SelectedCells[0].RowIndex; int IdCliente = (int)dgvClientes.Rows[linhaselecionada].Cells[0].Value; try { conexao.Open(); string idcliente = tbIDcliente.Text; sql.CommandText = $"SELECT * FROM Linhas WHERE IDCliente = {IdCliente}"; int i = sql.ExecuteNonQuery(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } finally { SqlDataAdapter adaptador = new SqlDataAdapter(sql.CommandText, conexao); DataTable tabela = new DataTable(); adaptador.Fill(tabela); dgvLinhas.DataSource = tabela; dgvLinhas.ClearSelection(); conexao.Close(); } } private void button5_Click(object sender, EventArgs e) { new GerenciarLinhas().Show(); this.Hide(); } private void button6_Click(object sender, EventArgs e) { new GerenciarPlanos().Show(); this.Hide(); } private void button7_Click(object sender, EventArgs e) { } } } <file_sep>/Avaliação/Avaliação/Cliente.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Avaliação { class Cliente { private string _nome; private int _CPF; private string _telefone; private int _CEP; private string _estado; private string _cidade; private string _rua; private string _número; private string _complemento; private int _id; public int ID { get => _id; set => _id = value; } public string Nome { get => _nome; set => _nome = value; } public int CPF { get => _CPF; set => _CPF = value; } public string Telefone { get => _telefone; set => _telefone = value; } public int CEP { get => _CEP; set => _CEP = value; } public string Estado { get => _estado; set => _estado = value; } public string Cidade { get => _cidade; set => _cidade = value; } public string Rua { get => _rua; set => _rua = value; } public string Número { get => _número; set => _número = value; } public string Complemento { get => _complemento; set => _complemento = value; } public Cliente(string nome, int cpf, string telefone, int cep, string estado, string cidade, string rua, string número, string complemento) { Nome = nome; CPF = cpf; Telefone = telefone; CEP = cep; Estado = estado; Cidade = cidade; Rua = rua; Número = número; Complemento = complemento; } public Cliente(string nome, string telefone, string rua) { Nome = nome; Telefone = telefone; Rua = rua; } } } <file_sep>/Avaliação/Avaliação/Plano.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Avaliação { class Plano { private string _nomeplano; private string _franquiagb; private string _conteudosilimitados; private string _caracteristicas; private float _mensalidade; public string NomePlano { get => _nomeplano; private set => _nomeplano = value; } public string FranquiaGB { get => _franquiagb; set => _franquiagb = value; } public string ConteudosIlimitados { get => _conteudosilimitados; set => _conteudosilimitados = value; } public string Caracteristicas { get => _caracteristicas; set => _caracteristicas = value; } public float Mensalidade { get => _mensalidade; set => _mensalidade = value; } } } <file_sep>/Avaliação/Avaliação/GerenciarCliente.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace Avaliação { public partial class GerenciarCliente : Form { public GerenciarCliente() { InitializeComponent(); } private void GerenciarCliente_Load(object sender, EventArgs e) { AtualizarClientes(); } public void AtualizarClientes() { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; sql.CommandText = $"Select * FROM Clientes"; try { conexao.Open(); int i = sql.ExecuteNonQuery(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } finally { SqlDataAdapter adaptador = new SqlDataAdapter(sql.CommandText, conexao); DataTable tabela = new DataTable(); adaptador.Fill(tabela); dgvClientes.DataSource = tabela; dgvClientes.ClearSelection(); conexao.Close(); } } private void textBox1_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { int id = int.Parse(tbID.Text); EditarCliente(id); } private void dgvClientes_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { DataGridViewRow row = this.dgvClientes.Rows[e.RowIndex]; tbNome.Text = row.Cells["Nome"].Value.ToString(); tbTelefone.Text = row.Cells["Telefone"].Value.ToString(); tbEstado.Text = row.Cells["Estado"].Value.ToString(); tbCidade.Text = row.Cells["Cidade"].Value.ToString(); tbRua.Text = row.Cells["Rua"].Value.ToString(); tbNumero.Text = row.Cells["Número"].Value.ToString(); tbID.Text = row.Cells["ID"].Value.ToString(); } } public void EditarCliente(int id) { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; try { conexao.Open(); sql.CommandText = $"UPDATE Clientes SET Nome = @nome, Telefone = @telefone, Rua = @rua, Estado = @estado, Cidade = @cidade, Número = @numero WHERE ID = @id"; sql.Parameters.AddWithValue("@nome", tbNome.Text); sql.Parameters.AddWithValue("@telefone", tbTelefone.Text); sql.Parameters.AddWithValue("@rua", tbRua.Text); sql.Parameters.AddWithValue("@cidade", tbCidade.Text); sql.Parameters.AddWithValue("@estado", tbEstado.Text); sql.Parameters.AddWithValue("@numero", tbNumero.Text); sql.Parameters.AddWithValue("@id", id); int i = sql.ExecuteNonQuery(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } finally { MessageBox.Show("Editado com sucesso!"); AtualizarClientes(); tbNome.Clear(); tbEstado.Clear(); tbTelefone.Clear(); tbRua.Clear(); tbCidade.Clear(); tbID.Clear(); tbNumero.Clear(); } } private void label7_Click(object sender, EventArgs e) { } private void label10_Click(object sender, EventArgs e) { new MenuPrincipal().Show(); this.Hide(); } private void button1_Click_1(object sender, EventArgs e) { RemoverCliente(); AtualizarClientes(); } public void RemoverCliente() { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; try { conexao.Open(); sql.CommandText = "DELETE FROM Clientes WHERE Nome = '" + tbNome.Text + " ' AND ID = '" + tbID.Text + "'"; int i = sql.ExecuteNonQuery(); } catch (Exception e) { MessageBox.Show(e.ToString()); } finally { MessageBox.Show($"O Cliente {tbNome.Text} foi removido com sucesso"); } } } } <file_sep>/Avaliação/Avaliação/GerenciarLinhas.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace Avaliação { public partial class GerenciarLinhas : Form { public GerenciarLinhas() { InitializeComponent(); } private void GerenciarLinhas_Load(object sender, EventArgs e) { AtualizarLinhas(); } public void AtualizarLinhas() { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; sql.CommandText = $"Select * FROM Linhas"; try { conexao.Open(); int i = sql.ExecuteNonQuery(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } finally { SqlDataAdapter adaptador = new SqlDataAdapter(sql.CommandText, conexao); DataTable tabela = new DataTable(); adaptador.Fill(tabela); dgvLinhasGerenciar.DataSource = tabela; dgvLinhasGerenciar.ClearSelection(); conexao.Close(); } } private void button1_Click(object sender, EventArgs e) { int id = int.Parse(tbIDLinha.Text); AtivarLinha(id); } public void AtivarLinha(int id) { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; try { conexao.Open(); sql.CommandText = $"UPDATE Linhas SET Ativo = @ativo WHERE ID = @id"; sql.Parameters.AddWithValue("@ativo", "Ativo"); sql.Parameters.AddWithValue("@id", tbIDLinha.Text); int i = sql.ExecuteNonQuery(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } finally { MessageBox.Show($"A Linha do id {tbIDLinha.Text} foi editada com sucesso ROUF ROOOUUFF"); AtualizarLinhas(); tbIDLinha.Clear(); tbAtivoLinha.Clear(); tbNumeroLinha.Clear(); conexao.Close(); } } public void DesativarLinha(int id) { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; try { conexao.Open(); sql.CommandText = $"UPDATE Linhas SET Ativo = @ativo WHERE ID = @id"; sql.Parameters.AddWithValue("@ativo", "Inativo"); sql.Parameters.AddWithValue("@id", tbIDLinha.Text); int i = sql.ExecuteNonQuery(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } finally { MessageBox.Show($"A Linha com o id {tbIDLinha.Text} foi editada com sucesso ROUF ROOOUUFF"); AtualizarLinhas(); tbIDLinha.Clear(); tbAtivoLinha.Clear(); tbNumeroLinha.Clear(); conexao.Close(); } } private void dgvLinhasGerenciar_CellContentClick(object sender, DataGridViewCellEventArgs e) { if(e.RowIndex >= 0) { DataGridViewRow row = this.dgvLinhasGerenciar.Rows[e.RowIndex]; tbAtivoLinha.Text = row.Cells["Ativo"].Value.ToString(); tbIDLinha.Text = row.Cells["ID"].Value.ToString(); tbNumeroLinha.Text = row.Cells["Número"].Value.ToString(); } } private void button2_Click(object sender, EventArgs e) { int id = int.Parse(tbIDLinha.Text); DesativarLinha(id); } private void label6_Click(object sender, EventArgs e) { new MenuPrincipal().Show(); this.Hide(); } private void button3_Click(object sender, EventArgs e) { PesquisarIDCliente(); } public void PesquisarIDCliente() { SqlConnection conexao = new SqlConnection(); SqlCommand sql = new SqlCommand(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; sql.Connection = conexao; try { conexao.Open(); sql.CommandText = $"Select * FROM Linhas WHERE IDCliente = {tbPesquisarIDC.Text}"; int i = sql.ExecuteNonQuery(); } catch(Exception e) { MessageBox.Show(e.ToString()); } finally { SqlDataAdapter adaptador = new SqlDataAdapter(sql.CommandText, conexao); DataTable tabela = new DataTable(); adaptador.Fill(tabela); dgvLinhasGerenciar.DataSource = tabela; dgvLinhasGerenciar.ClearSelection(); conexao.Close(); tbPesquisarIDC.Clear(); } } } } <file_sep>/Avaliação/Avaliação/InserirCliente.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace Avaliação { public partial class InserirCliente : Form { public InserirCliente() { InitializeComponent(); } private void InserirCliente_Load(object sender, EventArgs e) { } private void label11_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { if (txtNome.Text == "") { MessageBox.Show("Preencha os campos restantes"); txtNome.Focus(); lblfalachefe.Text = "ROUF PREENCHA OS CAMPOS"; } else if (txtCPF.Text == "") { MessageBox.Show("Preencha os campos restantes"); txtCPF.Focus(); lblfalachefe.Text = "ROUF PREENCHA OS CAMPOS"; } else if (txtTelefone.Text == "") { MessageBox.Show("Preencha os campos restantes"); txtTelefone.Focus(); lblfalachefe.Text = "ROUF PREENCHA OS CAMPOS"; } else if (txtCEP.Text == "") { MessageBox.Show("Preencha os campos restantes"); txtCEP.Focus(); lblfalachefe.Text = "ROUF PREENCHA OS CAMPOS"; } else if (txtRua.Text == "") { MessageBox.Show("Preencha os campos restantes"); txtRua.Focus(); lblfalachefe.Text = "ROUF PREENCHA OS CAMPOS"; } else if (txtCidade.Text == "") { MessageBox.Show("Preencha os campos restantes"); txtCidade.Focus(); lblfalachefe.Text = "ROUF PREENCHA OS CAMPOS"; } else if (txtEstado.Text == "") { MessageBox.Show("Preencha os campos restantes"); txtEstado.Focus(); } else if (txtNúmero.Text == "") { MessageBox.Show("Preencha os campos restantes"); txtNúmero.Focus(); lblfalachefe.Text = "ROUF PREENCHA OS CAMPOS"; } else { lblfalachefe.Text = "ROOOOOOOOOOOOOOUUUUFFFFFF"; AdicionarCliente(); } } private void lblfalachefe_Click(object sender, EventArgs e) { } public void AdicionarCliente() { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; try { conexao.Open(); sql.CommandText = $"INSERT INTO Clientes(Nome,CPF,Telefone,CEP,Estado,Cidade,Rua,Número,Complemento) VALUES (@nome,@cpf,@telefone,@cep,@estado,@cidade,@rua,@número,@complemento)"; sql.Parameters.AddWithValue("@nome", txtNome.Text); sql.Parameters.AddWithValue("@cpf", txtCPF.Text); sql.Parameters.AddWithValue("@telefone", txtTelefone.Text); sql.Parameters.AddWithValue("@cep", txtCEP.Text); sql.Parameters.AddWithValue("@estado", txtEstado.Text); sql.Parameters.AddWithValue("@cidade", txtCidade.Text); sql.Parameters.AddWithValue("@rua", txtRua.Text); sql.Parameters.AddWithValue("@número", txtNúmero.Text); sql.Parameters.AddWithValue("@complemento", txtComplemento.Text); int i = sql.ExecuteNonQuery(); } catch(Exception exception) { MessageBox.Show(exception.ToString()); } finally { MessageBox.Show($"O {txtNome.Text} caiu no esquema de piramide com sucesso ROUF ROUF"); conexao.Close(); } txtNome.Clear(); txtCPF.Clear(); txtCidade.Clear(); txtCEP.Clear(); txtEstado.Clear(); txtRua.Clear(); txtNúmero.Clear(); txtTelefone.Clear(); txtComplemento.Clear(); } private void label10_Click(object sender, EventArgs e) { new MenuPrincipal().Show(); this.Hide(); } } } <file_sep>/Avaliação/Avaliação/AdicionarLinhas.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace Avaliação { public partial class AdicionarLinhas : Form { public AdicionarLinhas() { InitializeComponent(); } private void dgvClientes_CellContentClick(object sender, DataGridViewCellEventArgs e) { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; if (e.RowIndex >= 0) { DataGridViewRow row = this.dgvClientes.Rows[e.RowIndex]; tbNome.Text = row.Cells["Nome"].Value.ToString(); tbNúmero.Text = row.Cells["Telefone"].Value.ToString(); tbCPF.Text = row.Cells["CPF"].Value.ToString(); tbID.Text = row.Cells["ID"].Value.ToString(); } } public void AtualizarClientes() { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; sql.CommandText = $"Select * FROM Clientes"; try { conexao.Open(); int i = sql.ExecuteNonQuery(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } finally { SqlDataAdapter adaptador = new SqlDataAdapter(sql.CommandText, conexao); DataTable tabela = new DataTable(); adaptador.Fill(tabela); dgvClientes.DataSource = tabela; dgvClientes.ClearSelection(); conexao.Close(); } } public void AtualizarPlanos() { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; sql.CommandText = $"Select * FROM Planos"; try { conexao.Open(); int i = sql.ExecuteNonQuery(); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } finally { SqlDataAdapter adaptador = new SqlDataAdapter(sql.CommandText, conexao); DataTable tabela = new DataTable(); adaptador.Fill(tabela); dgvPlanos.DataSource = tabela; dgvPlanos.ClearSelection(); conexao.Close(); } } private void AdicionarLinhas_Load(object sender, EventArgs e) { AtualizarClientes(); AtualizarPlanos(); } private void BtnInserir_Click(object sender, EventArgs e) { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = @"Data Source=DESKTOP-SO3COJV;Initial Catalog=provasenai;Integrated Security=True"; SqlCommand sql = new SqlCommand(); sql.Connection = conexao; try { conexao.Open(); sql.CommandText = $"INSERT INTO Linhas(IDCliente,IDPlano,Número,DATAC,Ativo) VALUES (@idcliente,@idplano,@número,@datac,@ativo)"; sql.Parameters.AddWithValue("@idcliente", tbID.Text); sql.Parameters.AddWithValue("@idplano", tbIDPlano.Text); sql.Parameters.AddWithValue("@número", tbNúmero.Text); sql.Parameters.AddWithValue("@datac", DateTime.Now); sql.Parameters.AddWithValue("@ativo", "Ativo"); int i = sql.ExecuteNonQuery(); } catch(Exception exception) { MessageBox.Show(exception.ToString()); } finally { MessageBox.Show("A linha foi adicionada com sucesso ROUF ROUF "); conexao.Close(); } } private void dgvPlanos_CellContentClick(object sender, DataGridViewCellEventArgs e) { if(e.RowIndex > 0) { DataGridViewRow row = this.dgvPlanos.Rows[e.RowIndex]; tbIDPlano.Text = row.Cells["ID"].Value.ToString(); tbNomePlano.Text = row.Cells["Nome_Plano"].Value.ToString(); tbConteudoIlimitado.Text = row.Cells["CI"].Value.ToString(); tbFranquia.Text = row.Cells["Franquia"].Value.ToString(); tbMensalidade.Text = row.Cells["Mensalidade"].Value.ToString(); } } private void label12_Click(object sender, EventArgs e) { new MenuPrincipal().Show(); this.Hide(); } } }
7c468d272c422c0fcd1f6218ace5d89337ac8410
[ "Markdown", "C#" ]
11
Markdown
viniciuss19/avaliacao-senai
e1b582db94bf7d1717fd7ff5740aee16ef683f80
215547cd85410f709d81a8c5e78d0d7b938f7972
refs/heads/master
<repo_name>jejewu/nphard_2020_fall<file_sep>/hw2/np_simple.cpp #include "macro.h" #include "function.h" #include "shell.h" #include "rwg.h" int main(int argc, char* argv[]){ // Check argument number if(argc != 2){ cerr << "./server [port]" << endl; return 69; } // Server prepare int listenfd, connfd; int nready; int flag; struct sockaddr_in servaddr, cliaddr; listenfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(atoi(argv[1])); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(int)); bind(listenfd, (SA *) &servaddr, sizeof(servaddr)); listen(listenfd, LISTENQ); // Prepare client array int maxfd, maxi; maxfd = listenfd; maxi = -1; for(int i=0; i<LISTENQ; i++){ client[i] = -1; name[i] = "(no name)"; ipaddr[i] = ""; port[i] = 0; process_line[i] = 0; env[i]["PATH"] = "bin:."; } FD_ZERO(&allset); FD_SET(listenfd, &allset); //Loop while(1){ rset = allset; nready = select(maxfd+1, &rset, NULL, NULL, NULL); socklen_t clilen = sizeof(cliaddr); if(FD_ISSET(listenfd, &rset)){ //Cew client connection connfd = accept(listenfd, (SA*) &cliaddr, &clilen); if(connfd < 0) printf("Connected fail\n"); //Add new user fd to array int i; for(i=1; i<LISTENQ; i++){ if(client[i] < 0) break; } if(i == LISTENQ) printf("Too many client\n"); else{ char addr[20]; inet_ntop(AF_INET, &cliaddr.sin_addr.s_addr, addr, sizeof(cliaddr)); client[i] = connfd; port[i] = ntohs(cliaddr.sin_port); ipaddr[i] = string(addr); string newer_msg = "% "; write(client[i], newer_msg.c_str(), newer_msg.length()); cout << "*** User '" << name[i] << "' entered from " << ipaddr[i] << ":" << port[i] << ". ***" << endl; } //Add new user to set FD_SET(connfd, &allset); if(connfd > maxfd) maxfd = connfd; if(i > maxi) maxi = i; if(--nready <= 0) continue; } for(int i=0; i<=maxi; i++){ //Check all clients for data int sockfd = client[i]; if(sockfd < 0) //empty continue; if(FD_ISSET(sockfd, &rset)){ vector<string> arg; char input[MAXLEN] = ""; int i=0; read(sockfd, input, sizeof(input)); string msg = string(input); arg = dealline(msg); for(int i=0; i<msg.length(); i++){ if(msg[i] == '\r' || msg[i] == '\n'){ msg.erase(msg.begin()+i); i --; } } if(arg.size() != 0){ if(arg[0] == "exit"){ int cli = i; for(int j=0; j<MAXPIPE; j++) pidq[cli][j].clear(); for(int j=0; j<MAXPIPE*2; j++) numpipfd[cli][j] = 0; // initialize left user close(sockfd); FD_CLR(sockfd, &allset); client[cli] = -1; name[cli] = "(no name)"; ipaddr[cli] = ""; port[cli] = 0; process_line[cli] = 0; env[cli].clear(); env[cli]["PATH"] = "bin:."; cout << "exit" << endl; //choose_rwg_fun(arg, sockfd, i); } else shell_function_preprocess(arg, msg, i, sockfd); } write(sockfd, "% ", strlen("% ")); if(--nready <= 0) break; } } } return 0; } <file_sep>/hw2/shell.h void shell_printenv(vector<string> arg, int sockfd, int cli){ if(arg.size() != 2){ string errmsg = "usage: printenv [variable name]\n"; write(sockfd, errmsg.c_str(), errmsg.length()); return; } if(! getenv(arg[1].c_str())) return; string msg = env[cli][arg[1]] + "\n"; write(sockfd, msg.c_str(), msg.length()); } void shell_setenv(vector<string> arg, int sockfd, int cli){ if(arg.size() != 3){ string errmsg = "usage: setenv [variable name] [value to assign]\n"; write(sockfd, errmsg.c_str(), errmsg.length()); return; } env[cli][arg[1]] = arg[2]; } void shell_other(vector<string> arg, vector<int> is_bad, int *pipfd, int sockfd, int cli){ int arg_num = arg.size(), status, pipth = is_bad[4]; char *argv[arg_num+1]; for(int i=0; i<arg_num; i++){ char tmp[MAXLEN]; strcpy(tmp, arg[i].c_str()); argv[i] = strdup(tmp); } argv[arg_num] = NULL; pid_t pid = fork(); while(pid < 0){ wait(&status); pid = fork(); } if(pid == 0){ dup2(sockfd, 1); dup2(sockfd, 2); check_pipe_in_child(pipth, is_bad, pipfd, cli); check_pipe_out_child(pipth, is_bad, pipfd, cli); int err = execvp(argv[0], argv); if(err != 0) cerr << "Unknown command: [" << argv[0] << "]." << endl; exit(0); } else check_pipe_parent(pipth, is_bad, pipfd, pid, cli); } void check_pipe_in_child(int pipth, vector<int> is_bad, int* pipfd, int cli){ int line = process_line[cli]; int target = (line + abs(IS_NUMPIPE)) % MAXPIPE; int last_pipe = pipth-1 >= 0 ? pipth-1 : pipth+MAXPIPE-1; if(LAST_PIPE){ // normal pipe close(pipfd[2*last_pipe+1]); dup2(pipfd[2*last_pipe], 0); close(pipfd[2*last_pipe]); } else{ if(pidq[cli][line].size() != 0){ // number pipe close(numpipfd[cli][2*line+1]); dup2(numpipfd[cli][2*line], 0); close(numpipfd[cli][2*line]); } if(USER_PIPE_IN > 0){ stringstream ss; ss << setw(2) << setfill('0') << USER_PIPE_IN; ss << setw(2) << setfill('0') << cli; string user_pipe_key = ss.str(); close(active_user_pipe[user_pipe_key].user_pipe[1]); dup2(active_user_pipe[user_pipe_key].user_pipe[0], 0); close(active_user_pipe[user_pipe_key].user_pipe[0]); } else if(USER_PIPE_IN < 0) dup2(DEVNULLI, 0); } } void check_pipe_out_child(int pipth, vector<int> is_bad, int* pipfd, int cli){ int line = process_line[cli]; if(IS_PIPE){ //pipe close(pipfd[2*pipth]); dup2(pipfd[2*pipth+1], 1); close(pipfd[2*pipth+1]); } if(IS_NUMPIPE){ //number pipe int target = (line + abs(IS_NUMPIPE)) % MAXPIPE; close(numpipfd[cli][2*target]); dup2(numpipfd[cli][2*target+1], 1); if(IS_NUMPIPE < 0) dup2(numpipfd[cli][2*target+1], 2); close(numpipfd[cli][2*target+1]); } if(IS_REDIRECT) //redirect dup2(IS_REDIRECT, 1); if(USER_PIPE_OUT > 0){ stringstream ss; ss << setw(2) << setfill('0') << cli; ss << setw(2) << setfill('0') << USER_PIPE_OUT; string user_pipe_key = ss.str(); close(active_user_pipe[user_pipe_key].user_pipe[0]); dup2(active_user_pipe[user_pipe_key].user_pipe[1], 1); close(active_user_pipe[user_pipe_key].user_pipe[1]); } else if(USER_PIPE_OUT < 0) dup2(DEVNULLO, 1); } void check_pipe_parent(int pipth, vector<int> is_bad, int* pipfd, int pid, int cli){ int line = process_line[cli]; int target = (line + abs(IS_NUMPIPE)) % MAXPIPE; int last_pipe = pipth-1 >= 0 ? pipth-1 : pipth+MAXPIPE-1; int status; pidq[cli][line].push_back(pid); //last pipe in from pipe if(LAST_PIPE){ close(pipfd[2*last_pipe+1]); close(pipfd[2*last_pipe]); } else{ if(pidq[cli][line].size() != 1){ close(numpipfd[cli][2*line+1]); close(numpipfd[cli][2*line]); } } //has next number pipe if(IS_NUMPIPE){ for(auto i : pidq[cli][line]) pidq[cli][target].push_back(i); pidq[cli][line].clear(); pidq[cli][target].push_back(pid); } if(USER_PIPE_IN > 0){ stringstream ss; ss << setw(2) << setfill('0') << USER_PIPE_IN; ss << setw(2) << setfill('0') << cli; string user_pipe_key = ss.str(); close(active_user_pipe[user_pipe_key].user_pipe[0]); close(active_user_pipe[user_pipe_key].user_pipe[1]); active_user_pipe.erase(user_pipe_key); } //pipe_end if(! IS_PIPE){ if(! IS_NUMPIPE && ! (USER_PIPE_OUT > 0)){ for(auto i : pidq[cli][line]) waitpid(i, &status, 0); } pidq[cli][line].clear(); } } <file_sep>/hw3/console_macro.h #include <iostream> #include <stdlib.h> #include <vector> #include <string> #include <fstream> #include <sstream> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <boost/asio.hpp> #include <memory> #include <utility> #include <array> #define MAXSERVER 5 #define MAXLEN 1024 using namespace std; //basic cgi argument vector<string> console_host(MAXSERVER); vector<string> console_port(MAXSERVER); vector<string> console_file(MAXSERVER); vector<string> console_id; struct sessions{ string host; string port; string file; string id; vector<string> cmd; }; // boost asio define boost::asio::io_service ioservice; class Console : public enable_shared_from_this<Console> { private: boost::asio::ip::tcp::resolver resolv{ioservice}; boost::asio::ip::tcp::socket tcp_socket{ioservice}; sessions info; array<char, MAXLEN> bytes; //demo boost::asio::deadline_timer timer; public: Console(sessions s) : resolv(ioservice), tcp_socket(ioservice), info(move(s)), timer(ioservice){} void start(){ say_hello(); connect_server(); } private: void say_hello(){ auto self(shared_from_this()); timer.expires_from_now(boost::posix_time::seconds(2)); timer.async_wait([this, self](boost::system::error_code ec){ if(!ec){ cout << "<script>document.getElementById('" << info.id << "').innerHTML += '<font color=\"white\">hello</font>';</script>" << endl; } say_hello(); }); } void read_handler(){ auto self(shared_from_this()); tcp_socket.async_read_some(boost::asio::buffer(bytes), [this, self](boost::system::error_code ec, size_t length) { if (!ec) { string str = bytes.data(); bytes.fill('\0'); deal_html(str); cout << "<script>document.getElementById('" << info.id << "').innerHTML += '<font color=\"white\">" << str << "</font>';</script>\n"; if(info.cmd.size() != 0){ if(str.find("%") != -1){ string msg = info.cmd[0]; tcp_socket.async_send(boost::asio::buffer(msg), [this, self, msg](boost::system::error_code ec, size_t){}); deal_html(msg); cout << "<script>document.getElementById('" << info.id << "').innerHTML += '<font color=\"green\">" << msg << "';</script>\n"; info.cmd.erase(info.cmd.begin()); read_handler(); } else read_handler(); } } }); } void connect_server(){ auto self(shared_from_this()); int session_id = stoi(info.id); string file_name = "test_case/" + info.file; boost::asio::ip::tcp::resolver::query q{info.host, info.port}; resolv.async_resolve(q, [this, self](const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it){ tcp_socket.async_connect(*it, [this, self](const boost::system::error_code &ec){ read_handler(); }); }); } void deal_html(string &str){ for(int i=0; i<str.length(); i++){ if(str[i] == '\r') str.erase(str.begin()+(i--)); else if(str[i] == '\n') str.replace(i, 1, "&NewLine;"); else if(str[i] == '\'') str.replace(i, 1, "&apos;"); else if(str[i] == '\"') str.replace(i, 1, "&quot;"); else if(str[i] == '>') str.replace(i, 1, "&gt;"); else if(str[i] == '<') str.replace(i, 1, "&lt;"); } } }; <file_sep>/hw3/http_server.cpp #include <iostream> #include <array> #include <boost/asio.hpp> #include <cstdlib> #include <memory> #include <utility> #include <string> #include <sstream> #include <vector> #include <sys/types.h> //#include <sys/wait.h> #define MAXLEN 1024 using namespace std; using namespace boost::asio; boost::asio::io_service ioservice; struct HttpRequest{ string request_method; string request_uri; string query_string; string server_protocol; string http_host; string server_addr; string server_port; string remote_addr; string remote_port; string filename; }; class HttpSession : public enable_shared_from_this<HttpSession>{ private: ip::tcp::socket tcp_socket; array<char, MAXLEN> bytes; vector<string> httpRequest; public: HttpSession(ip::tcp::socket socket) : tcp_socket(move(socket)) {} void start() { do_read(); } private: void do_read() { auto self(shared_from_this()); tcp_socket.async_read_some(boost::asio::buffer(bytes), [this, self](boost::system::error_code ec, size_t length) { if (!ec){ string str = bytes.data(); bytes.fill('\0'); stringstream ss(str); HttpRequest info; /******************************** example http request ************ * GET /~yian31415/cgi/console.cgi?h0=nplinux1.cs.nctu.edu.tw&p0=1234&f0=t1.txt&h1=&p1=&f1=&h2=&p2=&f2=&h3=&p3=&f3=&h4=&p4=&f4= HTTP/1.1 * Host: nplinux1.cs.nctu.edu.tw:8888 * Connection: keep-alive * Cache-Control: max-age=0 * Upgrade-Insecure-Requests: 1 * User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36 * Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,* / *;q=0.8,application/signed-exchange;v=b3;q=0.9 * Accept-Encoding: gzip, deflate * Accept-Language: zh-TW,zh;q=0.9 ******************************************************************/ ss >> str; info.request_method = str; cout << info.request_method; ss >> str; info.request_uri = str; info.filename = "./" + str.substr(1, str.find('?') - 1); str = str.substr(str.find('?') + 1, str.length() - str.find('?')); info.query_string = str; ss >> str; info.server_protocol = str; ss >> str >> str; info.http_host = str; info.server_addr = tcp_socket.local_endpoint().address().to_string(); info.server_port = to_string(tcp_socket.local_endpoint().port()); info.remote_addr = tcp_socket.remote_endpoint().address().to_string(); info.remote_port = to_string(tcp_socket.remote_endpoint().port()); setenv("REQUEST_METHOD", info.request_method.c_str(), 1); setenv("REQUEST_URI", info.request_uri.c_str(), 1); setenv("QUERY_STRING", info.query_string.c_str(), 1); setenv("SERVER_PROTOCOL", info.server_protocol.c_str(), 1); setenv("HTTP_HOST", info.http_host.c_str(), 1); setenv("SERVER_ADDR", info.server_addr.c_str(), 1); setenv("SERVER_PORT", info.server_port.c_str(), 1); setenv("REMOTE_ADDR", info.remote_addr.c_str(), 1); setenv("REMOTE_PORT", info.remote_port.c_str(), 1); tcp_socket.send(buffer(string("HTTP/1.1 200 OK\r\n"))); int fd = tcp_socket.native_handle(); dup2(fd, STDOUT_FILENO); char *argv[2]; strcpy(argv[0], info.filename.c_str()); argv[1] = (char*)NULL; if(execvp(argv[0], argv) == -1){ cerr << "Unknown command: [" << argv[0] << "]. " << endl; exit(-1); } exit(0); } }); } }; class HttpServer { private: boost::asio::ip::tcp::acceptor tcp_acceptor; boost::asio::ip::tcp::socket tcp_socket; public: HttpServer(short port) : tcp_acceptor(ioservice, ip::tcp::endpoint(ip::tcp::v4(), port)), tcp_socket(ioservice) { do_accept(); } private: void do_accept(){ tcp_acceptor.async_accept(tcp_socket, [this](boost::system::error_code ec) { if (!ec) { ioservice.notify_fork(boost::asio::io_service::fork_prepare); if(fork() == 0){ ioservice.notify_fork(boost::asio::io_service::fork_child); make_shared<HttpSession>(move(tcp_socket))->start(); } else{ ioservice.notify_fork(boost::asio::io_service::fork_parent); tcp_socket.close(); do_accept(); } } do_accept(); }); } }; int main(int argc, char* argv[]) { if (argc != 2) { cerr << "./http_server [port]" << endl; return 69; } unsigned short port = atoi(argv[1]); signal(SIGCHLD, SIG_IGN); HttpServer server(port); ioservice.run(); } <file_sep>/hw3/test/port.py #! /usr/bin/env python3 import os import socket def main(): listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listen_socket.bind(('0.0.0.0', 0)) port = listen_socket.getsockname()[1] pid = os.fork() if pid == 0: listen_socket.close() connect_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connect_socket.connect(('127.0.0.1', port)) else: listen_socket.listen(1) listen_socket.accept() listen_socket.close() print(port, end='') if __name__ == '__main__': main() <file_sep>/hw2/macro.h // NP shell include #include <iostream> #include <string> #include <cstring> #include <sstream> #include <fstream> #include <iomanip> #include <cmath> #include <vector> #include <map> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> // rwg system include #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> // NP shell define #define MAXLEN 15001 #define MAXPIPE 1001 #define IS_REDIRECT is_bad[0] #define IS_NUMPIPE is_bad[1] #define IS_PIPE is_bad[2] #define LAST_PIPE is_bad[3] #define USER_PIPE_IN is_bad[5] #define USER_PIPE_OUT is_bad[6] // rwg system define #define SA struct sockaddr #define MOTD "****************************************\n** Welcome to the information server. **\n****************************************\n" #define LISTENQ 35 using namespace std; // NP shell global int numpipfd[LISTENQ][2*MAXPIPE]; vector<vector<vector<int>>> pidq(LISTENQ, vector<vector<int>>(MAXPIPE)); int DEVNULLO = fileno(fopen("/dev/null", "w")); int DEVNULLI = fileno(fopen("/dev/null", "r")); // rwg system global vector<string> name(LISTENQ); vector<string> ipaddr(LISTENQ); vector<int> port(LISTENQ); vector<int> client(LISTENQ); vector<int> process_line(LISTENQ); vector<map<string, string>> env(LISTENQ); struct user_pipe { int user_pipe[2]; }; map<string, struct user_pipe> active_user_pipe; fd_set allset, rset; // NP shell function vector<string> dealline(string); void shell_function_preprocess(vector<string> &, string, int, int); bool choose_rwg_fun(vector<string>, int, int); bool choose_shell_fun(vector<string>, vector<int>, int*, int, int); void check_pipe_in_child(int, vector<int>, int*, int); void check_pipe_out_child(int, vector<int>, int*, int); void check_pipe_parent(int, vector<int>, int*, int, int); // shell.h function void shell_printenv(vector<string>, int, int); void shell_setenv(vector<string>, int, int); void shell_other(vector<string>, vector<int>, int*, int, int); // rwg.h function void rwg_who(vector<string>, int, int); void rwg_tell(vector<string>, int, int); void rwg_yell(vector<string>, int, int); void rwg_name(vector<string>, int, int); void rwg_exit(vector<string>, int, int); <file_sep>/hw3/test/start_np_single.sh #! /bin/sh cleanup() { rm -rf "$NP_SINGLE_DIR/$WORKING_DIR" } PORT=$(python3 port.py) NP_SINGLE_DIR="$1" WORKING_DIR="working_dir_${PORT}" cd "$NP_SINGLE_DIR" || exit cp -r "working_dir_template/" "$WORKING_DIR" trap cleanup 0 1 2 3 6 if cd "$WORKING_DIR"; then if [ -x ./np_single_golden ]; then echo "A chat room (np_single_golden) is listening on \"$(hostname)\" and port \"$PORT\"" ./np_single_golden "$PORT" else echo "Either np_single_golden cannot be found or it is not an executable..." exit 1 fi else echo "Cannot change to the directory \"/tmp/np_single/$WORKING_DIR\"" exit 1 fi <file_sep>/hw3/other.cpp #include <iostream> #include <array> #include <boost/asio.hpp> #include <cstdlib> #include <memory> #include <utility> #include <string> #include <sstream> #include <unistd.h> #include <fstream> #include <vector> using namespace std; using namespace boost::asio; using namespace boost::asio::ip; io_service global_io_service; struct query_request{ string hostname; string port; string filename; string session; vector<string> command; }; void output_shell(string session, string content); void output_command(string session, string content); string xml_escape(string cmd); void parse_query(string query_string, vector<query_request> &vect); class Console : public enable_shared_from_this<Console>{ private: tcp::resolver _resolver; tcp::socket _socket; query_request _request; enum {max_length = 15000}; array<char, max_length> _data; public: Console(query_request request) : _resolver(global_io_service), _socket(global_io_service), _request(move(request)){} void start(){ do_resolve(); } private: void do_resolve() { auto self(shared_from_this()); tcp::resolver::query q(_request.hostname, _request.port); _resolver.async_resolve(q, [this, self](const boost::system::error_code &ec, tcp::resolver::iterator it){ _socket.async_connect(*it, [this, self](const boost::system::error_code &ec){ do_read(); }); }); } void do_read(){ auto self(shared_from_this()); _socket.async_read_some( buffer(_data, max_length), [this, self](boost::system::error_code ec, size_t length) { if (!ec) { string res = _data.data(); _data.fill('\0'); output_shell(_request.session, res); if(_request.command.size() > 0){ if(res.find("% ") != -1){ string cmd = _request.command[0]; _request.command.erase(_request.command.begin()); if(cmd == "exit\n") _request.command.clear(); do_write(cmd); }else do_read(); } } }); } void do_write(string cmd){ auto self(shared_from_this()); _socket.async_send( buffer(cmd, cmd.length()), [this, self, cmd](boost::system::error_code ec, size_t /* length */) { if (!ec) { output_command(_request.session, cmd); do_read(); } }); } }; int main(){ string query_string = getenv("QUERY_STRING"); vector<query_request> vect; parse_query(query_string, vect); cout << "Content-type: Text/html" << endl << endl; cout << R"( <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>NP Project 3 Console</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous" /> <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" /> <link rel="icon" type="image/png" href="https://cdn0.iconfinder.com/data/icons/small-n-flat/24/678068-terminal-512.png" /> <style> * { font-family: 'Source Code Pro', monospace; font-size: 1rem !important; } body { background-color: #212529; } pre { color: #cccccc; } b { color: #ffffff; } </style> </head> <body> <table class="table table-dark table-bordered"> <thead> <tr> )"; for(int i = 0; i < vect.size(); i++) cout << "<th scope=\"col\">" << vect[i].hostname << ":" << vect[i].port << "</th>" << endl; cout << R"( </tr> </thead> <tbody> <tr> )"; for(int i = 0; i < vect.size(); i++) cout << "<td><pre id=\"s" << i << "\" class=\"mb-0\"></pre></td>" << endl; cout << R"( </tr> </tbody> </table> </body> </html> )"; for(int i = 0; i < vect.size(); i++){ ifstream f("./test_case/" + vect[i].filename); string cmd; while(getline(f,cmd)) vect[i].command.push_back(cmd + '\n'); f.close(); make_shared<Console>(move(vect[i]))->start(); } global_io_service.run(); return 0; } void output_shell(string session, string content){ content = xml_escape(content); cout << "<script>document.getElementById('" << session << "').innerHTML += '" << content << "';</script>"; cout.flush(); } void output_command(string session, string content){ content = xml_escape(content); cout << "<script>document.getElementById('" << session << "').innerHTML += '<b>" << content << "</b>';</script>"; cout.flush(); } string xml_escape(string cmd){ stringstream ss(cmd); string res; for(int i = 0; i < cmd.length(); i++){ char c = cmd[i]; switch(c){ case '&': res += "&amp;"; break; case '\"': res += "&quot;"; break; case '\'': res += "&apos;"; break; case '<': res += "&lt;"; break; case '>': res += "&gt;"; break; case '\n': res += "&NewLine;"; break; case '\r': break; default: res += c; break; } } return res; } void parse_query(string query_string, vector<query_request> &vect){ stringstream ss(query_string); string str; int i = 0; while(getline(ss, str, '&')){ query_request new_req; bool input = true; int pos = str.find('='); new_req.hostname = str.substr(pos + 1, str.length() - pos); if(str.length() <= 3) input = false; getline(ss, str, '&'); pos = str.find('='); new_req.port = str.substr(pos + 1, str.length() - pos); if(str.length() <= 3) input = false; getline(ss, str, '&'); pos = str.find('='); new_req.filename = str.substr(pos + 1, str.length() - pos); if(str.length() <= 3) input = false; new_req.session = "s" + to_string(i); i++; if(input) vect.push_back(new_req); } } <file_sep>/hw2/np_single_proc.cpp #include "macro.h" #include "function.h" #include "shell.h" #include "rwg.h" int main(int argc, char* argv[]){ // Check argument number if(argc != 2){ cerr << "./server [port]" << endl; return 69; } // Server prepare int listenfd, connfd; int nready; int flag; struct sockaddr_in servaddr, cliaddr; listenfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(atoi(argv[1])); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(int)); bind(listenfd, (SA *) &servaddr, sizeof(servaddr)); listen(listenfd, LISTENQ); // Prepare client array int maxfd, maxi; maxfd = listenfd; maxi = -1; for(int i=0; i<LISTENQ; i++){ client[i] = -1; name[i] = "(no name)"; ipaddr[i] = ""; port[i] = 0; process_line[i] = 0; env[i]["PATH"] = "bin:."; } FD_ZERO(&allset); FD_SET(listenfd, &allset); //Loop while(1){ rset = allset; nready = select(maxfd+1, &rset, NULL, NULL, NULL); socklen_t clilen = sizeof(cliaddr); if(FD_ISSET(listenfd, &rset)){ //Cew client connection connfd = accept(listenfd, (SA*) &cliaddr, &clilen); if(connfd < 0) printf("Connected fail\n"); //Add new user fd to array int i; for(i=1; i<LISTENQ; i++){ if(client[i] < 0) break; } if(i == LISTENQ) printf("Too many client\n"); else{ int j; char addr[20]; inet_ntop(AF_INET, &cliaddr.sin_addr.s_addr, addr, sizeof(cliaddr)); client[i] = connfd; port[i] = ntohs(cliaddr.sin_port); ipaddr[i] = string(addr); string msg = "*** User '" + name[i] + "' entered from " + ipaddr[i] + ":" + to_string(port[i]) + ". ***\n"; for(j=1; j<LISTENQ; j++){ if(j == i){ string newer_msg = MOTD + msg + "% "; write(client[j], newer_msg.c_str(), newer_msg.length()); } else write(client[j], msg.c_str(), msg.length()); } cout << "*** User '" << name[i] << "' entered from " << ipaddr[i] << ":" << port[i] << ". ***" << endl; } //Add new user to set FD_SET(connfd, &allset); if(connfd > maxfd) maxfd = connfd; if(i > maxi) maxi = i; if(--nready <= 0) continue; } for(int i=0; i<=maxi; i++){ //Check all clients for data int sockfd = client[i]; if(sockfd < 0) //empty continue; if(FD_ISSET(sockfd, &rset)){ func(sockfd, i); write(sockfd, "% ", strlen("% ")); if(--nready <= 0) break; } } } return 0; } <file_sep>/hw1/shell.cpp #include "macro.h" #include "function.h" int main(){ //Global argument string input; vector<string> arg; setenv("PATH", "bin:.", 1); //main function loop char redir[MAXLEN]; signal(SIGCHLD, SIG_IGN); while(1){ cout << "% "; getline(cin, input); if(input.length() == 0) continue; arg = dealline(input); vector<int> is_bad = {0, 0, 0, 0, 0}; //[redirect, numpip, has_next_pipe, has_last_pipe, pipeth] int arg_num = arg.size(); int pipfd[2*MAXPIPE]; //check pipe arg_num = arg.size(); int begin = 0, pipth = 0; for(int i=0; i<arg_num; i++){ if(arg[i] == "|"){ pipe(pipfd+2*pipth); IS_PIPE = 1; //has_next_pipe is_bad[4] = pipth; //pipth vector<string> tmp; for(int j=begin; j<i; j++) tmp.push_back(arg[j]); choose_fun(tmp, is_bad, pipfd); IS_PIPE = 0; LAST_PIPE = 1; //has_last_pipe begin = i+1; pipth = (pipth + 1) % MAXPIPE; } } //check redirect FILE* pfile; for(int i=0; i<arg_num; i++){ //check redirect if(arg[i] == ">" && !is_bad[0]){ if(i == arg_num-1){ cout << " [command] > [redirect file]]" << endl; break; } string str = arg[i+1]; strcpy(redir, str.c_str()); pfile = fopen(redir, "w"); is_bad[0] = fileno(pfile); } if(is_bad[0]) arg.pop_back(); } //check number pipe for(int i=0; i<arg_num; i++){ if((arg[i][0] == '|' || arg[i][0] == '!') && arg[i].length() > 1){ arg[i][0] == '|' ? IS_NUMPIPE = 1 : IS_NUMPIPE = -1; for(int j=1; j<arg[i].length(); j++){ char ch = arg[i][j]; if(ch < '0' || ch > '9'){ IS_NUMPIPE = 0; break; } } if(IS_NUMPIPE){ IS_NUMPIPE = IS_NUMPIPE * stoi(&arg[i][1]); arg.pop_back(); break; } } } int target = (line + abs(IS_NUMPIPE)) % MAXPIPE; if(IS_NUMPIPE && pidq[target].size() == 0) pipe(numpipfd + 2 * target); if(begin) arg.erase(arg.begin(), arg.begin()+begin); // jump to functions is_bad[4] = pipth; bool is_exit = choose_fun(arg, is_bad, pipfd); // change stdout back if(is_bad[0]) fclose(pfile); if(is_exit) break; line = (line + 1) % MAXPIPE; } } <file_sep>/hw3/test/README.md # NP Project3 Sample Demo Script ## This directory contains the following - src/ - Contains your source codes - np_single/ - Contains the working directory for np_single_golden, commands, and other needed files - working_dir/ - Contains test cases and CGI programs - demo.sh: - The Entry point of the sample demo script ## Usage - You should put your source codes under `src/` before running `demo.sh` 1. Create a folder naming by your student id 2. Put all source codes and Makefile in the folder created in step1 - `./demo.sh` - demo.sh create two panes in tmux - The upper pane - Execute three np_single_golden automatically - The hostname and the port for listening will be displayed - The lower pane - Compile your source codes - Put the executables into the correct working_dir (You can use `cat ~/.npdemo3` to get the path of working_dir) - Copy CGI programs into `~/public_html/npdemo3/` - Execute your `http_server` - Display some links for demo - If the script successfully finishes, you will see the two panes similar to the below screenshot. You can open the links to check the result ![](https://i.imgur.com/YHuCMUW.png) ## Result ### Part 1-1 - The results should be similar to the following screenshots - printenv.cgi ![](https://i.imgur.com/Rdio6wf.png) - hello.cgi ![](https://i.imgur.com/VAGCOax.png) - welcome.cgi ![](https://i.imgur.com/tOELTwM.png) ### Part 1-2 & 1-3 - The execution flow and the results in the web page should be similar to the [video](https://drive.google.com/file/d/16Zj3aFqdmhu-3qz3vwEQc2A4p9H7Ergv/view) <file_sep>/hw3/test/start_http_server.sh #! /bin/sh # This is the demo script for NP project 3. You should use this script to automatically compile and make the executables # as the spec says. # If nothing goes wrong, some urls will shown and you should manually use a browser to visit them. # Print a string with color modified. # e.g., $ ERROR "This is an error". ERROR() { echo -e "\e[91m[ERROR] $1\e[39m" } # Abbreviate from SUCCESS SUCCESS() { echo -e "\e[92m[SUCCESS] $1\e[39m" } INFO() { echo -e "\e[93m[INFO] $1\e[39m" } # Define variables NP_SCRIPT_PATH=$(readlink -f "$0") NP_SCRIPT_DIR=$(dirname "$NP_SCRIPT_PATH") DEMO_DIR="$1" # Fetching student id, by args or by searching if [ -n "$2" ]; then STUDENT_ID=$2 else STUDENT_ID=$(ldapsearch -LLLx "uid=$USER" csid | tail -n 2 | head -n 1 | cut -d " " -f 2) fi # Copy student's source code and utilities to the demo directory. cp -r "$NP_SCRIPT_DIR/src/$STUDENT_ID" "$DEMO_DIR/src" mkdir "$DEMO_DIR/working_dir" && cp -r "$NP_SCRIPT_DIR/working_dir/"* "$DEMO_DIR/working_dir" cp -r "$NP_SCRIPT_DIR/port.py" "$DEMO_DIR" # Copy files to default-http_server directory. mkdir -p "$HOME/public_html/npdemo3" && cp -r "$NP_SCRIPT_DIR/working_dir/"* "$HOME/public_html/npdemo3" # Change directory into the demo directory. # Compile, and let the student's programs do it's work. if cd "$DEMO_DIR"; then INFO "Compiling..." if (make part1 -C "$DEMO_DIR/src"); then SUCCESS "Compilation completed!" else ERROR "Your project cannot be compiled by make" exit 1 fi if ! (cp src/console.cgi src/http_server "$DEMO_DIR/working_dir"); then ERROR "Failed to copy the generated executables to the demo directory (Did you name them right?)." exit 1 fi if ! (cp src/console.cgi "$HOME/public_html/npdemo3"); then ERROR "Cannot copy your console.cgi to ~/public_html/npdemo3 (Did you name it right?)." exit 1 fi HTTP_SERVER_PORT=$(python3 port.py) SUCCESS "Your http_server is listening at port: $HTTP_SERVER_PORT" echo "" INFO "Part 1-1: http_server" echo " http://$(hostname).cs.nctu.edu.tw:$HTTP_SERVER_PORT/printenv.cgi?course_name=NP" echo " http://$(hostname).cs.nctu.edu.tw:$HTTP_SERVER_PORT/hello.cgi" echo " http://$(hostname).cs.nctu.edu.tw:$HTTP_SERVER_PORT/welcome.cgi" echo "" INFO "Part 1-2: console.cgi" echo " http://$(hostname).cs.nctu.edu.tw/~$(whoami)/npdemo3/panel.cgi" echo "" INFO "Part 1-3: combined" echo " http://$(hostname).cs.nctu.edu.tw:$HTTP_SERVER_PORT/panel.cgi" cd working_dir || exit 1 env -i ./http_server "$HTTP_SERVER_PORT" else ERROR "Cannot change to the demo directory!" exit fi <file_sep>/hw4/console.cpp #include "console_macro.h" void print_head(){ cout << "Content-type:text/html\r\n\r\n"; cout << "<!DOCTYPE html>\n"; cout << "<html lang=\"en\">\n"; cout << " <head>\n"; cout << " <meta charset=\"UTF-8\" />\n"; cout << " <title>NP Project 3 Sample Console</title>\n"; cout << " <link\n"; cout << " rel=\"stylesheet\"\n"; cout << " href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css\"\n"; cout << " integrity=\"<KEY>n"; cout << " crossorigin=\"anonymous\"\n"; cout << " />\n"; cout << " <link\n"; cout << " href=\"https://fonts.googleapis.com/css?family=Source+Code+Pro\"\n"; cout << " rel=\"stylesheet\"\n"; cout << " />\n"; cout << " <link\n"; cout << " rel=\"icon\"\n"; cout << " type=\"image/png\"\n"; cout << " href=\"https://cdn0.iconfinder.com/data/icons/small-n-flat/24/678068-terminal-512.png\"\n"; cout << " />\n"; cout << " <style>\n"; cout << " * {\n"; cout << " font-family: 'Source Code Pro', monospace;\n"; cout << " font-size: 1rem !important;\n"; cout << " }\n"; cout << " body {\n"; cout << " background-color: #212529;\n"; cout << " }\n"; cout << " pre {\n"; cout << " color: #cccccc;\n"; cout << " }\n"; cout << " b {\n"; cout << " color: #01b468;\n"; cout << " }\n"; cout << " </style>\n"; cout << " </head>\n"; } void print_body(vector<sessions> sessionsq){ cout << " <body>\n"; cout << " <table class=\"table table-dark table-bordered\">\n"; cout << " <thead>\n"; cout << " <tr>\n"; for(auto i : sessionsq) cout << "<th scope=\"col\">" << i.host << ":" << i.port << "</th>\n"; cout << " </tr>\n"; cout << " </thead>\n"; cout << " <tbody>\n"; cout << " <tr>\n"; for(auto i : sessionsq) cout << "<td><pre id=" << i.id << " class=\"mb-0\"></pre></td>\n"; cout << " </tr>\n"; cout << " </tbody>\n"; cout << " </table>\n"; cout << " </body>\n"; cout << "</html>\n"; } void console(vector<sessions> sessionsq){ print_head(); print_body(sessionsq); for(int i=0; i<sessionsq.size(); i++){ make_shared<Console>(move(sessionsq[i]))->start(); } ioservice.run(); } void get_query_string(vector<sessions> &sessionsq){ string QUERY_STRING = getenv("QUERY_STRING"); string tmp; stringstream ss(QUERY_STRING); while(getline(ss, tmp, '&')){ stringstream s2(tmp); string var, arg; getline(s2, var, '='); if(var[0] == 'h') getline(s2, sessionsq[atoi(&var[1])].host, '='); if(var[0] == 'p') getline(s2, sessionsq[atoi(&var[1])].port, '='); if(var[0] == 'f') getline(s2, sessionsq[atoi(&var[1])].file, '='); if(var[0] == 's' && var[1] == 'h') getline(s2, PHInfo.host, '='); if(var[0] == 's' && var[1] == 'p') getline(s2, PHInfo.port, '='); } int pos = 0, num = 0; for(num; num<MAXSERVER; num++){ sessions s = sessionsq[pos]; if( s.host == "" || s.port == "" || s.file == "") sessionsq.erase(sessionsq.begin()+pos); else{ sessionsq[pos].id = to_string(num); pos ++; } } } void read_file(vector<sessions> &sessionsq){ for(auto &i : sessionsq){ ifstream fd("./test_case/" + i.file); string line; while(getline(fd,line)){ i.cmd.push_back(line + "\r\n"); } fd.close(); } } int main (){ vector<sessions> sessionsq(5); get_query_string(sessionsq); read_file(sessionsq); console(sessionsq); } <file_sep>/hw1/function.h vector<string> dealline(string input){ stringstream ss; string s; vector<string> tmp; ss << input; while(ss >> s){ tmp.push_back(s); } return tmp; } void fun_printenv(vector<string> arg){ char env[MAXLEN]; if(arg.size() != 2){ cout << "usage: printenv [variable name]" << endl; return; } strcpy(env, arg[1].c_str()); if(! getenv(env)) return; cout << getenv(env) << endl; } void fun_setenv(vector<string> arg){ char env[MAXLEN], envarg[MAXLEN]; if(arg.size() != 3){ cout << "usage: setenv [variable name] [value to assign]" << endl; return; } strcpy(env, arg[1].c_str()); strcpy(envarg, arg[2].c_str()); setenv(env, envarg, 1); } void fun_other(vector<string> arg, vector<int> is_bad, int *pipfd){ int arg_num = arg.size(), status, pipth = is_bad[4]; char *argv[arg_num+1]; for(int i=0; i<arg_num; i++){ char tmp[MAXLEN]; strcpy(tmp, arg[i].c_str()); argv[i] = strdup(tmp); } argv[arg_num] = NULL; pid_t pid = fork(); while(pid < 0){ wait(&status); pid = fork(); } if(pid == 0){ check_pipe_in_child(pipth, is_bad, pipfd); check_pipe_out_child(pipth, is_bad, pipfd); int err = execvp(argv[0], argv); if(err != 0) cerr << "Unknown command: [" << argv[0] << "]." << endl; exit(0); } else check_pipe_parent(pipth, is_bad, pipfd, pid); } bool choose_fun(vector<string> arg, vector<int> is_bad, int *pipfd){ if(arg[0] == "printenv") fun_printenv(arg); else if(arg[0] == "setenv") fun_setenv(arg); else if(arg[0] == "exit") return 1; else fun_other(arg, is_bad, pipfd); return 0; } void check_pipe_in_child(int pipth, vector<int> is_bad, int* pipfd){ int target = (line + abs(IS_NUMPIPE)) % MAXPIPE; int last_pipe = pipth-1 >= 0 ? pipth-1 : pipth+MAXPIPE-1; if(LAST_PIPE){ // normal pipe close(pipfd[2*last_pipe+1]); dup2(pipfd[2*last_pipe], 0); close(pipfd[2*last_pipe]); } else{ if(pidq[line].size() != 1){ // number pipe close(numpipfd[2*line+1]); dup2(numpipfd[2*line], 0); close(numpipfd[2*line]); } } } void check_pipe_out_child(int pipth, vector<int> is_bad, int* pipfd){ if(IS_PIPE){ //pipe close(pipfd[2*pipth]); dup2(pipfd[2*pipth+1], 1); close(pipfd[2*pipth+1]); } if(IS_NUMPIPE){ //number pipe int target = (line + abs(IS_NUMPIPE)) % MAXPIPE; close(numpipfd[2*target]); dup2(numpipfd[2*target+1], 1); if(IS_NUMPIPE < 0) dup2(numpipfd[2*target+1], 2); close(numpipfd[2*target+1]); } if(is_bad[0]) //redirect dup2(is_bad[0], 1); } void check_pipe_parent(int pipth, vector<int> is_bad, int* pipfd, int pid){ int target = (line + abs(IS_NUMPIPE)) % MAXPIPE; int last_pipe = pipth-1 >= 0 ? pipth-1 : pipth+MAXPIPE-1; int status; pidq[line].push_back(pid); //last pipe in from pipe if(LAST_PIPE){ close(pipfd[2*last_pipe+1]); close(pipfd[2*last_pipe]); } else{ if(pidq[line].size() != 1){ close(numpipfd[2*line+1]); close(numpipfd[2*line]); } } //has next number pipe if(IS_NUMPIPE){ for(auto i : pidq[line]) pidq[target].push_back(i); pidq[line].clear(); pidq[target].push_back(pid); } //pipe_end if(! IS_PIPE){ if(! IS_NUMPIPE){ for(auto i : pidq[line]) waitpid(i, &status, 0); } pidq[line].clear(); } } <file_sep>/hw2/rwg.h void rwg_who(vector<string> arg, int sockfd, int cli){ string msg = "<ID>\t<nickname>\t<IP:port>\t<indicate me>\n"; for(int i=1; i<LISTENQ; i++){ if(client[i] > 0){ msg = msg + to_string(i) + "\t" + name[i] + "\t" + ipaddr[i] + ":" + to_string(port[i]); if(i == cli) msg = msg + "\t<-me"; msg = msg + "\n"; } } write(sockfd, msg.c_str(), msg.length()); cout << "who" << endl; } void rwg_tell(vector<string> arg, int sockfd, int cli){ string msg = "*** " + name[cli] + " told you ***: "; for(auto i : arg[1]){ if(i < '0' || i > '9'){ string errmsg = "*** tell <user id> <message> ***\n"; write(sockfd, errmsg.c_str(), errmsg.length()); return; } } int towho = stoi(arg[1]); for(int i=2; i<arg.size()-1; i++) msg = msg + arg[i] + " "; msg = msg + arg[arg.size()-1] + "\n"; if(client[towho] == -1){ string errmsg = "*** Error: user #" + to_string(towho) + " does not exist yet. ***\n"; write(sockfd, errmsg.c_str(), errmsg.length()); } else write(client[towho], msg.c_str(), msg.length()); cout << "tell" << endl; } void rwg_yell(vector<string> arg, int sockfd, int cli){ string msg = "*** " + name[cli] + " yelled ***: "; for(int i=1; i<arg.size()-1; i++) msg = msg + arg[i] + " "; msg = msg + arg[arg.size()-1] + "\n"; for(int i=1; i<LISTENQ; i++){ if(client[i] >= 0){ write(client[i], msg.c_str(), msg.length()); } } cout << "yell" << endl; } void rwg_name(vector<string> arg, int sockfd, int cli){ string newname = arg[1]; string msg = "*** User from " + ipaddr[cli] + ":" + to_string(port[cli]) + " is named '" + newname + "'. ***\n"; for(int i=1; i<LISTENQ; i++){ if(name[i] == newname){ string msg = "*** User '" + newname + "' already exists. ***\n"; write(sockfd, msg.c_str(), msg.length()); return; } } name[cli] = newname; for(int i=1; i<LISTENQ; i++){ if(client[i] >= 0){ write(client[i], msg.c_str(), msg.length()); } } cout << "name" << endl; } void rwg_exit(vector<string> arg, int sockfd, int cli){ string msg = "*** User '" + name[cli] + "' left. ***\n"; for(int i=1; i<LISTENQ; i++){ if(client[i] >= 0 && i != cli) write(client[i], msg.c_str(), msg.length()); } // Clean user pipe stringstream ss; ss << setw(2) << setfill('0') << cli; string user_id = ss.str(); map<string, struct user_pipe>::iterator iter; for(iter=active_user_pipe.begin(); iter != active_user_pipe.end(); iter++){ string key = iter->first; if(key.compare(0, 2, user_id) || key.compare(key.size()-2, 2, user_id)) active_user_pipe.erase(key); } for(int i=0; i<MAXPIPE; i++) pidq[cli][i].clear(); for(int i=0; i<MAXPIPE*2; i++) numpipfd[cli][i] = 0; // initialize left user close(sockfd); FD_CLR(sockfd, &allset); client[cli] = -1; name[cli] = "(no name)"; ipaddr[cli] = ""; port[cli] = 0; process_line[cli] = 0; env[cli].clear(); env[cli]["PATH"] = "bin:."; cout << "exit" << endl; } <file_sep>/hw3/test/demo.sh #! /bin/sh PROJECT_NAME="npdemo3" DEMO_DIR=$(mktemp -d -p /tmp ${PROJECT_NAME}.XXXX) NP_SINGLE_DIR="$DEMO_DIR/np_single" STUDENT_ID="$1" chmod 700 "$DEMO_DIR" cp -r np_single/ "$DEMO_DIR" cp start_np_single.sh "$NP_SINGLE_DIR" cp port.py "$NP_SINGLE_DIR" # If the demo working directory already exists (probably because you have executed it before), remove it. if [ -f ~/.$PROJECT_NAME ]; then INFO "Removing previously created demo directory." rm -rf "$(cat ~/.$PROJECT_NAME)" rm -rf "$HOME/.$PROJECT_NAME" fi # Create a hidden file and write the demo directory's path into it. cat >~/.$PROJECT_NAME <<EOF $DEMO_DIR EOF if [ -n "$(tmux ls | grep npdemo3)" ]; then tmux kill-session -t "npdemo3" fi tmux new-session -d -s "npdemo3" tmux split-window -v -p 60 tmux select-pane -t 0 tmux send "cd $(dirname "$(readlink -f "$0")"); ./start_np_singles.py $NP_SINGLE_DIR" ENTER tmux select-pane -t 1 tmux send "cd $(dirname "$(readlink -f "$0")"); ./start_http_server.sh $DEMO_DIR $STUDENT_ID" ENTER tmux attach-session -t "npdemo3" <file_sep>/hw3/cgi_server.cpp #include <iostream> #include <array> #include <boost/asio.hpp> #include <cstdlib> #include <memory> #include <utility> #include <string> #include <sstream> #include <fstream> #include <vector> #include <windows.h> #define MAXLEN 1024 using namespace std; boost::asio::io_service ioservice; struct HttpRequest{ string request_method; string request_uri; string query_string; string server_protocol; string http_host; string server_addr; string server_port; string remote_addr; string remote_port; string filename; }; struct sessions{ string host; string port; string file; string id; vector<string> cmd; }; /*----------------------NPShell----------------------*/ class NPShell : public enable_shared_from_this<NPShell>{ private: boost::asio::ip::tcp::resolver tcp_resolver; shared_ptr<boost::asio::ip::tcp::socket> tcp_socket; boost::asio::ip::tcp::socket npsocket; sessions tcp_request; array<char, MAXLEN> bytes; public: NPShell(shared_ptr<boost::asio::ip::tcp::socket> socket, sessions request): tcp_resolver(ioservice), npsocket(ioservice), tcp_socket(socket), tcp_request(move(request)){} void start(){ do_resolve(); bytes.fill('\0'); } private: void do_resolve(){ auto self(shared_from_this()); boost::asio::ip::tcp::resolver::query q(tcp_request.host, tcp_request.port); tcp_resolver.async_resolve(q, [this, self](const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it){ npsocket.async_connect(*it, [this, self](const boost::system::error_code &ec){ if(!ec) read_handler(); }); }); } void read_handler(){ auto self(shared_from_this()); npsocket.async_read_some( boost::asio::buffer(bytes), [this, self](boost::system::error_code ec, size_t length) { if (!ec) { string res = bytes.data(); bytes.fill('\0'); deal_html(res); string output = "<script>document.getElementById('" + tcp_request.id + "').innerHTML += '<font color=\"white\">" + res + "';</script>\n"; tcp_socket->async_send(boost::asio::buffer(output, output.length()), [this, self](boost::system::error_code ec, size_t){}); if(tcp_request.cmd.size() > 0){ if(res.find("% ") != -1){ string cmd = tcp_request.cmd[0]; tcp_request.cmd.erase(tcp_request.cmd.begin()); if(cmd == "exit\n") tcp_request.cmd.clear(); npsocket.async_send(boost::asio::buffer(cmd, cmd.length()), [this, self, cmd](boost::system::error_code ec, size_t)mutable{ deal_html(cmd); string output = "<script>document.getElementById('" + tcp_request.id + "').innerHTML += '<b>" + cmd + "</b>';</script>\n"; tcp_socket->async_send(boost::asio::buffer(output, output.length()), [this, self](boost::system::error_code ec, size_t){}); }); read_handler(); } else read_handler(); } } }); } void deal_html(string &str){ for(int i=0; i<str.length(); i++){ if(str[i] == '\r') str.erase(str.begin()+(i--)); else if(str[i] == '\n') str.replace(i, 1, "&NewLine;"); else if(str[i] == '\'') str.replace(i, 1, "&apos;"); } } }; /*--------------------Console.cgi--------------------*/ class Console : public enable_shared_from_this<Console>{ private: shared_ptr<boost::asio::ip::tcp::socket> tcp_socket; HttpRequest tcp_request; string output; vector<sessions> vect; public: Console(boost::asio::ip::tcp::socket socket, HttpRequest request): tcp_socket(make_shared<boost::asio::ip::tcp::socket>(move(socket))), tcp_request(move(request)){} void start(){ for(int i=0; i<5; i++){ sessions s; vect.push_back(s); } get_query_string(tcp_request.query_string); print(); } private: void get_query_string(string QUERY_STRING){ auto self(shared_from_this()); string tmp; stringstream ss(QUERY_STRING); while(getline(ss, tmp, '&')){ stringstream s2(tmp); string var, arg; getline(s2, var, '='); if(var[0] == 'h') getline(s2, vect[atoi(&var[1])].host, '='); if(var[0] == 'p') getline(s2, vect[atoi(&var[1])].port, '='); if(var[0] == 'f') getline(s2, vect[atoi(&var[1])].file, '='); } int pos = 0, num = 0; for(num; num<5; num++){ sessions s = vect[pos]; if( s.host == "" || s.port == "" || s.file == "") vect.erase(vect.begin()+pos); else{ vect[pos].id = to_string(num); pos ++; } } } void parse_query(string query_string){ auto self(shared_from_this()); stringstream ss(query_string); string str; int i = 0; while(getline(ss, str, '&')){ sessions new_req; bool input = true; int pos = str.find('='); new_req.host = str.substr(pos + 1, str.length() - pos); if(str.length() <= 3) input = false; getline(ss, str, '&'); pos = str.find('='); new_req.port = str.substr(pos + 1, str.length() - pos); if(str.length() <= 3) input = false; getline(ss, str, '&'); pos = str.find('='); new_req.file = str.substr(pos + 1, str.length() - pos); if(str.length() <= 3) input = false; new_req.id = "s" + to_string(i); i++; if(input) vect.push_back(new_req); } } void print(){ auto self(shared_from_this()); output = R"(Content-type: text/html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>NP Project 3 Sample Console</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous" /> <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" /> <link rel="icon" type="image/png" href="https://cdn0.iconfinder.com/data/icons/small-n-flat/24/678068-terminal-512.png" /> <style> * { font-family: 'Source Code Pro', monospace; font-size: 1rem !important; } body { background-color: #212529; } pre { color: #cccccc; } b { color: #01b468; } </style> </head> <body> <table class="table table-dark table-bordered"> <thead> <tr>)"; for(auto i : vect) output += "<th scope=\"col\">" + i.host + ".cs.nctu.edu.tw:" + i.port + "</th>"; output += R"(</tr> </thead> <tbody> <tr>)"; for(auto i : vect) output += "<td><pre id=\"" + i.id +"\" class=\"mb-0\"></pre></td>"; output += R"(</tr> </tbody> </table> </body> </html> )"; tcp_socket->async_send(boost::asio::buffer(output, output.length()),[this, self](boost::system::error_code ec, size_t){ if(!ec){ for(auto &i : vect){ ifstream fd("./test_case/" + i.file); string line; while(getline(fd,line)){ i.cmd.push_back(line + "\r\n"); } fd.close(); make_shared<NPShell>(tcp_socket, move(i))->start(); } } }); } }; /*--------------------HTTP Server--------------------*/ class HttpSession : public enable_shared_from_this<HttpSession>{ private: boost::asio::ip::tcp::socket tcp_socket; array<char, MAXLEN> bytes; vector<string> httpRequest; public: HttpSession(boost::asio::ip::tcp::socket socket) : tcp_socket(move(socket)) {} void start() { do_read(); } private: void do_read() { auto self(shared_from_this()); tcp_socket.async_read_some(boost::asio::buffer(bytes), [this, self](boost::system::error_code ec, size_t length) { if (!ec){ string request = bytes.data(); bytes.fill('\0'); //parsing stringstream ss(request); HttpRequest info; string str; ss >> str; info.request_method = str; ss >> str; info.request_uri = str; info.filename = str.substr(1, str.find('?') - 1); str = str.substr(str.find('?') + 1, str.length() - str.find('?')); info.query_string = str; ss >> str; info.server_protocol = str; ss >> str >> str; info.http_host = str; info.server_addr = tcp_socket.local_endpoint().address().to_string(); info.server_port = to_string(tcp_socket.local_endpoint().port()); info.remote_addr = tcp_socket.remote_endpoint().address().to_string(); info.remote_port = to_string(tcp_socket.remote_endpoint().port()); tcp_socket.send(boost::asio::buffer(string("HTTP/1.1 200 OK\r\n"))); if(info.filename == "panel.cgi"){ Panel(); }else if(info.filename == "console.cgi"){ make_shared<Console>(move(tcp_socket), move(info))->start(); } } }); } void Panel(){ auto self(shared_from_this()); int N_SERVER = 5; string output = ""; {output = R"( <!DOCTYPE html> <html lang="en"> <head> <title>NP Project 3 Panel</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous" /> <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" /> <link rel="icon" type="image/png" href="https://cdn4.iconfinder.com/data/icons/iconsimple-setting-time/512/dashboard-512.png" /> <style> * { font-family: 'Source Code Pro', monospace; } </style> </head> <body class="bg-secondary pt-5"> <form action="console.cgi" method="GET"> <table class="table mx-auto bg-light" style="width: inherit"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Host</th> <th scope="col">Port</th> <th scope="col">Input File</th> </tr> </thead> <tbody> <tr> <th scope="row" class="align-middle">Session 1</th> <td> <div class="input-group"> <select name="h0" class="custom-select"> <option></option><option value="nplinux1.cs.nctu.edu.tw">nplinux1</option><option value="nplinux2.cs.nctu.edu.tw">nplinux2</option><option value="nplinux3.cs.nctu.edu.tw">nplinux3</option><option value="nplinux4.cs.nctu.edu.tw">nplinux4</option><option value="nplinux5.cs.nctu.edu.tw">nplinux5</option><option value="nplinux6.cs.nctu.edu.tw">nplinux6</option><option value="nplinux7.cs.nctu.edu.tw">nplinux7</option><option value="nplinux8.cs.nctu.edu.tw">nplinux8</option><option value="nplinux9.cs.nctu.edu.tw">nplinux9</option><option value="nplinux10.cs.nctu.edu.tw">nplinux10</option><option value="nplinux11.cs.nctu.edu.tw">nplinux11</option><option value="nplinux12.cs.nctu.edu.tw">nplinux12</option> </select> <div class="input-group-append"> <span class="input-group-text">.cs.nctu.edu.tw</span> </div> </div> </td> <td> <input name="p0" type="text" class="form-control" size="5" /> </td> <td> <select name="f0" class="custom-select"> <option></option> <option value="t1.txt">t1.txt</option><option value="t2.txt">t2.txt</option><option value="t3.txt">t3.txt</option><option value="t4.txt">t4.txt</option><option value="t5.txt">t5.txt</option><option value="t6.txt">t6.txt</option><option value="t7.txt">t7.txt</option><option value="t8.txt">t8.txt</option><option value="t9.txt">t9.txt</option><option value="t10.txt">t10.txt</option> </select> </td> </tr> <tr> <th scope="row" class="align-middle">Session 2</th> <td> <div class="input-group"> <select name="h1" class="custom-select"> <option></option><option value="nplinux1.cs.nctu.edu.tw">nplinux1</option><option value="nplinux2.cs.nctu.edu.tw">nplinux2</option><option value="nplinux3.cs.nctu.edu.tw">nplinux3</option><option value="nplinux4.cs.nctu.edu.tw">nplinux4</option><option value="nplinux5.cs.nctu.edu.tw">nplinux5</option><option value="nplinux6.cs.nctu.edu.tw">nplinux6</option><option value="nplinux7.cs.nctu.edu.tw">nplinux7</option><option value="nplinux8.cs.nctu.edu.tw">nplinux8</option><option value="nplinux9.cs.nctu.edu.tw">nplinux9</option><option value="nplinux10.cs.nctu.edu.tw">nplinux10</option><option value="nplinux11.cs.nctu.edu.tw">nplinux11</option><option value="nplinux12.cs.nctu.edu.tw">nplinux12</option> </select> <div class="input-group-append"> <span class="input-group-text">.cs.nctu.edu.tw</span> </div> </div> </td> <td> <input name="p1" type="text" class="form-control" size="5" /> </td> <td> <select name="f1" class="custom-select"> <option></option> <option value="t1.txt">t1.txt</option><option value="t2.txt">t2.txt</option><option value="t3.txt">t3.txt</option><option value="t4.txt">t4.txt</option><option value="t5.txt">t5.txt</option><option value="t6.txt">t6.txt</option><option value="t7.txt">t7.txt</option><option value="t8.txt">t8.txt</option><option value="t9.txt">t9.txt</option><option value="t10.txt">t10.txt</option> </select> </td> </tr> <tr> <th scope="row" class="align-middle">Session 3</th> <td> <div class="input-group"> <select name="h2" class="custom-select"> <option></option><option value="nplinux1.cs.nctu.edu.tw">nplinux1</option><option value="nplinux2.cs.nctu.edu.tw">nplinux2</option><option value="nplinux3.cs.nctu.edu.tw">nplinux3</option><option value="nplinux4.cs.nctu.edu.tw">nplinux4</option><option value="nplinux5.cs.nctu.edu.tw">nplinux5</option><option value="nplinux6.cs.nctu.edu.tw">nplinux6</option><option value="nplinux7.cs.nctu.edu.tw">nplinux7</option><option value="nplinux8.cs.nctu.edu.tw">nplinux8</option><option value="nplinux9.cs.nctu.edu.tw">nplinux9</option><option value="nplinux10.cs.nctu.edu.tw">nplinux10</option><option value="nplinux11.cs.nctu.edu.tw">nplinux11</option><option value="nplinux12.cs.nctu.edu.tw">nplinux12</option> </select> <div class="input-group-append"> <span class="input-group-text">.cs.nctu.edu.tw</span> </div> </div> </td> <td> <input name="p2" type="text" class="form-control" size="5" /> </td> <td> <select name="f2" class="custom-select"> <option></option> <option value="t1.txt">t1.txt</option><option value="t2.txt">t2.txt</option><option value="t3.txt">t3.txt</option><option value="t4.txt">t4.txt</option><option value="t5.txt">t5.txt</option><option value="t6.txt">t6.txt</option><option value="t7.txt">t7.txt</option><option value="t8.txt">t8.txt</option><option value="t9.txt">t9.txt</option><option value="t10.txt">t10.txt</option> </select> </td> </tr> <tr> <th scope="row" class="align-middle">Session 4</th> <td> <div class="input-group"> <select name="h3" class="custom-select"> <option></option><option value="nplinux1.cs.nctu.edu.tw">nplinux1</option><option value="nplinux2.cs.nctu.edu.tw">nplinux2</option><option value="nplinux3.cs.nctu.edu.tw">nplinux3</option><option value="nplinux4.cs.nctu.edu.tw">nplinux4</option><option value="nplinux5.cs.nctu.edu.tw">nplinux5</option><option value="nplinux6.cs.nctu.edu.tw">nplinux6</option><option value="nplinux7.cs.nctu.edu.tw">nplinux7</option><option value="nplinux8.cs.nctu.edu.tw">nplinux8</option><option value="nplinux9.cs.nctu.edu.tw">nplinux9</option><option value="nplinux10.cs.nctu.edu.tw">nplinux10</option><option value="nplinux11.cs.nctu.edu.tw">nplinux11</option><option value="nplinux12.cs.nctu.edu.tw">nplinux12</option> </select> <div class="input-group-append"> <span class="input-group-text">.cs.nctu.edu.tw</span> </div> </div> </td> <td> <input name="p3" type="text" class="form-control" size="5" /> </td> <td> <select name="f3" class="custom-select"> <option></option> <option value="t1.txt">t1.txt</option><option value="t2.txt">t2.txt</option><option value="t3.txt">t3.txt</option><option value="t4.txt">t4.txt</option><option value="t5.txt">t5.txt</option><option value="t6.txt">t6.txt</option><option value="t7.txt">t7.txt</option><option value="t8.txt">t8.txt</option><option value="t9.txt">t9.txt</option><option value="t10.txt">t10.txt</option> </select> </td> </tr> <tr> <th scope="row" class="align-middle">Session 5</th> <td> <div class="input-group"> <select name="h4" class="custom-select"> <option></option><option value="nplinux1.cs.nctu.edu.tw">nplinux1</option><option value="nplinux2.cs.nctu.edu.tw">nplinux2</option><option value="nplinux3.cs.nctu.edu.tw">nplinux3</option><option value="nplinux4.cs.nctu.edu.tw">nplinux4</option><option value="nplinux5.cs.nctu.edu.tw">nplinux5</option><option value="nplinux6.cs.nctu.edu.tw">nplinux6</option><option value="nplinux7.cs.nctu.edu.tw">nplinux7</option><option value="nplinux8.cs.nctu.edu.tw">nplinux8</option><option value="nplinux9.cs.nctu.edu.tw">nplinux9</option><option value="nplinux10.cs.nctu.edu.tw">nplinux10</option><option value="nplinux11.cs.nctu.edu.tw">nplinux11</option><option value="nplinux12.cs.nctu.edu.tw">nplinux12</option> </select> <div class="input-group-append"> <span class="input-group-text">.cs.nctu.edu.tw</span> </div> </div> </td> <td> <input name="p4" type="text" class="form-control" size="5" /> </td> <td> <select name="f4" class="custom-select"> <option></option> <option value="t1.txt">t1.txt</option><option value="t2.txt">t2.txt</option><option value="t3.txt">t3.txt</option><option value="t4.txt">t4.txt</option><option value="t5.txt">t5.txt</option><option value="t6.txt">t6.txt</option><option value="t7.txt">t7.txt</option><option value="t8.txt">t8.txt</option><option value="t9.txt">t9.txt</option><option value="t10.txt">t10.txt</option> </select> </td> </tr> <tr> <td colspan="3"></td> <td> <button type="submit" class="btn btn-info btn-block">Run</button> </td> </tr> </tbody> </table> </form> </body> </html>)"; } tcp_socket.async_send(boost::asio::buffer(output, output.length()),[this, self](boost::system::error_code ec, size_t){ tcp_socket.close(); }); } }; class HttpServer { private: boost::asio::ip::tcp::acceptor tcp_acceptor; boost::asio::ip::tcp::socket tcp_socket; public: HttpServer(short port) : tcp_acceptor(ioservice, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)), tcp_socket(ioservice) { do_accept(); } private: void do_accept() { tcp_acceptor.async_accept(tcp_socket, [this](boost::system::error_code ec) { if (!ec) { make_shared<HttpSession>(move(tcp_socket))->start(); } do_accept(); }); } }; /*---------------------------------------------------*/ BOOL WINAPI consoleHandler(DWORD signal){ if (signal == CTRL_C_EVENT){ cout << "User Interrupted"; exit(-1); } return true; } int main(int argc, char* const argv[]){ if (!SetConsoleCtrlHandler(consoleHandler, TRUE)) { cerr << "\nERROR: Could not set control handler"; return 1; } if (argc != 2){ cerr << "Usage:" << argv[0] << " [port]" << endl; return 1; } unsigned short port = atoi(argv[1]); HttpServer server(port); ioservice.run(); return 0; } <file_sep>/hw1/README.md # I. Introduction In this project, you are asked to design a shell with special piping mechanisms. # II. Specification ## A. Input 1. The length of a single-line input will not exceed 15000 characters. 2. Each command will not exceed 256 characters. 3. There must be one or more spaces between commands and symbols (or arguments), but no spaces between pipe and numbers. ```sh % cat hello.txt | number % cat hello.txt |4 % cat hello.txt !4 ``` 4. There won't xist any `/` character in test cases. ## B. NPShell Behavior 1. Use `% ` as the command line prompt. Notice that there is one space character after `%`. 2. The npshell terminates after receiving the exit command or `EOF`. 3. Notice that you must handle the forked processes properly, or there might be zombie processes. 4. Built-in commands (setenv, printenv, exit) will appear solely in a line. No command will be piped together with built-in commands. ## C. setenv and printenv 1. The initial environment variable PATH should be set to `bin/` and `./` by default. ```sh % printenv PATH bin:. ``` 2. setenv usage: `setenv [variable name] [value to assign]` 3. printenv usage: `printenv [variable name]` ```sh % printenv QQ # Show nothing if the variable does not exist. % printenv LANG en_US.UTF-8 ``` 4. The number of arguments for setenv and printenv will be correct in all test cases. ## D. Numbered-Pipes and Ordinary Pipe 1. `|N` means the STDOUT of the left hand side command should be piped to the first command of the next N-th line, where 1 ≤ N ≤ 1000. 2. `!N` means both STDOUT and STDERR of the left hand side command should be piped to the first command of the next N-th line, where 1 ≤ N ≤ 1000. 3. `|` is an ordinary pipe, it means the STDOUT of the left hand side command will be piped to the right hand side command. It will only appear between two commands, not at the beginning or at the end of the line. 4. The command number still counts for unknown commands. ``` % ls |2 % ctt Unknown command: [ctt]. % number 1 bin/ 2 test.html ``` 5. setenv and printenv count as one command. ``` % ls |2 % printenv PATH bin:. % cat bin test.html ``` 6. Empty line does not count. ``` % ls |1 % # press Enter % number 1 bin/ 2 test.html ``` ## E. Unknown Command 1. If there is an unknown command, print error message as the following format: `Unknown command: [command].` e.g. ``` % ctt Unknown command: [ctt]. ``` 2. You don't have to print out the arguments. ``` % ctt -n Unknown command: [ctt]. ``` 3. The commands after unknown commands will still be executed. ``` % ctt | ls Unknown command: [ctt]. bin/ test.html ``` 4. Messages piped to unknown commands will disappear. ``` % ls | ctt Unknown command: [ctt]. ``` <file_sep>/hw3/README.md # I. Introduction The project is divided into two parts. This is the first part of the project. Here, you are asked to write a Remote Batch System, which consists of a simple HTTP server called http server and a CGI program console.cgi. We will use **Boost.Asio** library to accomplish this project. # II. Specification ## A. http server 1. In this project, the URI of HTTP requests will always be in the form of /${cgi name}.cgi (e.g., /panel.cgi, /console.cgi, /printenv.cgi), and we will only test for the HTTP GET method. 2. Your http server should parse the HTTP headers and **follow the CGI procedure** (fork, set environment variables, dup, exec) to execute the specified CGI program. 3. The following environment variables are required to set: (a) REQUEST METHOD (b) REQUEST URI (c) QUERY STRING (d) SERVER PROTOCOL (e) HTTP HOST (f) SERVER ADDR (g) SERVER PORT (h) REMOTE ADDR (i) REMOTE PORT For instance, if the HTTP request looks like: ``` GET /console.cgi?h0=nplinux1.cs.nctu.edu.tw&p0= ... (too long, ignored) Host: nplinux8.cs.nctu.edu.tw:7779 User-Agent: Mozilla/5.0 Accept: text/html,application/xhtml+xml,applica ... (too long, ignored) Accept-Language: en-US,en;q=0.8,zh-TW;q=0.5,zh; ... (too long, ignored) Accept-Encoding: gzip, deflate DNT: 1 Connection: keep-alive Upgrade-Insecure-Requests: 1 ``` Then before executing console.cgi, you need to set the corresponding environment variables. In this case, REQUEST METHOD should be "GET" HTTP HOST should be "plinux8.cs.nctu.edu.tw:7779" and so on and so forth. ## B. console.cgi 1. You are highly recommended to inspect and run the CGI samples before you start this section. 2. The console.cgi should parse the connection information (e.g. host, port, file) from the environment variable QUERY STRING, which is set by your HTTP server. For example, if QUERY STRING is: `0=nplinux1.cs.nctu.edu.tw&p0=1234&f0=t1.txt&h1=nplinux2.cs.nctu.edu.tw&p1=5678&f1=t2.txt&h2=&p2=&f2=&h3=&p3=&f3=&h4=&p4=&f4=` It should be understood as: ``` h0=nplinux1.cs.nctu.edu.tw # the hostname of the 1st server p0=1234 # the port of the 1st server f0=t1.txt # the file to open h1=nplinux2.cs.nctu.edu.tw # the hostname of the 2nd server p1=5678 # the port of the 2nd server f1=t2.txt # the file to open h2= # no 3rd server, so this field is empty p2= # no 3rd server, so this field is empty f2= # no 3rd server, so this field is empty h3= # no 4th server, so this field is empty p3= # no 4th server, so this field is empty f3= # no 4th server, so this field is empty h4= # no 5th server, so this field is empty p4= # no 5th server, so this field is empty f4= # no 5th server, so this field is empty ``` 3. After parsing, console.cgi should connect to these servers. Note that the maximum number of the servers never exceeds 5. 4. The remote servers that console.cgi connects to are Remote Working Ground Servers with shell prompt `%` , and the files we sent (e.g., t1.txt) are the commands for the remote shells. However, you should not send the entire file to the remote server and execute them all at once. Instead, send them line-by-line whenever you receive a shell prompt `%` from remote. 5. Your console.cgi should display the hostname and the port of the connected remote server at the top of each session. 6. Your console.cgi should display the remote server’s replies in real-time. Everything you send to remote or receive from remote should be displayed on the web page as soon as possible. For example: ``` % ls bin test.html ``` Here, the blue part is the content (output) you received from the remote shell, and the brown part is the content (command) you sent to the remote. The output order matters and needs to be preserved. You should make sure that commands are displayed right after the shell prompt `%`, but before the execution result received from remote. 7. Regarding how to display the server' reply (console.cgi), please refer to sample console.cgi. Since we will not judge your answers with diff for this project, feel free to modify the layout of the web page. Just make sure you follow the below rules: (a) Each session should be separate. (b) The commands and the outputs of the shell are displayed in the right order and at the right time (c) The commands can be easily distinguished from the outputs of the shell. ## C. panel.cgi (Provided by TA) 1. This CGI program generates the form in the web page. It detects all files in the directory test case/ and display them in the selection menu. <file_sep>/hw4/README.md # I. Introduction In this project, you are going to implement the SOCKS 4/4A protocol in the application layer of the OSI model. SOCKS is similar to a proxy (i.e., intermediary-program) that acts as both server and client for the purpose of making requests on behalf of other clients. Because the SOCKS protocol is independent of application protocols, it can be used for many different services: telnet, ftp, WWW, etc. There are two types of the SOCKS operations, namely CONNECT and BIND. You have to implement both of them in this project. We will use Boost.Asio library to accomplish this project. # II. SOCKS 4 Implementation After the SOCKS server starts listening, if a SOCKS client connects, use fork() to tackle with it. Each child process will do: 1. Receive SOCKS4 REQUEST from the SOCKS client 2. Get the destination IP and port from SOCKS4 REQUEST 3. Check the firewall (socks.conf), and send SOCKS4 REPLY to the SOCKS client if rejected 4. Check CD value and choose one of the operations (a) CONNECT (CD=1) i. Connect to the destination ii. Send SOCKS4 REPLY to the SOCKS client iii. Start relaying traffic on both directions (b) BIND (CD=2) i. Bind and listen a port ii. Send SOCKS4 REPLY to SOCKS client to tell which port to connect iii. (SOCKS client tells destination to connect to SOCKS server) iv. Accept connection from destination and send another SOCKS4 REPLY to SOCKS client v. Start relaying traffic on both directions If the SOCKS server decides to reject a request from a SOCKS client, the connection will be closed immediately. # III. Requirements ## Part I: SOCKS 4 Server Connect Operation * Open your browser and connect to any webpages. * Turn on and set your SOCKS server, then * Be able to connect any webpages on Google Search. * Your SOCKS server need to show messages below: ``` <S_IP>: source ip <S_PORT>: source port <D_IP>: destination ip <D_PORT>: destination port <Command>: CONNECT or BIND <Reply>: Accept or Reject ``` ## Part II: SOCKS 4 Server Bind Operation * FlashFXP settings: * Set your SOCKS server * Connection type is FTP (cannot be SFTP) * Data connection mode is Active Mode (PORT) * Connect to FTP server, and upload/download files larger than 1GB completely. e.g., Ubuntu 20.04 ISO image (download link) * Upload a file and download a file. * Check whether the SOCKS server’s output message shows that BIND operation is used. ## Part III: CGI Proxy * Modify console.cgi in Project 3 to implement SOCKS client mode * Accept SocksIP and SocksPort parameters in QUERY STRING as sh and sp, respectively * Use SocksIP and SocksPort to connect to your SOCKS server (by CONNECT operation) * Clear browser's proxy setting Open your http server, connect to panel socks.cgi Key in IP, port, filename, SocksIP, SocksPort Connect to 5 ras/rwg servers through SOCKS server and check the output Test Case. ## Firewall * You only need to implement a simple firewall. List permitted destination IPs into socks.conf (deny all traffic by default) e.g., ``` permit c 140.114.*.* # permit NTHU IP for Connect operation permit c 140.113.*.* # permit NCTU IP for Connect operation permit b *.*.*.* # permit all IP for Bind operation ``` * Be able to change firewall rules without restarting the SOCKS server. ## Specification * Port number of SOCKS server is specified by the first argument: ./socks server [port] * You can only use C/C++ to implement this project. Except for Boost, other third-party libraries are NOT allowed. * Every function that touches network operations (e.g., DNS query, connect, accept, send, receive) MUST be implemented using the library **Boost.Asio**. * Both synchronous and asynchronous functions can be used. Notice that some situations only work with non-blocking operations. Be thoughtful when using synchronous ones. <file_sep>/hw4/socks_server.cpp #include "socks_server.h" class SocksConnect : public enable_shared_from_this<SocksConnect>{ private: shared_ptr<boost::asio::ip::tcp::socket> cli_socket; boost::asio::ip::tcp::socket ser_socket; SocksReq req; array<char, MAXLEN> bytes; public: SocksConnect(boost::asio::ip::tcp::socket socket, SocksReq request): cli_socket(make_shared<boost::asio::ip::tcp::socket>(move(socket))), ser_socket(ioservice), req(request){} void start(int op){ bytes.fill('\0'); if(op == 1) //Connect do_connect(); else if(op == 2) //Bind do_accept(); else SocksReply(req, false); } private: void SocksReply(SocksReq req, bool granted){ auto self(shared_from_this()); string msg; msg += '\0'; msg += (granted ? 0x5A : 0x5B); for(int i=0; i<2; i++){ msg += req.DSTPORT[i]; } for(int i=0; i<4; i++){ msg += req.DSTIP[i]; } cli_socket->async_send(boost::asio::buffer(msg), [this, self, msg](boost::system::error_code ec, size_t){}); } void SocksRedirect(bool enableser_socket, bool enablecli_socket){ auto self(shared_from_this()); if(enableser_socket){ ser_socket.async_read_some(boost::asio::buffer(bytes, bytes.size()), [this, self](boost::system::error_code ec, size_t length){ if(!ec){ cli_socket->async_send(boost::asio::buffer(bytes, length), [this, self](boost::system::error_code ec, size_t){}); bytes.fill('\0'); SocksRedirect(1, 0); } if(ec == boost::asio::error::eof){ cli_socket->close(); } }); } if(enablecli_socket){ cli_socket->async_read_some(boost::asio::buffer(bytes, bytes.size()), [this, self](boost::system::error_code ec, size_t length) { if(!ec){ ser_socket.async_send(boost::asio::buffer(bytes, length), [this, self](boost::system::error_code ec, size_t){}); bytes.fill('\0'); SocksRedirect(0, 1); } }); } } void do_connect(){ auto self(shared_from_this()); boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string(req.D_IP), req.D_PORT); ser_socket.async_connect(ep, [this, self](const boost::system::error_code &ec){ if(!ec){ cout << "connection build to " << req.D_IP << ":" << req.D_PORT << endl; SocksReply(req, true); SocksRedirect(1, 1); } else cout << "connect failed" << endl; }); } void do_accept(){ boost::asio::ip::tcp::acceptor tcp_acceptor(ioservice, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 0)); tcp_acceptor.listen(); int b_port = tcp_acceptor.local_endpoint().port(); req.D_PORT = b_port; req.DSTPORT[0] = b_port/256; req.DSTPORT[1] = b_port%256; for(int i=0; i<4; i++) req.DSTIP[i] = 0; SocksReply(req, true); try{ tcp_acceptor.accept(ser_socket); SocksReply(req, true); SocksRedirect(1, 1); } catch (boost::system::error_code ec){ cout << "failed: " << ec << endl; } } }; class SocksSession : public enable_shared_from_this<SocksSession>{ private: boost::asio::ip::tcp::socket tcp_socket; boost::asio::ip::tcp::socket rsock; array<char, MAXLEN> bytes; public: SocksSession(boost::asio::ip::tcp::socket socket) : tcp_socket(move(socket)), rsock(ioservice) {} void start() { do_read(); } private: bool CheckFW(SocksReq req){ char D_Mode = req.CD == 1 ? 'c' : 'b'; ifstream infile("socks.conf"); string line; while(getline(infile, line)){ string str, mode, ip; stringstream ss(line); vector<string> sub_ip; ss >> str; ss >> mode; ss >> ip; if(str == "permit"){ if(mode[0] == D_Mode){ stringstream ssip(ip); string s; while(getline(ssip, s, '.')) sub_ip.push_back(s); for(int i=0; i<4; i++){ s = to_string(Ch2Int(req.DSTIP, i, 1)); if(sub_ip[i] != s && sub_ip[i] != "*") break; if(i == 3) return 1; } } } } return 0; } int Ch2Int(string data, int begin, int bytes_num){ int power = 1, ans = 0; for(int i=begin+bytes_num-1; i>=begin; i--){ char ch = data[i]; for(int j=0; j<8; j++){ ans += ((ch & (1 << j))? power : 0); power *= 2; } } return ans; } void printinfo(SocksReq req){ cout << "<S_IP>: " << req.S_IP << endl; cout << "<S_PORT>: " << req.S_PORT << endl; cout << "<D_IP>: " << req.D_IP << endl; cout << "<D_PORT>: " << req.D_PORT << endl; cout << "<Command>: "; if(req.CD == 1) cout << "CONNECT" << endl; else if(req.CD == 2) cout << "BIND" << endl; } void do_read(){ auto self(shared_from_this()); tcp_socket.async_read_some(boost::asio::buffer(bytes), [this, self](boost::system::error_code ec, size_t length) { if (!ec){ string data(length, '\0'); for(int i=0; i<length; i++) data[i] = bytes[i]; bytes.fill('\0'); //parsing SocksReq new_req; new_req.VN = data[0]; new_req.CD = data[1]; new_req.D_PORT = Ch2Int(data, 2, 2); for(int i=0; i<2; i++){ new_req.DSTPORT[i] = data[i+2]; } new_req.D_IP = ""; for(int i=0; i<4; i++){ new_req.D_IP += to_string(Ch2Int(data, i+4, 1)); new_req.D_IP += (i == 3 ? "" : "."); new_req.DSTIP[i] = data[i+4]; } bool is_socks4a = 1; for(int i=0; i<4; i++){ if(i != 3){ if(new_req.DSTIP[i] != 0){ is_socks4a = 0; break; } } else{ if(new_req.DSTIP[i] == 0){ is_socks4a = 0; break; } } } new_req.DOMAIN_NAME = ""; if(is_socks4a){ int pos = 8; while(data[pos++] != 0); while(pos != length-1) new_req.DOMAIN_NAME += data[pos++]; cout << new_req.DOMAIN_NAME << endl; boost::asio::ip::tcp::resolver resolv{ioservice}; auto results = resolv.resolve(new_req.DOMAIN_NAME, to_string(new_req.D_PORT)); for(auto entry : results) { if(entry.endpoint().address().is_v4()) { new_req.D_IP = entry.endpoint().address().to_string(); stringstream ss(new_req.D_IP); string s; for(int i=0; i<4; i++){ getline(ss, s, '.'); new_req.DSTIP[i] = Ch2Int(s, 0, s.length()); } break; } } } boost::asio::ip::tcp::endpoint remote_ep = tcp_socket.remote_endpoint(); boost::asio::ip::address remote_ad = remote_ep.address(); new_req.S_IP = remote_ad.to_string(); new_req.S_PORT = (int)remote_ep.port(); printinfo(new_req); if(new_req.CD == 1){ //socks connect if(CheckFW(new_req)){ cout << "<Reply> Accept" << endl << endl; make_shared<SocksConnect>(move(tcp_socket), new_req)->start(1); } else{ cout << "<Reply> Reject" << endl << endl; make_shared<SocksConnect>(move(tcp_socket), new_req)->start(0); } } else if(new_req.CD == 2){ //socks bind if(CheckFW(new_req)){ cout << "<Reply> Accept" << endl << endl; make_shared<SocksConnect>(move(tcp_socket), new_req)->start(2); } else{ cout << "<Reply> Reject" << endl << endl; make_shared<SocksConnect>(move(tcp_socket), new_req)->start(0); } } do_read(); } }); } }; class SocksServer { private: boost::asio::ip::tcp::acceptor tcp_acceptor; boost::asio::ip::tcp::socket tcp_socket; public: SocksServer(short port) : tcp_acceptor(ioservice, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)), tcp_socket(ioservice) { do_accept(); } private: void do_accept(){ boost::asio::socket_base::reuse_address option(true); tcp_acceptor.set_option(option); tcp_acceptor.async_accept(tcp_socket, [this](boost::system::error_code ec) { if (!ec) { ioservice.notify_fork(boost::asio::io_service::fork_prepare); if(fork() == 0){ ioservice.notify_fork(boost::asio::io_service::fork_child); make_shared<SocksSession>(move(tcp_socket))->start(); } else{ ioservice.notify_fork(boost::asio::io_service::fork_parent); tcp_socket.close(); do_accept(); } } do_accept(); }); } }; int main(int argc, char* argv[]) { if (argc != 2) { cerr << "./http_server [port]" << endl; return 69; } unsigned short port = atoi(argv[1]); signal(SIGCHLD, SIG_IGN); SocksServer server(port); ioservice.run(); } <file_sep>/hw3/test/start_np_singles.py #! /usr/bin/env python3 import random import getpass import subprocess import time import sys class ChatRoomsController: USERNAME = getpass.getuser() @staticmethod def create(): NP_SINGLE_DIR = sys.argv[1] OPEN_CHAT_ROOM_CMD = f'{NP_SINGLE_DIR}/start_np_single.sh {NP_SINGLE_DIR}' for i in range(3): subprocess.Popen(OPEN_CHAT_ROOM_CMD, shell=True, stderr=subprocess.DEVNULL) time.sleep(1) @staticmethod def delete(): KILL_CHAT_ROOMS_CMD = "killall -u {} np_single_golden" subprocess.check_call( KILL_CHAT_ROOMS_CMD.format(ChatRoomsController.USERNAME), shell=True, stdout=subprocess.DEVNULL) if __name__ == '__main__': try: ChatRoomsController.create() input("(Press any key (or Ctrl+C) to close...)") print("\nClosing chat rooms...") ChatRoomsController.delete() except KeyboardInterrupt: ... <file_sep>/hw4/socks_server.h #include <iostream> #include <array> #include <boost/asio.hpp> #include <cstdlib> #include <memory> #include <utility> #include <string> #include <sstream> #include <fstream> #include <vector> #include <sys/types.h> #include <bitset> #define MAXLEN 20000 using namespace std; boost::asio::io_service ioservice; struct SocksReq{ int VN; int CD; int S_PORT; string S_IP; int D_PORT; char DSTPORT[2]; string D_IP; char DSTIP[4]; string DOMAIN_NAME; }; <file_sep>/hw3/test/src/0616216/Makefile all: clean g++ http_server.cpp -o http_server -std=c++14 -pedantic -pthread -lboost_system g++ console.cpp -o console.cgi -pthread -std=c++14 g++ other.cpp -o other.cgi -pthread -std=c++14 cp extra_files/cgi/panel.cgi . cp *.cgi ~/public_html/cgi hw: cp http_server.cpp ~/0616216 cp console.cpp ~/0616216 cp cgi_server.cpp ~/0616216 cp Makefile ~/0616216 cp *.h ~/0616216 ssh -t linux3 "zip -r 0616216.zip 0616216" mv ~/0616216.zip ~/public_html part1: g++ http_server.cpp -o http_server -std=c++14 -pedantic -pthread -lboost_system g++ console.cpp -o console.cgi -pthread -std=c++14 part2: g++ cgi_server.cpp -o cgi_server -lws2_32 -lwsock32 -std=c++14 clean: rm -f ./*.cgi rm -f ~/public_html/cgi/*.cgi <file_sep>/hw1/test/README.md # NP Project1 Demo Script ### This directory contains the following - demo.sh: - Usage: `./demo.sh [npshell_path]` - demo.sh does the following: 1. Construct the working directory (work_template and work_dir) 2. Compile the commands (noop, removetag...) and place them into bin/ inside the working directory 3. Copy cat and ls into bin/ inside the working directory 4. Run the npshell inside work_dir 5. Redirect stdin of npshell to files in test_case/ 6. Redirect stdout and stderr of npshell to files in output/ 7. Use diff to compare the files inside output/ and answer/ 8. Show the result of demo - compare.sh - Usage: `./compare.sh [n]` - Compare.sh will run vimdiff on the n'th answer and your output - test_case/ - Contains test cases - answer/ - Contains answers - src/ - Contains source code of commands (noop, removetag...) and test.html ### Test Output ``` bash$ ./demo.sh npshell ... ... # Some messeges generated while compiling and setting up environment ... ===== Test case 1 ===== Your answer is correct ===== Test case 2 ===== Your answer is correct ===== Test case 3 ===== Your answer is correct ===== Test case 4 ===== Your answer is correct ===== Test case 5 ===== Your answer is correct ===== Test case 6 ===== Your answer is wrong ======= Summary ======= [Correct]: 1 2 3 4 5 [ Wrong ]: 6 bash$ ./compare 6 # Check out the difference between the 6th output and answer ``` <file_sep>/hw1/macro.h #include <iostream> #include <string> #include <cstring> #include <sstream> #include <vector> #include <fstream> #include <iomanip> #include <cmath> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #define MAXLEN 15001 #define MAXPIPE 1001 #define MAXPROCESS 400 #define IS_NUMPIPE is_bad[1] #define IS_PIPE is_bad[2] #define LAST_PIPE is_bad[3] using namespace std; int numpipfd[2*MAXPIPE]; vector<vector<int>> pidq(MAXPIPE); int line = 0; void check_pipe_in_child(int pipth, vector<int> is_bad, int* pipfd); void check_pipe_out_child(int pipth, vector<int> is_bad, int* pipfd); void check_pipe_parent(int pipth, vector<int> is_bad, int* pipfd, int pid); vector<string> dealline(string input); void fun_printenv(vector<string> arg); void fun_setenv(vector<string> arg); void fun_removetag(vector<string> arg, vector<int> is_bad, int *pipfd); void fun_removetag0(vector<string> arg, vector<int> is_bad, int *pipfd); void fun_number(vector<string> arg, vector<int> is_bad, int *pipfd); void fun_other(vector<string> arg, vector<int> is_bad, int *pipfd); bool choose_fun(vector<string> arg, vector<int> is_bad, int *pipfd); <file_sep>/hw2/README.md # I. Introduction In this project, you are asked to design 3 kinds of servers: 1. Design a Concurrent connection-oriented server. This server allows one client connect to it. 2. Design a server of the chat-like systems, called remote working systems (rwg). In this system, users can communicate with other users. You need to use the single-process concurrent paradigm to design this server. # II. Scenario of Part One You can use telnet to connect to your server. Assume your server is running on nplinux1 and listening at port 7001. ``` bash$ telnet nplinux1.cs.nctu.edu.tw 7001 % ls | cat bin test.html % ls |1 % cat bin test.html % exit bash$ ``` # III. Scenario of Part Two You are asked to design the following features in your server. 1. Pipe between different users. Broadcast message whenever a user pipe is used. 2. Broadcast message of login/logout information. 3. New commands: * **who**: show information of all users. * **tell**: send a message to another user. * **yell**: send a message to all users. * **name**: change your name. 4. All commands in hw1 <file_sep>/hw2/function.h void func(int sockfd, int cli){ vector<string> arg; char input[MAXLEN] = ""; int i=0; read(sockfd, input, sizeof(input)); string msg = string(input); arg = dealline(msg); for(int i=0; i<msg.length(); i++){ if(msg[i] == '\r' || msg[i] == '\n'){ msg.erase(msg.begin()+i); i --; } } if(arg.size() == 0) return; if(choose_rwg_fun(arg, sockfd, cli)) shell_function_preprocess(arg, msg, cli, sockfd); } vector<string> dealline(string input){ stringstream ss; string s; vector<string> tmp; ss << input; while(ss >> s) tmp.push_back(s); return tmp; } bool choose_rwg_fun(vector<string> arg, int sockfd, int cli){ if(arg[0] == "who") rwg_who(arg, sockfd, cli); else if(arg[0] == "tell") rwg_tell(arg, sockfd, cli); else if(arg[0] == "yell") rwg_yell(arg, sockfd, cli); else if(arg[0] == "name") rwg_name(arg, sockfd, cli); else if(arg[0] == "exit") rwg_exit(arg, sockfd, cli); else return 1; return 0; } bool choose_shell_fun(vector<string> arg, vector<int> is_bad, int *pipfd, int sockfd, int cli){ if(arg[0] == "printenv") shell_printenv(arg, sockfd, cli); else if(arg[0] == "setenv") shell_setenv(arg, sockfd, cli); else shell_other(arg, is_bad, pipfd, sockfd, cli); return 0; } void shell_function_preprocess(vector<string> &arg, string input, int cli, int sockfd){ char redir[MAXLEN]; vector<int> is_bad = {0, 0, 0, 0, 0, 0, 0}; //[redirect, numpip, has_next_pipe, has_last_pipe, pipeth, user_pipe_in, user_pipe_out] int arg_num = arg.size(); int pipfd[2*MAXPIPE]; signal(SIGCHLD, SIG_IGN); //environment argument setup map<string, string>::iterator iter; for(iter=env[cli].begin(); iter != env[cli].end(); iter++) setenv(iter->first.c_str(), iter->second.c_str(), 1); //check user pipe int tmp_user_pipe_out = 0; for(int i=0; i<arg_num; i++){ if((arg[i][0] == '<' || arg[i][0] == '>') && arg[i].length() > 1){ int user_pipe_num = stoi(&arg[i][1]); for(int j=1; j<arg[i].length(); j++){ if(arg[i][j] > '9' || arg[i][j] < '0'){ user_pipe_num = 0; break; } } if(user_pipe_num){ // user does not exist if(client[user_pipe_num] < 0){ cout << "User does not exist " << user_pipe_num << endl; if(arg[i][0] == '<') USER_PIPE_IN = -1 * user_pipe_num; else if(arg[i][0] == '>') tmp_user_pipe_out = -1 * user_pipe_num; arg.erase(arg.begin()+i); arg_num --; i --; continue; } stringstream ss; ss << setw(2) << setfill('0') << user_pipe_num; string other = ss.str(); ss.str(""); ss << setw(2) << setfill('0') << cli; string me = ss.str(); string user_pipe_key = arg[i][0] == '<' ? other + me : me + other; // User pipe in if(arg[i][0] == '<'){ if(active_user_pipe.find(user_pipe_key) != active_user_pipe.end()) USER_PIPE_IN = user_pipe_num; else USER_PIPE_IN = -1 * user_pipe_num; } //User pipe out else if(arg[i][0] == '>'){ if(active_user_pipe.find(user_pipe_key) == active_user_pipe.end()){ tmp_user_pipe_out = user_pipe_num; struct user_pipe new_pipe; pipe(new_pipe.user_pipe); active_user_pipe[user_pipe_key] = new_pipe; } else tmp_user_pipe_out = -1 * user_pipe_num; } arg.erase(arg.begin()+i); arg_num --; i --; } } } //return user pipe in msg if(USER_PIPE_IN > 0){ string msg = "*** " + name[cli] + " (#" + to_string(cli) + ") just received from " + name[USER_PIPE_IN] + " (#" + to_string(USER_PIPE_IN) + ") by \'" + input + "' ***\n"; for(int i=1; i<LISTENQ; i++){ if(client[i] > 0) write(client[i], msg.c_str(), msg.length()); } } else if(USER_PIPE_IN < 0){ int src = -1 * USER_PIPE_IN; string errmsg; if(client[src] < 0) errmsg = "*** Error: user #" + to_string(src) + " does not exist yet. ***\n"; else errmsg = "*** Error: the pipe #" + to_string(src) + "->#" + to_string(cli) + " does not exist yet. ***\n"; write(sockfd, errmsg.c_str(), errmsg.length()); } //check pipe int begin = 0, pipth = 0; arg_num = arg.size(); for(int i=0; i<arg_num; i++){ if(arg[i] == "|"){ pipe(pipfd+2*pipth); IS_PIPE = 1; //has_next_pipe is_bad[4] = pipth; //pipth vector<string> tmp; for(int j=begin; j<i; j++) tmp.push_back(arg[j]); choose_shell_fun(tmp, is_bad, pipfd, sockfd, cli); IS_PIPE = 0; LAST_PIPE = 1; //has_last_pipe USER_PIPE_IN = 0; begin = i+1; pipth = (pipth + 1) % MAXPIPE; } } //check redirect FILE* pfile; for(int i=0; i<arg_num; i++){ //check redirect if(arg[i] == ">" && !is_bad[0]){ if(i == arg_num-1){ cout << " [command] > [redirect file]]" << endl; break; } string str = arg[i+1]; strcpy(redir, str.c_str()); pfile = fopen(redir, "w"); is_bad[0] = fileno(pfile); } if(is_bad[0]) arg.pop_back(); } //check number pipe for(int i=0; i<arg_num; i++){ if((arg[i][0] == '|' || arg[i][0] == '!') && arg[i].length() > 1){ arg[i][0] == '|' ? IS_NUMPIPE = 1 : IS_NUMPIPE = -1; for(int j=1; j<arg[i].length(); j++){ char ch = arg[i][j]; if(ch < '0' || ch > '9'){ IS_NUMPIPE = 0; break; } } if(IS_NUMPIPE){ IS_NUMPIPE = IS_NUMPIPE * stoi(&arg[i][1]); arg.pop_back(); break; } } } int target = (process_line[cli] + abs(IS_NUMPIPE)) % MAXPIPE; if(IS_NUMPIPE && pidq[cli][target].size() == 0) pipe(numpipfd[cli] + 2 * target); // return message if user pipe if(tmp_user_pipe_out){ USER_PIPE_OUT = tmp_user_pipe_out; if(tmp_user_pipe_out > 0){ // return msg string msg = "*** " + name[cli] + " (#" + to_string(cli) + ") just piped '" + input + "' to " + name[USER_PIPE_OUT] + " (#" + to_string(USER_PIPE_OUT) + ") ***\n"; for(int i=1; i<LISTENQ; i++){ if(client[i] > 0) write(client[i], msg.c_str(), msg.length()); } } else if(tmp_user_pipe_out < 0){ int dst = -1 * tmp_user_pipe_out; string errmsg; if(client[dst] < 0) errmsg = "*** Error: user #" + to_string(dst) + " does not exist yet. ***\n"; else errmsg = "*** Error: the pipe #" + to_string(cli) + "->#" + to_string(dst) + " already exists. ***\n"; write(sockfd, errmsg.c_str(), errmsg.length()); } } // clean arguments if there is pipe in command if(begin) arg.erase(arg.begin(), arg.begin()+begin); // jump to functions is_bad[4] = pipth; choose_shell_fun(arg, is_bad, pipfd, sockfd, cli); // change stdout back if(is_bad[0]) fclose(pfile); process_line[cli] = (process_line[cli] + 1) % MAXPIPE; for(iter=env[cli].begin(); iter != env[cli].end(); iter++) setenv(iter->first.c_str(), "", 1); }
ad158ca89229e2b9337d3121488ee217605c289e
[ "Markdown", "Makefile", "Python", "C", "C++", "Shell" ]
28
C++
jejewu/nphard_2020_fall
c35215c6b17bd6fabddf6b9df9ccc11b190193e0
320ad88b12cf2ac3a778eaffe5aa2f17e81bddd1
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.Text; namespace Composite { interface Person { int BornAndExist(); } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace Composite { class GeneologyComposite : Person { private List<Person> members = new List<Person>(); private int budget = 0; public int Budget { get; set; } public void addMember(Person member) { members.Add(member); } public void removeMember(Person member) { members.Remove(member); } public int BornAndExist() { foreach (Person member in members) { Budget+= member.BornAndExist(); } return Budget; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Composite { class Male: Person { public string Name { get; set; } public int Salary { get; set; } public Male(string name, int salary) { Name = name; Salary = salary; } public int BornAndExist() { Console.WriteLine("Name: " + Name); return Salary; } } } <file_sep>using System; namespace Composite { class Program { static void Main(string[] args) { Console.WriteLine("List of family members"); Person grandmother = new Female("Yadviga", 3500); Person grandfather = new Male("Andrey", 3000); Person father = new Male("Yura", 2000); Person mother = new Male("Tany", 8000); Person elderSister = new Female("Ira", 1300); Person youngerSister = new Female("Vika", 0); GeneologyComposite firstGeneration = new GeneologyComposite(); GeneologyComposite secondGeneration = new GeneologyComposite(); GeneologyComposite thirdGeneration = new GeneologyComposite(); firstGeneration.addMember(grandfather); firstGeneration.addMember(grandmother); firstGeneration.addMember(secondGeneration); secondGeneration.addMember(thirdGeneration); secondGeneration.addMember(father); secondGeneration.addMember(mother); thirdGeneration.addMember(elderSister); thirdGeneration.addMember(youngerSister); GeneologyComposite family = new GeneologyComposite(); family.addMember(firstGeneration); family.BornAndExist(); Console.WriteLine("Budget of family:"); Console.WriteLine(firstGeneration.Budget); } } }
c94ccd1beb1076b4b278f2ad19707657cfb42e25
[ "C#" ]
4
C#
Melllo/Composite
6f2c986df436ac2aee26dbd1561e2ebd8d377457
ed6c63506cd2a7253f3ff16c0d159521050d5c3b
refs/heads/master
<repo_name>Callen-Reid/ScienceCenterProject<file_sep>/docking.py #some code import matplotlib.pyplot as plt import numpy as np import math # Parameters m0 = 3*(10**6)# initial mass of rocket (kg) ### Will have to change m_rock = 0.51*(10**6) # kg mass of rocket without fuel ### Will have to change r_init = 99*(10**6) # m distance away from planet during landing/docking stage ### Will have to change v0 = -7*10**3 # initial velocity (m/s) ### Will have to change m_mars = 6.39*(10**23) # mass of Mars (kg) r = 3.3895*(10**6) # radius of Mars (m) G = 6.67408*(10**-11)# gravitational constant # g = 9.81 # m/s^2 #earth # g_mars = 3.711 # m/s^2 F_thrust = 4*10**7 # kg*m/s^2 Reverse thrust of rocket ### Will Have to change constant v_ex = -4*10**(3) # m/s velocity of ejecting fuel ### Will have to change constant # Equations def accel_grav(r): g = (G * m_mars) / r**2 return g # Time for Simulation dt = 1 # day tmax = 500 # days for 5 years timestep = int(tmax/dt) # Array for data allocation time = np.zeros(timestep) # duration of landing/docking m = np.zeros(timestep) # mass of rocket x = np.zeros(timestep) # distance from Mars v = np.zeros(timestep) # velocity (in m/s) of rocket a = np.zeros(timestep) # acceleration (in m/s^2) of rocket m[0] = m0 x[0] = r_init v[0] = v0 a[0] = -accel_grav(r_init) ifinal = -1 for i in range(1, timestep): dm = F_thrust/v_ex if m[i-1] >= m_rock: m[i] = m[i-1] + dm * dt else: m[i] = m[i-1] F_thrust = 0 a[i] = a[i-1] - accel_grav(x[i-1]) - F_thrust / m[i-1] v[i] = v[i-1] + a[i-1] * dt x[i] = x[i-1] + v[i-1] * dt time[i] = time[i-1] + dt if x[i] <= 0: ifinal = i break print(ifinal) plt.plot(m, label='Mass', color='green') plt.plot(v, label='Velocity', color='blue') plt.legend() plt.show() plt.plot(a, label='Acceleration') plt.legend() plt.show() plt.plot(x, label='Position', color='black') plt.legend() plt.show()
a538de3162d8b6aa5e3ddd41c0d4b9beef998e18
[ "Python" ]
1
Python
Callen-Reid/ScienceCenterProject
cb06bf714dc4be4916736715b7a9037b2c8411f7
85ece1d1054e73f0702a6607bca9562b57e27c20
refs/heads/master
<repo_name>BrutalistInstruments/Tsunami-CS-1<file_sep>/TsunamiCS1Master/tsunamiLib.c /* * tsunamiLib1.c * * Created: 8/9/2019 12:18:54 PM * Author: Hal */ #include "serialLib.h" #include <avr/io.h> #include "globalVariables.h" #include <avr/interrupt.h> // 0 1 2 3 4 5 6 7 8 9 //message format:0xf0, 0xaa, 0x0a, 0x03, 0x01, 0x11, 0x00, 0x00, 0x00, 0x55 //|StartOfMessage|StartOfMessage|BytesInMessage|MessageCode|MessageData|EndOfData| //| 0 | 1 | 2 | 3 | 4-8 | 9 | void initEnvelopes() { //here we need to set up a timer to tell when the release stage needs to happen. //should be in milliseconds, and should hold a 32 bit integer. We could probably store it in Globals. //we also need an update envelopes function that checks if the timer has been reached, if the 16 bit flag has been set, and do the release stage. //We'll be using timer3 for this. //TCCR3A = (1<<WGM32); //set timer to CTC mode (clear timer on correct value) //TCCR3B = (1<<CS30);//(1<<CS31);//|(1<<CS30); //64 prescaller. //no prescaler //OCR3AH = 0x06; //totaling 1600 //OCR3AL = 0x40; //250*64 = 1,600 ->1Ms worth of clock cycles. //TIMSK3 = (1<<OCIE3A); //output compare interrupt enable timer 3 compare Register A } void getVersion() {//gets the version from tsunami. may be useful in later versions, //to print the version on the OLED Screen. unsigned char version[5] = {0xf0, 0xaa, 0x05, 0x01, 0x55}; serialWrite0(version, 5); } void getSysInfo() {//requests total number of voices in firmware, and total tracks on SD Card. unsigned char info[5] = {0xf0, 0xaa, 0x05, 0x02, 0x55}; serialWrite0(info, 5); } void setReporting(char reportBool) {//if true, set reporting to on. unsigned char report[6] = {0xf0, 0xaa, 0x06, 0x0d, reportBool, 0x55}; serialWrite0(report, 6); } void trackControl(char trackNumberLSB, char trackNumberMSB, char outputNumber, char trackCommand) { unsigned char sendtrackCommand[10] = {0xf0, 0xaa, 0x0a, 0x03, trackCommand, trackNumberLSB, trackNumberMSB, outputNumber, 0x00, 0x55}; serialWrite0(sendtrackCommand, 10); } void stopAll() { unsigned char stop[5] = {0xf0, 0xaa, 0x05, 0x04, 0x55}; serialWrite0(stop, 5); } void setOutputVolume(uint8_t gainLSB, uint8_t gainMSB, uint8_t outputNumber ) { unsigned char outVolume[8] = {0xf0, 0xaa, 0x08, 0x05, outputNumber, gainLSB, gainMSB, 0x55}; serialWrite0(outVolume, 8); } void setTrackVolume(uint8_t trackLSB, uint8_t trackMSB, uint8_t gainLSB, uint8_t gainMSB) {//we may want to make a conversion function to convert 1 negative int into a 2 uint8_t number. unsigned char trackVolume[9] = {0xf0, 0xaa, 0x09, 0x08, trackLSB, trackMSB, gainLSB, gainMSB, 0x55}; serialWrite0(trackVolume, 9); } void setTrackFade(uint8_t trackLSB, uint8_t trackMSB, uint8_t gainLSB, uint8_t gainMSB, uint8_t millisecondsLSB, uint8_t millisecondsMSB, uint8_t stopFlag) {//sets envelope time, must be called directly after a play message. //envelopes can range from 0 to 2000ms unsigned char trackEnvelope[12] = {0xf0, 0xaa, 0x0c, 0x0a, trackLSB, trackMSB, gainLSB, gainMSB, millisecondsLSB, millisecondsMSB, stopFlag, 0x55}; serialWrite0(trackEnvelope, 12); } void resumeAll() { unsigned char resumePlay[5] = {0xf0, 0xaa, 0x05, 0x0b, 0x55}; serialWrite0(resumePlay, 5); } void outputSampleRate(uint8_t outputSelect, uint8_t offsetLSB, uint8_t offsetMSB) { unsigned char pitchChange[8] = {0xf0, 0xaa, 0x08, 0x0c, outputSelect, offsetLSB, offsetMSB, 0x55}; serialWrite0(pitchChange, 8); } void setInPutMix(uint8_t outputMask) { unsigned char inMix[6] = {0xf0, 0xaa, 0x06, 0x0f, outputMask, 0x55}; serialWrite0(inMix,6); } void playTrack(Pattern *currentPattern, Globals *currentGlobals, uint8_t trigInput) //most of these params are just getting passed through. { //4 cases: //uint16_t totalReleaseTime = currentPattern->trackReleaseTimeLSB[trigInput]|((currentPattern->trackReleaseTimeMSB[trigInput])<<8); //we need to handle attackTimes less than 20ms. switch(currentPattern->envelopeType[trigInput]) { case 0:; //A-R trackControl(currentPattern->trackSampleLSB[trigInput], currentPattern->trackSampleMSB[trigInput], currentPattern->trackOutputRoute[trigInput], currentPattern->trackPlayMode[trigInput]); setTrackFade(currentPattern->trackSampleLSB[trigInput], currentPattern->trackSampleMSB[trigInput], currentPattern->trackMainVolumeLSB[trigInput], currentPattern->trackMainVolumeMSB[trigInput], currentPattern->trackAttackTimeLSB[trigInput], currentPattern->trackAttackTimeMSB[trigInput], 0); currentGlobals->releaseTracker|=(1<<trigInput); //set tracking uint16_t sustainTime = (currentPattern->trackSustainTimeLSB[trigInput])|((currentPattern->trackSustainTimeMSB[trigInput])<<8); uint16_t totalAttackTime = (currentPattern->trackAttackTimeLSB[trigInput])|((currentPattern->trackAttackTimeMSB[trigInput])<<8); currentGlobals->sustainCounterArray[trigInput] = (currentGlobals->releaseCounter)+((sustainTime+totalAttackTime)*10); break; case 1:; //R trackControl(currentPattern->trackSampleLSB[trigInput], currentPattern->trackSampleMSB[trigInput], currentPattern->trackOutputRoute[trigInput], currentPattern->trackPlayMode[trigInput]); currentGlobals->releaseTracker|=(1<<trigInput); uint16_t sustainTimeR = (currentPattern->trackSustainTimeLSB[trigInput])|((currentPattern->trackSustainTimeMSB[trigInput])<<8); currentGlobals->sustainCounterArray[trigInput] = currentGlobals->releaseCounter+(sustainTimeR*10); //sustain counter is in millis, and release Counter is now 1 order of magnitude smaller than millis. break; case 2: //A trackControl(currentPattern->trackSampleLSB[trigInput], currentPattern->trackSampleMSB[trigInput], currentPattern->trackOutputRoute[trigInput], currentPattern->trackPlayMode[trigInput]); setTrackFade(currentPattern->trackSampleLSB[trigInput], currentPattern->trackSampleMSB[trigInput], currentPattern->trackMainVolumeLSB[trigInput], currentPattern->trackMainVolumeMSB[trigInput], currentPattern->trackAttackTimeLSB[trigInput], currentPattern->trackAttackTimeMSB[trigInput], 0); break; case 3: //none trackControl(currentPattern->trackSampleLSB[trigInput], currentPattern->trackSampleMSB[trigInput], currentPattern->trackOutputRoute[trigInput], currentPattern->trackPlayMode[trigInput]); break; } } void sendPatternOnLoad(Pattern *currentPattern, Pattern oldPattern) { for(int i=0; i<8; i++) { //if(currentPattern->outputLevelLSB[i]!=oldPattern.outputLevelLSB[i]) //if the volume does not change from pattern to pattern, no need to send serial data. //{//this should speed up the physical time this method takes significantly. //set output volume here setOutputVolume(currentPattern->outputLevelLSB[i], currentPattern->outputLevelMSB[i], i); //} } for(int i=0; i<8; i++) { //if(currentPattern->outputPitch[i]!=oldPattern.outputPitch[i]) //{ //set pitch volume outputSampleRate(i,0,currentPattern->outputPitch[i]); //} } for(int i=0; i<16; i++) { //not really a good way to do a redundancy check here, since tsunami indexes is track volumes per sample //i.e., it stores 4096 sample volumes per session. //we actually could maybe send all of those on startup? and then never have to send them unless there is a change? //this should be fine for now though. //set track volume setTrackVolume(currentPattern->trackSampleLSB[i], currentPattern->trackSampleMSB[i], currentPattern->trackMainVolumeLSB[i], currentPattern->trackMainVolumeMSB[i]); } } void releaseUpdate(Pattern *currentPattern, Globals *currentGlobals) { uint16_t releaseTrackerParse = currentGlobals->releaseTracker; for(int i = 0; i<16; i++) {//check every track, if there is a 1 in release counter, we check math. if(releaseTrackerParse&1) //if the first bit in the counter is a 1, we check for release times. //we could role this into one if statement, but I'm not sure that would be more efficient. Here we're using the release tracker as sort of an initial buffer. { if((currentGlobals->sustainCounterArray[i])<=(currentGlobals->releaseCounter)) { //we need to do the release state here. setTrackFade(currentPattern->trackSampleLSB[i],currentPattern->trackSampleMSB[i],186,255,currentPattern->trackReleaseTimeLSB[i],currentPattern->trackReleaseTimeMSB[i],1); currentGlobals->releaseTracker = currentGlobals->releaseTracker&(~(1<<i)); //turn off that track, so release stage does not play again. } } releaseTrackerParse = releaseTrackerParse>>1; } }<file_sep>/TsunamiCS1Master/EncoderLib.c /* */ #include <avr/io.h> #include "globalVariables.h" #include <avr/interrupt.h> #define F_CPU 16000000UL #include "OLEDLib.h" #include "twiLib.h" #include "knobLib.h" #include "tsunamiLib.h" #define topEncoderPinA 0 #define topEncoderPinB 1 #define bottomEncoderPinA 2 #define bottomEncoderPinB 3 #define topEncoderRead (PINE&0b00110000)>>4 //we want to read pins 4 and 5., and shift them down 4 spaces. #define bottomEncoderRead (PIND&0b0000110)>>1 //we want to read pins 3 and 2 of Port D, and shift them down one space. //volatile uint8_t prevNextCodeTop = 0; //volatile uint8_t storeTop = 0; //static int8_t rot_enc_table[] = {0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0}; volatile uint8_t topEncoderValue = 0; volatile uint8_t bottomEncoderValue = 0; uint8_t topEncoderLastValue = 0; uint8_t bottomEncoderLastValue = 0; uint8_t topEncoderPortState = 0; volatile uint8_t encoderPortStates = 0; void initEncoders() { //Interrupt pins - 2,3,4,5 //setup rising edge detection on Int pins 2 and 3 (would maybe want all pin states if this doesn't work). EICRA |=(1<<ISC31)|(1<<ISC30)|(1 << ISC21)|(1 << ISC20); //same setup on pins 4 and 5 EICRB |=(1<<ISC51)|(1<<ISC50)|(1 << ISC41)|(1 << ISC40); //enable all 4 interrupts through masking EIMSK |=(1<<INT2)|(1<<INT3)|(1<<INT4)|(1<<INT5); //DDRE &=0xCF; //we want to set every bit that is on, except for pins 5 and 4. //DDRD &=0xF3; //we want to set every bit that is on, except for pins 2 and 3. } ISR(INT2_vect) { if((1<<topEncoderPinB)&encoderPortStates)//this means Pin 2 is coming after pin 3 { bottomEncoderValue--; encoderPortStates&=(1<<bottomEncoderPinB)|(1<<bottomEncoderPinA);//reset our two pins to low. } else { encoderPortStates|=(1<<topEncoderPinA); //we want to set bit 0. } } ISR(INT3_vect) { if((1<<topEncoderPinA)&encoderPortStates)//this means Pin 3 is coming after pin 2 { bottomEncoderValue++; encoderPortStates&=(1<<bottomEncoderPinA)|(1<<bottomEncoderPinB); //reset our two pins to low. } else { encoderPortStates|=(1<<topEncoderPinB); //we want to set bit 1. } } ISR(INT4_vect) { if((1<<bottomEncoderPinB)&encoderPortStates)//this means Pin 4 is coming after pin 5 { topEncoderValue++; encoderPortStates&=(1<<topEncoderPinA)|(1<<topEncoderPinB); //reset our two pins to low. } else { encoderPortStates|=(1<<bottomEncoderPinA); //we want to set bit 2. } } ISR(INT5_vect) { if((1<<bottomEncoderPinA)&encoderPortStates)//this means Pin 3 is coming after pin 2 { topEncoderValue--; encoderPortStates&=(1<<topEncoderPinA)|(1<<topEncoderPinB); //reset our two pins to low. } else { encoderPortStates|=(1<<bottomEncoderPinB); //we want to set bit 3. } } /* void listenEncodersNew(Pattern *currentPattern, Globals *currentGlobals) { //this will happen every millisecond. prevNextCodeTop <<2; prevNextCodeTop |= topEncoderRead; prevNextCodeTop &= 0x0F; if(rot_enc_table[prevNextCodeTop]) { storeTop << 4; storeTop |= prevNextCodeTop; if ((storeTop&0xff)==0x2b) { topEncoderValue++; } if ((storeTop&0xff)==0x17) { topEncoderValue--; } } } */ void listenEncoders(Pattern *currentPattern, Globals *currentGlobals) { if(topEncoderValue!=topEncoderLastValue) { currentGlobals->menuState = ((topEncoderValue%4)<<4); bottomEncoderValue = 0; bottomEncoderLastValue = 0; currentGlobals->valueChangeFlag |= (1<<encoderChange); topEncoderLastValue = topEncoderValue; } if(bottomEncoderValue!=bottomEncoderLastValue) { uint8_t menuSub = bottomEncoderValue - bottomEncoderLastValue; currentGlobals->valueChangeFlag |= (1<<encoderChange); //if this value is negative, we increase the menu. //if positive, we decrement the menu. switch(currentGlobals->menuState) { case PreformanceModeInit: if(menuSub==1) { currentGlobals->currentPatternNumber = (currentGlobals->currentPatternNumber) + 1; if(currentGlobals->currentPatternNumber==0) { currentGlobals->currentPatternNumber=255; } }else if(menuSub==255) //we don't want to hit this when switching menus after changing from the sequencer. { currentGlobals->currentPatternNumber = (currentGlobals->currentPatternNumber) - 1; if(currentGlobals->currentPatternNumber==255) { currentGlobals->currentPatternNumber=0; } } eepromLoadPattern(currentPattern, currentGlobals->currentPatternNumber); break; case SequencerMenuArrow1: if(menuSub==1) { currentGlobals->menuState = SequencerMenuArrow3; }else { currentGlobals->menuState = SequencerMenuArrow2; } break; case SequencerMenuArrow1Select: if(menuSub==1) { currentGlobals->currentPatternNumber = (currentGlobals->currentPatternNumber) + 1; if(currentGlobals->currentPatternNumber==0) { currentGlobals->currentPatternNumber=255; } }else { currentGlobals->currentPatternNumber = (currentGlobals->currentPatternNumber) - 1; if(currentGlobals->currentPatternNumber==255) { currentGlobals->currentPatternNumber=0; } } eepromLoadPattern(currentPattern, currentGlobals->currentPatternNumber); //this keeps the knob reads that will happen right after the eeprom load to write over the loaded values. //Now when you load a pattern, the saved positions of the knobs are unchanged until you turn a knob. break; case SequencerMenuArrow2: if(menuSub==1) { currentGlobals->menuState = SequencerMenuArrow1; }else { currentGlobals->menuState = SequencerMenuArrow3; } break; case SequencerMenuArrow2Select: if(menuSub==1) { currentPattern->numSteps++; if(currentPattern->numSteps>64) {//we only have 64 spaces to write patterns into currentPattern->numSteps=64; } }else { currentPattern->numSteps--; if(currentPattern->numSteps<1) {//we can't have a 0 step pattern. currentPattern->numSteps=1; } } break; case SequencerMenuArrow3:; if(menuSub==1) { currentGlobals->menuState = SequencerMenuArrow2; }else { currentGlobals->menuState = SequencerMenuArrow1; } break; case SequencerMenuArrow3Select: //change current step number if(menuSub==1) { currentGlobals->currentStep++; if(currentGlobals->currentStep>=currentPattern->numSteps) {//our ceiling is the maximum number of steps. currentGlobals->currentStep=(currentPattern->numSteps)-1; } }else { currentGlobals->currentStep--; if(currentGlobals->currentStep>currentPattern->numSteps) {//do no write notes to step 0. currentGlobals->currentStep=0; } } break; case TrackMenuArrow1:; if(menuSub==1) { currentGlobals->menuState = TrackMenuArrow5; }else { currentGlobals->menuState = TrackMenuArrow2; } break; case TrackMenuArrow1Select:; uint16_t currentSample = ((currentPattern->trackSampleMSB[currentGlobals->currentTrack])<<8)|(currentPattern->trackSampleLSB[currentGlobals->currentTrack]); if(menuSub==1) { currentSample++; if(currentSample>4096) {//maximum number of indexable samples. currentSample=4096; } }else {//no samples in space 0. currentSample--; if(currentSample<1) { currentSample=1; } } currentPattern->trackSampleLSB[currentGlobals->currentTrack] = (currentSample&0x00FF);//we want to lob off the top 8 bits, just in case. May be unnecessary. currentPattern->trackSampleMSB[currentGlobals->currentTrack] = (currentSample>>8); break; case TrackMenuArrow2: if(menuSub==1) { currentGlobals->menuState = TrackMenuArrow1; }else { currentGlobals->menuState = TrackMenuArrow3; } break; case TrackMenuArrow2Select: //change play mode of currently selected track //since we only have two play modes currently, //we only need to flip the play mode. currentPattern->trackPlayMode[currentGlobals->currentTrack] = (!(currentPattern->trackPlayMode[currentGlobals->currentTrack]))&(0b00000001); //flip all bits, mask for first bit. break; case TrackMenuArrow3: if(menuSub==1) { currentGlobals->menuState = TrackMenuArrow2; }else { currentGlobals->menuState = TrackMenuArrow4; } break; case TrackMenuArrow3Select: if(menuSub==1) { //indexing might be an issue here, don't remember if this is 0 indexed or not. (currentPattern->trackOutputRoute[currentGlobals->currentTrack]) = (currentPattern->trackOutputRoute[currentGlobals->currentTrack])+1 ; if(currentPattern->trackOutputRoute[currentGlobals->currentTrack]>7) { currentPattern->trackOutputRoute[currentGlobals->currentTrack]=7; } }else { (currentPattern->trackOutputRoute[currentGlobals->currentTrack]) = (currentPattern->trackOutputRoute[currentGlobals->currentTrack])-1; if(currentPattern->trackOutputRoute[currentGlobals->currentTrack]>7) { currentPattern->trackOutputRoute[currentGlobals->currentTrack]=0; } } break; case TrackMenuArrow4: if(menuSub==1) { currentGlobals->menuState = TrackMenuArrow3; }else { currentGlobals->menuState = TrackMenuArrow5; } break; case TrackMenuArrow4Select: if(menuSub==1) { (currentPattern->envelopeType[currentGlobals->currentTrack])++; if((currentPattern->envelopeType[currentGlobals->currentTrack])>3) { (currentPattern->envelopeType[currentGlobals->currentTrack])=3; } }else { (currentPattern->envelopeType[currentGlobals->currentTrack])--; if((currentPattern->envelopeType[currentGlobals->currentTrack])>3) { (currentPattern->envelopeType[currentGlobals->currentTrack])=0; } } if(currentPattern->envelopeType[currentGlobals->currentTrack]==0||currentPattern->envelopeType[currentGlobals->currentTrack]==2) //AR or A { setTrackVolume(currentPattern->trackSampleLSB[currentGlobals->currentTrack], currentPattern->trackSampleMSB[currentGlobals->currentTrack],255,186); }else { setTrackVolume(currentPattern->trackSampleLSB[currentGlobals->currentTrack], currentPattern->trackSampleMSB[currentGlobals->currentTrack], currentPattern->trackMainVolumeLSB[currentGlobals->currentTrack],currentPattern->trackMainVolumeMSB[currentGlobals->currentTrack]); } break; case TrackMenuArrow5: if(menuSub==1) { currentGlobals->menuState = TrackMenuArrow4; }else { currentGlobals->menuState = TrackMenuArrow1; } break; case TrackMenuArrow5Select:; uint16_t sustainTime = (currentPattern->trackSustainTimeLSB[currentGlobals->currentTrack])|((currentPattern->trackSustainTimeMSB[currentGlobals->currentTrack])<<8); if(menuSub==1) { if((currentGlobals->currentGPButtons)&(0x04)) { sustainTime++; } else { sustainTime = sustainTime+236; } if(sustainTime>60000) { sustainTime = 60000; } }else { if((currentGlobals->currentGPButtons)&(0x04)) { sustainTime--; }else { sustainTime = sustainTime - 236; } if(sustainTime>60000) { sustainTime = 0; } } currentPattern->trackSustainTimeMSB[currentGlobals->currentTrack] = (sustainTime>>8); currentPattern->trackSustainTimeLSB[currentGlobals->currentTrack] = sustainTime; //upper bits will be truncated. break; case GlobalMenuArrow1: if(menuSub==1) { currentGlobals->menuState = GlobalMenuArrow1; }else { currentGlobals->menuState = GlobalMenuArrow2; } break; //this may need to be in the range 0 to 15, and displayed with + 1. case GlobalMenuArrow1Select: if(menuSub==1) { //increment midi number currentGlobals->midiChannel = (currentGlobals->midiChannel)+1; if(currentGlobals->midiChannel>15) { currentGlobals->midiChannel=15; } } else { //decrement midi number currentGlobals->midiChannel = (currentGlobals->midiChannel)-1; if(currentGlobals->midiChannel>254) { currentGlobals->midiChannel=0; } } break; case GlobalMenuArrow2: if(menuSub==1) { currentGlobals->menuState = GlobalMenuArrow1; }else { currentGlobals->menuState = GlobalMenuArrow2; } break; case GlobalMenuArrow2Select:; //change midi note for selected track. //midi range is 0 to 127. uint8_t currentMidiNote = currentGlobals->midiTrackNote[currentGlobals->currentTrack]; if(menuSub==1) { //not 100% sure how to set this up. currentMidiNote++; if(currentMidiNote>127) { currentMidiNote = 127; } }else { currentMidiNote--; if(currentMidiNote>128) { currentMidiNote = 0; } } currentGlobals->midiTrackNote[currentGlobals->currentTrack] = currentMidiNote; break; case GlobalMenuArrow3: //currently unreachable, no settings live here atm if(menuSub==1) { currentGlobals->menuState = GlobalMenuArrow2; }else { currentGlobals->menuState = GlobalMenuArrow1; } break; case GlobalMenuArrow3Select: //nothing to put here yet. break; } bottomEncoderLastValue = bottomEncoderValue; //menuSub=0; } } uint8_t listenEnoderReset() { uint8_t returnMe = 2; if(topEncoderValue!=topEncoderLastValue){ returnMe = topEncoderValue%2; //should be 0 or 1. } return returnMe; } <file_sep>/Enclosure/enclosureReadMe.md ## Enclosure Current revision of enclosure has a few issues, but will be resolved with final revision of Front Panel and IO PCBs. Issues will be solved when final revision is complete.<file_sep>/Master to-Do list.md # CS1-Tsunami Sampler #### Master Buglist and Implementation progress This document exist to keep record of the status of features and bugs in the firmware, hardware, and enclosure of the CS1Tsunami. This is mainly to help us keep track of what needs doing. What's here: - Know bugs / issues - Un-implemented features - Hardware and enclosure to-dos. (In version 1.0, you'll see nothing here) ## Bugs #### Firmware | Known Bug| Proposed Solution | | ------ | ------ | |Encoder Reading sometimes goes backwards|timer based debouncing, a bit more research| |BPM readout for patterns is incorrect|Need to work on the BPM/sequencer algorythm a bit more| ## To-Implement #### Firmware | Feature |Depenencies| | ------- |-------| |Program Change messages change patterns|1.1| |Midi-Out on Trigger Buttons|Version 1.1| |TR Style Step Sequencer|1.1| |Logarithmic Knob Reading|Verion 1.2| #### Hardware |Feature|Dependencies| |----|----| |Voltage Divider for Tsunami Serial port out|Board Revision 8| |A2 eeprom chip tied to +5v instead of GND|Board Revision 8| |Schematic reading of 4.7K pullups on TWI Buss|Board Revision 8| All above hardware features are now implemented, and just need to be tested when new boards are ordered 8/5/2020 ## Enclosure |Feature| |need to start work on aluminum enlcosure| <file_sep>/TsunamiCS1Master/sequencerLib.c /* * sequencerLib.c * * Created: 3/30/2020 9:18:03 PM * Author: OurBl */ #include "globalVariables.h" #include "tsunamiLib.h" #include <avr/io.h> #include <avr/interrupt.h> //should both of these be globals? //uint16_t clockCounter = 0; // how many 0.0001 seconds have passed. //(1 degree of magnitude smaller than millis) uint8_t currentPlayStep = 0; //this is different than the currentStep, which is for editing. //if a real-time sequencer is implemented, they will end up being the same thing. void initSequencer() { //here we need to setup our timer interrupt //TCCR0A = (1 << WGM01); //set to clear on correct compare //TCCR0B = (1 << CS01) | (1 << CS00); // set pre-scaler to 64 //OCR0A = 21; // every 25 ticks will be 0.0001 seconds at this prescale. //TIMSK0 = (1 << OCIE0A); // Enable OCR0A compare interrupt //interrupts should now be good to go. } //ISR(TIMER0_COMPA_vect) //{ // clockCounter++; //we don't want to do anything else here. //} void updateSequencer(Pattern sequencerPattern, Globals *currentGlobals) { uint16_t BPMvar = 150000/(sequencerPattern.patternBPM); if(currentGlobals->clockCounter>=BPMvar && currentGlobals->playState) //if playstate is on, play next note in sequence. { //this will be where we play samples currentGlobals->clockCounter = 0; currentGlobals->currentTrigSequencer = 0; //we want to re-set this every time. uint16_t parseStep = sequencerPattern.trackSequence[currentPlayStep]; for (uint8_t sc=0; sc<16; sc++) //sequencer counter {//we're going to loop through all of the possible tracks, and trigger them if((parseStep&1)==1) { //trackControl(sequencerPattern.trackSampleLSB[sc], sequencerPattern.trackSampleMSB[sc], sequencerPattern.trackOutputRoute[sc], sequencerPattern.trackPlayMode[sc]); playTrack(&sequencerPattern, currentGlobals, sc); currentGlobals->currentTrigSequencer |= (1<<sc); //start to fill our lighting buffer. } parseStep = parseStep>>1; //shift bits down one to check the next slot in the sequence. } currentPlayStep = currentPlayStep+1; if(currentPlayStep>(sequencerPattern.numSteps-1)) { currentPlayStep=0; // don't play more steps than are in the sequence. } }else if(currentGlobals->clockCounter>=BPMvar && !currentGlobals->playState) { currentPlayStep=0; currentGlobals->clockCounter = 0; currentGlobals->currentTrigSequencer=0; } } <file_sep>/TsunamiCS1Master/serialLib.h /* * serialLib.h * * Created: 8/9/2019 10:59:59 AM * Author: Hal */ #include <avr/io.h> #ifndef SERIALLIB_H_ #define SERIALLIB_H_ void appendSerial0(char c); void serialWrite0(char c[], uint8_t messageLength); void serialInit0(); char getChar(); #endif /* SERIALLIB_H_ */ <file_sep>/TsunamiCS1Master/MidiLib.c #include <avr/interrupt.h> #include <avr/io.h> #include "globalVariables.h" #include "tsunamiLib.h" #define F_CPU 16000000UL #define MIDI_BAUD_RATE 31250 #define MIDI_NOTE_ON 0b1001 #define MIDI_NOTE_OFF 0b1000 #define MIDI_EVENT_BUFFER_SIZE 10 //we might want to make this bigger, since we will be receiving a lot of notes. extern uint8_t midiChannel; volatile typedef struct { uint8_t statusByte; uint8_t dataByte[2]; } midiEvent; midiEvent midiEventBuffer[MIDI_EVENT_BUFFER_SIZE]; volatile uint8_t midiWriteIndex = 0; volatile uint8_t midiWriteFlag = 255; uint8_t midiReadIndex=0; ISR (USART3_RX_vect) // interrupt service routine called each time USART data is received { uint8_t data = UDR3; // receives data from USART data register uint8_t midiMessageType = (data >> 4); if ( midiMessageType == MIDI_NOTE_ON || midiMessageType == MIDI_NOTE_OFF ) // if we receive a midi note on message or a midi note off message, begin writing to the midi buffer { midiEventBuffer[midiWriteIndex].statusByte = data; // write the status byte to the current midi write index midiWriteFlag = 0; // set the writing flag to begin writing data bytes } else if ( midiWriteFlag < 1 ) // we're only concerned with 2 data bytes, but if we were accepting messages of different lengths this value would have to be determined dynamically in the previous block { midiEventBuffer[midiWriteIndex].dataByte[midiWriteFlag] = data; // write data bytes to current midi write index midiWriteFlag++; // increment the midi writing flag in order to write the next data byte } else if ( midiWriteFlag < 255 ) { midiEventBuffer[midiWriteIndex].dataByte[midiWriteFlag] = data; // write data bytes to current midi write index uint8_t currentStatusByte = midiEventBuffer[midiWriteIndex].statusByte; midiWriteIndex = (midiWriteIndex + 1) % MIDI_EVENT_BUFFER_SIZE; // increment the midi write index since we've completed a midi event, use modulo operator for circular buffer midiEventBuffer[midiWriteIndex].statusByte = currentStatusByte; // write the next midi event's status byte in case of running status midiWriteFlag = 0; // set the writing flag to begin writing data bytes in case of running status } } void initMidi() { uint16_t UBRR = (F_CPU / 16 / MIDI_BAUD_RATE) -1; UBRR3H = (uint8_t) (UBRR >> 8); UBRR3L = (uint8_t) (UBRR); UCSR3B |= 0b10011000; //(1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0); // configuring USART (RXEN = receiver enable, TXEN = transmitter enable, RXCIE = receiver interrupt enable UCSR3C |= 0b00000110; ////(1 << USCZ11) | (1 << USCZ10); // for some reasone USCZ11 and USCZ10 are not recognized } void midiTransmit(uint8_t data) { while (!(UCSR3A & (1 << UDRE3))); UDR3 = data; } void midiRead(Pattern currentPattern, Globals currentGlobals) { while (midiReadIndex != midiWriteIndex) { uint8_t midiMessageType = ((midiEventBuffer[midiReadIndex].statusByte)>>4); uint8_t midiVelocity = (midiEventBuffer[midiReadIndex].dataByte[1]); uint8_t midiChannelIn = ((midiEventBuffer[midiReadIndex].statusByte)&0b00001111); //uint8_t midiChannelRead = ((midiEventBuffer[midiReadIndex].statusByte)&00001111); if ((midiMessageType==MIDI_NOTE_ON)&&(midiVelocity!=0)&&currentGlobals.midiChannel==midiChannelIn) { for (int i=0; i<16; i++) { if(midiEventBuffer[midiReadIndex].dataByte[0]==currentGlobals.midiTrackNote[i]) { //we don't care about velocity, at least not yet. playTrack(&currentPattern,&currentGlobals, i); //this might be out of scope? need to test. } } } midiReadIndex=(midiReadIndex+1)%MIDI_EVENT_BUFFER_SIZE; //we always want to increase the read index, even if our channel or message is not being used. } } <file_sep>/TsunamiCS1Master/OLEDLib.h /* * OLEDLib.h * * Created: 6/26/2019 5:47:25 PM * Author: Hal */ #ifndef OLEDLIB_H_ #define OLEDLIB_H_ #include <avr/io.h> void enableCycle(); void send8bit(uint8_t value); void command(uint8_t c); void data(uint8_t d); void initScreen(); void outputS(unsigned char* lineIn, int row); void numPrinter(unsigned char* charArray,uint8_t startingPos, uint8_t numCharacters, uint16_t inputNumber); void midiNotePrinter(char* charArray, uint8_t startingPosition, uint8_t noteNumber); #endif /* OLEDLIB_H_ */<file_sep>/TsunamiCS1Master/DebounceLib.c /* * DebounceLib.c this library is based on the AVR freaks debounce tutorial: https://www.avrfreaks.net/sites/default/files/forum_attachments/debounce.pdf */ #include "debounceLib.h" volatile uint8_t buttons_down; uint8_t button_down(uint8_t button_mask) { //I should probably check out what this is. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { button_mask &= buttons_down; buttons_down ^= button_mask; } return button_mask; }<file_sep>/README.md # Tsunami CS-1 Readme The Tsunami CS-1 is an open Source Audio Sample Player, based on the [Tsunami Wav Trigger by RobertSonics](https://robertsonics.com/tsunami/) and the Atmega 2560/Arduino Mega development board. Check out the build progress with pictures and video over at https://www.instagram.com/halford_c/ ### Features: Tactile Control over Tsunami Wave Trigger: - 255 Banks of 16 wav samples - 8 Individual Assignable Outputs - Per output volume control - Per output pitch control (1 octave up and down) - Volume envelope per sample - Per Sample volume control - Midi control of all tracks - Midi In, Out and Through - Internal 64 Step Sequencer, with variable sequence length and BPM - 32 Voice Polyphony in mono mode, 16 in stereo mode In this repository, you'll find: ## Schematics We currently have schematics for the Main Control Surface, and the IO Board ## TsunamiArduinoCore Where the .hex file for the current stable version lives. ## TsunamiCS1Master This is the development section of repository, only to be used with Atmel Studio and the Atmel Ice programmer. If you're interested In development and onboard debugging through J-tag, this is what you want to use. (currently depreciated) ## Enclosure This has Files for laser cutting 1/8th " material to create enclosure. As this project progresses, new enclosure files for different fabrication facilities will be placed here. (New enclosure files needed for new board revisions) ## BOM Currently, our BOM is just a text file with links to carts, and component numbers. If any of these parts go out of stock, or are non-stocked, get in touch with us, and we'll post up a new cart link. <file_sep>/TsunamiCS1Master/twiLib.c //based on the avr twi library from <NAME> #include <avr/io.h> #include "globalVariables.h" #include <util/delay.h> #include "OLEDLib.h" #include "twiLib.h" #include "tsunamiLib.h" #include <avr/eeprom.h> #define F_CPU 16000000UL /* A Note about the weird delay times in this library: For some reason, the F_CPU define above is throwing some weird errors. On my current compilation, compiler is complaining about it being re-defined, but also that it's undefined. (Not sure how that works...) So, this library results to the original F_CPU definition in the delay.h library, which is 1000000, or 1Mhz. Since we are running at 16 times the speed, our delay times are 16x larger. So, instead of delaying the 5ms recommended in the data sheet, we are delaying 16*5 = 80ms. Which, in our terms, is really 5ms. This quick fix will no longer be required after we set the save and load commands to run off of timer interrupts instead of delays. Should happen before larger release, or soon after. */ void twi_init() { TWSR = 0; TWBR = ((F_CPU/SCL_CLOCK-16)/2); //is this line the issue? } uint8_t twi_start(uint8_t address) { uint8_t twst; // send START condition TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN); // wait until transmission completed while(!(TWCR & (1<<TWINT))); // check value of TWI Status Register. Mask pre-scaler bits. twst = TW_STATUS & 0xF8; if ( (twst != TW_START) && (twst != TW_REP_START)) { return 1; } // send device address TWDR = address; TWCR = (1<<TWINT) | (1<<TWEN); // wail until transmission completed and ACK/NACK has been received while(!(TWCR & (1<<TWINT))); // check value of TWI Status Register. Mask pre-scaler bits. twst = TW_STATUS & 0xF8; if ( (twst != TW_MT_SLA_ACK) && (twst != TW_MR_SLA_ACK) ) { return 1; } return 0; // } void twi_start_wait(uint8_t address) { uint8_t twst; while ( 1 ) { // send START condition TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN); // wait until transmission completed while(!(TWCR & (1<<TWINT))); // check value of TWI Status Register. Mask pre-scaler bits. twst = TW_STATUS & 0xF8; if ( (twst != TW_START) && (twst != TW_REP_START)) continue; // send device address TWDR = address; TWCR = (1<<TWINT) | (1<<TWEN); // wail until transmission completed while(!(TWCR & (1<<TWINT))); // check value of TWI Status Register. Mask pre-scaler bits. twst = TW_STATUS & 0xF8; if ( (twst == TW_MT_SLA_NACK )||(twst ==TW_MR_DATA_NACK) ) { /* device busy, send stop condition to terminate write operation */ TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // wait until stop condition is executed and bus released while(TWCR & (1<<TWSTO)); continue; } break; } }/* twi_start_wait */ uint8_t twi_rep_start(uint8_t address) { return twi_start( address ); }/* twi_rep_start */ void twi_stop() { /* send stop condition */ TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // wait until stop condition is executed and bus released while(TWCR & (1<<TWSTO)); }/* twi_stop */ uint8_t twi_write(uint8_t data ) { uint8_t twst; // send data to the previously addressed device TWDR = data; TWCR = (1<<TWINT) | (1<<TWEN); // wait until transmission completed while(!(TWCR & (1<<TWINT))); // check value of TWI Status Register. Mask prescaler bits twst = TW_STATUS & 0xF8; if( twst != TW_MT_DATA_ACK) return 1; return 0; }/* twi_write */ uint8_t twi_readAck(void) { TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWEA); while(!(TWCR & (1<<TWINT))); return TWDR; }/* twi_readAck */ uint8_t twi_readNak(void) { TWCR = (1<<TWINT) | (1<<TWEN); while(!(TWCR & (1<<TWINT))); return TWDR; }/* twi_readNak */ void eepromSavePattern(Pattern inPattern, uint8_t patternNumber) { //write buffer will have to be the size of one page, so we will need to do 3 page writes. //every bank will take up 3 pages of memory, or 384 bytes //for 256 patterns of 384 bytes, we'll have 98,304 bytes. //each page on the EEprom is only 65,536 Bytes, so we need to go to the other block of the chip to have this many patterns. //we'll split the blocks for now, since that should be simpler with the algorytm. uint8_t eepromWriteBlock = EEPROMADDRESSWRITEA; uint16_t eepromWriteAddress = ((patternNumber-1)*384); if(patternNumber>127) { eepromWriteBlock = EEPROMADDRESSWRITEB; eepromWriteAddress = ((patternNumber-128)*384); //128 is our 0 index for BlockB. } uint8_t eepromWriteBuffer[128]; //first write (first 128 bytes)============================///////// for(int i = 0; i<8; i++)//0-7 bytes { eepromWriteBuffer[i]=inPattern.outputLevelMSB[i]; } for(int i=0; i<8; i++)//8-15 bytes { eepromWriteBuffer[i+8]=inPattern.outputLevelLSB[i]; } for(int i=0; i<8; i++)//16-23 bytes { eepromWriteBuffer[i+16]=inPattern.outputPitch[i]; } for(int i=0; i<16; i++)//24-39 bytes { eepromWriteBuffer[i+24]=inPattern.trackOutputRoute[i]; } for(int i=0; i<16; i++)//40-55 bytes { eepromWriteBuffer[i+40]=inPattern.trackMainVolumeMSB[i]; } for(int i=0; i<16; i++)//56-71 bytes { eepromWriteBuffer[i+56]=inPattern.trackMainVolumeLSB[i]; } for(int i=0; i<16; i++)//72-87 bytes { eepromWriteBuffer[i+72]=inPattern.trackAttackTimeMSB[i]; } for(int i=0; i<16; i++)//88-103 bytes { eepromWriteBuffer[i+88]=inPattern.trackAttackTimeLSB[i]; } for(int i=0; i<16; i++)//104-120 bytes { eepromWriteBuffer[i+104]=inPattern.trackReleaseTimeMSB[i]; }//first buffer filled eepromWriteBuffer[121] = (inPattern.patternBPM>>8); //MSB eepromWriteBuffer[122] = (inPattern.patternBPM & 0xFF); //LSB eepromWriteBuffer[123] = (inPattern.numSteps); //page write here. if(twi_start(eepromWriteBlock)==1) { char error1[20] = "Address Write Error1"; outputS(error1,3); } twi_write((eepromWriteAddress>>8)); //MSB twi_write((eepromWriteAddress & 0xFF)); //LSB for (int i = 0; i<124; i++) { twi_write(eepromWriteBuffer[i]); } twi_stop(); _delay_ms(80); for(int i=0; i<16; i++)//0-15 bytes { eepromWriteBuffer[i]=inPattern.trackReleaseTimeLSB[i]; } for(int i=0; i<16; i++)//16-31 bytes { eepromWriteBuffer[i+16]=inPattern.trackPlayMode[i]; } for(int i=0; i<16; i++)//32-47 bytes { eepromWriteBuffer[i+32]=inPattern.trackSampleMSB[i]; } for(int i=0; i<16; i++)//48-63 bytes { eepromWriteBuffer[i+48]=inPattern.trackSampleLSB[i]; } for(int i=0; i<16; i++)//64-79 bytes { eepromWriteBuffer[i+64]=inPattern.voiceLockFlag[i]; } for(int i=0; i<16; i++)//80-95 { eepromWriteBuffer[i+80]=inPattern.trackSustainTimeMSB[i]; } for(int i=0; i<16; i++)//96-111 { eepromWriteBuffer[i+96]=inPattern.trackSustainTimeLSB[i]; } for(int i=0; i<16; i++)//112-127 { eepromWriteBuffer[i+112]=inPattern.envelopeType[i]; } //we need to move these to the previous eeprom write. //page write here, but with 128 bytes of offset from the first write if(twi_start(eepromWriteBlock)==1) { char error1[20] = "Address Write Error2"; outputS(error1,3); } twi_write(((eepromWriteAddress+128)>>8)); //MSB twi_write(((eepromWriteAddress+128) & 0xFF)); //LSB for (int i = 0; i<128; i++) { twi_write(eepromWriteBuffer[i]); } twi_stop(); _delay_ms(80); if(twi_start(eepromWriteBlock)==1) { char error1[20] = "Address Write Error3"; outputS(error1,3); } twi_write(((eepromWriteAddress+256)>>8)); //MSB twi_write(((eepromWriteAddress+256) & 0xFF)); //LSB for (int i = 0; i<64; i++) { twi_write((inPattern.trackSequence[i]>>8)); twi_write((inPattern.trackSequence[i] & 0xFF)); } twi_stop(); _delay_ms(80); } void eepromLoadPattern(Pattern *currentPattern, uint8_t patternNumber) { // read buffer can be the size of a pattern, we can sequentially read more than just one page. //Pattern returnPattern; uint8_t eepromReadBlock = EEPROMADDRESSREADA; uint8_t eepromWriteBlock = EEPROMADDRESSWRITEA; uint16_t eepromReadAddress = ((patternNumber-1)*384); //this is the start. if(patternNumber>127) { eepromReadBlock = EEPROMADDRESSREADB; eepromWriteBlock = EEPROMADDRESSWRITEB; eepromReadAddress = ((patternNumber-128)*384); } //We'll be hijacking this function to send relevant pattern data to the tsunami as it loads. This should (I think) give the serial buffer enough time to catch up. //at least a few clock cycles from the other copying happening in the loop. uint8_t patternBuffer[384]; //this will hold all of the info from the reads. We don't want to lose anything. //start page read if(twi_start(eepromWriteBlock)==1) { outputS("Address Read Error1 ",3); } twi_write((eepromReadAddress>>8)); //MSB twi_write((eepromReadAddress & 0xFF)); //LSB if(twi_start(eepromReadBlock)==1) //this may need to be a repeat start? or a start wait? { char error2[20] = "Address Read Error2 "; outputS(error2,3); } for(int j=0; j<383; j++) { patternBuffer[j] = twi_readAck(); } patternBuffer[383] = twi_readNak(); twi_stop(); // now we get to assign all the numbers from this read into there respective locations in this pattern. for(int i = 0; i<8; i++)//0-7 bytes { currentPattern->outputLevelMSB[i] = patternBuffer[i]; } for(int i=0; i<8; i++)//8-15 bytes { currentPattern->outputLevelLSB[i]=patternBuffer[i+8]; setOutputVolume(currentPattern->outputLevelLSB[i], currentPattern->outputLevelMSB[i], i); } for(int i=0; i<8; i++)//16-23 bytes { currentPattern->outputPitch[i]=patternBuffer[i+16]; outputSampleRate(i,0,currentPattern->outputPitch[i]); } for(int i=0; i<16; i++)//24-39 bytes { currentPattern->trackOutputRoute[i]=patternBuffer[i+24]; } for(int i=0; i<16; i++)//40-55 bytes { currentPattern->trackMainVolumeMSB[i]=patternBuffer[i+40]; } for(int i=0; i<16; i++)//56-71 bytes { currentPattern->trackMainVolumeLSB[i]=patternBuffer[i+56]; } for(int i=0; i<16; i++)//72-87 bytes { currentPattern->trackAttackTimeMSB[i]=patternBuffer[i+72]; } for(int i=0; i<16; i++)//88-103 bytes { currentPattern->trackAttackTimeLSB[i]=patternBuffer[i+88]; } for(int i=0; i<16; i++)//104-120 bytes { currentPattern->trackReleaseTimeMSB[i]=patternBuffer[i+104]; } currentPattern->patternBPM = ((patternBuffer[121]<<8)|patternBuffer[122]); currentPattern->numSteps=patternBuffer[123]; for(int i=0; i<16; i++)//0-15 bytes //start of the read of the next block { currentPattern->trackReleaseTimeLSB[i]=patternBuffer[i+128]; } for(int i=0; i<16; i++)//16-31 bytes { currentPattern->trackPlayMode[i]=patternBuffer[i+144]; } for(int i=0; i<16; i++)//32-47 bytes { currentPattern->trackSampleMSB[i]=patternBuffer[i+160]; } for(int i=0; i<16; i++)//48-63 bytes { currentPattern->trackSampleLSB[i]=patternBuffer[i+176]; setTrackVolume(currentPattern->trackSampleLSB[i], currentPattern->trackSampleMSB[i], currentPattern->trackMainVolumeLSB[i], currentPattern->trackMainVolumeMSB[i]); } for(int i=0; i<16; i++)//64-79 bytes { currentPattern->voiceLockFlag[i]=patternBuffer[i+192]; } for(int i=0; i<16; i++)//80-95 { currentPattern->trackSustainTimeMSB[i]=patternBuffer[i+208]; } for(int i=0; i<16; i++)//96-111 { currentPattern->trackSustainTimeLSB[i]=patternBuffer[i+224]; } for(int i=0; i<16; i++)//112-127 { currentPattern->envelopeType[i]=patternBuffer[i+240]; } // now we just need to read in the sequencer for (int i = 0; i<64; i++) { uint16_t patternBuffIndex = 256+(i*2); //start on 3rd page, uint16_t msb = patternBuffer[patternBuffIndex]; uint16_t lsb = patternBuffer[patternBuffIndex+1]; currentPattern->trackSequence[i]=((msb<<8)|lsb); } //after this, we need to set the volume on all of the knob settings that have changed. //if we don't, loading will have no effect. //sendPatternOnLoad(currentPattern, oldPattern); } void factoryResetEeprom(Pattern inPattern) { char progressBar[21] = " "; for(uint8_t i = 0; i<255; i++) { eepromSavePattern(inPattern,i); _delay_ms(80); progressBar[(i/13)] = 219; outputS(progressBar,3); } } uint8_t readEEpromChar(uint16_t readAddress) { uint8_t returnNum; if(twi_start(EEPROMADDRESSWRITEA)==1) { //Serial.print("EEprom read address error"); } twi_write((readAddress>>8)); //MSB twi_write((readAddress & 0xFF)); //LSB if(twi_start(EEPROMADDRESSREADA)==1) { //Serial.print("EEprom read address error"); } returnNum=twi_readNak(); return returnNum; } //this happens when save button is pressed on global menu. void globalWrite(Globals *currentGlobals) { eeprom_write_byte(0,currentGlobals->midiChannel); //this may be wrong, but it does get rid of the warning. eeprom_write_block(currentGlobals->midiTrackNote,1,16); } //This happens at startup only, in function "initGlobals" void globalLoad(Globals *currentGlobals, uint8_t factoryReset) { //we need to load all of the global midi settings here. //we can also check the factory reset bit here. //if the program has not gone through the initial state, and had the internal eeprom formatted, then this will return garbage. if(factoryReset==0) { currentGlobals->midiChannel = eeprom_read_byte(0); eeprom_read_block(currentGlobals->midiTrackNote,1,16); } } <file_sep>/TsunamiCS1Master/Debug/makedep.mk ################################################################################ # Automatically-generated file. Do not edit or delete the file ################################################################################ ButtonLib.c DebounceLib.c EncoderLib.c globalVariables.c knobLib.c LEDLib.c main.c menu.c MidiLib.c OLEDLib.c sequencerLib.c serialLib.c tsunamiLib.c twiLib.c <file_sep>/TsunamiCS1Master/globalVariables.h /* * globalVariables.h * * Created: 8/13/2019 5:30:21 PM * Author: Hal */ #include <avr/io.h> #ifndef GLOBALVARIABLES_H_ #define GLOBALVARIABLES_H_ //defines for menu states. //this menu system lets us have 8 menu items per menu, and up to 8 menus. More than this, //and I think we have a feature creep problem. //Bits - 7 encoderA Flag, 6-4 EncoderAState, 3: EncoderBFlag, 2-0: encoderBState //Encoder B State: 0 = no arrow; //Encoder B State: 1 = arrow on screen, init state, very top //Encoder B State: 2 = arrow in middle of screen //Encoder B State: 3 = arrow at bottom of the page #define PreformanceModeInit 0 //case 0 000 0 000 #define SequencerMenuInit 16 //case 0 001 0 000 #define SequencerMenuArrow1 17 //case 0 001 0 001 #define SequencerMenuArrow2 18 //case 0 001 0 010 #define SequencerMenuArrow3 19//case 0 001 0 011 #define SequencerMenuArrow1Select 25 //case 0 001 1 001 #define SequencerMenuArrow2Select 26 //case 0 001 1 010 #define SequencerMenuArrow3Select 27 //case 0 001 1 011 #define TrackMenuInit 32 //case 0 010 0 000 #define TrackMenuArrow1 33 //case 0 010 0 001 #define TrackMenuArrow2 34 //case 0 010 0 010 #define TrackMenuArrow3 35 //case 0 010 0 011 #define TrackMenuArrow4 36 //case 0 010 0 100 #define TrackMenuArrow5 37 //case 0 010 0 101 #define TrackMenuArrow1Select 41 //case 0 010 1 001 #define TrackMenuArrow2Select 42 //case 0 010 1 010 #define TrackMenuArrow3Select 43 //case 0 010 1 011 #define TrackMenuArrow4Select 44 //case 0 010 1 100 #define TrackMenuArrow5Select 45 //case 0 010 1 101 #define GlobalMenuInit 48 //case 0 011 0 000 #define GlobalMenuArrow1 49 //case 0 011 0 001 #define GlobalMenuArrow2 50 //case 0 011 0 010 #define GlobalMenuArrow3 51//case 0 011 0 011 #define GlobalMenuArrow1Select 57 //case 0 011 1 001 #define GlobalMenuArrow2Select 58 //case 0 011 1 010 #define GlobalMenuArrow3Select 59 //case 0 011 1 011 #define encoderChange 0 #define triggerChange 1 #define knobChange 2 typedef struct Pattern { uint8_t outputLevelMSB[8]; //8 bytes uint8_t outputLevelLSB[8]; //8 bytes uint8_t outputPitch[8]; // 8 bytes uint8_t trackOutputRoute[16]; // 16 bytes uint8_t trackMainVolumeMSB[16]; //16 bytes uint8_t trackMainVolumeLSB[16]; //16 bytes uint8_t trackAttackTimeMSB[16]; //16 bytes uint8_t trackAttackTimeLSB[16]; //16 bytes uint8_t trackReleaseTimeMSB[16]; //16 bytes uint8_t trackReleaseTimeLSB[16]; //16 bytes uint8_t trackPlayMode[16]; //16 bytes //right now, only play solo (0)and Poly (1)are supported. loop mode (4) is in the works. uint8_t trackSampleMSB[16]; //16 bytes uint8_t trackSampleLSB[16]; //16 bytes uint8_t voiceLockFlag[16]; //16 bytes uint16_t patternBPM; //2 bytes uint8_t numSteps; //1 byte uint8_t trackSustainTimeMSB[16]; //16 bytes uint8_t trackSustainTimeLSB[16]; //16 bytes uint8_t envelopeType[16]; //16 bytes //currently we only have 4, but eventually I'd like to have release stages triggered by "off" messages, especially for looped samples. uint16_t trackSequence[64]; //128 bytes - this will be a separate page } Pattern; //total bytes - 128 for the sequence, 251 bytes for all other data. //so 3 pages in total, 1 for sequencer data, 2 for all other data (248 bytes, room for expansion) typedef struct Screen { unsigned char screen0[9][21]; //since each screen can hold 3 bit menu states, there are 9 values that each menu can have. unsigned char screen1[9][21]; //not every array needs to be initialized, but it is important for our initArray method that they be uniform. unsigned char screen2[9][21]; unsigned char screen3[9][21]; unsigned char knobScreen[9][21]; } Screen; typedef struct Globals { uint16_t currentTrigButtons; //current state of Trig buttons. uint8_t currentGPButtons; //current state of GP buttons uint16_t currentTrigSequencer; uint16_t currentTrigMidi; uint8_t currentPatternNumber; //current pattern, between 1 and 256 uint8_t currentStep; // current step in the sequencer uint8_t currentTrack; //current track being edited uint8_t menuState; //where the menu is currently uint8_t playState; //whether the sequencer is playing, stopped, or paused. uint8_t factoryReset; //we may not need this in this struct, but good to have for now. uint8_t buttonSwitchFlag; // could be rolled into value bits. uint8_t valueChangeFlag; //bit 0 -> changes in encoders, bit 1-> changes in buttons, bit2 -> changes in knobs uint8_t knobStatus; //top 4 bits: knob type, bottom 4 bits: knob location. //these are editable in global edit menu uint8_t midiChannel; uint8_t midiTrackNote[16]; //16 bytes uint8_t rawKnobBuffer[44]; //we write to this to collect raw knob reads uint8_t filteredKnobBuffer[44]; //we do math to the raw Knob buffer, and store it here, to check against current knobs with. uint8_t lastFilteredKnobBuffer[44]; //we use this to check if any knob positions have changed. //envelope variables uint32_t releaseCounter; uint16_t releaseTracker; //this is a bitwise tracker to keep track of which tracks still need to be releases. uint32_t sustainCounterArray[16]; //this will be where we store values for release times to check against the release counter. uint16_t clockCounter; uint32_t lastGlobalTimer; uint8_t timerFlag; //if 1, then timer has increased. if 0, timer has not increased. }Globals; void initArrays(unsigned char myArray[9][21], int stringNumber, char* myString); void initBank(Pattern *currentInitPattern); void initGlobals(Globals *currentGlobals, uint8_t factoryReset); void initTimer(); void updateTimers(); void factoryResetCheck(uint8_t *factoryReset, Pattern *currentPattern, Globals *currentGlobals); #endif /* GLOBALVARIABLES_H_ */ <file_sep>/TsunamiCS1Master/OLEDLib.c /* * OLEDLib.c * * Created: 6/26/2019 5:47:50 PM * Author: Hal */ #define F_CPU 16000000UL #include <util/delay.h> #include <avr/io.h> uint8_t new_line[4] = {0x80, 0xA0, 0xC0, 0xE0}; //enable cycle is functioning properly. void enableCycle() { //required for timing on LCD Screen //the only delay in this library. PORTH |= 0B00100000; _delay_us(1); PORTH &= 0B11011111; } void send8bit(uint8_t value) { //set all pins on port C to output pins. //using unsigned int 8 bit values should protect this //function from overflow. //also,this should just work. //since we want to send an 8 bit value over an entire port. PORTC = value; } void command(uint8_t c) { //digitalWrite(DC, 0); PORTH &= 0B10111111; //set our DC pin low, to get ready to write data. //we need to figure out where our DC pin is. send8bit(c); enableCycle(); } void data(uint8_t d) { //digitalWrite(DC, 1); PORTH |=0B01000000; //set out DC Pin high, so it's ready to write data. send8bit(d); enableCycle(); } void initScreen() { //this is where we will do all of the screen //initialization. DDRH = 0x60; //pins 14 and 15, 14 is Enable (PortJ1), 15 is data/command (PortJ0) DDRC =0xFF; //all pins on the LCD Data Bus. PORTH &= 0B10011111; //set both the DC line and E line of the display to 0. leave all other bits on the ports alone PORTC = 0x00; // Initializes all Arduino pins for the data bus _delay_us(200); // Waits 200 us for stabilization purpose uint8_t rows = 0x08; // Display mode: 2/4 lines command(0x22 | rows); // Function set: extended command set (RE=1), lines # command(0x71); // Function selection A: data(0x5C); // enable internal Vdd regulator at 5V I/O mode (def. value) (0x00 for disable, 2.8V I/O) command(0x20 | rows); // Function set: fundamental command set (RE=0) (exit from extended command set), lines # command(0x08); // Display ON/OFF control: display off, cursor off, blink off (default values) command(0x22 | rows); // Function set: extended command set (RE=1), lines # command(0x79); // OLED characterization: OLED command set enabled (SD=1) command(0xD5); // Set display clock divide ratio/oscillator frequency: command(0x70); // divide ratio=1, frequency=7 (default values) command(0x78); // OLED characterization: OLED command set disabled (SD=0) (exit from OLED command set) command(0x09); // Extended function set (RE=1): 5-dot font, B/W inverting disabled (def. val.), 3/4 lines command(0x06); // Entry Mode set - COM/SEG direction: COM0->COM31, SEG99->SEG0 (BDC=1, BDS=0) command(0x72); // Function selection B: data(0x0A); // ROM/CGRAM selection: ROM C, CGROM=250, CGRAM=6 (ROM=10, OPR=10) command(0x79); // OLED characterization: OLED command set enabled (SD=1) command(0xDA); // Set SEG pins hardware configuration: command(0x10); // alternative odd/even SEG pin, disable SEG left/right remap (default values) command(0xDC); // Function selection C: command(0x00); // internal VSL, GPIO input disable command(0x81); // Set contrast control: command(0x7F); // contrast=127 (default value) command(0xD9); // Set phase length: command(0xF1); // phase2=15, phase1=1 (default: 0x78) command(0xDB); // Set VCOMH deselect level: command(0x40); // VCOMH deselect level=1 x Vcc (default: 0x20=0,77 x Vcc) command(0x78); // OLED characterization: OLED command set disabled (SD=0) (exit from OLED command set) command(0x20 | rows); // Function set: fundamental command set (RE=0) (exit from extended command set), lines # command(0x01); // Clear display _delay_ms(2); // After a clear display, a minimum pause of 1-2 ms is required command(0x80); // Set DDRAM address 0x00 in address counter (cursor home) (default value) command(0x0C); // Display ON/OFF control: display ON, cursor off, blink off _delay_ms(250); // Waits 250 ms for stabilization purpose after display on } void outputS(char* lineIn, int row) { uint8_t r = row; uint8_t c = 0; command(new_line[r]); //20, because our display is 20x4. for(c=0; c<20; c++) { data(lineIn[c]); } } void numPrinter(char* charArray,uint8_t startingPos, uint8_t numCharacters, uint16_t inputNumber) { //this needs to go in the OLED Library. uint8_t onesPlace = 0; uint8_t tensPlace = 0; uint8_t hunderedsPlace = 0; uint8_t thousandsPlace = 0; uint8_t tenThousandsPlace = 0; switch(numCharacters) { case 0: break; case 1: onesPlace = (inputNumber%10)+48; //this should be a value between 1 and 10. charArray[startingPos] = onesPlace; break; case 2: onesPlace = (inputNumber%10)+48; //this should be a value between 1 and 10. tensPlace = (inputNumber/10)+48; charArray[(startingPos+1)] = onesPlace; charArray[startingPos] = tensPlace; break; case 3: onesPlace = (inputNumber%10)+48; //this should be a value between 1 and 10. tensPlace = ((inputNumber%100)/10)+48; hunderedsPlace = (inputNumber/100)+48; charArray[(startingPos+2)] = onesPlace; charArray[(startingPos+1)] = tensPlace; charArray[startingPos] = hunderedsPlace; break; case 4: onesPlace = (inputNumber%10)+48; //this should be a value between 1 and 10. tensPlace = ((inputNumber%100)/10)+48; hunderedsPlace = ((inputNumber%1000)/100)+48; thousandsPlace = (inputNumber/1000)+48; charArray[(startingPos+3)] = onesPlace; charArray[(startingPos+2)] = tensPlace; charArray[(startingPos+1)] = hunderedsPlace; charArray[startingPos] = thousandsPlace; break; case 5: onesPlace = (inputNumber%10)+48; //this should be a value between 1 and 10. tensPlace = ((inputNumber%100)/10)+48; hunderedsPlace = ((inputNumber%1000)/100)+48; thousandsPlace = ((inputNumber%10000)/1000)+48; tenThousandsPlace = (inputNumber/10000)+48; charArray[(startingPos+4)] = onesPlace; charArray[(startingPos+3)] = tensPlace; charArray[(startingPos+2)] = hunderedsPlace; charArray[(startingPos+1)] = thousandsPlace; charArray[startingPos] = tenThousandsPlace; break; //if your number is higher than 16 bit, sorry, no can do. default: break; } } void midiNotePrinter(char* charArray, uint8_t startingPosition, uint8_t noteNumber) { //will take up 3 character spaces. char printLetter = 0; char printNumber = 0; char printSharp = 0; uint8_t valueSwitch = 0; //numbers will always go from B to C, and have 12 distinct values. //we can get our number from this with division. //midi note C0 starts at 12. So, we'll need to do some math there. printNumber = (noteNumber/12)+47; //theres a weird wrap around with note numbers here. Since there isn't really an easy math patern we can take advantage of. valueSwitch = noteNumber%12; //this should give us a value between 0 and 11. switch(valueSwitch) { case 0: printLetter = 'C'; printSharp = ' '; break; case 1: printLetter = 'C'; printSharp = '#'; break; case 2: printLetter = 'D'; printSharp = ' '; break; case 3: printLetter = 'D'; printSharp = '#'; break; case 4: printLetter = 'E'; printSharp = ' '; break; case 5: printLetter = 'F'; printSharp = ' '; break; case 6: printLetter = 'F'; printSharp = '#'; break; case 7: printLetter = 'G'; printSharp = ' '; break; case 8: printLetter = 'G'; printSharp = '#'; break; case 9: printLetter = 'A'; printSharp = ' '; break; case 10: printLetter = 'A'; printSharp = '#'; break; case 11: printLetter = 'B'; printSharp = ' '; break; } charArray[startingPosition] = printLetter; charArray[startingPosition+1]= printSharp; charArray[startingPosition+2]= printNumber; }<file_sep>/TsunamiCS1Master/ButtonLib.h /* * ButtonLib.h * * Created: 7/31/2019 4:32:17 PM * Author: Hal */ #ifndef BUTTONLIB_H_ #define BUTTONLIB_H_ void listenTrigButtons(Pattern *buttonCurrentPattern, Globals *currentGlobals); void initButtons(); void listenGPButtons(Pattern currentPattern, Globals *currentGlobals); #endif /* BUTTONLIB_H_ */<file_sep>/TsunamiCS1Master/menu.c /* * menu.c * * Created: 8/13/2019 5:54:51 PM * Author: Hal */ #include <avr/io.h> #include "globalVariables.h" #include "OLEDLib.h" #define selectBit 0xF7 char midiNote[4] = "C-0"; uint8_t prevMenuState; //do we need this anymore? //I don't like using a global extern here, instead of a passed pointer, //but I can't seem to get the struct to stay in scope. void initMenu(Screen *initTheScreen, Pattern currentPattern, Globals currentGlobals) { //screen0 initArrays(initTheScreen->screen0,0,"Performance Mode"); initArrays(initTheScreen->screen0,1,"Pattern:"); initArrays(initTheScreen->screen0,2,"BPM:"); initArrays(initTheScreen->screen0,3,"Stop"); //screen1 initArrays(initTheScreen->screen1,0,"Sequence Edit"); initArrays(initTheScreen->screen1,1,"Pattern:"); initArrays(initTheScreen->screen1,2,"Steps:"); initArrays(initTheScreen->screen1,3,"Step number:"); //screen2 initArrays(initTheScreen->screen2,0,"Track Settings"); initArrays(initTheScreen->screen2,1,"Track:"); initArrays(initTheScreen->screen2,2,"PlayMode:"); initArrays(initTheScreen->screen2,3,"OutRoute:"); initArrays(initTheScreen->screen2,4,"EnvelopeMode:"); initArrays(initTheScreen->screen2,5,"SustainTime: S"); //screen3 initArrays(initTheScreen->screen3,1,"Midi Channel:"); initArrays(initTheScreen->screen3,2,"Midi trig :"); initArrays(initTheScreen->screen3,3," "); initArrays(initTheScreen->screen3,0,"Global Settings"); //init all of the knob arrays: initArrays(initTheScreen->knobScreen,0,"OutVolume x : xxxdb");//string 0 is outVolume initArrays(initTheScreen->knobScreen,1,"Pitch : xxx");//string 1 is pitch initArrays(initTheScreen->knobScreen,2,"AttackTime : S"); //string 2 is Envelope gain initArrays(initTheScreen->knobScreen,3,"ReleaseTimexx:xx xxx"); //string 3 is Envelop Time initArrays(initTheScreen->knobScreen,4,"TrackVolume xx:xxxdb"); //string 4 is track Level. //initArrays(initTheScreen->knobScreen,5,"BPM: "); //we might want to put in one of these for BPM, but I'm not sure. numPrinter(initTheScreen->screen0[2],5,3, currentPattern.patternBPM); numPrinter(initTheScreen->screen3[1],14,2, (currentGlobals.midiChannel)+1); numPrinter(initTheScreen->screen0[1], 9, 3, (currentGlobals.currentPatternNumber)+1); numPrinter(initTheScreen->screen1[1], 9, 3, (currentGlobals.currentPatternNumber)+1); numPrinter(initTheScreen->screen1[2], 7, 2, currentPattern.numSteps); numPrinter(initTheScreen->screen1[3], 13, 2, (currentGlobals.currentStep)+1); for(uint8_t i=0;i<4; i++ ) { outputS(initTheScreen->screen0[i],i); } } //this method fills all the relevant screens once we load a new pattern. void reInitMenuOnLoad(Screen *initTheScreen, Pattern *currentPattern, Globals *currentGlobals) { numPrinter(initTheScreen->screen0[2],5,3, currentPattern->patternBPM); numPrinter(initTheScreen->screen1[2], 7, 2, currentPattern->numSteps); numPrinter(initTheScreen->screen1[1],9,3,(currentGlobals->currentPatternNumber)+1); numPrinter(initTheScreen->screen0[1],9,3,(currentGlobals->currentPatternNumber)+1); } void updateScreen(Screen *menuScreen, Pattern *currentPattern, Globals *currentGlobals) { if((currentGlobals->valueChangeFlag)&(1<<encoderChange))//check if encoder bit is high { currentGlobals->valueChangeFlag = currentGlobals->valueChangeFlag&(0xFF&(0<<encoderChange));//set encoder bit low, and carry our whatever encoder change has occurred. //we need to debug this to make sure it's doing what we think it's doing. switch(currentGlobals->menuState) { case PreformanceModeInit: //initial state reInitMenuOnLoad(menuScreen, currentPattern, currentGlobals); outputS(menuScreen->screen0[0], 0); outputS(menuScreen->screen0[1], 1); outputS(menuScreen->screen0[2], 2); outputS(menuScreen->screen0[3], 3); break; case SequencerMenuInit: outputS(menuScreen->screen1[0], 0); outputS(menuScreen->screen1[1], 1); outputS(menuScreen->screen1[2], 2); outputS(menuScreen->screen1[3], 3); currentGlobals->menuState = SequencerMenuArrow1; case SequencerMenuArrow1: menuScreen->screen1[1][19]= 8; menuScreen->screen1[2][19] = ' '; menuScreen->screen1[3][19] = ' '; outputS(menuScreen->screen1[1], 1); outputS(menuScreen->screen1[2], 2); outputS(menuScreen->screen1[3], 3); break; case SequencerMenuArrow1Select: reInitMenuOnLoad(menuScreen, currentPattern, currentGlobals); outputS(menuScreen->screen1[1],1); break; case SequencerMenuArrow2: menuScreen->screen1[1][19]= ' '; menuScreen->screen1[2][19] = 8; menuScreen->screen1[3][19] = ' '; outputS(menuScreen->screen1[1], 1); outputS(menuScreen->screen1[2], 2); outputS(menuScreen->screen1[3], 3); break; case SequencerMenuArrow2Select: numPrinter(menuScreen->screen1[2],7,2,currentPattern->numSteps); outputS(menuScreen->screen1[2],2); break; case SequencerMenuArrow3: menuScreen->screen1[1][19]= ' '; menuScreen->screen1[2][19] = ' '; menuScreen->screen1[3][19] = 8; outputS(menuScreen->screen1[1], 1); outputS(menuScreen->screen1[2], 2); outputS(menuScreen->screen1[3], 3); break; case SequencerMenuArrow3Select: numPrinter(menuScreen->screen1[3],14,2,(currentGlobals->currentStep)+1); //these are 0 indexed, so we need to add 1 to the display. outputS(menuScreen->screen1[3],3); break; case TrackMenuInit: outputS(menuScreen->screen2[0], 0); outputS(menuScreen->screen2[1], 1); outputS(menuScreen->screen2[2], 2); outputS(menuScreen->screen2[3], 3); currentGlobals->menuState = TrackMenuArrow1; case TrackMenuArrow1: menuScreen->screen2[1][19]= 8; menuScreen->screen2[2][19] = ' '; menuScreen->screen2[3][19] = ' '; outputS(menuScreen->screen2[1], 1); outputS(menuScreen->screen2[2], 2); outputS(menuScreen->screen2[3], 3); break; case TrackMenuArrow1Select:; uint16_t trackSample = (currentPattern->trackSampleMSB[currentGlobals->currentTrack]<<8)|(currentPattern->trackSampleLSB[currentGlobals->currentTrack]); numPrinter(menuScreen->screen2[1],10,4,(trackSample)); outputS(menuScreen->screen2[1],1); break; case TrackMenuArrow2: menuScreen->screen2[1][19]= ' '; menuScreen->screen2[2][19] = 8; menuScreen->screen2[3][19] = ' '; outputS(menuScreen->screen2[1], 1); outputS(menuScreen->screen2[2], 2); outputS(menuScreen->screen2[3], 3); break; case TrackMenuArrow2Select: //we need some serious button code in these two cases. switch (currentPattern->trackPlayMode[currentGlobals->currentTrack]) { case 0: menuScreen->screen2[2][10] = 'S'; menuScreen->screen2[2][11] = 'o'; menuScreen->screen2[2][12] = 'l'; menuScreen->screen2[2][13] = 'o'; break; case 1: menuScreen->screen2[2][10] = 'P'; menuScreen->screen2[2][11] = 'o'; menuScreen->screen2[2][12] = 'l'; menuScreen->screen2[2][13] = 'y'; break; //these additional cases will be for loops and other stuff. have not decided on how to deal with them yet. case 2: break; case 3: break; } outputS(menuScreen->screen2[2], 2); break; case TrackMenuArrow3: menuScreen->screen2[1][19]= ' '; menuScreen->screen2[2][19] = ' '; menuScreen->screen2[3][19] = 8; outputS(menuScreen->screen2[1], 1); outputS(menuScreen->screen2[2], 2); outputS(menuScreen->screen2[3], 3); break; case TrackMenuArrow3Select: numPrinter(menuScreen->screen2[3],10,2,(currentPattern->trackOutputRoute[currentGlobals->currentTrack])+1); outputS(menuScreen->screen2[3],3); break; case TrackMenuArrow4: menuScreen->screen2[2][19]= ' '; menuScreen->screen2[3][19] = ' '; menuScreen->screen2[4][19] = 8; outputS(menuScreen->screen2[2], 1); outputS(menuScreen->screen2[3], 2); outputS(menuScreen->screen2[4], 3); break; case TrackMenuArrow4Select: switch(currentPattern->envelopeType[currentGlobals->currentTrack]) { case 0: //A/R menuScreen->screen2[4][14] = 'A'; menuScreen->screen2[4][15] = '-'; menuScreen->screen2[4][16] = 'R'; menuScreen->screen2[4][17] = ' '; break; case 1: //only release menuScreen->screen2[4][14] = 'R'; menuScreen->screen2[4][15] = ' '; menuScreen->screen2[4][16] = ' '; menuScreen->screen2[4][17] = ' '; break; case 2: //only attack menuScreen->screen2[4][14] = 'A'; menuScreen->screen2[4][15] = ' '; menuScreen->screen2[4][16] = ' '; menuScreen->screen2[4][17] = ' '; break; case 3: //No envelope menuScreen->screen2[4][14] = 'N'; menuScreen->screen2[4][15] = 'o'; menuScreen->screen2[4][16] = 'n'; menuScreen->screen2[4][17] = 'e'; break; } outputS(menuScreen->screen2[4],3); break; case TrackMenuArrow5: menuScreen->screen2[3][19]= ' '; menuScreen->screen2[4][19] = ' '; menuScreen->screen2[5][19] = 8; outputS(menuScreen->screen2[3], 1); outputS(menuScreen->screen2[4], 2); outputS(menuScreen->screen2[5], 3); break; case TrackMenuArrow5Select:; uint16_t totalSustainTime = currentPattern->trackSustainTimeLSB[currentGlobals->currentTrack]|((currentPattern->trackSustainTimeMSB[currentGlobals->currentTrack])<<8); numPrinter(menuScreen->screen2[5],13, 5, totalSustainTime); menuScreen->screen2[5][12] = menuScreen->screen2[5][13]; menuScreen->screen2[5][13] = menuScreen->screen2[5][14]; menuScreen->screen2[5][14] = '.'; outputS(menuScreen->screen2[5],3); break; case GlobalMenuInit: outputS(menuScreen->screen3[0], 0); outputS(menuScreen->screen3[1], 1); outputS(menuScreen->screen3[2], 2); outputS(menuScreen->screen3[3], 3); currentGlobals->menuState = GlobalMenuArrow1; case GlobalMenuArrow1: menuScreen->screen3[1][19]= 8; menuScreen->screen3[2][19] = ' '; menuScreen->screen3[3][19] = ' '; outputS(menuScreen->screen3[1], 1); outputS(menuScreen->screen3[2], 2); outputS(menuScreen->screen3[3], 3); break; case GlobalMenuArrow1Select: numPrinter(menuScreen->screen3[1],14,2,(currentGlobals->midiChannel)+1); outputS(menuScreen->screen3[1],1); break; case GlobalMenuArrow2: menuScreen->screen3[1][19]= ' '; menuScreen->screen3[2][19] = 8; menuScreen->screen3[3][19] = ' '; outputS(menuScreen->screen3[1], 1); outputS(menuScreen->screen3[2], 2); outputS(menuScreen->screen3[3], 3); break; case GlobalMenuArrow2Select: midiNotePrinter(menuScreen->screen3[2],14,currentGlobals->midiTrackNote[currentGlobals->currentTrack]); outputS(menuScreen->screen3[2],2); break; case GlobalMenuArrow3: menuScreen->screen3[1][19]= ' '; menuScreen->screen3[2][19] = ' '; menuScreen->screen3[3][19] = 8; outputS(menuScreen->screen3[1], 1); outputS(menuScreen->screen3[2], 2); outputS(menuScreen->screen3[3], 3); break; } prevMenuState = currentGlobals->menuState; } //We should only reach this in track selection and global settings for setting midi notes. if(currentGlobals->valueChangeFlag&(1<<triggerChange)) { currentGlobals->valueChangeFlag = currentGlobals->valueChangeFlag&(0<<triggerChange); //this is wrong. Will erase all of valueChange Flag. switch((currentGlobals->menuState)>>4) //we don't need to worry about what the bottom encoder is doing. { case 2:; uint16_t trackSample = (currentPattern->trackSampleMSB[currentGlobals->currentTrack]<<8)|(currentPattern->trackSampleLSB[currentGlobals->currentTrack]); numPrinter(menuScreen->screen2[1], 7, 2, (currentGlobals->currentTrack)+1); numPrinter(menuScreen->screen2[1], 10, 4, trackSample); //this feels dumb having it in two places, but It should take care of both cases. Maybe this should be a function? switch (currentPattern->trackPlayMode[currentGlobals->currentTrack]) { case 0: menuScreen->screen2[2][10] = 'S'; menuScreen->screen2[2][11] = 'o'; menuScreen->screen2[2][12] = 'l'; menuScreen->screen2[2][13] = 'o'; break; case 1: menuScreen->screen2[2][10] = 'P'; menuScreen->screen2[2][11] = 'o'; menuScreen->screen2[2][12] = 'l'; menuScreen->screen2[2][13] = 'y'; break; //these additional cases will be for loops and other stuff. have not decided on how to deal with them yet. case 2: break; case 3: break; } numPrinter(menuScreen->screen2[3], 10, 2, (currentPattern->trackOutputRoute[currentGlobals->currentTrack]+1)); switch(currentPattern->envelopeType[currentGlobals->currentTrack]) { case 0: //A/R menuScreen->screen2[4][14] = 'A'; menuScreen->screen2[4][15] = '-'; menuScreen->screen2[4][16] = 'R'; menuScreen->screen2[4][17] = ' '; break; case 1: //only release menuScreen->screen2[4][14] = 'R'; menuScreen->screen2[4][15] = ' '; menuScreen->screen2[4][16] = ' '; menuScreen->screen2[4][17] = ' '; break; case 2: //only attack menuScreen->screen2[4][14] = 'A'; menuScreen->screen2[4][15] = ' '; menuScreen->screen2[4][16] = ' '; menuScreen->screen2[4][17] = ' '; break; case 3: //No envelope menuScreen->screen2[4][14] = 'N'; menuScreen->screen2[4][15] = 'o'; menuScreen->screen2[4][16] = 'n'; menuScreen->screen2[4][17] = 'e'; break; } uint16_t totalSustainTime = currentPattern->trackSustainTimeLSB[currentGlobals->currentTrack]|((currentPattern->trackSustainTimeMSB[currentGlobals->currentTrack])<<8); numPrinter(menuScreen->screen2[5],13, 5, totalSustainTime); menuScreen->screen2[5][12] = menuScreen->screen2[5][13]; menuScreen->screen2[5][13] = menuScreen->screen2[5][14]; menuScreen->screen2[5][14] = '.'; //the track settings screens should now be populated //this is a bit messy, but seems to fix bugs on this portion of the menu for now. uint8_t triggerChangeScreen = 1; if(((currentGlobals->menuState)&selectBit)>35) //this accounts for menu stats 36,37,44, and 45 { triggerChangeScreen = ((currentGlobals->menuState)&selectBit) - 34; //mask to get rid of encoder B pushed state. } outputS(menuScreen->screen2[triggerChangeScreen], 1); outputS(menuScreen->screen2[triggerChangeScreen+1], 2); outputS(menuScreen->screen2[triggerChangeScreen+2], 3); break; case 3:; //do we need this variable? numPrinter(menuScreen->screen3[2],10,2,(currentGlobals->currentTrack)+1); midiNotePrinter(menuScreen->screen3[2],14,currentGlobals->midiTrackNote[currentGlobals->currentTrack]); outputS(menuScreen->screen3[2],2); break; } } if(currentGlobals->valueChangeFlag&(1<<knobChange)) { uint8_t positionSelect = currentGlobals->knobStatus&0x0F; //this is the bottom 4 bits, for the track location uint8_t positionSelectUpper = 0; if((currentGlobals->buttonSwitchFlag)&0x01) { positionSelectUpper = 8; } switch((currentGlobals->knobStatus)>>4) { case 0: //output volume if((currentPattern->outputLevelMSB[positionSelect])==0) { //value is positive menuScreen->knobScreen[0][14] = ' '; numPrinter(menuScreen->knobScreen[0],15,2,currentPattern->outputLevelLSB[positionSelect]); //should be a value between 0 and 8 }else { menuScreen->knobScreen[0][14] = '-'; menuScreen->knobScreen[0][15] = ((((currentPattern->outputLevelLSB[positionSelect]^255)+1)%100)/10)+48; //negative 8 bit numbers: flip every bit and add 1. menuScreen->knobScreen[0][16] = (((currentPattern->outputLevelLSB[positionSelect]^255)+1)%10)+48; } menuScreen->knobScreen[0][10] = positionSelect + 49; outputS(menuScreen->knobScreen[0], 3); break; case 1: //pitch menuScreen->knobScreen[1][5] = positionSelect+49; if(currentPattern->outputPitch[positionSelect]>>7) { menuScreen->knobScreen[1][7] = '-'; numPrinter(menuScreen->knobScreen[1], 8, 3, (currentPattern->outputPitch[positionSelect])^255); }else { menuScreen->knobScreen[1][7] = '+'; numPrinter(menuScreen->knobScreen[1],8,3,currentPattern->outputPitch[positionSelect]); } outputS(menuScreen->knobScreen[1],3); break; case 2:; //attack envelope uint16_t totalAttackTime = currentPattern->trackAttackTimeLSB[positionSelect+positionSelectUpper]|((currentPattern->trackAttackTimeMSB[positionSelect+positionSelectUpper])<<8); numPrinter(menuScreen->knobScreen[2],14, 5, totalAttackTime); menuScreen->knobScreen[2][13] = menuScreen->knobScreen[2][14]; menuScreen->knobScreen[2][14] = menuScreen->knobScreen[2][15]; menuScreen->knobScreen[2][15] = '.'; numPrinter(menuScreen->knobScreen[2],10,2,(positionSelect+1+positionSelectUpper)); outputS(menuScreen->knobScreen[2], 3); //This is not MS, but ideal for testing it Attack really works. break; case 3:; //release envelope uint16_t totalReleaseTime = currentPattern->trackReleaseTimeLSB[positionSelect+positionSelectUpper]|((currentPattern->trackReleaseTimeMSB[positionSelect+positionSelectUpper])<<8); numPrinter(menuScreen->knobScreen[3],15, 5, totalReleaseTime); menuScreen->knobScreen[3][14] = menuScreen->knobScreen[3][15]; menuScreen->knobScreen[3][15] = menuScreen->knobScreen[3][16]; menuScreen->knobScreen[3][16] = '.'; numPrinter(menuScreen->knobScreen[3],11,2,(positionSelect+1+positionSelectUpper)); outputS(menuScreen->knobScreen[3], 3); break; case 4: //track volume if(currentPattern->trackMainVolumeMSB[(positionSelect+positionSelectUpper)]==0) { menuScreen->knobScreen[4][15] = ' '; numPrinter(menuScreen->knobScreen[4],16, 2, currentPattern->trackMainVolumeLSB[(positionSelect+positionSelectUpper)]); }else { menuScreen->knobScreen[4][15] = '-'; menuScreen->knobScreen[4][16] = ((((currentPattern->trackMainVolumeLSB[(positionSelect+positionSelectUpper)]^255)+1)%100)/10)+48; //negative 8 bit numbers: flip every bit and add 1. menuScreen->knobScreen[4][17] = (((currentPattern->trackMainVolumeLSB[(positionSelect+positionSelectUpper)]^255)+1)%10)+48; } numPrinter(menuScreen->knobScreen[4],12,2,(positionSelect+positionSelectUpper+1)); outputS(menuScreen->knobScreen[4], 3); break; case 5: numPrinter(menuScreen->screen0[2],5,3,currentPattern->patternBPM); if(currentGlobals->menuState==PreformanceModeInit) { outputS(menuScreen->screen0[2],2); } break; } currentGlobals->valueChangeFlag = currentGlobals->valueChangeFlag&(0xFF&(0<<knobChange)); } }<file_sep>/TsunamiCS1Master/menu.h /* * menu.h * * Created: 8/13/2019 5:54:40 PM * Author: Hal */ #ifndef MENU_H_ #define MENU_H_ void initMenu(Screen *initTheScreen, Pattern currentPattern, Globals currentGlobals); void updateScreen(Screen *menuScreen, Pattern *currentPattern, Globals *currentGlobals); //void numToMidiNote(uint8_t inputNum, char midiNote[3]); #endif /* MENU_H_ */ <file_sep>/TsunamiCS1Master/twiLib.h /* * twiLib.h * * Created: 12/23/2019 1:01:17 PM * Author: Hal * this library servers mainly to interact with with eeprom. */ #include <avr/io.h> #include "globalVariables.h" #define SCL_CLOCK 100000 // I2C clock in Hz - 100KHz #define TW_STATUS TWSR //define for Two wire status Register #define TW_START 0x08 #define TW_REP_START 0x10 #define TW_MT_SLA_ACK 0x18 //master transmit SLaddress Acknowledge #define TW_MT_SLA_NACK 0x20 //master transmit SLAdress Not Acknowledge #define TW_MR_SLA_ACK 0x40//master receive SLAddress Acknowledge #define TW_MR_DATA_NACK 0x58//master receive Data Not Acknowledge #define TW_MT_DATA_ACK 0x28 #define EEPROMADDRESSWRITEA 0b10100000 //512K bit block A #define EEPROMADDRESSWRITEB 0b10101000 //512K bit block B #define EEPROMADDRESSREADA 0b10100001 #define EEPROMADDRESSREADB 0b10101001 #define F_CPU 16000000UL #ifndef TWILIB_H_ #define TWILIB_H_ void twi_init(); uint8_t twi_start(uint8_t address); void twi_start_wait(uint8_t address); uint8_t twi_rep_start(uint8_t address); void twi_stop(); uint8_t twi_write(uint8_t data ); uint8_t twi_readAck(); uint8_t twi_readNak(); void eepromSavePattern(Pattern inPattern, uint8_t patternNumber); void eepromLoadPattern(Pattern *currentPattern, uint8_t patternNumber); void factoryResetEeprom(Pattern inPattern); uint8_t readEEpromChar(uint16_t readAddress); void globalWrite(Globals *currentGlobals); void globalLoad(Globals *currentGlobals, uint8_t factoryReset); #endif /* TWILIB_H_ */<file_sep>/TsunamiCS1Master/LEDLib.c /* LED Info: ShiftRegisterPins: Data: PG5 Clock: PG0 Latch: PG2 bits to write: 21 1 8bit and 2 16 bits shifted in should work alright. */ #include <avr/io.h> #include "globalVariables.h" #include "OLEDLib.h" //for debugging purposes only uint16_t holdTrig = 0; extern uint8_t encoderAValue; extern uint16_t currentTrigButtons; extern Pattern currentPattern; extern uint8_t currentStep; void initLEDs() { DDRG = 0B00000111; //outputs on G5,2, and 0. } void parseLEDs(uint16_t LEDInput, uint8_t gpButtonInput) //this should not be a 16 bit int, or we need an additional 8 bits { uint16_t trigLEDParse = LEDInput; uint8_t gpParse = gpButtonInput; //we might not need these variables if they revert after they fall out of scope. These might be 2 whole wasted clock cycles. PORTG &= (~(1 << PG2)); //set latch low for data input for(uint8_t j=0; j<7; j++) { PORTG |= (1 << PG0); //turn clock pin high if(gpParse&0x80) { PORTG |= (1 << PG1); //send current 1's place bit to the data pin } else { PORTG &= (~(1 << PG1)); } PORTG &= (~(1 << PG0)); //turn clock pin low. gpParse = gpParse << 1; } for(uint8_t i = 0; i<17; i++) { PORTG |= (1 << PG0); //turn clock pin high if(trigLEDParse&32768) { PORTG |= (1 << PG1); //send current 1's place bit to the data pin } else { PORTG &= (~(1 << PG1)); } PORTG &= (~(1 << PG0)); //turn clock pin low. trigLEDParse = trigLEDParse << 1; } PORTG |= (1 << PG2); //latch pin high } void updateLEDs(Pattern ledCurrentPattern, Globals currentGlobals) { uint8_t shiftedState = currentGlobals.menuState >> 4; //this will get rid of EncoderB uint16_t totalLights = currentGlobals.currentTrigButtons|currentGlobals.currentTrigMidi|currentGlobals.currentTrigSequencer; //we want lights from all sources. //no input from midi yet, but we will have that eventually. switch(shiftedState) { case 0: parseLEDs(totalLights, currentGlobals.currentGPButtons); break; case 1: parseLEDs(ledCurrentPattern.trackSequence[currentGlobals.currentStep], currentGlobals.currentGPButtons); break; case 2: parseLEDs(totalLights, currentGlobals.currentGPButtons); break; case 3: parseLEDs(totalLights, currentGlobals.currentGPButtons); break; } } <file_sep>/TsunamiCS1Master/ButtonLib.c /* * ButtonLib.c * * Created: 7/31/2019 4:31:55 PM * Author: Hal */ #include "globalVariables.h" #include "tsunamiLib.h" #include "OLEDLib.h" #include <avr/io.h> #include "DebounceLib.h" #include "twiLib.h" //These are declared here instead of in the functions they are used to save clock cycles. //we only initialized them once, and hold in memory, instead of allocating every time one of these functions are called. //(at least I think that's how C works) uint8_t buttonsCurrentCycle; uint16_t lastFullBits = 0; uint8_t currentTrig; //ISR(TIMER2_OVF_vect) //{ // debounce(); //} void initButtons() { //this will initialize all of the buttons on the front panel //main trigger buttons PORTA = 0xFF; PORTL = 0xFF; //GPButtons and Encoder buttons PORTB = 0b01111111; } void listenTrigButtons(Pattern *buttonCurrentPattern, Globals *currentGlobals) { buttonsCurrentCycle = (PINL^255); //^ = bitwise XOR operation. (currentGlobals->currentTrigButtons) = (buttonsCurrentCycle << 8) | (PINA^255); if(currentGlobals->currentTrigButtons!=lastFullBits) //we do read the buttons every cycle, but we don't need to update everything base on the buttons if they haven't changed. { lastFullBits = currentGlobals->currentTrigButtons; uint16_t fullBitsParse = currentGlobals->currentTrigButtons; //play sounds, if that is the switch case on the encoder //updateLEDs for(uint8_t bc = 0; bc<16; bc++)//bc for buttonCounter { currentTrig = (fullBitsParse&1); if(currentTrig) { uint8_t encoderAstate = currentGlobals->menuState >> 4; switch (encoderAstate) { //for "performance mode", we should just use the default case, and only have code for the cases where things are outside of that use case. case 0: //performance mode //we trigger a sound here based on the location of bc playTrack(buttonCurrentPattern, currentGlobals,bc); break; case 1: buttonCurrentPattern->trackSequence[currentGlobals->currentStep] ^= currentGlobals->currentTrigButtons; //turn on step number, or turn off step number. //step sequencer mode. break; //we want this functionality for both case 2 and case 3 case 2: case 3:; //select track for sample assignment //uint16_t currentSample = (buttonCurrentPattern->trackSampleMSB[bc]<<8)|(buttonCurrentPattern->trackSampleLSB[bc]); currentGlobals->currentTrack = bc; currentGlobals->valueChangeFlag |=(1<<triggerChange); playTrack(buttonCurrentPattern, currentGlobals,bc); break; default: //this should be the same as case 0; break; } } fullBitsParse = fullBitsParse>>1; } } } void listenGPButtons(Pattern currentPattern, Globals *currentGlobals) //may need to be a pointer { if(button_down(1 << PB5)) { //top encoder button if(currentGlobals->menuState>>4==3) { globalWrite(currentGlobals); }else { eepromSavePattern(currentPattern, currentGlobals->currentPatternNumber); } } uint8_t encoderSwitchMask = 0b00001000; if(button_down(1<<PB6)) {//bottom encoder button uint8_t encoderBCheck = currentGlobals->menuState&encoderSwitchMask; if(encoderBCheck) { currentGlobals->menuState &=0b11110111;//turn off the encoderBFlag }else { currentGlobals->menuState |=0b00001000; //turn on the encoderBFlag bit } } uint8_t playButtonMask = 0b0000001; //we could probably make a define for both of these masks. uint8_t playStateCheck = currentGlobals->playState & playButtonMask; if(button_down(1<<PB4)) { if(playStateCheck) { currentGlobals->playState=0; //playstate is on, turn it off currentGlobals->currentGPButtons &=(~0x20); //turn the first bit }else { currentGlobals->playState=1; currentGlobals->currentGPButtons |= 0x20; //turn on the first bit } } //not sure which button this is uint8_t trackButtonMask = 0b00000001; uint8_t trackStateCheck = (currentGlobals->buttonSwitchFlag) & trackButtonMask; if(button_down(1<<PB0)) { if(trackStateCheck) { currentGlobals->buttonSwitchFlag = 0; currentGlobals->currentGPButtons &=(~0x02); }else { currentGlobals->buttonSwitchFlag = 1; currentGlobals->currentGPButtons |=0x02; } } uint8_t fineButtonMask = 4; uint8_t fineStateCheck = (currentGlobals->currentGPButtons) & fineButtonMask; if(button_down(1<<PB1)) { if(fineStateCheck) { currentGlobals->currentGPButtons &=(~0x04); }else { currentGlobals->currentGPButtons |=0x04; } } } <file_sep>/TsunamiCS1Master/globalVariables.c /* * globalVariables.c * * Created: 8/16/2019 7:26:29 AM * Author: Hal */ #include <avr/io.h> #include "globalVariables.h" #include <string.h> #include <avr/delay.h> #include "OLEDLib.h" #include "EncoderLib.h" #include "twiLib.h" #define F_CPU 16000000UL //takes an array less than 20 and fills it with blank characters void initArrays(unsigned char myArray[9][21], int stringNumber, char* myString) { uint8_t lengthOfString = strlen(myString); uint8_t charLeft = 20 - lengthOfString; uint8_t currentIndex = 0; for(currentIndex; currentIndex<lengthOfString; currentIndex++) { myArray[stringNumber][currentIndex] = myString[currentIndex]; } for(charLeft; charLeft>0; charLeft--) { myArray[stringNumber][currentIndex] = ' '; currentIndex++; } } void initBank(Pattern *currentInitPattern) { for(uint8_t i = 0; i<16; i++) { currentInitPattern->trackSampleLSB[i] = i+1; currentInitPattern->trackPlayMode[i] = 0x01; currentInitPattern->envelopeType[i] = 3; currentInitPattern->trackSustainTimeLSB[i] = 0; currentInitPattern->trackSustainTimeMSB[i] = 0; } for(uint8_t j = 0; j<64; j++) { currentInitPattern->trackSequence[j] = 0; //start with an empty sequence. } //We need to take these and put them in global. currentInitPattern->patternBPM = 120; currentInitPattern->numSteps = 16; } void initGlobals(Globals *currentGlobals, uint8_t factoryReset) { currentGlobals->currentTrigButtons=0; //current state of Trig buttons. currentGlobals->currentGPButtons=0; //current state of GP buttons currentGlobals->currentPatternNumber=0; //current pattern, between 1 and 256 currentGlobals->currentStep=0; // current step in the sequencer currentGlobals->currentTrack=0; //current track being edited currentGlobals->menuState=0; //where the menu is currently currentGlobals->playState=0; //whether the sequencer is playing, stopped, or paused. currentGlobals->factoryReset=0; //we may not need this in this struct, but good to have for now. currentGlobals->buttonSwitchFlag=0; // could be rolled into value bits. currentGlobals->valueChangeFlag=0; //bit 0 -> changes in encoders, bit 1-> changes in buttons, bit2 -> changes in knobs currentGlobals->knobStatus=0; //top 4 bits: knob type, bottom 4 bits: knob location. currentGlobals->releaseCounter = 0; currentGlobals->lastGlobalTimer = 0; currentGlobals->clockCounter = 0; currentGlobals->currentTrigSequencer = 0; currentGlobals->currentTrigMidi = 0; if(factoryReset==1) { currentGlobals->midiChannel=0; currentGlobals->midiTrackNote[0] = 0x24; currentGlobals->midiTrackNote[1] = 0x25; currentGlobals->midiTrackNote[2] = 0x26; currentGlobals->midiTrackNote[3] = 0x27; currentGlobals->midiTrackNote[4] = 0x28; currentGlobals->midiTrackNote[5] = 0x29; currentGlobals->midiTrackNote[6] = 0x2a; currentGlobals->midiTrackNote[7] = 0x2b; currentGlobals->midiTrackNote[8] = 0x2c; currentGlobals->midiTrackNote[9] = 0x2d; currentGlobals->midiTrackNote[10] = 0x2e; currentGlobals->midiTrackNote[11] = 0x2f; currentGlobals->midiTrackNote[12] = 0x30; currentGlobals->midiTrackNote[13] = 0x31; currentGlobals->midiTrackNote[14] = 0x32; currentGlobals->midiTrackNote[15] = 0x33; } } void initTimer() //we only need to use 1 timer, and Use ISRs for that. { //we're using timer 2, because it's the highest priority 8 bit timer interupt. //here we need to setup our timer interrupt TCCR2A = (1 << WGM21); //set to clear on correct compare TCCR2B = (1 << CS21) | (1 << CS20); // set pre-scaler to 64 OCR2A = 50; // every 25 ticks will be 0.0001 seconds at this pre scale. TIMSK2 = (1 << OCIE2A); // Enable OCR0A compare interrupt //interrupts should now be good to go. } void updateTimers(Globals *currentGlobals, uint32_t currentTime) { uint8_t change = 0; if(change=currentTime-(currentGlobals->lastGlobalTimer)) //check if there has been a change. { currentGlobals->clockCounter = (currentGlobals->clockCounter)+change; currentGlobals->releaseCounter = (currentGlobals->releaseCounter)+change; currentGlobals->lastGlobalTimer = currentTime; //currentGlobals->timerFlag = 1; } //else //{ // currentGlobals->timerFlag = 0; //we may want to change this some other point in the code, like when everything reliant on this flag is complete. //just so we're not wasting a conditional every time. //} } void factoryResetCheck(uint8_t *factoryReset, Pattern *currentPattern, Globals *currentGlobals) { if(((~PINA)&0x01)&&((~PINL)&0x01)) {//if both buttons are pressed on startup, wait 4 seconds outputS("FactoryReset? ",0); _delay_ms(4000); if(((~PINA)&0x01)&&((~PINL)&0x01)) { uint8_t choice = 2; uint8_t select = 0; char resetArray[21] = "yes? no? "; while(choice==2){ outputS(resetArray,1); select = listenEnoderReset(); if(select==0) { resetArray[4] = 8; resetArray[15] = ' '; } if(select==1) { resetArray[4] = ' '; resetArray[15] = 8; } if((~PINB)&(1<<5)) { choice = select; //break out of while loop, and reset, or not. } } if(select==0) //yes was selected. { outputS("Progress: ",2); (*factoryReset)=1; initGlobals(currentGlobals, *factoryReset); factoryResetEeprom(*currentPattern); globalWrite(currentGlobals); } } } }<file_sep>/BOM.md ## Electronics Components: The current BOM is held at this mangaged DigiKey shopping cart. If a part becomes obselete, we'll be updating it here. https://www.digikey.com/short/zrz401 In addition to the Digikey cart, You'll also need to source your own Tsunami Wav Trigger, and Arduio mega boards. The wav trigger can be had from here, or any sparkfun distributer: https://www.sparkfun.com/products/13810 Arduino Mega development boards can be had from a number of sources at a few different price points. (ebay, amazon, official sources, robotics webstores, ect) This project was developed on Elagoo clones. Any clone should get the job done, as long as it has a 16Mhz Crystal Oscillator. I have seen a few mega clones that have 12Mhz Oscillators, and some with ceramic Oscillators. Since timing is extremely important to this code, having the correct clock source is vital. ## Mounting Hardware: We're currently sourcing all of our mounting hardware from McMaster Carr. https://www.mcmaster.com/ Parts numbers are as follows: Screws (short, for frontpannel mounting): 92125A128 Screws (longer, for sidepannels): 92125A132 Bolts: 90592A085 Standoffsx18: 98952A106 Standoffs for OLED Screenx4: 98952A103 Screws are hex driven, so any standard allen wrench set should suit you well. This project requires 18 standoffs. The other packages of 100 screws and nuts should get you though the rest of enclosure, and only run around $4. # Notes -Currently, it looks like digikey and mouser are both out of the required audio jacks. It looks like this is a suitable drop in replacement:https://www.mouser.com/ProductDetail/Amphenol-Audio/ACJM-HHDR?qs=t8%2F5FiDdxGZR4gBVKrXjqA%3D%3D ## Practical BOM For buidling purposes, here are the part names and values for this project: ## Tsunami-CS1 Board: |Qty|Value|Part Number|Name|Description| | ------- |-------| ------- |-------| ------- | |1|CONN_02|0705530036‎|TSUNAMIPOWER|Power Connector for Tsunami Board| |1|CONN_03|N/C|EXTERNALSERIALHEADER|Header is not included, availible for possible expansion| |1|CONN_06|0705530040‎|MIDIHEADER|Molex connector for midi portion of IO Board| |1|CONN_07|‎2190‎|BUCKCONVERTER|Adafruit Buck Converter| |2|FE05-1|FE05-1|JTAGLEFT, JTAGRIGHT|Unnecessary for non-debug / development builds| |26|LED3MM|WP710A10SRD/J4‎|LED1, LED2, LED3, LED4, LED5, LED6, LED7, LED8, LED9, LED10, LED11, LED12, LED13, LED14, LED15, LED16, LED17, LED18, LED19, LED20, LED21, LED22, LED23, LED24, LED25, LED26|LEDs| |1|PINHD-1X20-BIG|‎NHD-0420CW-AY3‎|OLED|OLED display and 1x20 pinheader | |5|0.1uF|AR205F104K4R‎|C1, C2, C3, C4, C5|ceramic capacitor| |26|1.5K|‎LR1F1K5|R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, R12, R13, R14, R15, R16, R17, R18, R19, R20, R21, R36, R38, R39, R40, R41|Axial Resistor| |8|10K| ‎LR1F10K‎ |R22, R23, R24, R25, R26, R27, R28, R29|Axial Resistor| |4|10nF|FA18C0G2A103JRU06‎|C6, C7, C8, C9|ceramic capacitor| |3|1K|LR1F1K0‎ |R30, R31, R43|Generic Resistor Package| |1|1N4448|‎1N4448TR‎|D1|Diode| |1|2.2K|‎CF18JT2K20‎|R44|Axial Resistor| |1|240|‎LR1F240R‎|R32|Axial Resistor| |2|24LC1025-I/P|24LC1025-I/P|U9, U10|Eeprom chips, storage| |2|4.02K|‎MFR-25FBF52-4K02‎|R37, R42|Axial Reistor| |1|6N138|‎6N138-000E‎|U11|Optocoupler/Optoisolator| |1|6_PIN_SERIAL_CABLEPTH|0705530040|J1|Serial Connection to Tsunami Board| |1|7414N|‎SN74HC14N‎|IC1|Hex schmitt trigger INVERTER| |1|ARDUINO_MEGA_R3FULL|ARDUINO_MEGA_R3FULL|B2|Arduino Mega R3| |5|CD74HC4051E|CD74HC4051E|U1, U2, U3, U4, U5|analog Multiplexer| |2|ENCODER| ‎EN11-HSM1BF20|ENCODERBOTTOM, TOPENCODER|Rotary Encoders| |8|10K|PTA4543-2015DPB103‎ |TRACKVOLUME0, TRACKVOLUME1, TRACKVOLUME2, TRACKVOLUME3, TRACKVOLUME4, TRACKVOLUME5, TRACKVOLUME6, TRACKVOLUME7|Slide Potentiometers| |22|MOMENTARY-SWITCH-SPST-PTH-12MM|‎TL1100F160Q‎|GPBUTTON0, GPBUTTON1, GPBUTTON2, GPBUTTON3, GPBUTTON4, GPBUTTON5, TRIG1, TRIG2, TRIG3, TRIG4, TRIG5, TRIG6, TRIG7, TRIG8, TRIG9, TRIG10, TRIG11, TRIG12, TRIG13, TRIG14, TRIG15, TRIG16|Momentary Switch (Pushbutton) - SPST| |26|10K|‎PTV09A-4025F-B103‎|ATTACK0, ATTACK1, ATTACK2, ATTACK3, ATTACK4, ATTACK5, ATTACK6, ATTACK7, KNOB0, KNOB1, OUTVOL0, OUTVOL1, OUTVOL2, OUTVOL3, OUTVOL4, OUTVOL5, OUTVOL6, OUTVOL7, RELEASE0, RELEASE1, RELEASE2, RELEASE3, RELEASE4, RELEASE5, RELEASE6, RELEASE7|Pannel Mount Potentiometers| |10|10K|‎PTV09A-4225F-B103|KNOB2, KNOB3,PITCH0, PITCH1, PITCH2, PITCH3, PITCH4, PITCH5, PITCH6, PITCH7|Pannel mount Potentiometers, Center Dentent| |3|SN74HC595N|‎SN74HC595N‎|U6, U7, U8|8 bit shift registers| ## Tsunami IO Board |Qty|Value|Part Number|Name|Description| | ------- |-------| ------- |-------| ------- | |2|CONN_10X2|3020-20-0200-00|J14|IDC Connector to Tsunami Audio headers| |1|PINHD-1X6|0705530040|JP1|Molex connector for Midi to CS Board| |4|240|‎LR1F240R‎|R1, R2, R3, R4|Axial Resistor| |10|ACJS-MHDR|ACJS-MHDR‎| J4, J5, J6, J7, J8, J9, J10, J11, J12, J13|1/4" audio connection jacks| |1|MIDI-IN|SDS-50J|J1|Midi Din socket| |1|MIDI-OUT|SDS-50J|J2|Midi Din socket| |1|MIDI-THRU|SDS-50J|J3|Midi Din socket|<file_sep>/TsunamiCS1Master/knobLib.c /* * knobLib.c * //inspiration taken from bastl instruments 60 knobs * Created: 8/11/2019 8:00:19 AM * Author: Hal */ //and another comment for git testing //knob index: //output 1-8: 0-7 //pitch 1-8:8-15 //envelope level 1-8:16-23 //envelope time 1-8:24-31 //track volume 1-8: 32-39 //gpKnob uL: 40 (up left) //gpKnob uR: 41 (up right) //gpKnob dR: 42 //gpKnob dL: 43 #include <avr/io.h> #include "OLEDLib.h" #include "tsunamiLib.h" #include "MidiLib.h" #include "globalVariables.h" #include "knobLib.h" uint8_t NegativeOffset = 71; float volumeDivisor = 3.135; //uint8_t checkValue = 0; //uint8_t knobBuffer[44]; //uint8_t checkBuffer[44]; uint8_t knobBufferCounter; uint8_t startADCConversion() { ADCSRA |= (1 << ADSC); //this moves the read instruction bit to the ADC Register. while (ADCSRA & (1 << ADSC)); return ADCH; //this is the top 8 bits of the 10 bit ADC Read. } void initADC() { DDRF |= 0B00000111; //init pins F2, 1, and 0 as select pins on the external mux. ADMUX = (1 << ADLAR);//we're using the AREF pin to reduce analog noise, and only grabbing 8 bits from the ADC ADCSRA = (1 << ADEN) | (1 <<ADPS2) | (0 << ADPS1) | (0 << ADPS0); //prescaler of 8 CPU cycles. ADCSRB = (1 << MUX5); DIDR0 = 0xff; // we should set this register to all 1s, so there is no digital input triggering. DIDR2 = 0xff; knobBufferCounter = 0; startADCConversion(); } void selectKnob(uint8_t select) { select = select%44; //accounts for overflows, may be unnecessary if(select<40) { ADCSRB = (1 << MUX5); uint8_t muxSelect = select%8; //this should produce a number between 1 and 7. //uint8_t tempMuxSelect = muxSelect; //we need to set the internal multiplexer uint8_t internalMuxSelect = select/8; ADMUX = internalMuxSelect|(1 << ADLAR); startADCConversion();//this should throw away our first read after the mux changeover. //then the external multiplexer PORTF = muxSelect; }else { //we only have to change the ADC Register, since these knobs are wired directly into our microcontroller. switch (select){ case 40: ADMUX = 5|(1 << ADLAR); startADCConversion(); break; case 41: ADMUX = 6|(1 << ADLAR); startADCConversion(); break; case 42: ADMUX = 7|(1 << ADLAR); startADCConversion(); break; case 43: //remember, this knob is in port A0. ADMUX = 0|(1 << ADLAR); ADCSRB = (0 << MUX5); startADCConversion(); break; } } } void updateKnob(uint8_t select, Globals *currentGlobals) { //IIR filter. currentGlobals->rawKnobBuffer[select] = startADCConversion(); //raw reads currentGlobals->filteredKnobBuffer[select] = currentGlobals->filteredKnobBuffer[select] + ((currentGlobals->rawKnobBuffer[select]-currentGlobals->filteredKnobBuffer[select])/2); //reads with math done to them } void initializeKnob(Globals *currentGlobals) { //we do this after we fill the knob buffer at startup. for(int i = 0; i<44; i++){ currentGlobals->lastFilteredKnobBuffer[i] = currentGlobals->filteredKnobBuffer[i]; } } void interperetKnob(uint8_t select, Pattern *currentKnobPattern, Globals *currentGlobals) {//this function will compare outputs, and write to our struct. select = select%44; if (select<40) { uint8_t positionSelect = select%8; uint8_t positionSelectTracks = select%8; //this seems redundant looking at it. Maybe there is a clever way we can avoid this? uint8_t bankSwitch = select/8; if(((currentGlobals->buttonSwitchFlag)&0x01)==1) //we only want to check bit 1 of the GP buttons. We might want to check other values later. { positionSelectTracks=positionSelectTracks+8; } switch (bankSwitch){ uint8_t prevRead = 0; uint8_t newRead = 0; case 0:; //outputVolume //int16_t currentOutVoulume = ((currentKnobPattern->outputLevelMSB[positionSelect]<<8)|(currentKnobPattern->outputLevelLSB[positionSelect])); //this should be a regular integer between -70 and +10 prevRead = currentGlobals->lastFilteredKnobBuffer[select]; newRead = currentGlobals->filteredKnobBuffer[select]; if(checkVariation(newRead,prevRead)>2) { int16_t negCheckValue = (currentGlobals->filteredKnobBuffer[select] / volumeDivisor)-NegativeOffset; currentGlobals->valueChangeFlag |= (1<<knobChange); //if knob change bit is already set, this should be fine. currentGlobals->knobStatus = (bankSwitch<<4)|positionSelect; //we don't want to | this, we just want to set it equal, so the screen only updates the last value currentKnobPattern->outputLevelLSB[positionSelect] = (negCheckValue); if(negCheckValue>(-1)) { currentKnobPattern->outputLevelMSB[positionSelect] = 0; }else { currentKnobPattern->outputLevelMSB[positionSelect] = 255; } setOutputVolume(currentKnobPattern->outputLevelLSB[positionSelect], currentKnobPattern->outputLevelMSB[positionSelect], positionSelect); currentGlobals->lastFilteredKnobBuffer[select] = currentGlobals->filteredKnobBuffer[select]; } break; case 1: //pitch if(currentGlobals->lastFilteredKnobBuffer[select]!=(currentGlobals->filteredKnobBuffer[select])) { currentGlobals->valueChangeFlag |= (1<<knobChange); //if knob change bit is already set, this should be fine. currentGlobals->knobStatus = (bankSwitch<<4)|positionSelect; //we don't want to | this, we just want to set it equal, so the screen only updates the last value currentKnobPattern->outputPitch[positionSelect] = (currentGlobals->filteredKnobBuffer[select]^128); currentGlobals->lastFilteredKnobBuffer[select] = currentGlobals->filteredKnobBuffer[select]; outputSampleRate(positionSelect, 0, currentKnobPattern->outputPitch[positionSelect]); } break; case 2:; //attackEnvelope if(currentGlobals->lastFilteredKnobBuffer[select]!=currentGlobals->filteredKnobBuffer[select]) { uint16_t totalAttackTime = currentKnobPattern->trackAttackTimeLSB[positionSelectTracks]|((currentKnobPattern->trackAttackTimeMSB[positionSelectTracks])<<8); currentGlobals->valueChangeFlag |= (1<<knobChange); //if knob change bit is already set, this should be fine. currentGlobals->knobStatus = (bankSwitch<<4)|positionSelect; //we don't want to | this, we just want to set it equal, so the screen only updates the last value if(currentGlobals->currentGPButtons&0x04) { //if "fine" is on: totalAttackTime = totalAttackTime+((currentGlobals->filteredKnobBuffer[select])-(currentGlobals->lastFilteredKnobBuffer[select])); }else { totalAttackTime = ((currentGlobals->filteredKnobBuffer[select])-1)*238; } if(totalAttackTime<20) { totalAttackTime = 20; } currentKnobPattern->trackAttackTimeMSB[positionSelectTracks] = ((totalAttackTime)>>8); currentKnobPattern->trackAttackTimeLSB[positionSelectTracks] = (totalAttackTime); //this should truncate the top 8 bits. currentGlobals->lastFilteredKnobBuffer[select] = currentGlobals->filteredKnobBuffer[select]; } break; case 3: //release Envelope if(currentGlobals->lastFilteredKnobBuffer[select]!=currentGlobals->filteredKnobBuffer[select]) { uint16_t totalReleaseTime = currentKnobPattern->trackReleaseTimeLSB[positionSelectTracks]|((currentKnobPattern->trackReleaseTimeMSB[positionSelectTracks])<<8); currentGlobals->valueChangeFlag |= (1<<knobChange); //if knob change bit is already set, this should be fine. currentGlobals->knobStatus = (bankSwitch<<4)|positionSelect; //we don't want to | this, we just want to set it equal, so the screen only updates the last value if(currentGlobals->currentGPButtons&0x04) { //if "fine" is on: totalReleaseTime = totalReleaseTime+((currentGlobals->filteredKnobBuffer[select])-(currentGlobals->lastFilteredKnobBuffer[select])); }else { totalReleaseTime = ((currentGlobals->filteredKnobBuffer[select])-1)*238; } if(totalReleaseTime<20) { totalReleaseTime = 220; } currentKnobPattern->trackReleaseTimeMSB[positionSelectTracks] = ((totalReleaseTime)>>8); currentKnobPattern->trackReleaseTimeLSB[positionSelectTracks] = (totalReleaseTime); currentGlobals->lastFilteredKnobBuffer[select] = currentGlobals->filteredKnobBuffer[select]; } break; case 4:; prevRead = currentGlobals->lastFilteredKnobBuffer[select]; newRead = currentGlobals->filteredKnobBuffer[select]; if(checkVariation(newRead,prevRead)>2) { int16_t negCheckValueTrack = (currentGlobals->filteredKnobBuffer[select] / volumeDivisor)-NegativeOffset; currentGlobals->valueChangeFlag |= (1<<knobChange); //if knob change bit is already set, this should be fine. currentGlobals->knobStatus = (bankSwitch<<4)|positionSelect; //we don't want to | this, we just want to set it equal, so the screen only updates the last value currentKnobPattern->trackMainVolumeLSB[positionSelectTracks] = (negCheckValueTrack); if(negCheckValueTrack>(-1)) { currentKnobPattern->trackMainVolumeMSB[positionSelectTracks] = 0; }else { currentKnobPattern->trackMainVolumeMSB[positionSelectTracks] = 255; } if(currentKnobPattern->envelopeType[positionSelectTracks]==1||currentKnobPattern->envelopeType[positionSelectTracks]==3) //set track volume directly if Envelope mode is only release, or none. { setTrackVolume(currentKnobPattern->trackSampleLSB[positionSelectTracks], currentKnobPattern->trackSampleMSB[positionSelectTracks], currentKnobPattern->trackMainVolumeLSB[positionSelectTracks], currentKnobPattern->trackMainVolumeMSB[positionSelectTracks]); } currentGlobals->lastFilteredKnobBuffer[select] = currentGlobals->filteredKnobBuffer[select]; } break; } }else { switch (select) { // case 40: // if(gpKnob0!=checkValue) // { // gpKnob0 = checkValue; // } // break; // // case 41: // if(gpKnob1!=checkValue) // { // gpKnob1 = checkValue; // } // break; // case 42: //we need to do a bit more filtering here. Not sure if that's happening here, or in the actual knob read. if(currentGlobals->lastFilteredKnobBuffer[select]!=(currentGlobals->filteredKnobBuffer[select])) {//not sure if this works here, but we're going to try it. currentGlobals->valueChangeFlag |= (1<<knobChange); //if knob change bit is already set, this should be fine. currentGlobals->knobStatus = (5<<4); //since all other pot banks are 0-4, the next ones will be 5-8. We should maybe figure out a better system for this, //maybe some defines? currentKnobPattern->patternBPM = currentGlobals->filteredKnobBuffer[select]; currentGlobals->lastFilteredKnobBuffer[select] = currentGlobals->filteredKnobBuffer[select]; } break; // // case 43: // if(gpKnob3!=checkValue) // { // gpKnob3 = checkValue; // } // break; } } } void listenKnobs(Pattern *currentKnobPattern, Globals *currentGlobals) { for(uint8_t loopCounter = 0; loopCounter<44; loopCounter++) { selectKnob(loopCounter); updateKnob(loopCounter, currentGlobals); interperetKnob(loopCounter,currentKnobPattern, currentGlobals); } } uint8_t checkVariation(uint8_t v1, uint8_t v2) //this is used to check the difference between 2 knob reads, and give how far apart they are. { uint8_t returnMe=0; if(v1>v2) { returnMe = v1-v2; } else { returnMe = v2-v1; } return returnMe; }<file_sep>/TsunamiCS1Master/EncoderLib.h /* * EncoderLib.h * * Created: 7/31/2019 4:57:43 PM * Author: Hal */ #ifndef ENCODERLIB_H_ #define ENCODERLIB_H_ void initEncoders(); void listenEncoders(Pattern *currentPattern, Globals *currentGlobals); uint8_t listenEnoderReset(); //void listenEncodersNew(Pattern *currentPattern, Globals *currentGlobals); #endif /* ENCODERLIB_H_ */<file_sep>/TsunamiCS1Master/MidiLib.h #ifndef MIDILIB_H_ #define MIDILIB_H_ #include <avr/io.h> #include "globalVariables.h" void initMidi(); void transmitMidi(); void midiRead(Pattern currentPattern, Globals currentGlobals); #endif /* MIDILIB_H_ */ <file_sep>/TsunamiArduinoCore/readMe.md ## Programming the Arduino Since this whole Project was developed using the atmel studio platform, Porting over to the Arduino IDE is not exactly the smoothest port. Mainly due to C to C++ conversions and the Arduino overhead. Instead, we provide a .hex file of the most stable build, which you can upload to your arduio via AVRDUDE. You can use this via command line, or use a tool we very much like, AVRDUDESS: https://blog.zakkemble.net/avrdudess-a-gui-for-avrdude/ Steps: - Connect your arduino via USB - under the MCU dropdown, choose "Atmega2560" - select your COM Port on the Port drop down (should be the only one that says "COM") - use a baud rate of 115200 - for Programmer, use "Wiring" - under the "Flash" section, locate the .hex file that you downloaded from thr repository by clicking the "..." button. - check the "disable flash erase" check box, and the "Disable Verify" box. Now you can click either "Go" under the flash section, or "Program". The firmware should be flashed to your Board! If you experience some crazy values printng on your screen for knob movement, be sure your power supply is plugged in. This unit can not sucessfully be powered via the USB port. the last step is to do a factory reset to Format the external memory, and you've completed the programming process!<file_sep>/TsunamiCS1Master/serialLib.c /* * serialLib.c * * Created: 8/9/2019 10:59:42 AM * Author: Hal */ #define F_CPU 16000000UL #define TX_BUFFER_SIZE 384 //this serial buffer is big, yes, but Every load is 272 bytes, so if a pattern is playing, it is necessary. #define BUADTsunami 57600 #define BRCTsunami ((F_CPU/16/BUADTsunami)-1) //#define RX_BUFFER_SIZE 128 //buad rate: 57.6 kbps // 57600 buad - for Tsunami #include <avr/interrupt.h> #include <avr/io.h> char serial0Buffer[TX_BUFFER_SIZE]; int serialReadPos = 0; int serialWritePos = 0; ISR (USART0_TX_vect) { if(serialReadPos != serialWritePos) { UDR0 = serial0Buffer[serialReadPos]; serialReadPos++; if(serialReadPos >= TX_BUFFER_SIZE) { serialReadPos=0; //this seems wrong, I think we should be setting this to 0. } } } void appendSerial0(unsigned char c) { serial0Buffer[serialWritePos] = c; serialWritePos++; if(serialWritePos >= TX_BUFFER_SIZE) { serialWritePos = 0; } } void serialWrite0(unsigned char c[], uint8_t messageLength) { for (uint8_t i = 0; i<messageLength; i++) //this may need to be 11 { appendSerial0(c[i]); } if(UCSR0A & (1 << UDRE0)) { UDR0 = 0; } } void serialInit0() { UBRR0H = (BRCTsunami >> 8); UBRR0L = BRCTsunami; UCSR0B = (1 << TXEN0) | (1 << TXCIE0); UCSR0C = (1 << UCSZ01) | (1 << UCSZ00); //8 bit chars will be sent } /* char getChar() { char returnMe = '\0'; if(rxReadPosition != rxWritePosition) { returnMe = serial1Buffer[rxReadPosition]; rxReadPosition++; if(rxReadPosition >= RX_BUFFER_SIZE) { rxReadPosition = 0; } } return returnMe; } */ <file_sep>/TsunamiCS1Master/LEDLib.h /* * LEDLib.h * * Created: 8/22/2019 8:58:27 AM * Author: Hal */ #ifndef LEDLIB_H_ #define LEDLIB_H_ void initLEDs(); void parseLEDs(uint16_t LEDInput); void updateLEDs(Pattern ledCurrentPattern,Globals currentGlobals); #endif /* LEDLIB_H_ */<file_sep>/TsunamiCS1Master/sequencerLib.h #ifndef SEQUENCERLIB_H_ #define SEQUENCERLIB_H_ #include "globalVariables.h" void initSequencer(); void updateSequencer(Pattern sequencerPattern, Globals *currentGlobals); #endif /* SEQUENCERLIB_H_ */ <file_sep>/TsunamiCS1Master/knobLib.h /* * knobLib.h * * Created: 8/11/2019 8:00:34 AM * Author: Hal */ #ifndef KNOBLIB_H_ #define KNOBLIB_H_ #include "globalVariables.h" void selectKnob(uint8_t select); void updateKnob(uint8_t select, Globals *currentGlobals); void initializeKnob(Globals *currentGlobals); void interperetKnob(uint8_t select, Pattern *currentKnobPattern, Globals *currentGlobals); uint8_t startADCConversion(); void initADC(); void listenKnobs(Pattern *currentKnobPattern, Globals *currentGlobals); uint8_t checkVariation(uint8_t v1, uint8_t v2); #endif /* KNOBLIB_H_ */<file_sep>/TsunamiCS1Master/main.c #include <avr/io.h> #include "OLEDLib.h" #include "serialLib.h" #include "globalVariables.h" #include "knobLib.h" #include "ButtonLib.h" #include "DebounceLib.h" #include "menu.h" #include "tsunamiLib.h" #include "LEDLib.h" #include "encoderLib.h" #include "sequencerLib.h" #include "twiLib.h" #include "midiLib.h" #include <avr/interrupt.h> #include <avr/delay.h> #define F_CPU 16000000UL //Pattern may not need to be volatile, but I'd like to keep it around. volatile Pattern currentPattern; volatile Globals currentGlobals; volatile uint32_t globalTimer = 0; int main(){ uint8_t factoryReset=0; // set this to 1 if you would like to fill the eeprom with Factory data, and erase all user data. Screen screenBank; char testArray[21] = "CurrentTime: "; initScreen(); initButtons(); initEncoders(); initBank(&currentPattern); twi_init(); sei(); //factory Reset, we should turn this into a global function. factoryResetCheck(&factoryReset,&currentPattern, &currentGlobals); initTimer(); initGlobals(&currentGlobals, factoryReset); initLEDs(); initADC(); serialInit0(); initMidi(); //initEnvelopes(); //initSequencer(); eepromLoadPattern(&currentPattern,currentGlobals.currentPatternNumber); for(uint16_t i = 0; i<440; i++ ) //we need to load the FilterKnobbuffer into a stable state { uint8_t loadSelect = i%44; selectKnob(loadSelect); updateKnob(loadSelect, &currentGlobals); } initializeKnob(&currentGlobals); //then copy it to the lastFilteredKnobBuffer. globalLoad(&currentGlobals, factoryReset); initMenu(&screenBank, currentPattern, currentGlobals); //fills screenBank with menu strings //this ISR is used for Button De-Bouncing. Maybe we could put it somewhere else. //TCCR2B = 1<<CS22;//using 256 from pre-scaler //TIMSK2 = 1<<TOIE2; //interupt on counter overflow. since we're interupting on value 256 of with a 256 pre-scaler, we're calling this function every 65,536 //clock cycles. at 16MHz, that equates to every 0.004096, seconds, or every 4 milliseconds. We ~~~should be able to do the same thing from our global counter. cli(); //this may not be needed, but also may be effecting things since we're setting interrupt registers after sei has already happened. sei(); while(1) { updateTimers(&currentGlobals, globalTimer); //we update our global timers here. //if(currentGlobals.timerFlag) //triggers every millisecond / 16000 cycles. // { // listenEncodersNew(&currentPattern, &currentGlobals); //we may not need to check this every millisecond. If we can just do these checks on //pin changes, it should be fine. and we have the specific pins to check from, so we should be good. // } listenTrigButtons(&currentPattern, &currentGlobals); listenGPButtons(currentPattern, &currentGlobals); updateLEDs(currentPattern, currentGlobals); listenKnobs(&currentPattern, &currentGlobals); listenEncoders(&currentPattern, &currentGlobals); updateSequencer(currentPattern, &currentGlobals); updateScreen(&screenBank, &currentPattern, &currentGlobals); midiRead(currentPattern, currentGlobals); releaseUpdate(&currentPattern, &currentGlobals); //numPrinter(testArray, 11,5,currentGlobals.releaseCounter); //numPrinter(testArray, 11,5,(globalTimer/10)); //the only thing that should be effecting this timer, is the ISRs from the encoders. //outputS(testArray,0); } } ISR(TIMER2_COMPA_vect) { globalTimer++; //this counts in one order of magnitude smaller than millis : 0.0001 seconds. //we don't want to do anything else here. if(globalTimer%40==0) //every 40 ticks, we want to call De bounce { debounce(); } if(globalTimer%100==0) { //listenEncodersNew(&currentPattern, &currentGlobals); } }<file_sep>/TsunamiCS1Master/debounceLib.h /* * DebounceLib.h * * Created: 9/6/2019 8:15:54 PM * Author: user */ #ifndef DEBOUNCELIB_H_ #define DEBOUNCELIB_H_ #include <avr/io.h> #include <avr/interrupt.h> #include <util/atomic.h> #define BUTTON_PIN PINB #define BUTTON_PORT PORTB #define BUTTON_MASK 0B01111111 extern volatile uint8_t buttons_down; uint8_t button_down(uint8_t button_mask); #define VC_DEC_OR_SET(high, low, mask) \ low = ~(low & mask); \ high = low ^ (high & mask) static inline void debounce() //is this Timer interrupt too long? { static uint8_t vcount_low = 0xFF, vcount_high = 0xFF; static uint8_t button_state = 0; uint8_t state_changed = ~BUTTON_PIN ^ button_state; VC_DEC_OR_SET(vcount_high, vcount_low, state_changed); state_changed &= vcount_low & vcount_high; button_state ^= state_changed; buttons_down |= button_state&state_changed; } #endif /* DEBOUNCELIB_H_ */
50050a77cda137f135aabd7039f312da707374b2
[ "Markdown", "C", "Makefile" ]
32
C
BrutalistInstruments/Tsunami-CS-1
0e1885daa967ed4d4b49a9ff564cd63d0252c0e2
3c5b8bb3cc812660f33cac1841d6beffdbb2502a
refs/heads/master
<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Providing a common interface for performing topology test (`AU test`_) over protein alignments using various programs. Users are asked to provide a multiple sequence alignment (MSA) file, a NEWICK format tree file, and a topology test program's executable. If only one tree in the tree file was provided, a maximum-likelihood (ML) tree would be inferred and AU test will be performed to test the difference between the user specified tree and the ML tree. If a set of trees in NEWICK format was provided in the tree file, only these trees would be evaluated without reconstructing the ML tree. In both cases, only the p-value of AU test for the first tree will be returned. Users are recommended only to use function ``aut()`` and avoid to use any private functions inside the module. However, users are recommended to implement new private functions for additional topology test programs that they are interested and incorporate them into the general use function ``aut()``. .. _`AU test`: https://academic.oup.com/sysbio/article/51/3/492/1616895 """ import os import sys import shutil import random import logging import tempfile import argparse from io import StringIO from subprocess import PIPE, Popen try: from textwrap import indent except ImportError: from ProtParCon.utilities import indent from ProtParCon.utilities import basename, Tree from ProtParCon.mlt import mlt from Bio import Phylo LEVEL = logging.INFO LOGFILE, LOGFILEMODE = '', 'w' HANDLERS = [logging.StreamHandler(sys.stdout)] if LOGFILE: HANDLERS.append(logging.FileHandler(filename=LOGFILE, mode=LOGFILEMODE)) logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=HANDLERS, level=LEVEL) logger = logging.getLogger('[iMC]') warn, info, error = logger.warning, logger.info, logger.error def _iqtree(exe, msa, tree, model, seed): """ Perform topology test (AU test) using IQ-TREE_. :param msa: str, path to a FASTA format MSA file. :param tree: str, path to a NEWICK format tree file. :param exe: str, path to a topology test program's executable. :param model: str, name of the model or path of the model file. :param seed: int, the seed used to initiate the random number generator. :return: tuple, p-value of the AU test (float), first tree (string), and second tree (string). .. _IQ-TREE: www.iqtree.org/ """ trees = Phylo.parse(tree, 'newick') number = sum(1 for t in trees) wd = tempfile.mkdtemp(dir=os.path.dirname(os.path.abspath(msa))) args = [exe, '-s', 'msa.fasta', '-zb', '10000', '-au', '-nt', '1', '-pre', 'autest', '-n', '0'] if model: args.extend(['-m', model]) else: args.extend(['-m', 'TEST']) shutil.copy(msa, os.path.join(wd, 'msa.fasta')) t1, t2 = '', '' if number == 1: info('One tree found in tree file, inferring ML tree.') mltree = mlt(exe, msa, model=model) if mltree: trees = os.path.join(wd, 'trees.newick') if isinstance(tree, str): with open(tree) as f1: t1 = f1.readline().rstrip() else: t1 = tree.format('newick').rstrip() with open(trees, 'w') as o, open(mltree) as f2: t2 = f2.read().strip() o.write('{}\n{}\n'.format(t1, t2)) args.extend(['-z', 'trees.newick']) else: error('Infer ML tree failed, AU TEST aborted.') sys.exit(1) else: with open(tree) as f: t1, t2 = f.readline().strip(), f.readline().strip() shutil.copy(tree, os.path.join(wd, 'trees.newick')) args.extend(['-z', 'trees.newick']) try: info('Running AU TEST (IQ-TREE) using the following command:\n\t' '{}'.format(' '.join(args))) process = Popen(args, cwd=wd, stdout=PIPE, stderr=PIPE, universal_newlines=True) code = process.wait() if code: msg = indent(process.stderr.read(), prefix='\t') error('Topology test (AU TEST) failed for {}\n{}'.format(msa, msg)) sys.exit(1) else: info('Parsing tree topology test (AU TEST) results.') with open(os.path.join(wd, 'autest.iqtree')) as f: for line in f: if 'USER TREES' in line: break for line in f: if line.strip().startswith('1'): aup = float(line.split()[-2]) return aup, t1, t2 error('Parsing tree topology test (AU TEST) failed, no test' 'result found.') sys.exit(1) except OSError: error('Invalid IQ-TREE executable (exe) {}, topology test (AU TEST) ' 'failed for {}.'.format(exe, msa)) sys.exit(1) finally: shutil.rmtree(wd) def aut(exe, msa, tree, model='', seed=0, outfile='', verbose=False): """ General use function for performing topology test (AU test). :param msa: str, path to a FASTA format MSA file. :param tree: str, path to a NEWICK format tree file. :param exe: str, path to a topology test program's executable. :param model: str, name of the model or path of the model file. :param seed: int, the seed used to initiate the random number generator. :param outfile: str, path to the output file for storing test result. If not set, only return the result without save to a file. :param verbose: bool, invoke verbose or silent process mode, default: False, silent mode. :return: tuple, p-value of the AU test (float), first tree (string), and second tree (string). """ logger.setLevel(logging.INFO if verbose else logging.ERROR) if os.path.isfile(msa): msa = os.path.abspath(msa) else: error('Alignment {} is not a file or does not exist.'.format(msa)) sys.exit(1) if not os.path.isfile(tree): error('Tree {} is not a file a does not exist.'.format(tree)) sys.exit(1) if not isinstance(model, str): error('Argument model accepts a string for the name of the model or ' 'path of the model file') sys.exit(1) try: seed = int(seed) if seed else random.randint(0, 1000000) except ValueError: warn('Invalid seed, generating seed using random number generator.') seed = random.randint(0, 1000000) aup, t1, t2 = _iqtree(exe, msa, tree, model, seed) if outfile: try: with open(outfile, 'w') as o: o.write('P-value: {:.4f}\n' 'Tree1: {}\n' 'Tree2: {}\n'.format(aup, t1, t2)) except OSError as err: error('Save AU TEST result to file failed due to:\n' '\t{}'.format(outfile, err)) return aup, t1, t2 def main(): des = 'Perform topology test (AU test) over protein alignments.' epilog = """ The minimum requirement for running iMC-aut is an executable of a AU test program, a multiple sequence alignment (MSA) file (in FASTA format), a tree file (in NEWICK format). If you only provide one tree in the tree file, a maximum-likelihood tree will be inferred and AU-TEST will be performed to test the difference between them. If a set of trees in NEWICK format was provided in the tree file, only these trees will be evaluated without reconstructing the ML tree. In both case, only the p-value of AU TEST for the first tree will be printed out. Without providing a output file path, AU test results will not be saved to local file system, but the results will be always printed out. """ formatter = argparse.RawDescriptionHelpFormatter parse = argparse.ArgumentParser(description=des, prog='ProtParCon-aut', usage='%(prog)s EXE MSA TREE [OPTIONS]', formatter_class=formatter, epilog=epilog) parse.add_argument('EXE', help='Path to the executable of the topology test (AU ' 'test) program.') parse.add_argument('MSA', help='Path to the alignment file in FASTA format.') parse.add_argument('TREE', help='Path to the tree file or string in NEWICK format.') parse.add_argument('-m', '--model', help='Name of the substitution model or filename of the ' 'model file.') parse.add_argument('-o', '--output', help='Path to the output file.') parse.add_argument('-s', '--seed', help='The seed for initiating the random number ' 'generator.') parse.add_argument('-v', '--verbose', action='store_true', help='Invoke verbose or silent (default) process mode.') args = parse.parse_args() msa, tree, exe, model = args.MSA, args.TREE, args.EXE, args.model aup, t1, t2 = aut(exe, msa, tree, model=model, seed=args.seed, outfile=args.out, verbose=args.verbose) print(aup) print(t1) print(t2) if __name__ == '__main__': main() <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Providing a common interface for simulating amino acid sequences using various simulation programs. At this stage, the module only support simulate sequences using EVOLVER (inside PAML program) and Seq-Gen. The minimum requirement of this interface asks users to provide a NEWICK format tree string or tree file and a executable of a simulation program. Users can also pass additional options to simulate amino acid sequences under various cases. Users are recommended to only use function sim() and avoid to use any private functions inside the module. However, users are strongly recommended to implement new private functions for additional simulation programs and wrap them into the general use function aut(). """ import os import re import sys import shutil import random import logging import tempfile import argparse from io import StringIO try: from textwrap import indent except ImportError: from ProtParCon.utilities import indent from collections import Counter from subprocess import PIPE, Popen from ProtParCon.utilities import basename, modeling, Tree, trim from ProtParCon.models import models from Bio import Phylo, AlignIO, SeqIO LEVEL = logging.INFO LOGFILE, LOGFILEMODE = '', 'w' HANDLERS = [logging.StreamHandler(sys.stdout)] if LOGFILE: HANDLERS.append(logging.FileHandler(filename=LOGFILE, mode=LOGFILEMODE)) logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=HANDLERS, level=LEVEL) logger = logging.getLogger('[iMC]') warn, info, error = logger.warning, logger.info, logger.error AMINO_ACIDS = 'ARNDCQEGHILKMFPSTWYV' MC_DAT = """0 * 0: paml format (mc.paml); 1:paup format (mc.nex) {} * random number seed (odd number) {} {} {} * <# seqs> <# sites> <# replicates> -1 * <tree length, use -1 if tree below has absolute branch lengths> {} {} {} * <alpha> <#categories for discrete gamma>' {} {} * <model> [aa substitution rate file, need only if model=2 or 3] {} {} A R N D C Q E G H I L K M F P S T W Y V """ def _guess(exe): """ Guess the name of a sequence simulation program according to its executable. :param exe: str, path to the executable of an simulation program. :return: tuple, name of the simulation program and the corresponding function. """ wd = tempfile.mkdtemp() try: process = Popen([exe, '-h'], cwd=wd, stdout=PIPE, stderr=PIPE, universal_newlines=True) try: outs, errs = process.communicate(timeout=3) out = outs or errs if 'seq-gen' in out: return 'seq-gen', _seqgen else: return 'evolver', _evolver except Exception as exc: process.terminate() process.wait(timeout=10) return 'evolver', _evolver except OSError: error("The exe ({}) is empty or may not be an valid executable of a " "sequence simulation program.".format(exe)) sys.exit(1) finally: shutil.rmtree(wd) def _evolver_parse(wd): """ Parse the work directory of EVOLVER to get the simulated results. :param wd: str, work directory of EVOLVER. :return: tuple, a list of simulated sequences (dict) and a tree object. """ simulations, tree = [], None notation, ts, ancs, leaves = '', [], [], [] with open(os.path.join(wd, "ancestral.txt")) as f: for line in f: line = line.strip() if line and line[0].isdigit() and line[-1].isdigit(): notation = line break for line in f: if line.startswith('['): break for line in f: if line.strip() and not line.startswith('['): ancs.append(line) with open(os.path.join(wd, 'mc.paml')) as f: for line in f: if line.strip(): leaves.append(line) with open(os.path.join(wd, 'simulation.log')) as f: for line in f: if line.startswith('(') and line.strip().endswith(';'): ts.append(line) branches = {} for branch in notation.split(): head, tail = branch.split('..') branches[tail] = head tree, code = [Phylo.read(StringIO(t.replace(' ', '')), 'newick') for t in ts] root = None for clade, node in zip(tree.find_clades(order='postorder'), code.find_clades(order='postorder')): try: parent = tree.get_path(clade)[-2] parent.name = branches[node.name] if node.name else branches[ clade.name] except IndexError: if len(tree.get_path(clade)) == 1: root = branches[node.name] if node.name else branches[ clade.name] else: clade.name = root number, maps = tree.count_terminals(), {} for clade in tree.find_clades(): if not clade.is_terminal(): number += 1 old, new = clade.name, 'NODE{}'.format(number) maps[old] = new clade.name = new if ancs and leaves: for inter, leaf in zip( AlignIO.parse(StringIO(''.join(ancs)), 'phylip-relaxed'), AlignIO.parse(StringIO(''.join(leaves)), 'phylip-relaxed')): leaf.extend(inter) for record in leaf: name = record.id.replace('node', 'NODE') record.id = maps.get(name, name) simulations.append(leaf) return simulations, tree def _evolver(exe, tree, length, freq, model, n, seed, gamma, alpha, invp, outfile): """ Sequence simulation via EVOLVER. :param exe: str, path to the executable of EVOLVER. :param tree: str, path to the tree (must has branch lengths and in NEWICK format). :param length: int, the number of the amino acid sites need to be simulated. :param freq: list or None, base frequencies of 20 amino acids. :param model: str, name of a model a filename of a model file. :param n: int, number of datasets (or duplicates) need to be simulated. :param seed: int, the seed used to initiate the random number generator. :param gamma: int, 0 means discrete Gamma model not in use, any positive integer larger than 1 will invoke discrete Gamma model and set the number of categories to gamma. :param alpha: float, the Gamma shape parameter alpha, without setting, the value will be estimated by the program, in case an initial value is needed, the initial value of alpha will be set to 0.5. :param invp: float, proportion of invariable site. :param outfile: pathname of the output ML tree. If not set, default name [basename].[program].ML.newick, where basename is the filename of the sequence file without extension, program is the name of the ML inference program, and newick is the extension for NEWICK format tree file. :return: str, path to the simulation output file. """ wd = os.path.dirname(outfile) cwd = tempfile.mkdtemp(dir=wd) dat = 'MCaa.dat' tree = Tree(tree, leave=True) tn, ts = tree.leaves, tree.string() m = modeling(model) if m.type == 'custom': mf = m.name else: name = m.name if name.lower() in models: info('Using {} model for simulation.'.format(name)) with open(os.path.join(cwd, name), 'w') as o: o.write(models[name.lower()]) mf = name else: error('PAML (evolver) does not support model {}.'.format(name)) sys.exit(1) if freq is None: mn = 2 f1, f2 = '', '' else: mn = 3 f1 = ' '.join([str(i) for i in freq[:10]]) f2 = ' '.join([str(i) for i in freq[10:]]) with open(os.path.join(cwd, dat), 'w') as o: o.write(MC_DAT.format(seed, tn, length, n, ts, alpha, gamma, mn, mf, f1, f2)) try: info('Simulating sequences using EVOLVER.') log = os.path.join(cwd, 'simulation.log') with open(log, 'w') as stdoe: process = Popen([exe, '7', dat], cwd=cwd, stdout=stdoe, stderr=stdoe, universal_newlines=True) code = process.wait() if code: with open(log) as handle: error('Sequence simulation via EVOLVER failed for {} due to:' '\n{}'.format(tree, indent(handle.read(), prefix='\t'))) sys.exit(1) else: info('Parsing and saving simulation results.') simulations, tree = _evolver_parse(cwd) try: with open(outfile, 'w') as o: o.write('#TREE\t{}\n'.format(tree.format('newick'))) for simulation in simulations: o.writelines('{}\t{}\n'.format(s.id, s.seq) for s in simulation) o.write('\n') except OSError: error('Failed to save simulation results to {} (' 'IOError, permission denied).'.format(outfile)) outfile = '' info('Successfully saved simulation results to {}'.format(outfile)) except OSError: error('Invalid PAML (EVOLVER) executable {}, running EVOLVER failed ' 'for {}.'.format(exe, tree)) sys.exit(1) finally: shutil.rmtree(cwd) return outfile def _seqgen(exe, tree, length, freq, model, n, seed, gamma, alpha, invp, outfile): """ Sequence simulation via EVOLVER. :param exe: str, path to the executable of EVOLVER. :param tree: str, path to the tree (must has branch lengths and in NEWICK format). :param length: int, the number of the amino acid sites need to be simulated. :param freq: list or None, base frequencies of 20 amino acids. :param model: str, name of a model a filename of a model file. :param n: int, number of datasets (or duplicates) need to be simulated. :param seed: int, the seed used to initiate the random number generator. :param gamma: int, 0 means discrete Gamma model not in use, any positive integer larger than 1 will invoke discrete Gamma model and set the number of categories to gamma. :param alpha: float, the Gamma shape parameter alpha, without setting, the value will be estimated by the program, in case an initial value is needed, the initial value of alpha will be set to 0.5. :param invp: float, proportion of invariable site. :param outfile: pathname of the output ML tree. If not set, default name [basename].[program].ML.newick, where basename is the filename of the sequence file without extension, program is the name of the ML inference program, and newick is the extension for NEWICK format tree file. :return: str, path to the simulation output file. """ wd = os.path.dirname(outfile) cmd = [exe, '-l{}'.format(length), '-n{}'.format(n), '-z{}'.format(seed)] m = modeling(model) if m.type == 'custom': try: with open(m.name) as handle: lines = handle.readlines() except IndexError: error('Invalid model file {}, Line 22 (amino acid frequencies)' 'does not exist in model file.'.format(m.name)) sys.exit(1) r = [line.strip() for line in lines[:19]] r = re.sub('\s+', ',', ','.join(r)) cmd.append('-r{}'.format(r)) if freq is None: freq = re.sub(r'\s+', ',', ','.join(lines[21])) cmd.append('-f{}'.format(freq)) freq = None else: cmd.append('-m{}'.format(m.name.upper())) if freq: cmd.append('-f{}'.format(','.join([str(i) for i in freq]))) if gamma: cmd.append('-g{}'.format(gamma)) if alpha: cmd.append('-a{}'.format(alpha)) cmd.extend(['-wa', '-q']) cwd = tempfile.mkdtemp(dir=wd) output = os.path.join(cwd, 'output.phylip') tree = Tree(tree).file(os.path.join(cwd, 'tree.newick')) try: info('Simulating sequences using Seq-Gen.') stdout, stdin = open(output, 'w'), open(tree) process = Popen(cmd, cwd=cwd, stdout=stdout, stdin=stdin, stderr=PIPE, universal_newlines=True) code = process.wait() stdout.close(), stdin.close() if code: msg = indent(process.stderr.read(), prefix='\t') error('Sequence simulation via Seq-Gen failed due to:' '\n{}'.format(tree, msg)) sys.exit(1) else: info('Parsing and saving simulation results.') tree = Phylo.read(tree, 'newick') number, nodes = tree.count_terminals(), [] for clade in tree.find_clades(): if not clade.is_terminal(): number += 1 clade.name = 'NODE{}'.format(number) nodes.append(str(number)) try: with open(outfile, 'w') as o: o.write('#TREE\t{}\n'.format(tree.format('newick'))) with open(output) as f: for line in f: if line.strip(): i, s = line.strip().split() if i.isdigit() and s.isdigit(): o.write('\n') else: if i.isdigit(): i = 'NODE{}'.format(i) o.write('{}\t{}\n'.format(i, s)) except OSError: error('Failed to save simulation results to {} (' 'IOError, permission denied).'.format(outfile)) outfile = '' info('Successfully saved simulation results to {}'.format(outfile)) except OSError: error('Invalid Seq-Gen executable {}, running Seq-Gen failed for ' '{}.'.format(exe, tree)) sys.exit(1) finally: shutil.rmtree(cwd) return outfile def _seq2info(sequence): tree, length, frequency = None, 0, None if os.path.isfile(sequence): with open(sequence) as handle: line = handle.readline().strip() if line.startswith('>'): handle.seek(0) try: aln = AlignIO.read(handle, 'fasta') except ValueError: error('Specified sequence {} is not a valid multiple ' 'sequence alignment, fetch info failed.') return tree, length, frequency records = {a.description: a.seq for a in aln} elif line.startswith('#TREE'): ts = line.split()[1] tree = Phylo.read(StringIO(ts), 'newick') records = {} while 1: line = handle.readline() if line: if line.strip() and not line.startswith('#'): if not line.startswith('NODE'): name, seq = line.strip().split() records[name] = seq else: break else: error('The first line of non FASTA file does not start ' 'with #TREE, can not find a tree for simulating.') sys.exit(1) if records: AA = set(AMINO_ACIDS) fs = Counter({a: 0 for a in AMINO_ACIDS}) sites = len(list(records.values())[0]) for i in range(sites): aa = [v[i] for v in records.values()] if set(aa).issubset(AA): length += 1 fs += Counter(aa) total = float(sum(fs.values())) if total: frequency = ['{:.8f}'.format(fs.get(a, 0) / total) for a in AMINO_ACIDS] else: error('Sequence {} is not a file or does not exist, ' 'simulation aborted.'.format(sequence)) sys.exit(1) return tree, length, frequency def sim(exe, tree='', sequence='', model='JTT', length=100, freq='empirical', n=100, seed=0, gamma=4, alpha=0.5, invp=0, outfile='', verbose=False): """ Sequence simulation via EVOLVER. :param exe: str, path to the executable of EVOLVER. :param tree: str, path to the tree (must has branch lengths and in NEWICK format). If not provided, sequence file need to be a tsv file consisting a tree with branch lengths and sequences. If both tree and sequence in tsv format file were provided, the tree in tsv file will be ignored. :param sequence: str, path to a multiple sequence alignment file in FASTA format or a tsv file generated by function `asr()` that have a line contains a tree with branch lengths. If provided, the length and base amino acid frequencies will be calculated based on the leaf sequences. :param model: str, name of a model a filename of a model file. :param length: int, the number of the amino acid sites need to be simulated, default: 0, the length will be obtained from the sequence. :param freq: str, "empirical", "estimate", or a comma separated string of base frequencies of 20 amino acids in the order of "ARNDCQEGHILKMFPSTWYV". :param n: int, number of datasets (or duplicates) need to be simulated. :param seed: int, the seed used to initiate the random number generator. :param gamma: int, 0 means discrete Gamma model not in use, any positive integer larger than 1 will invoke discrete Gamma model and set the number of categories to gamma. :param alpha: float, the Gamma shape parameter alpha, without setting, the value will be estimated by the program, in case an initial value is needed, the initial value of alpha will be set to 0.5. :param invp: float, proportion of invariable site. :param outfile: pathname of the output ML tree. If not set, default name [basename].[program].ML.newick, where basename is the filename of the sequence file without extension, program is the name of the ML inference program, and newick is the extension for NEWICK format tree file. :param verbose: bool, invoke verbose or silent process mode, default: False, silent mode. :return: str, path to the simulation output file. """ logger.setLevel(logging.INFO if verbose else logging.ERROR) if tree: t = Tree(tree, leave=True) if not t.length: error('Unscaled tree: {}, cannot simulate sequences without branch' 'lengths.'.format(tree)) sys.exit(1) if sequence: _, l, freqs = _seq2info(sequence) else: l, freqs = 0, None elif sequence: t, l, freqs = _seq2info(sequence) else: error('Neither tree or a sequence file contains a tree was provided, ' 'simulation aborted.') sys.exit(1) if length: try: length = int(length) except ValueError: error('Invalid length, length should be a integer.') sys.exit(1) else: if l: length = l else: error('Neither valid sequence nor argument length was specified, ' 'failed to obtain length, simulation aborted.') sys.exit(1) fs = freqs if freq == 'estimate' else None if freq: if freq == 'equal': fs = ['0.05'] * 20 elif freq == 'estimate': fs = freqs if not fs: warn('Failed to get observed amino acid frequency from ' 'sequence, use the default frequency of model instead.') elif freq == 'empirical': fs = None elif freq.startswith('0') and freq.count(',') == 19: fs = [i.strip() for i in freq.split(',')] if 1 - sum([float(s) for s in fs]) > 0.000001: error('Specified frequencies do not add up to 1.0, simulation ' 'aborted.') sys.exit(1) else: warn('Unknown frequency encounter, use the default frequency of ' 'model instead.') fs = None try: seed = int(seed) if seed else random.randint(0, 10000) except ValueError: warn('Invalid seed, use generated random number instead.') seed = random.randint(0, 10000) name, func = _guess(exe) if not outfile: outfile = os.path.join(os.getcwd(), '{}.simulations.tsv'.format(name)) if os.path.isfile(outfile): info('Found pre-existing simulated sequences.') else: outfile = func(exe, tree, length, fs, model, n, seed, gamma, alpha, invp, outfile) return outfile def main(): des = 'Perform topology test (AU TEST) over protein alignments.' epilog = """ The minimum requirement for running iMC-aut is a multiple sequence alignment (MSA) file, a tree file and an executable of a AU TEST program. If users only provide one tree in the tree file, a maximum-likelihood tree will be inferred and AU-TEST will be performed to test the difference between them. If a set of trees in NEWICK format was provided in the tree file, only these trees will be evaluated without inferring the ML tree. In both case, only the p-value of AU TEST for the first tree will be printed out. """ formatter = argparse.RawDescriptionHelpFormatter parse = argparse.ArgumentParser(description=des, prog='ProtParCon-sim', usage='%(prog)s EXE [OPTIONS]', formatter_class=formatter, epilog=epilog) parse.add_argument('EXE', help='Pathname of the executable of the sequence ' 'simulation program.') parse.add_argument('-t', '--tree', help='Pathname of a tree file or a tree string in ' 'newick format.') parse.add_argument('-r', '--sequence', help='Pathname of the sequence file (a MSA file or a ' 'TSV file storing tree and sequences) file.') parse.add_argument('-l', '--length', default=0, help='the number of the amino acid sites need to ' 'be simulated, default: 0, the length will be ' 'obtained from the sequence.') parse.add_argument('-f', '--frequency', default='empirical', help='String, can be "empirical", "estimate", or a comma' ' separated string of base frequencies of 20 amino ' 'acids in the order of "ARNDCQEGHILKMFPSTWYV".') parse.add_argument('-m', '--model', default='JTT', help='Name of the evolutionary model or filename of the ' 'model file.') parse.add_argument('-g', '--gamma', default=4, help='The number of categories for the discrete gamma ' 'rate heterogeneity model.') parse.add_argument('-a', '--alpha', default=0.5, help='The shape (alpha) for the gamma rate ' 'heterogeneity.') parse.add_argument('-n', '--number', default=3, help='Number of datasets to be simulated.') parse.add_argument('-s', '--seed', help='Random number seed.') parse.add_argument('-i', '--invp', default=0, help='The proportion of invariable sites.') parse.add_argument('-o', '--output', help='Pathname of the output file for storing ' 'simulated sequences.') parse.add_argument('-v', '--verbose', action='store_true', help='Invoke verbose or silent (default) process mode.') args = parse.parse_args() exe, tree = args.EXE, args.TREE sim(exe, tree=tree, model=args.model, sequence=args.sequence, length=args.length, freq=args.frequency, n=args.number, seed=args.seed, gamma=args.gamma, alpha=args.alpha, invp=args.invp, outfile=args.output, verbose=args.verbose) if __name__ == '__main__': main() <file_sep>.. _intro-usage-shell: Using ProtParCon in terminal ============================ Check ProtParCon command-line toolsets ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ After ProtParCon has been installed, you should also have six command-line tools installed, they are: msa, asr, mlt, aut, imc, and sim. To check the availability and usage of any of these command-line tools, you can type the name of the command-line tool with '-h' flag in a terminal to see the usage page, for example:: $ msa -h The above command should print out the usage of `msa` without any error. The '-h' flag can also be used to check the usage for other commands. We suggest you use this flag to display the usage of the command and learn how to use it from its usage. Using toolsets in terminal ~~~~~~~~~~~~~~~~~~~~~~~~~~ By checking usage of command line tool, it should be very easy for you to use the toolsets shipped by ProtParCon. For example, the following command will align a sequence file named `seq.fa` using `MUSCLE` and save the alignment output to a file named `alignment.fasta`:: $ msa muscle seq.fa -o alignment.fasta In the following example, `imc` is used to automate sequence alignment, ancestral states reconstruction, sequence simulation, and identify parallel and convergent amino acid replacements both in the reconstructed ancestral sequences and the simulated sequences:: $ imc seq.fa tree.newick -l muscle -a codeml -s seqgen After running the above command, there are several files stored in your current work directory. You can get the information about identified parallel and convergent amino acid replacements in file `imc.counts.tsv` and file `imc.details.tsv`. All command-line tools have nearly the same signatures as the equivalent functions in python module, refer to the usage of each command and the examples showing the usage of the equivalent functions, it should be very easy for you to use the command-line toolsets. In the following part, we list examples of using command-line commands to do the same work that we have done in the ProtParCon python usage part. We are not going to repeat the details of each example, if you have any question about to details, see ProtParCon python usage part. Align sequences using MUSCLE and save the alignment output to a file named `seq.muscle.fasta` (default name):: $ msa muscle seq.fa Align sequence using MAFFT and save the alignment output to a FASTA format file named 'seq.mafft.fasta' (default name):: $ msa mafft seq.fa And this will align the same sequence with Clustal (Omega) and save the alignment to a FASTA file named 'seq.clustal.fasta':: $ msa clustal seq.fa .. note:: The above example assumes that you have system wide Clustal Omega installed and the string clustal point to the executable of Clustal Omega. If your Clustal Omega is not system widely installed, or the path to its executable is not `clustal`, change it accordingly. Align sequence using MUSCLE and save the alignment output into a file name `alignment.fasta`:: msa muscle seq.fa -o alignment.fasta Infer ML tree using IQ-TREE and save the best ML tree to a file named `msa.IQ-TREE.ML.newick` (default name):: $ mlt iqtree msa.fa Infer ML tree using RAxML and save the ML tree to a file named 'msa.RAxML.ML.newick' (default name):: $ mlt raxml msa.fa Infer ML tree using PjyML and save the ML tree to a file named 'msa.PhyML.ML.newick' (default name):: $ mlt phyml msa.fa Infer ML tree using FastTree and save the ML tree to a file named 'msa.FastTree.ML.newick' (default name):: $ mlt fasttree msa.fa Infer ML tree using RAxML and save the tree into a file named `tree.newick` in the same directory of the alignment file with '-o' option:: $ mlt raxml msa.fa -o tree.newick Infer ML tree using LG model with 8 Gamma categories accounting for among-site rate variation and estimating ML base frequencies of 20 amino acids via PhyML:: $ mlt PhyML msa.fa -o tree.newick -model LG+G8+F The same as the above example, use '-g' and '-f' options:: $ mlt PhyML msa.fa -o tree.newick -m LG -g 9, -f estimate Infer ML tree with a start tree and/or constraint tree via `start_tree` and `constraint_tree` options:: $ mlt raxml msa.fa -o tree.newick -m LG+G8+I -p /path/to/the/start/tree/file -q /path/to/the/constraint/tree/file Reconstruct ancestral states using CODEML and save the ancestral states output to a file named `msa.codeml.tsv` (default name):: $ asr codeml msa.fa tree.newick Reconstruct ancestral states using RAxML and save the ancestral states output to a file named 'msa.raxml.tsv' (default name):: $ asr raxml msa.fa Reconstruct ancestral states using RAxML and save the ancestral states output to a file named `ancestors.tsv` via '-o' option:: $ asr raxml msa.fa -o ancestors.tsv Reconstruct ancestral states via CODEML using WAG model (-model option):: $ asr codeml msa.fa tree.newick -m WAG Reconstruct ancestral states via RAxML using 'WAG' model:: $ asr raxml msa.fa tree.newick -m WAG Reconstruct ancestral states using LG model with 8 Gamma categories and a ML estimate of base frequencies of 20 amino acids via RAxML:: $ asr raxml msa.fa tree.newick -m LG+G8+F Do the same thing as the above example, but use '-g' and '-f' options:: $ asr raxml msa.fa tree.newick -m LG -g 8 -f estimate Use a specified model (or matrix) file along with complicated modeling information for ancestral states reconstruction:: $ asr codeml msa.fa tree.newick -m /path/to/my/own/model -g 8 -f estimate .. note:: The model (or matrix) file needs to be in the right format required by ASR programs, before use the model file, check the manual for your ASR program to make sure you model file is in the right format. Simulate sequences in the simplest way:: $ sim evolver tree.newick Use Seq-Gen to simulate 200 protein datasets with the length set to 500 amino acids and substitution model set to LG with 8 Gamma categories to account for among sites rate variation:: $ sim seqgen tree.newick -l 500 -n 200 -m LG -g 8 Use Seq-Gen to simulate 200 protein datasets with the length and base frequencies of 20 amino acids extracted from a multiple protein sequence alignment file:: $ sim seqgen tree.newick -n 200 -m LG -g 8 -r /path/to/the/multiple/sequence/alignment/file -f estimate Topology test (AU test) using `aut`:: $ aut iqtree msa.fa tree.newick -m WAG Identify parallel and convergent amino acid replacements using ancestral states reconstruction generated by ProtParCon:: $ imc path/to/the/ancestral/states/file <file_sep>from ProtParCon.imc import imc from ProtParCon.asr import asr from ProtParCon.aut import aut from ProtParCon.mlt import mlt from ProtParCon.msa import msa from ProtParCon.sim import sim from ProtParCon.detect import detect<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Providing a common interface for identifying parallel and convergent amino acid replacements in orthologous protein sequences. In order to make this module for general use, function ``ProtParCon()`` is built on top of other modules to facilitate the identification of parallel and convergent amino acid replacements using a wide range of sequence data. Depending on the sequence data, optional parameters and external programs may be required. """ import os import sys import glob import shutil import logging import tempfile import argparse import numpy as np from io import StringIO from itertools import combinations from collections import namedtuple, Counter, defaultdict from Bio import Phylo, SeqIO, AlignIO from scipy.stats import poisson from ProtParCon import msa, asr, aut, sim, detect, utilities from ProtParCon.models import models LEVEL = logging.INFO LOGFILE, LOGFILEMODE = '', 'w' HANDLERS = [logging.StreamHandler(sys.stdout)] if LOGFILE: HANDLERS.append(logging.FileHandler(filename=LOGFILE, mode=LOGFILEMODE)) logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=HANDLERS, level=LEVEL) logger = logging.getLogger('[iMC]') warn, info, error = logger.warning, logger.info, logger.error AMINO_ACIDS = 'ARNDCQEGHILKMFPSTWYV' def _pairing(tree, indpairs=True): """ Checking whether two branches are sister branch pair or branch pair sharing the same evolutionary path. :param tree: object, a tree object. :param indpairs: bool, only return independent branch pairs if true, or return all branch pairs if False. :return: tuple, a list of branches and a list of branch pairs. """ def comparable(tree, b1, b2): (p1, t1), (p2, t2) = b1[:2], b2[:2] if p1 == p2: return False else: t1a = [a.name for a in tree.get_path(t1)] t2a = [a.name for a in tree.get_path(t2)] if (t1 in t2a) or (t2 in t1a): return False else: return True branches = [] for clade in tree.find_clades(): for child in clade: branches.append([clade.name, child.name]) if indpairs: pairs = [(b1, b2) for (b1, b2) in combinations(branches, 2) if comparable(tree, b1, b2)] else: pairs = [(b1, b2) for (b1, b2) in combinations(branches, 2)] return branches, pairs def _load(tsv): """ Load tree, rates, and data blocks from a tsv file. :param tsv: str, path to the tsv file stores ancestral states or simulated sequences. :return: tuple, tree, rates (list) and sequence records (defaultdict). """ tree, rates, records, aps = None, [], defaultdict(list), {} with open(tsv) as handle: for line in handle: blocks = line.strip().split() if len(blocks) >= 2: if blocks[0] == '#TREE' and blocks[1].endswith(';'): tree = Phylo.read(StringIO(blocks[1]), 'newick') elif blocks[0] == '#RATES': rates = [float(i) for i in blocks[1:]] elif blocks[0].startswith('#NODE'): k = blocks[0].replace('#', '') ps = blocks[1].split(')')[:-1] aps[k] = [p.split('(') for p in ps] else: records[blocks[0]].append(blocks[1]) size = [len(v) for v in records.values()] if size: size = size[0] else: error('Invalid sequence file {}, the file does not have tab ' 'separated lines for sequences.'.format(tsv)) sys.exit(1) if tree is None: error('Invalid sequence file {}, the file does not have a line stores ' 'labeled tree for internal nodes.'.format(tsv)) sys.exit(1) else: names = set([clade.name for clade in tree.find_clades()]) if records: ids = set(records.keys()) if names != ids: error('Sequence name space does not match tree name space.') sys.exit(1) else: error('Invalid sequence file {}, the file does not have ' 'tab separated lines for sequence blocks.'.format(tsv)) sys.exit(1) return tree, rates, records, aps, size def _sequencing(sequence, tree, aligner, ancestor, wd, asr_model, verbose): """ Identify the type of the sequence file. :param sequence: str, path to a sequence data file. :param tree: str, path to a NEWICK tree file. :return: tuple, sequence, alignment, ancestor, and simulation data file. """ if tree: utilities.Tree(tree, leave=True) AA, lengths, aa = set(AMINO_ACIDS), [], [] with open(sequence) as handle: line = handle.readline().strip() if line.startswith('>'): handle.seek(0) records = SeqIO.parse(handle, 'fasta') for record in records: lengths.append(len(record.seq)) aa.append(set(record.seq).issubset(AA)) else: error('NEWICK format tree was provided, but the sequence file ' 'was not in the FASTA format.') sys.exit(1) if len(set(lengths)) == 1: alignment = sequence if all(aa): trimmed = alignment else: trimmed = ''.join([utilities.basename(alignment), '.trimmed.fasta']) if os.path.isfile(trimmed): info('Using pre-existed trimmed alignment file.') else: _, trimmed = utilities.trim(alignment, outfile=trimmed) else: if aligner: aler, _ = msa._guess(aligner) outfile = ''.join([utilities.basename(sequence), '.{}.fasta'.format(aler)]) if os.path.isfile(outfile): info('Using pre-existed alignment file') alignment = outfile trimmed = ''.join( [utilities.basename(alignment), '.trimmed.fasta']) if os.path.isfile(trimmed): info('Using pre-existed trimmed alignment file.') else: _, trimmed = utilities.trim(alignment, outfile=trimmed) else: trimmed = msa.msa(aligner, sequence, verbose=verbose, outfile=outfile, trimming=True) else: error('FASTA format sequence file was provided, but no ' 'alignment program was provided.') sys.exit(1) if trimmed: if ancestor: if trimmed.endswith('.trimmed.fasta'): name = trimmed.replace('.trimmed.fasta', '') else: name = trimmed aser, _ = asr._guess(ancestor) outfile = '{}.{}.tsv'.format(utilities.basename(name), aser) if os.path.isfile(outfile): info('Using pre-existed ancestral states sequence file.') sequence = outfile else: sequence = asr.asr(ancestor, trimmed, tree, asr_model, verbose=verbose, outfile=outfile) else: error('No ancestral reconstruction program was provided.') sys.exit(1) else: sys.exit(1) tree, rate, records, aps, size = _load(sequence) return tree, rate, records, aps, size, sequence def _frequencing(record, site=True): if isinstance(record, dict): tips = [v for k, v in record.items() if not k.startswith('NODE')] else: tips = record nseq, nsites = float(len(tips)), len(tips[0]) if site: freq = [] for i in range(nsites): site = [v[i] for v in tips] freq.append([site.count(a) / nseq for a in AMINO_ACIDS]) freq = np.array(freq) else: counts = Counter(''.join(tips)) total = float(sum([v for k, v in counts.items() if k in AMINO_ACIDS])) freq = ','.join(['{:.8f}'.format(counts.get(aa, 0) / total) for aa in AMINO_ACIDS]) return freq def _prob(tree, rates, record, pos, pair, probs, pi): (t1p, t1), (t2p, t2) = pair mrca = tree.common_ancestor(t1, t2).name ancestor = record[mrca][pos] times = np.array([tree.distance(c[0], c[1]) for c in [(mrca, t1p), (t1p, t1), (mrca, t2p), (t2p, t2)]]) sf = _frequencing(record) rate = rates[pos] ts = np.around(times * rate * 10000).astype(int) anc = np.array([1 if ancestor == AMINO_ACIDS[i] else 0 for i in range(20)]) u = sf[pos, :] / pi u.shape = (1, 20) um = u.repeat(20, axis=0) pm = probs / 100 * um for i in range(20): pm[i, i] = 1 - (np.sum(pm[i, :]) - pm[i, i]) eye = np.eye(20) t1pP = np.dot(anc, np.linalg.matrix_power(pm, ts[0])) t2pP = np.dot(anc, np.linalg.matrix_power(pm, ts[2])) t1p = np.dot(eye, np.linalg.matrix_power(pm, ts[1])) t2p = np.dot(eye, np.linalg.matrix_power(pm, ts[3])) for i in range(20): t1p[i, i], t2p[i, i] = 0, 0 t1pP.shape, t2pP.shape = (20, 1), (20, 1) pc = np.sum( np.multiply(np.sum(np.multiply(t2pP, t2p), axis=0, keepdims=True), np.multiply(t1pP, t1p))) p = np.sum(np.multiply(np.multiply(t1pP, t2pP), np.multiply(t1p, t2p))) c = pc - p return p, c def _pc(tree, rates, records, aps, size, length, probs, pi, indpairs, threshold): branches, pairs = _pairing(tree, indpairs=indpairs) pars, cons, divs = defaultdict(list), defaultdict(list), defaultdict(list) details = [] detail = namedtuple('replacement', 'category position pair r1 r2 dataset') for i in range(size): record = {k: v[i] for k, v in records.items()} for pair in pairs: (t1p, t1), (t2p, t2) = pair name = '-'.join([t1, t2]) po, pe, co, ce, do = 0, 0, 0, 0, 0 for pos in range(length): if threshold and aps: s1p, p_s1p = aps[t1p][pos] if t1p in aps else (record[t1p][ pos], 1.0) s1, p_s1 = aps[t1][pos] if t1 in aps else (record[t1][ pos], 1.0) s2p, p_s2p = aps[t2p][pos] if t2p in aps else (record[t2p][ pos], 1.0) s2, p_s2 = aps[t2][pos] if t2 in aps else (record[t2][ pos], 1.0) if not all([True if float(p) >= threshold else False for p in [p_s1p, p_s1, p_s2p, p_s2]]): continue else: s1p, s1 = record[t1p][pos], record[t1][pos] s2p, s2 = record[t2p][pos], record[t2][pos] if s1p != s1 and s2p != s2: if s1 == s2: if size == 1 and i == 0: label = 'OBSERVATION' else: label = 'SIMULATION-{:05d}'.format(i + 1) r1, r2 = '{}{}'.format(s1p, s1), '{}{}'.format(s2p, s2) if s1p == s2p: po += 1 cat = 'P' else: co += 1 cat = 'C' details.append(detail(cat, pos, name, r1, r2, label)) else: if size == 1 and i == 0: label = 'OBSERVATION' else: label = 'SIMULATION-{:05d}'.format(i + 1) r1, r2 = '{}{}'.format(s1p, s1), '{}{}'.format(s2p, s2) do += 1 cat = 'D' details.append(detail(cat, pos, name, r1, r2, label)) if i == 0 and size == 1 and rates and probs is not None: p, c = _prob(tree, rates, record, pos, pair, probs, pi) pe += p ce += c if rates and probs is not None: pars[name].extend([po, pe]) cons[name].extend([co, ce]) divs[name].extend([do, 0.0]) else: pars[name].append(po) cons[name].append(co) divs[name].append(do) return tree, pars, cons, divs, details def _load_matrix(model): probs, pi = np.zeros((20, 20)), np.zeros((20,)) model = utilities.modeling(model).name if model.lower() in ('jtt', 'jones'): handle = StringIO(models['jtt']) model = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'ProtParCon', 'data', 'jtt') else: if os.path.isfile(model): handle = open(model) else: error('Unsupported model for computing expected changes, ' 'calculation aborted.') return None, None for line in handle: fields = line.strip().split() if len(fields) == 20 and all([i.replace('.', '').isdigit() for i in fields]): pi = np.array([float(i) for i in fields]) break n = 0 for line in handle: fields = line.strip().split() if len(fields) == 20 and all([i.replace('.', '').isdigit() for i in fields]): probs[n, :] = [float(field) for field in fields] n += 1 handle.close() return probs, pi def imc(sequence, tree='', aligner='', ancestor='', simulator='', asr_model='JTT', exp_model='JTT', n=100, divergent=True, indpairs=True, threshold=0.0, exp_prob=False, verbose=False): """ Identify molecular parallel and convergent changes. :param sequence: str, path to the sequence data file. Sequence data file here covers a wide range of files and formats: * sequences: raw protein sequence file, need to be in FASTA format and a NEWICK format tree is also required for argument tree. * msa: multiple sequence alignment file, need to be in FASTA format and a NEWICK format tree is also required for argument tree. * ancestors: reconstructed ancestral states file, need to be in tsv (tab separated) file, the first line needs to start with #TREE, second line needs to be a blank line, and the rest lines in the file need to be tab separated sequence name (or ID) and amino acid sequences. * simulations: simulated sequences, need to be in tsv file, the first line needs to start with #TREE, second line needs to be a blank line, each dataset need to be separated by a blank line and inside each dataset block, each line should consist of tab separated sequence name (or ID) and amino acid sequences. :param tree: str, NEWICK format tree string or tree file. This need to be set according to argument sequence. if sequence is raw sequence file or MSA file, tree is required for guiding ancestral states reconstruction. If sequence is ancestors or simulations, then tree is not necessary. :param aligner: str, executable of an alignment program. :param ancestor: str, executable of an ancestral states reconstruction program. :param simulator: str, executable of an sequence simulation program. :param asr_model: str, model name or model file for ancestral states reconstruction, default: JTT. :param exp_model: str, model name or model file for estimate expected changes based on simulation or replacement probability manipulation, default: JTT. :param n: int, number of datasets (or duplicates) should be simulated. :param divergent: bool, identify divergent changes if True, or only identify parallel and convergent changes if False. :param indpairs: bool, only identify changes for independent branch pairs if true, or identify changes for all branch pairs if False. :param threshold: float, a probability threshold that ranges from 0.0 to 1.0. If provided, only ancestral states with probability equal or larger than the threshold will be used, default: 0.0. :param exp_prob: bool, calculate the probability of expected changes if set to True and the exp_model contains a probability matrix. Time consuming process, be patient for the calculation. :param verbose: bool, invoke verbose or silent process mode, default: False, silent mode. :return: tuple, a dict object of counts of parallel replacements, a dict object of counts of convergent replacements, a list consists of details of replacements (namedtuple) and the p-value of AU Test (float or None). """ logger.setLevel(logging.INFO if verbose else logging.ERROR) if os.path.isfile(sequence): sequence = os.path.abspath(sequence) wd = os.path.dirname(sequence) else: error('Invalid sequence {}, sequence is not a file or dose not ' 'exist, exited.'.format(sequence)) sys.exit(1) basename = utilities.basename(sequence) rs = _sequencing(sequence, tree, aligner, ancestor, wd, asr_model, verbose) tree, rates, records, aps, size, sequence = rs basename_more = utilities.basename(sequence) pars, cons, divs, details, aup = None, None, None, None, None h1 = ['Category', 'BranchPair'] h2 = ['Category', 'Position', 'BranchPair', 'R1', 'R2', 'Dataset'] probs, pi = None, None if size == 1: h1.append('OBS') if exp_model: if simulator: h1.append('EXP') h1.extend(['SIM-{}'.format(i + 1) for i in range(n)]) else: if exp_prob: probs, pi = _load_matrix(exp_model) if probs is not None: h1.append('EXP') else: h1.append('EXP') h1.extend(['SIM-{}'.format(i + 1) for i in range(size)]) tips = [v[0] for k, v in records.items() if not k.startswith('NODE')] length = len(tips[0]) if size > 1: info('Estimating expected changes ... ') else: info('Identifying observed changes ...') tree, pars, cons, divs, details = _pc(tree, rates, records, aps, size, length, probs, pi, indpairs, threshold) if size == 1 and simulator: freq = _frequencing(tips, site=False) ts = tree.format('newick').strip() out = '{}.{}.tsv'.format(basename, sim._guess(simulator)[0]) s = sim.sim(simulator, ts, model=exp_model, length=length, freq=freq, n=n, outfile=out, verbose=verbose) if s and os.path.isfile(s): tree, rates, records, aps, size = _load(s) info('Estimating expected changes ... ') tree, par, con, div, detail = _pc(tree, rates, records, aps, size, length, None, None, indpairs, threshold) for k, v in par.items(): pars[k].append(np.mean(v)) cons[k].append(np.mean(con[k])) divs[k].append(np.mean(div[k])) pars[k].extend(v), cons[k].extend(con[k]) divs[k].extend(div[k]) details.extend(detail) if any([pars, cons, divs, details]): info('Writing identified parallel and convergent amino acid ' 'replacements to files.') counts = ''.join([basename_more, '.counts.tsv']) changes = ''.join([basename_more, '.details.tsv']) with open(counts, 'w') as o, open(changes, 'w') as c: o.write('{}\n'.format('\t'.join(h1))) s = lambda x: '{:.4f}'.format(x) if isinstance(x, float) else str(x) o.writelines('P\t{}\t{}\n'.format(k, '\t'.join([s(x) for x in v])) for k, v in pars.items()) o.writelines('C\t{}\t{}\n'.format(k, '\t'.join([s(x) for x in v])) for k, v in cons.items()) o.writelines('D\t{}\t{}\n'.format(k, '\t'.join([s(x) for x in v])) for k, v in divs.items()) c.write('{}\n'.format('\t'.join(h2))) c.writelines('{}\t{}\t{}\t{}\t{}\t{}\n'.format(*detail) for detail in details) return pars, cons, divs, details, length def main(): des = """Identifying parallel and convergent amino acid replacements in orthologous protein sequences""" epilog = """ Sequence data file covers a wide range of files and formats: * sequences: raw protein sequence file, need to be in FASTA format and a NEWICK format tree is also required for argument tree. * msa: multiple sequence alignment file, need to be in FASTA format and a NEWICK format tree is also required for argument tree. * ancestors: reconstructed ancestral states file, need to be in tsv (tab separated) file, the first line needs to start with #TREE, second line need to be a blank line, and the rest lines in the file need to be tab separated sequence name (or ID) and amino acid sequences. * simulations: simulated sequences, need to be in tsv file, the first line needs to start with #TREE, second line need to be a blank line, each dataset need to be separated by a blank line and inside each dataset block, each line should consist of tab separated sequence name (or ID) and amino acid sequences. """ formatter = argparse.RawDescriptionHelpFormatter parse = argparse.ArgumentParser(description=des, prog='imc', usage='%(prog)s SEQUENCE [OPTIONS]', formatter_class=formatter, epilog=epilog) parse.add_argument('SEQUENCE', help='Path to the sequence data file.') parse.add_argument('-t', '--tree', help='Path to the NEWICK format tree file.') parse.add_argument('-l', '--aligner', help='Path to the executable of an alignment program') parse.add_argument('-a', '--ancestor', help='Path to the executable of an ancestral states ' 'reconstruction program.') parse.add_argument('-s', '--simulator', help='Path to the executable of an sequence simulation ' 'program.') parse.add_argument('-m', '--asr_model', default='JTT', help='Model name or model file for ancestral states ' 'reconstruction.') parse.add_argument('-r', '--exp_model', default='JTT', help='Model name or model file for sequence simulation.') parse.add_argument('-n', '--number', default=100, type=int, help='Number of datasets (or duplicates) should be ' 'simulated.') parse.add_argument('-p', '--probability', default=0.0, type=float, help='a probability threshold that ranges from 0.0 to ' '1.0. If provided, only ancestral states with ' 'probability equal or larger than the threshold ' 'will be used, default: 0.0') parse.add_argument('-i', '--indpairs', action='store_false', help='Identify changes for all branch pairs.') parse.add_argument('-c', '--exp_prob', action='store_true', help='Calculate the probability of expected changes if ' 'the exp_model contains a probability matrix. ' 'Highly time consuming, be patient.') parse.add_argument('-v', '--verbose', action='store_true', help='Invoke verbose or silent (default) process mode.') args = parse.parse_args() s, tree = args.SEQUENCE, args.tree imc(s, tree=tree, aligner=args.aligner, ancestor=args.ancestor, simulator=args.simulator, asr_model=args.asr_model, exp_model=args.exp_model, n=args.number, exp_prob=args.exp_prob, threshold=args.probability, indpairs=args.indpairs, verbose=args.verbose) if __name__ == '__main__': main() <file_sep>.. _intro-overview: ProtParCon ========== ProtParCon is an application framework for manipulating molecular data and identifying parallel and convergent amino acid replacements at the molecular level. Although ProtParCon was not designed for implementing new methods or algorithms for molecular data manipulation, ProtParCon integrates several widely used programs for multiple sequence alignment (MSA), ancestral states reconstruction (ASR), protein sequence simulation, Maximum-Likelihood tree inference (ML Tree) and molecular convergence identification. Therefore, it can be used as a general tool to do MSA, ASR, and simulation under a common interface by using various pre-existed programs under hood. Work-Flow of ProtParCon ======================= ProtParCon processes a set of orthologous protein sequences with known phylogenetic relationships in six stages: - MSA - ASR - IDENTIFY - SIM - IDENTIFY, - TEST .. figure:: https://www.mdpi.com/genes/genes-10-00181/article_deploy/html/images/genes-10-00181-g001.png :alt: Overview of the ProtParCon analytical scheme :align: center Overview of the ProtParCon analytical scheme During the multiple sequence alignment (MSA) stage, protein sequences are aligned while gaps and ambiguous character states are trimmed. In the ancestral state reconstruction (ASR) stage, ancestral character states at each site are inferred for each internal node in the reconstructed tree. Observed parallel and convergent amino acid replacements for pairs of branches are identified in the IDENTIFY stage. Parallel replacements are denoted by P (red) and convergent replacements by C (blue). Simulations are conducted in the SIM (simulation) stage. Simulated sequences are evolved according to the following parameters: a. an evolutionary model (a replacement rate matrix) b. the branching pattern and branch lengths of the tree estimated in the ASR stage c. amino acid frequencies and sequence length estimated from the trimmed alignment. Expected parallel and convergent replacements are identified after the SIM stage or they are directly calculated if no simulation is conducted. The differences between numbers of observed and expected parallel and convergent replacements for branch pairs of interest are tested during the TEST stage. For better readability, only part of simulated sequences and detailed P&C data are shown. TSV (Tab Separated Values) format data are reformatted. Notation of branch pair, A-B, means a branch pair involving two branches that are leading to A and B, respectively. R1 and R2 represent two amino acid replacement events along two branches. The standard one-letter abbreviations for amino acids is used for the replacements. Walk-through of an example ========================== In order to show you what ProtParCon brings to the table, we'll walk you through an example using the simplest way to identify parallel and convergent amino acid replacements at the protein sequence level. Here is the code for ProtParCon identifying parallel and convergent amino acid replacements within an orthologous protein:: from ProtParCon import imc sequence = 'path/to/the/orthologous/protein/sequence' tree = 'path/to/the/phylogenetic/tree' muscle = 'path/to/the/executable/of/muscle/alignment/program' codeml = 'path/to/the/executable/of/codeml/program' evolver = 'path/to/the/executable/of/evolver/program' imc(sequence, tree, aligner=muscle, ancestor=codeml, simulator=evolver) Put the above code in a text file, name it something like `imc_analyze.py` and run the script using Python in a terminal:: $ python imc_analyze.py Wait for this to finish you will have six files in your work directory: `msa.fa`, `trimmed.msa.fa`, `ancestors.tsv`, `simulations.tsv`, `imc.counts.tsv`, and `imc.details.tsv`. From their names, you may already know what contents in these files. The `imc.counts.tsv` contains the number of parallel and convergent amino acid replacements that have been identified among all comparable branches, and it looks like this (reformatted here for better readability):: Category BranchPair OBS SIM-1 SIM-2 SIM-3 SIM-4 SIM-5 P A-B 0 0 1 1 0 1 P A-NODE10 0 0 0 0 0 0 P A-NODE11 3 2 1 0 3 2 P A-NODE13 0 2 0 1 0 2 P A-E 0 0 0 0 0 0 C A-B 0 2 1 2 2 0 C A-NODE10 0 0 0 0 0 0 C A-NODE11 0 0 0 1 1 0 C A-NODE13 0 0 1 2 0 1 The `imc.details.tsv` contains the details of parallel and convergent amino acid replacements that have been identified, e.g. replacement occurred between which branch pairs, on which position of the protein sequence, what kind of replacement, and so on. What just happened? =================== When you run the script, ``imc()`` look for a sequence file and pass it to a multiple sequence alignment program (`MUSCLE <www.drive5.com/muscle/>`_ program was used in this example), after done with the sequence alignment, ``imc()`` look for a phylogenetic tree file and pass it along with the alignment (already removed all gaps and ambiguous characters) to a ancestral sequence reconstruction program (``CODEML`` program inside `PAML <http://web.mit.edu/6.891/www/lab/paml.html>`_ package is used) to infer the ancestral states. Since a simulation program (``EVOLVER`` program inside PAML package) is specified via argument simulator, ProtParCon will automatically prepare all files needed by evolver and then use evolver to conduct sequence simulation. Once ``imc()`` all these works are done, it will start to identify parallel and convergent amino acid replacements along the protein sequence and finally save the results to text files. Here you notice that one of the main advantages about ProtParCon: sequence alignment, ancestral states reconstruction, and sequence simulation are automatically done without users calling each program step by step. This means ProtParCon already have a pipeline that chained all these processes together, users are only required to tell ProtParCon how they want the sequence to be handled and what results they want to get. Another advantage of using ProtParCon is that it provides a common interface for all supported programs, users no longer need to learn how to use the program and handle the results of these programs. While ProtParCon enables users to do very fast parallel and convergent amino acid replacement identifications (by use a single sequence file and a tree file) , ProtParCon also gives users full control of the identification process through explicitly manage the workflow step by step. Users are able to do things like choosing preferred sequence alignment program to get high quality sequence alignment, passing more parameters to ancestral states reconstruction program to get accurate ancestral states, and getting full control of sequence simulation process by explicitly using the simulation module with additional options. What else? ========== You've seen how to run fast parallel and convergent amino acid replacement identifications using general function ``imc()`` in ProtParCon package, but this is just the surface. ProtParCon provides a lot of powerful features for manipulating molecular data and makes parallelism and convergence identification even phylogenetic analysis much easier and more efficient, such as: * Built-in support for a lot of sequence alignment programs for multiple sequence alignment (MSA) using simple function. * Built-in support for a lot of phylogenetic tree inference programs for inferring best maximum likelihood tree using simple function. * Built-in support for a lot of ancestral states reconstruction programs for ancestral states reconstruction (ASR) using simple function. * Built-in support for a lot of sequence simulation programs for simulating sequences under various evolutionary scenarios using simple function. * Built-in support for identifying parallel and convergent amino acid replacements using raw orthologous sequence, multiple sequence alignment, reconstructed ancestral sequences, or even simulated sequences. What's next? ============ The next steps for you to do: install ProtParCon, follow through the pre-made examples to learn how to unleash the full power of ProtParCon, use ProtParCon in your routine work to ease the process of molecular data manipulation and molecular parallelism and convergence identification, and finally extend ProtParCon to make it support more and more programs if you are interested in ProtParCon. Thanks for you interest! See the full description and `documentation`_ of ProtParCon for more details! .. _documentation: https://ibiology.github.io/ProtParCon/ <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Query and retrieve orthologous proteins from OMA orthology Database. """ import os import sys import gzip import logging import binascii import argparse import collections from itertools import chain from urllib.request import urlretrieve, urlcleanup from Bio import SeqIO, SeqRecord LEVEL = logging.INFO LOGFILE, LOGFILEMODE = '', 'w' HANDLERS = [logging.StreamHandler(sys.stdout)] if LOGFILE: HANDLERS.append(logging.FileHandler(filename=LOGFILE, mode=LOGFILEMODE)) logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=HANDLERS, level=LEVEL) logger = logging.getLogger('[iMC]') warn, info, error = logger.warning, logger.info, logger.error OMA_SPECIES = 'https://omabrowser.org/All/oma-species.txt' OMA_GROUPS = 'https://omabrowser.org/All/oma-groups.txt.gz' OMA_SEQUENCES = 'https://omabrowser.org/All/oma-seqs.fa.gz' def _download(url): """ Private function for checking and downloading data files from OMA database if necessary. """ filename = url.split('/')[-1] if os.path.isfile(filename): info('Using pre-existed file {} from local system.'.format(filename)) else: info('Downloading {} from OMA Database.'.format(url.split('/')[-1])) filename, _ = urlretrieve(url, filename) return filename def _gz(filename): """ Private function for checking if the file is gzipped file. """ with open(filename, 'rb') as f: return binascii.hexlify(f.read(2)) == b'1f8b' def _lines(filename): """ Private function for parsing tab separated lines of regular/gzip text file into blocks. """ handle = gzip.open(filename, 'rt') if _gz(filename) else open(filename) for line in handle: if not line.startswith('#'): yield line.strip().split('\t') def _group(codes, group_file): """ Private function for retrieving orthologous groups. """ groups, size = {}, len(codes) group_temp = 'oma_temporary_groups.tsv' if os.path.isfile(group_temp): info('Loading pre-existed temporary OMA ortholog groups (oma_temporary_' 'groups.tsv) ...') for blocks in _lines(group_temp): groups[blocks[0]] = blocks[1:] else: info('Parsing OMA ortholog groups (oma-groups.txt.gz) ...') for blocks in _lines(group_file): number, finger, entries = blocks[0], blocks[1], blocks[2:] ids = [entry for entry in entries if entry[:5] in codes] if size == len(set(i[:5] for i in ids)): groups[finger] = ids if groups: with open(group_temp, 'w') as o: o.writelines('{}\t{}\n'.format(k, '\t'.join(v)) for k, v in groups.items()) info('Yield {} one-to-one ortholog groups for {} query items.'.format( len(groups), size)) return groups def _seq(codes, seq_file): """ Private function for retrieving orthologous protein sequences. """ seq_temp = 'oma_temporary_sequences.fasta' if os.path.isfile(seq_temp): info('Indexing pre-existed temporary protein sequences (' 'oma_temporary_sequences.fasta) ... ') seqs = SeqIO.index(seq_temp, 'fasta') else: info('Parsing OMA protein sequences (oma-seqs.fa.gz) ... ') handle = gzip.open(seq_file, 'rt') if _gz(seq_file) else open(seq_file) records = SeqIO.parse(handle, 'fasta') seqs = {record.id: record for record in records if record.id[:5] in codes} SeqIO.write(seqs.values(), seq_temp, 'fasta') handle.close() return seqs def oma(query, group='', seq='', outdir='', verbose=False): """ Query and retrieve 1:1 orthologous protein sequences from OMA orthology Database (https://omabrowser.org) :param query: sequence object consists of taxa IDs, OMA codes or scientific names or mix of them. For example (all these four queries will yield the same result): [9606,9913,9823,9685], ('Homo sapiens', 'Bos taurus', 'Sus scrofa', 'Felis catus'), ['HUMAN', 'BOVIN', 'PIGXX', 'FELCA'], [9606, 'BOVIN', 'Sus_scrofa', 'Felis_catus'] :param group: str, path to the OMA groups gzip (or unzipped) file stored on local drive. :param seq: str, path to the OMA sequences gzip (or unzipped) file stored on local drive. :param outdir: str, output directory, if not set, current work directory will be used. :param verbose: bool, invoke verbose or silent process mode, default: False, silent mode. :return: list, consists of absolute paths of protein sequences saved for all one-to-one orthologous groups. .. notes:: Without assigning group and/or seq, the corresponding file will be automatically downloaded from OMA Database. Orthologous protein sequence file will be saved in FASTA format using [finger].fasta as the file name. """ level = logging.INFO if verbose else logging.ERROR logger.setLevel(level) if isinstance(query, (list, tuple, collections.Iterable)): queries = [] for q in query: try: queries.append(str(q).replace('_', ' ')) except ValueError: error('Invalid query item found: {}.'.format(q)) error('Query items accept taxa ids (integer or string) or ' 'scientific names (string) or mix of them.') sys.exit(1) else: error('Invalid query, query only accepts Python sequence object.') sys.exit(1) if os.path.isdir(outdir): cwd = os.path.abspath(outdir) else: try: os.mkdir(outdir) cwd = os.path.abspath(outdir) except IOError: cwd = os.getcwd() warn('Failed to create output directory: {}, using current work ' 'directory: {} instead.'.format(outdir, cwd)) os.chdir(cwd) size = len(queries) info('Searching OMA database with {} query items ...'.format(size)) species = 'oma-species.txt' if os.path.isfile( 'oma-species.txt') else _download(OMA_SPECIES) codes = {} for blocks in _lines(species): code, taxid, name = blocks[:3] if (name in queries) or (taxid in queries) or (code in queries): codes[code] = name.replace(' ', '_') if len(codes) != size: records = list(chain.from_iterable( [(k, v.replace('_', ' ')) for k, v in codes.items()])) absent = [q for q in query if q not in records] error('The following {} query items are not found in OMA:' '\n\t{}.'.format(len(absent), ', '.join(absent))) sys.exit(1) group_file = group if os.path.isfile(group) else _download(OMA_GROUPS) groups = _group(codes, group_file) sequences = [] if groups: size = len(groups) seq_file = seq if os.path.isfile(seq) else _download(OMA_SEQUENCES) seqs = _seq(codes, seq_file) for i, (finger, entries) in enumerate(groups.items(), start=1): filename = os.path.join(cwd, '{}.fasta'.format(finger)) if os.path.isfile(filename): sequences.append(filename) else: sequence = [seqs.get(entry, None) for entry in entries] if all(sequence): sequence = [ SeqRecord.SeqRecord(s.seq, codes[s.id[:5]], '', '') for s in sequence] SeqIO.write(sequence, filename, 'fasta') sequences.append(filename) else: warn('Missing sequence was found in ortholog group: {}, ' 'skipped.'.format(finger)) info('Yield {} orthologous protein sequences for {} query ' 'items.'.format(len(sequences), size)) return sequences def main(): des = 'Query and retrieve orthologous proteins from OMA orthology Database.' epilog = """ If the query string contains scientific names, space needs to be replaced with underscore ('_'). Without assigning group and/or seq, the corresponding file will be automatically downloaded from OMA Database. Orthologous protein sequence file will be saved in FASTA format using [finger].fasta as the file name. """ formatter = argparse.RawDescriptionHelpFormatter parse = argparse.ArgumentParser(description=des, prog='ProtParCon-oma', usage='%(prog)s QUERY [OPTIONS]', formatter_class=formatter, epilog=epilog) parse.add_argument('QUERY', help='Comma separated string consists of taxa IDs, ' 'OMA codes or scientific names or mix of them.') parse.add_argument('-g', '--group', help='Path to the OMA groups gzip (or unzipped) file.') parse.add_argument('-s', '--sequence', help='Path to the OMA sequences gzip (or unzipped) ' 'file.') parse.add_argument('-o', '--output', help='Path of the output directory.') parse.add_argument('-v', '--verbose', action='store_true', help='Invoke verbose or silent (default) process mode.') args = parse.parse_args() query = args.QUERY.split(',') oma(query, group=args.group, seq=args.sequence, outdir=args.output, verbose=args.verbose) if __name__ == '__main__': main() # folder = r'C:\Users\tianz\Downloads\iparcon-dataset\oma' # taxa = [('ORNAN', 9258, 'Ornithorhynchus anatinus'), # ('TURTR', 9739, 'Tursiops truncatus'), # ('SARHA', 9305, 'Sarcophilus harrisii'), # ('FELCA', 9685, 'Felis catus'), # ('MYOLU', 59463, 'Myotis lucifugus'), # ('AILME', 9646, 'Ailuropoda melanoleuca'), # ('CANLF', 9615, 'Canis lupus familiaris'), # ('OTOGA', 30611, 'Otolemur garnettii'), # ('HORSE', 9796, 'Equus caballus'), # ('LOXAF', 9785, 'Loxodonta africana'), # ('BOVIN', 9913, 'Bos taurus'), ('SHEEP', 9940, 'Ovis aries'), # ('PIGXX', 9823, 'Sus scrofa'), # ('GORGO', 9595, 'Gorilla gorilla gorilla'), # ('CALJA', 9483, 'Callithrix jacchus'), # ('HUMAN', 9606, 'Homo sapiens'), # ('DASNO', 9361, 'Dasypus novemcinctus'), # ('MACMU', 9544, 'Macaca mulatta'), # ('RATNO', 10116, 'Rattus norvegicus'), # ('MOUSE', 10090, 'Mus musculus')] # # t1 = [t[-1] for t in taxa] # Query consists of scientific names # t2 = [t[1] for t in taxa] # Query consists of taxa ID # t3 = [t[0] for t in taxa] # Query consists of OMA codes # # index = [1, 2] * 10 # # Query consists of mix of scientific names and taxa IDs # t4 = [t[i] for t, i in zip(taxa, index)] # # index = [0, 1, 2] * 7 # # Query consists of mix of scientific names, taxa IDs, and OMA codes # t5 = [t[i] for t, i in zip(taxa, index)] # oma(t5, outdir=folder) <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Before run any test, all the executables of programs that you are going to use need to be set to their actual paths on your system accordingly, otherwise tests that using these programs will be skipped. If you want the test script do cleanup after testing, set True for CLEANUP, then all the files and directories generated during testing will be removed upon all tests finished. """ MUSCLE = 'muscle' MAFFT = 'mafft' CLUSTAL = 'clustalo' # Path to the executables of ancestral states reconstruction programs CODEML = 'codeml' RAXML = 'raxml' # Path to the executables of ML tree inference programs FASTTREE = 'FastTree' IQTREE = 'iqtree' PHYML = 'PhyML' # Path to the executables of ML tree inference programs EVOLVER = 'evolver' SEQGEN = 'seq-gen' CLEANUP = True VERBOSE = True # The following executables are used by myself, I have all these executables # installed into $HOME/bin directory and the directory is a part of $PATH. # Path to the executables of multiple sequence alignment programs # MUSCLE = 'muscle' # MUSCLE v3.8.31 # MAFFT = 'mafft' # MAFFT v7.407 (2018/Jul/23) # CLUSTAL = 'clustal' # Clustal Omega - 1.2.4 # # # Path to the executables of ancestral states reconstruction programs # CODEML = 'codeml' # PAML 4.9e # RAXML = 'raxml' # RAxML version 8.2.12 # # # Path to the executables of ML tree inference programs # FASTTREE = 'FastTree' # FastTree 2.1.10 # IQTREE = 'iqtree' # IQ-TREE multicore version 1.5.4 # PHYML = 'PhyML' # PhyML version 20120412 # # # Path to the executables of ML tree inference programs # EVOLVER = 'evolver' # PAML 4.9e # SEQGEN = 'seq-gen' # Version 1.3.4 if __name__ == '__main__': pass <file_sep>for t in `ls test_*.py` do echo "Testing $t" python $t done<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Providing a common interface for ancestral stated reconstruction (ASR) using various ASR programs. Users are only asked to provide an ASR programs's executable, an aligned multiple sequence file (in FASTA format), and a guide tree (in NEWICK) format. The general use function ``asr()`` will always return dict object containing sequence records and a tree object (generated by ``Bio.Phylo`` module inside Biopython_) or exit with an error code 1 and an error message logged. Users are recommended only to use function ``asr()`` and avoid to use any private function inside the module. However, users are strongly recommended to implement new private functions for additional ASR programs that they are interested and incorporate them into the general use function ``asr()``. .. _Biopython: https://biopython.org/ """ import os import sys import shutil import logging import argparse import tempfile from io import StringIO from subprocess import PIPE, Popen try: from textwrap import indent except ImportError: from ProtParCon.utilities import indent from Bio import Phylo, AlignIO from ProtParCon.utilities import basename, modeling, Tree from ProtParCon.models import models LEVEL = logging.INFO LOGFILE, LOGFILEMODE = '', 'w' HANDLERS = [logging.StreamHandler(sys.stdout)] if LOGFILE: HANDLERS.append(logging.FileHandler(filename=LOGFILE, mode=LOGFILEMODE)) logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=HANDLERS, level=LEVEL) logger = logging.getLogger('[iMC]') warn, info, error = logger.warning, logger.info, logger.error CODEML_MODELS = os.path.join(os.path.dirname(__file__), 'ProtParCon', 'data') RAXML_MODELS = ['DAYHOFF', 'DCMUT', 'JTT', 'MTREV', 'WAG', 'RTREV', 'CPREV', 'VT', 'BLOSUM62', 'MTMAM', 'LG', 'MTART', 'MTZOA', 'PMB', 'HIVB', 'HIVW', 'JTTD', 'CMUT', 'FLU', 'STMTREV', 'DUMMY', 'DUMMY2', 'AUTO', 'LG4M', 'LG4X', 'PROT_FILE', 'GTR_UNLINKED', 'GTR'] FASTML_MODELS = ['JTT', 'LG', 'mtREV', 'cpREV', 'WAG', 'DAYHOFF'] CTL = """ seqfile = {seq} * sequence data file name outfile = mlc * main result file name treefile = {tree} * tree structure file name noisy = 0 * 0,1,2,3,9: how much rubbish on the screen verbose = 0 * 1: detailed output, 0: concise output runmode = 0 * 0: user tree; 1: semi-automatic; 2: automatic * 3: StepwiseAddition; (4,5): PerturbationNNI; -2: pairwise seqtype = 2 * 1: codons; 2: AAs; 3: codons --> AAs clock = 0 * 0: no clock, 1: clock, 2: local clock aaRatefile = {mf} * only used for aa seqs with model=empirical_(F) model = {mn} * models for AAs or codon-translated AAs: * 0: poisson, 1: proportional, 2: Empirical, 3: Empirical+F * 6: FromCodon, 8: REVaa_0, 9: REVaa(nr=189) fix_alpha = 0 * 0: estimate gamma shape parameter; 1: fix it at alpha alpha = {alpha} * initial or fixed alpha, 0: infinity (constant rate) Malpha = 0 * different alphas for genes ncatG = {gamma} * # of categories in dG of NSsites models getSE = 0 * don't want them, 1: want S.E.s of estimates RateAncestor = 1 * (0,1,2): rates (alpha>0) or ancestral states (1 or 2) """ def _guess(exe): """ Guess the name of a ancestral states reconstruction (ASR) program according to its executable. :param exe: str, path to the executable of an ASR program. :return: tuple, name of the ASR program and the corresponding function. """ wd = tempfile.mkdtemp() try: if 'FastML_Wrapper.pl' in exe: return 'fastml', _fastml process = Popen([exe, '-h'], cwd=wd, stdout=PIPE, stderr=PIPE, universal_newlines=True) try: outs, errs = process.communicate(timeout=3) out = outs or errs if 'RAxML' in out: return 'raxml', _raxml else: return 'codeml', _codeml except Exception as exc: process.terminate() process.wait(timeout=10) return 'codeml', _codeml except OSError: error("The exe ({}) is empty or may not be an valid executable of a " "ancestral states reconstruction program.".format(exe)) sys.exit(1) finally: shutil.rmtree(wd) def _label(tree, ancestors): """ Relabel internal nodes of a tree and map them to the corresponding name of ancestral sequences. :param tree: str, a NEWICK format string or file for a tree (must start with "(" and end with ';'). :param ancestors: dict, a dict object stores sequences. :return: tuple, a relabeled tree object and a dict object for sequences. """ if isinstance(tree, str): if os.path.isfile(tree): pass elif tree.startswith('(') and tree.endswith(';'): tree = StringIO(tree) else: error('Invalid tree encounter, tree relabel aborted.') sys.exit(1) tree = Phylo.read(tree, 'newick') number, maps = tree.count_terminals(), {} for clade in tree.find_clades(): if not clade.is_terminal(): clade.confidence = None number += 1 old, new = clade.name, 'NODE{}'.format(number) maps[old] = new clade.name = new ancestors = {maps.get(k, k): v for k, v in ancestors.items()} return tree, ancestors def _parse(wd): """ Parse the rst file generated by CODEML. :param wd: str, work directory of CODEML (inside PAML_ package). :return: tuple, a tree object, a dict for sequences, and a list or rates. .. _PAML: https://www.paml.com/ """ trees, tree, sequences, probs, rates = [], None, [], [], [] ancestors, aps = {}, {} rst, rs = os.path.join(wd, 'rst'), os.path.join(wd, 'rates') if os.path.isfile(rst): with open(rst) as f: for line in f: line = line.strip() if line.startswith('(') and line.endswith(';'): trees.append(line) elif 'Prob of best state at each node' in line: break for line in f: line = line.strip() if line and line[0].isdigit() and line.endswith(')'): probs.append(line) elif 'List of extant and reconstructed sequences' in line: break for line in f: line = line.strip() if 'Overall accuracy' in line: break if line: sequences.append(line) if trees: t1 = Phylo.read(StringIO(trees[0].replace(' ', '')), 'newick') brlens = [clade.branch_length for clade in t1.find_clades()] tree = Phylo.read(StringIO(trees[2].replace(' ', '')), 'newick') for i, clade in enumerate(tree.find_clades()): clade.branch_length = float(brlens[i]) if brlens[ i] else 0.000000 name = clade.name if name and '_' in name: clade.name = name.split('_', maxsplit=1)[1] if clade.confidence: clade.name = 'NODE{}'.format(clade.confidence) clade.confidence = None else: error('Incomplete rst file encounter, no trees were found, parse ' 'rst file aborted.') sys.exit(1) if sequences: for sequence in sequences[1:]: blocks = sequence.split() if blocks[0] == 'node': name = blocks[1].replace('#', 'NODE') seq = ''.join(blocks[2:]) else: name, seq = blocks[0], ''.join(blocks[1:]) ancestors[name] = seq else: error('Incomplete rst file encounter, no ancestral sequences were ' 'found, parse rst file aborted.') sys.exit(1) # if tree and ancestors: # tree, ancestors = _label(tree, ancestors) if ancestors and probs: aps = {k: '' for k in ancestors.keys() if k.startswith('NODE')} nodes = sorted(aps.keys(), key=lambda n: int(n.replace('NODE', ''))) for prob in probs: ps = prob.split()[3:] for i, node in enumerate(nodes): aps[node] += ps[i] if os.path.isfile(rs): with open(os.path.join(wd, 'rates')) as f: for line in f: line = line.strip() if line: blocks = line.split() if len(blocks) == 5 and blocks[0].isdigit(): rates.append(float(blocks[3])) if blocks[0] == 'Site' and rates: break else: warn('\tParsing PAML result failed (not rates file was found).') else: error('Parse rst file aborted, the rst file {} does not ' 'exist'.format(rst)) sys.exit(1) return tree, ancestors, rates, aps def _write(tree, ancestor, rates, aps, outfile): """ Write tree (object) and ancestor (dict) to a output file. :param tree: object, tree object. :param ancestor: dict, dict object for sequence records. :param aps: dict, dict object for probabilities of ancestral states. :param outfile: str, path to the output file. :return: str, path to the output file. """ try: with open(outfile, 'w') as o: o.write('#TREE\t{}\n'.format(tree.format('newick'))) if rates: o.write('#RATES\t{}\n\n'.format('\t'.join([str(r) for r in rates]))) if aps: nodes = sorted(aps.keys(), key=lambda n: int(n.replace('NODE', ''))) o.writelines('#{}\t{}\n'.format(k, aps[k]) for k in nodes) o.write('\n') o.writelines('{}\t{}\n'.format(k, v) for k, v in ancestor.items()) except IOError as err: error('Write ancestral reconstruction results to file failed due to:' '\n\t{}'.format(err)) sys.exit(1) return outfile def _codeml(exe, msa, tree, model, gamma, alpha, freq, outfile): """ Reconstruct ancestral sequences using CODEML (inside PAML_ package). :param exe: str, path to the executable of an ASR program. :param msa: str, path to the MSA file (must in FASTA format). :param tree: str, path to the tree file (must in NEWICK format) or a NEWICK format tree string (must start with "(" and end with ";"). :param model: namedtuple, substitution model for ASR. :param gamma: int, The number of categories for the discrete gamma rate heterogeneity model. :param freq: str, the equilibrium frequencies of the twenty amino acids. :param alpha: float, the shape (alpha) for the gamma rate heterogeneity. :param outfile: str, path to the output file. :return: tuple, a tree object, a dict for sequences, and a list or rates. .. note:: See doc string of function ``asr()`` for details of all arguments. .. _PAML: https://www.paml.com/ """ cwd = os.getcwd() wd, tf = tempfile.mkdtemp(dir=os.path.dirname(msa)), 'codeml.tree.newick' tf = tree.file(os.path.join(wd, tf), brlen=False) if model.type == 'custom': mf = model.name info('Use custom model file {} for ancestral states ' 'reconstruction.'.format(mf)) else: name = model.name if name.lower() in models: info('Using {} model for ancestral states reconstruction.'.format( name)) with open(os.path.join(wd, name), 'w') as o: o.write(models[name.lower()]) mf = name else: error('PAML (codeml) does not support model {}.'.format(name)) sys.exit(1) parameters = {'seq': msa, 'tree': tf, 'mf': mf} if model.frequency == 'estimate': parameters['mn'] = 3 else: parameters['mn'] = 2 parameters['alpha'] = alpha if alpha else 0.5 gamma = gamma or model.gamma parameters['gamma'] = gamma if gamma else 4 with open(os.path.join(wd, 'ctl.dat'), 'w') as o: o.write(CTL.format(**parameters)) try: # No clue why stdout and stderr PIPEs are here (not in _raxml()) will cause # the following warn in unittest: # # ResourceWarning: unclosed file <_io.TextIOWrapper name=3 # encoding='cp1252'> # # ResourceWarning: unclosed file <_io.TextIOWrapper name=4 # encoding='cp1252'> info('Reconstructing ancestral states for {} using CODEML.'.format(msa)) process = Popen([exe, 'ctl.dat'], cwd=wd, stdout=PIPE, stderr=PIPE, universal_newlines=True) code = process.wait() msg = process.stdout.read() + process.stderr.read() if code: error('Ancestral reconstruction via CODEML failed for {} due to:' '\n{}'.format(msa, indent(msg, prefix='\t'))) sys.exit(1) else: info('Parsing ancestral sequence reconstruction results.') tree, ancestors, rates, aps = _parse(wd) outfile = _write(tree, ancestors, rates, aps, outfile) info('Successfully save ancestral states reconstruction ' 'results to {}.'.format(outfile)) return outfile except OSError: error('Invalid PAML (CODEML) executable {}, running CODEML failed for ' '{}.'.format(exe, msa)) sys.exit(1) finally: shutil.rmtree(wd) def _raxml(exe, msa, tree, model, gamma, alpha, freq, outfile): """ Reconstruct ancestral sequences using RAxML_. :param exe: str, path to the executable of an ASR program. :param msa: str, path to the MSA file (must in FASTA format). :param tree: str, path to the tree file (must in NEWICK format) or a NEWICK format tree string (must start with "(" and end with ";"). :param model: namedtuple, substitution model for ASR. :param gamma: int, The number of categories for the discrete gamma rate heterogeneity model. :param freq: str, the equilibrium frequencies of the twenty amino acids. :param alpha: float, the shape (alpha) for the gamma rate heterogeneity. :param outfile: str, path to the output file. :return: tuple, a tree object and a dict for sequences. .. note:: See doc string of function ``asr()`` for details of all arguments. .. _RAxML: https://sco.h-its.org/exelixis/web/software/raxml/ """ if model.type == 'custom': mf = model.name name = 'WAG' info('Use model file {} for ancestral states reconstruction.'.format(mf)) else: name = model.name if name.upper() in RAXML_MODELS: mf = '' info('Use {} model for ancestral states ' 'reconstruction.'.format(name)) else: error('RAxML does not accept {} model, aborted.'.format(name)) sys.exit(1) wd, tf = tempfile.mkdtemp(dir=os.path.dirname(msa)), 'raxml.tree.newick' tf = tree.file(os.path.join(wd, tf), brlen=False) cmd = [exe, '-f', 'A', '-s', msa, '-t', tf, '-n', 'iMC'] m = 'PROTGAMMA' if (gamma or model.gamma) else 'PROTCAT' m += name.upper() freq = 'F' if freq == 'estimate' or model.frequency == 'estimate' else 'X' if 'AUTO' not in m: m += freq cmd.extend(['-m', m]) if mf: cmd.extend(['-P', mf]) cmd.append('--silent') try: info('Reconstructing ancestral states for {} using RAxML.'.format(msa)) process = Popen(cmd, cwd=wd, stdout=PIPE, stderr=PIPE, universal_newlines=True) code = process.wait() msg = process.stdout.read() or process.stderr.read() # Sometime RAxML does not return a non-zero code when it runs error if code: error('Ancestral reconstruction via RAxML failed for {} due to:' '\n{}'.format(msa, indent(msg, prefix='\t'))) sys.exit(1) else: ancestor = os.path.join(wd, 'RAxML_marginalAncestralStates.iMC') # Check again to see if reconstruction success if not os.path.isfile(ancestor): msg = '\n'.join([line for line in msg.splitlines() if line.strip().startswith('ERROR')]) error('Ancestral reconstruction via RAxML failed for {} due to:' '\n{}'.format(msa, indent(msg, prefix='\t'))) sys.exit(1) info('Parsing ancestral sequence reconstruction results.') with open(ancestor) as handle: ancestor = dict(line.strip().split() for line in handle) tree = os.path.join(wd, 'RAxML_nodeLabelledRootedTree.iMC') tree = Phylo.read(tree, 'newick') for clade in tree.find_clades(): if clade.confidence and not clade.name: clade.name = str(clade.confidence) tree, ancestor = _label(tree, ancestor) for record in AlignIO.read(msa, 'fasta'): ancestor[record.id] = record.seq _write(tree, ancestor, [], {}, outfile) info('Successfully save ancestral states reconstruction ' 'results to {}.'.format(outfile)) return outfile except OSError as err: print(err) error('Invalid RAxML executable {}, running RAxML failed for ' '{}.'.format(exe, msa)) sys.exit(1) finally: shutil.rmtree(wd) def _fastml(exe, msa, tree, model, gamma, alpha, freq, outfile): """ Reconstruct ancestral sequences using FastML_. :param exe: str, path to the executable of an ASR program. :param msa: str, path to the MSA file (must in FASTA format). :param tree: str, path to the tree file (must in NEWICK format) or a NEWICK format tree string (must start with "(" and end with ";"). :param model: namedtuple, substitution model for ASR. :param gamma: int, The number of categories for the discrete gamma rate heterogeneity model. :param freq: str, the equilibrium frequencies of the twenty amino acids. :param alpha: float, the shape (alpha) for the gamma rate heterogeneity. :param outfile: str, path to the output file. :return: tuple, a tree object and a dict for sequences. .. note:: See doc string of function ``asr()`` for details of all arguments. .. _FastML: http://fastml.tau.ac.il/ """ if model.type == 'custom': mf = model.name name = 'JTT' info('Use model file {} for ancestral states reconstruction.'.format(mf)) else: name = model.name if name in FASTML_MODELS: mf = '' info('Use {} model for ancestral states reconstruction.'.format(name)) else: error('RAxML does not accept {} model, aborted.'.format(name)) sys.exit(1) wd, tf = tempfile.mkdtemp(dir=os.path.dirname(msa)), 'fastml.tree.newick' tf = tree.file(os.path.join(wd, tf), brlen=False) cmd = ['perl', exe, '--MSA_File', msa, '-seqType', 'AA', '--Tree', tf, '--outDir', wd] if gamma or model.gamma: cmd.extend(['--UseGamma', 'yes']) if alpha: cmd.extend(['--Alpha', str(alpha)]) try: info('Reconstructing ancestral states for {} using FastML.'.format(msa)) process = Popen(cmd, cwd=wd, stdout=PIPE, stderr=PIPE, universal_newlines=True) code = process.wait() msg = process.stdout.read() or process.stderr.read() if code: error('Ancestral reconstruction via FastML failed for {} due to:' '\n{}'.format(msa, indent(msg, prefix='\t'))) sys.exit(1) else: ancestor = os.path.join(wd, 'seq.marginal.txt') # Check again to see if reconstruction success if not os.path.isfile(ancestor): msg = '\n'.join([line for line in msg.splitlines() if line.strip().startswith('ERROR')]) error('Ancestral reconstruction via RAxML failed for {} due to:' '\n{}'.format(msa, indent(msg, prefix='\t'))) sys.exit(1) info('Parsing ancestral sequence reconstruction results.') ancestor = {a.id: a.seq for a in AlignIO.read(ancestor, 'fasta')} tree = os.path.join(wd, 'tree.newick.txt') tree = Phylo.read(tree, 'newick') _write(tree, ancestor, [], {}, outfile) info('Successfully save ancestral states reconstruction ' 'results to {}.'.format(outfile)) return outfile except OSError as err: error('Invalid FastML executable {}, running RAxML failed for ' '{}.'.format(exe, msa)) sys.exit(1) finally: shutil.rmtree(wd) def asr(exe, msa, tree, model, gamma=4, alpha=1.8, freq='', outfile='', verbose=False): """ General use function for (marginal) ancestral states reconstruction (ASR). :param exe: str, path to the executable of an ASR program. :param msa: str, path to the MSA file (must in FASTA format). :param tree: str, path to the tree file (must in NEWICK format) or a NEWICK format tree string (must start with "(" and end with ";"). :param model: str, substitution model for ASR. Either a path to a model file or a valid model string (name of an empirical model plus some other options like gamma category and equilibrium frequency option). If a model file is in use, the file format of the model file depends on the ASR program, see the its documentation for details. :param gamma: int, The number of categories for the discrete gamma rate heterogeneity model. Without setting gamma, RAxML will use CAT model instead, while CODEML will use 4 gamma categories. :param freq: str, the base frequencies of the twenty amino acids. Accept empirical, or estimate, where empirical will set frequencies use the empirical values associated with the specified substitution model, and estimate will use a ML estimate of base frequencies. :param alpha: float, the shape (alpha) for the gamma rate heterogeneity. :param outfile: str, path to the output file. Whiteout setting, results of ancestral states reconstruction will be saved using the filename `[basename].[asrer].tsv`, where basename is the filename of MSA file without known FASTA file extension, asrer is the name of the ASR program (in lower case). The first line of the file will start with '#TREE' and followed by a TAB (\t) and then a NEWICK formatted tree string, the internal nodes were labeled. The second line of the tsv file is intentionally left as a blank line and the rest lines of the file are tab separated sequence IDs and amino acid sequences. :param verbose: bool, invoke verbose or silent (default) process mode. :return: tuple, the paths of the ancestral states file. .. note:: If a tree (with branch lengths and/or internal nodes labeled) is provided, the branch lengths and internal node labels) will be ignored. If the model name combined with Gamma category numbers, i.e. JTT+G4, WAG+G8, etc., only the name of the model will be used. For all models contain G letter, a discrete Gamma model will be used to account for among-site rate variation. If there is a number after letter G, the number will be used to define number of categories in CODEML. For RAxML, the number of categories will always be set to 4 if G presented. """ level = logging.INFO if verbose else logging.ERROR logger.setLevel(level) if os.path.isfile(msa): msa = os.path.abspath(msa) else: error('Ancestral reconstruction aborted, msa {} is not a file or ' 'does not exist.'.format(msa)) sys.exit(1) tree = Tree(tree, leave=True) if not isinstance(model, str): error('Ancestral reconstruction aborted, model {} is not a valid ' 'model name or model file.'.format(model)) sys.exit(1) model = modeling(model) asrer, func = _guess(exe) if not outfile: if msa.endswith('.trimmed.fasta'): name = msa.replace('.trimmed.fasta', '') else: name = msa outfile = '{}.{}.tsv'.format(basename(name), asrer) if os.path.isfile(outfile): info('Found pre-existing ancestral state file.') else: outfile = func(exe, msa, tree, model, gamma, alpha, freq, outfile) return outfile def main(): des = 'Ancestral states reconstruction (ML method) over protein alignments.' epilog = """ The minimum requirement for running iMC-aut is an executable of a ancestral states reconstruction program, a multiple sequence alignment (MSA) file in FASTA format, and a guide tree (or topology) file in NEWICK format file or string. If a tree (with branch lengths and/or internal nodes labeled) was provided, the branch lengths and internal node labels will be ignored. All branch length will be estimated during states reconstruction and all names of internal nodes will be correspondingly relabeled to match the sequence IDs. If the model name combined with Gamma category numbers, i.e. JTT+G4, WAG+G8, ... a discrete Gamma model will be used to account for among-site rate variation. If there is a number after letter G, the number will be used to define number of categories in CODEML. Without the number, argument gamma will be checked, if not set, 4 categories will be applied to CODEML and RAxML. For RAxML, if no G in the model and no gamma was set, CAT model will be used. Ancestral states will be always saved to a tab separated text file. In case of no output filename was set via -o flag, a filename `[basename].[asrer].tsv` will be used, where basename is the filename of MSA file without known FASTA file extension, asrer is the name of the ASR program (in lower case). The first line of the file will start with '#TREE' and followed by a TAB ('\t') and then a NEWICK formatted tree string, the internal nodes were labeled. The second line of the tsv file is intentionally left as a blank line and the rest lines of the file are tab separated sequence IDs and amino acid sequences. """ formatter = argparse.RawDescriptionHelpFormatter parse = argparse.ArgumentParser(description=des, prog='ProtParCon-anc', usage='%(prog)s EXE MSA TREE [OPTIONS]', formatter_class=formatter, epilog=epilog) parse.add_argument('EXE', help='Pathname of the executable of the ancestral ' 'states reconstruction program.') parse.add_argument('MSA', help='Pathname of the multiple sequence alignment (MSA) ' 'file in FASTA format.') parse.add_argument('TREE', help='Pathname of the guide tree (or topology) file ' 'in NEWICK format.') parse.add_argument('-m', '--model', default='JTT', help='Name of the evolutionary model or filename of the ' 'model file.') parse.add_argument('-g', '--gamma', help='The number of categories for the discrete gamma ' 'rate heterogeneity model.') parse.add_argument('-a', '--alpha', help='The shape (alpha) for the gamma rate ' 'heterogeneity.') parse.add_argument('-f', '--frequency', help='Comma separated state frequencies.') parse.add_argument('-o', '--output', help='Path of the output file.') parse.add_argument('-v', '--verbose', action='store_true', help='Invoke verbose or silent (default) process mode.') args = parse.parse_args() exe, tree, msa, model = args.EXE, args.TREE, args.MSA, args.model out = args.output if args.output else '' asr(exe, msa, tree, model, gamma=args.gamma, alpha=args.alpha, freq=args.frequency, outfile=out, verbose=args.verbose) if __name__ == '__main__': main() <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import logging LEVEL = logging.INFO LOGFILE, LOGFILEMODE = '', 'w' HANDLERS = [logging.StreamHandler(sys.stdout)] if LOGFILE: HANDLERS.append(logging.FileHandler(filename=LOGFILE, mode=LOGFILEMODE)) logging.basicConfig(format='%(asctime)s %(levelname)-8s %(name)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=HANDLERS, level=LEVEL) logger = logging.getLogger('[iTOL]') warn, info, error = logger.warning, logger.info, logger.error if __name__ == '__main__': pass <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import shutil import logging import unittest PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, PATH) from ProtParCon.aut import aut sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import settings logger = logging.getLogger('[iMC]') logger.setLevel(logging.INFO if settings.VERBOSE else logging.ERROR) CLEANUP = settings.CLEANUP IQTREE = settings.IQTREE class TestAUT(unittest.TestCase): def setUp(self): self.msa = os.path.join(PATH, 'tests', 'data', 'aut', 'msa.fa') self.tree = os.path.join(PATH, 'tests', 'data', 'aut', 'tree.newick') self.trees = os.path.join(PATH, 'tests', 'data', 'aut', 'trees.newick') self.rm = '' def tearDown(self): if CLEANUP and self.rm and os.path.exists(self.rm): try: if os.path.isfile(self.rm): os.remove(self.rm) else: shutil.rmtree(self.rm) except OSError as err: logging.warning('Failed to cleanup testing data {} due to:' '\n\t{}'.format(self.rm, err)) @unittest.skipIf(IQTREE is None, 'No IQ-TREE executable was provided.') def test_aut_default(self): aup, _, _ = aut(IQTREE, self.msa, self.tree) print('AU TEST P-value: {} (test default)'.format(aup)) self.assertLessEqual(0.0, aup) # @unittest.skipIf(IQTREE is None, 'No IQ-TREE executable was provided.') # def test_aut_model(self): # aup, _, _ = aut(IQTREE, self.msa, self.tree, model='JTT') # print('AU TEST P-value: {} (test JTT model)'.format(aup)) # self.assertLessEqual(0.0, aup) # @unittest.skipIf(IQTREE is None, 'No IQ-TREE executable was provided.') # def test_aut_trees(self): # aup, _, _ = aut(IQTREE, self.msa, self.trees, model='JTT') # print('AU TEST P-value: {} (test multiple trees)'.format(aup)) # self.assertLessEqual(0.0, aup) # @unittest.skipIf(IQTREE is None, 'No IQ-TREE executable was provided.') # def test_aut_outfile(self): # out = os.path.join(PATH, 'tests', 'data', 'aut', 'iMC.autest.txt') # aup, _, _ = aut(IQTREE, self.msa, self.tree, outfile=out) # print('AU TEST P-value: {} (test outfile)'.format(aup)) # self.assertLessEqual(0.0, aup) # self.assertTrue(os.path.isfile(out)) # self.rm = out if __name__ == '__main__': unittest.main(warnings='ignore') <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import logging import unittest PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, PATH) from ProtParCon.mlt import _guess, mlt sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import settings CLEANUP = settings.CLEANUP FASTTREE = settings.FASTTREE RAXML = settings.RAXML IQTREE = settings.IQTREE PHYML = settings.PHYML MLTS = {'FastTree': FASTTREE, 'IQ-TREE': IQTREE, 'RAxML': RAXML, 'PhyML': PHYML} def _newick(filename): with open(filename) as f: line = f.readline().rstrip() return True if line.startswith('(') and line.endswith(';') else False class TestMLT(unittest.TestCase): def setUp(self): self.msa = os.path.join(PATH, 'tests', 'data', 'mlt', 'msa.fa') self.rm = '' def tearDown(self): if CLEANUP and self.rm and os.path.exists(self.rm): try: if os.path.isfile(self.rm): os.remove(self.rm) else: shutil.rmtree(self.rm) except OSError as err: logging.warning('Failed to cleanup testing data {} due to:' '\n\t{}'.format(self.rm, err)) @unittest.skipIf(not all(MLTS.values()), 'No ML tree inference program provided.') def test__guess(self): aligners = set(MLTS.keys()) self.assertSetEqual(aligners, set(_guess(a)[0] for a in MLTS.values())) @unittest.skipIf(FASTTREE is None, 'No FastTree executable was provided.') def test_fasttree_dfault(self): out = mlt(FASTTREE, self.msa) self.assertTrue(os.path.isfile(out)) self.assertTrue(_newick(out)) self.rm = out @unittest.skipIf(FASTTREE is None, 'No FastTree executable was provided.') def test_fasttree_outfile(self): out = os.path.join(PATH, 'tests', 'data', 'mlt', 'fastatree.ml.tree.newick') outfile = mlt(FASTTREE, self.msa, outfile=out) self.assertTrue(os.path.isfile(outfile)) self.assertEqual(out, outfile) self.assertTrue(_newick(out)) self.rm = out @unittest.skipIf(IQTREE is None, 'No IQ-TREE executable was provided.') def test_iqtree_dfault(self): out = mlt(IQTREE, self.msa) self.assertTrue(os.path.isfile(out)) self.assertTrue(_newick(out)) self.rm = out @unittest.skipIf(IQTREE is None, 'No IQ-TREE executable was provided.') def test_iqtree_outfile(self): out = os.path.join(PATH, 'tests', 'data', 'mlt', 'iqtree.ml.tree.newick') outfile = mlt(IQTREE, self.msa, outfile=out) self.assertTrue(os.path.isfile(outfile)) self.assertEqual(out, outfile) self.assertTrue(_newick(out)) self.rm = out @unittest.skipIf(RAXML is None, 'No RAxML executable was provided.') def test_raxml_dfault(self): out = mlt(RAXML, self.msa) self.assertTrue(os.path.isfile(out)) self.assertTrue(_newick(out)) self.rm = out @unittest.skipIf(RAXML is None, 'No RAxML executable was provided.') def test_raxml_outfile(self): out = os.path.join(PATH, 'tests', 'data', 'mlt', 'raxml.ml.tree.newick') outfile = mlt(RAXML, self.msa, outfile=out) self.assertTrue(os.path.isfile(outfile)) self.assertEqual(out, outfile) self.assertTrue(_newick(out)) self.rm = out @unittest.skipIf(PHYML is None, 'No PhyML executable was provided.') def test_phyml_dfault(self): out = mlt(PHYML, self.msa) self.assertTrue(os.path.isfile(out)) self.assertTrue(_newick(out)) self.rm = out @unittest.skipIf(PHYML is None, 'No PhyML executable was provided.') def test_phyml_outfile(self): out = os.path.join(PATH, 'tests', 'data', 'mlt', 'phyml.ml.tree.newick') outfile = mlt(PHYML, self.msa, outfile=out) self.assertTrue(os.path.isfile(outfile)) self.assertEqual(out, outfile) self.assertTrue(_newick(out)) self.rm = out if __name__ == '__main__': unittest.main(warnings='ignore') <file_sep>.. _intro-install: Install ProtParCon ================== ProtParCon runs only on Python 3.4 or above, if you are already familiar with installation of Python packages, you can easily install ProtParCon and its dependencies from PyPI with the following command on all major platforms (Windows, MacOS, or Linux): pip install ProtParCon It is strongly recommended that you install ProtParCon in a dedicated virtualenv, to avoid conflicting with your system packages. Install ProtParCon to a virtual environment (recommended) ========================================================= We recommend installing ProtParCon inside a virtual environment on all platforms. Python packages can be installed either globally (a.k.a system wide), or in a user specified space. We do not recommend installing ProtParCon system wide. Instead, we recommend that you install ProtParCon within a so-called "virtual environment" (`virtualenv`_). Virtualenvs allows users not to conflict with already-installed Python system packages (which could break some of your system tools and scripts), and still install packages normally with ``pip`` (without ``sudo`` and the likes). To get started with virtual environments, see `virtualenv installation instructions`_. .. _virtualenv: https://virtualenv.pypa.io .. _virtualenv installation instructions: https://virtualenv.pypa.io/en/stable/installation/ Things that are good to know ============================ ProtParCon is written in pure Python and depends only on standard libraries and one third party library: `Biopython`_. .. note:: `NumPy`_ is required by biopython, however, if biopython can be successfully installed as a dependency package of ProtParCon, NumPy should not be a problem. Although ProtParCon itself is platform independent, the built-in supports for many programs, e.g. MAFFT for sequence alignment, FastTree for phylogenetic tree inference, and Seq-Gen for sequence simulation may not be platform independent, it is strongly recommended that ProtParCon is used on MacOS or Linux platforms. ProtParCon is designed for providing a easy and common interface for various programs related to phylogenetic analysis and analysis of molecular parallel and convergent amino acid replacements, therefore, users are recommended to use ProtParCon inside their scripts for efficiently calling external programs and building their pipeline by chaining several external programs. .. _Biopython: https://biopython.org .. _NumPy: www.numpy.org/ <file_sep>.. _intro-usage-python: The best way to learn is with examples, and ProtParCon is no exception. For this reason, the following sections describe some pre-made examples of how to use ProtParCon to manipulate molecular sequence data and identify molecular convergences. Since ProtParCon is written in pure Python, you can use ProtParCon in any Python script or interactive Python session. Meanwhile, ProtParCon also ships a command-line toolset to you, you are able to use the command-line tools in a terminal. We will show you examples of using ProtParCon in Python and terminal separately. Use ProtParCon in Python ======================== Import ProtParCon ~~~~~~~~~~~~~~~~~ You can import ProtParCon as a module or directly import general use functions inside the module, thus the following two ways of importing are acceptable: >>> import ProtParCon >>> from ProtParCon import msa, aut, mlt, asr, imc Align multiple sequences ~~~~~~~~~~~~~~~~~~~~~~~~ Multiple sequence alignment (MSA) can be easily done in ProtParCon by using function ``msa()``, and this function has a common interface for all supported MSA programs. At this stage, MSA via MUSCLE, MAFFT, and Clustal (Omega) are supported. You are only required to pass the path to the executable of any supported MSA program and the path to a sequence file in FASTA format to function ``msa()``, ProtParCon will then take care of everything related to sequence alignment for you. The following examples assume that you have the needed MSA program installed in your system and the path to its executable is the same as used here. Otherwise, you need to replace the path to the executable of a MSA program with its actual path. In our case, the executable of MUSCLE is named `muscle` and it is already in the system path, so we are able to directly use `muscle` as the path to the MUSCLE executable. All the examples also assume that the sequence file used is in the current work directory and it is named `seq.fa`. If this is not the case for you, you need to use either a relative or absolute path of the files accordingly to make ProtParCon works as expected. This Python session will automatically align sequences using MUSCLE and save the alignment output to a file named `seq.muscle.fasta` in the same directory of the sequence file: >>> from ProtParCon import msa >>> msa('muscle', 'seq.fa') The default naming rule for alignment output will be in the format of [basename].[aligner].fasta, where basename is the filename of the sequence file without known FASTA format file's extension, aligner is the name of the MSA program (figured by ProtParCon according to the MSA's executable) in lower case, and fasta is the file extension for FASTA file. Thus, the following session will align sequence using MAFFT and save the alignment output to a FASTA format file named 'seq.mafft.fasta': >>> from ProtParCon import msa >>> msa('mafft', 'seq.fa') And this will align the same sequence with Clustal (Omega) and save the alignment to a FASTA file named 'seq.clustal.fasta': >>> from ProtParCon import msa >>> msa('clustal', 'seq.fa') .. note:: The above example assumes that you have system wide Clustal Omega installed and the string clustal point to the executable of Clustal Omega. If your Clustal Omega is not system widely installed, or the path to its executable is not `clustal`, change it accordingly. If you want to save the alignment output to a file using a customized name, you can pass a filename to argument ``outfile``. This session will align sequence using MUSCLE and save the alignment output into a file named `alignment.fasta` in the same directory of the sequence file (if you want to save the alignment to a different directory, pass a relative or absolute path accordingly): >>> from ProtParCon import msa >>> msa('muscle', 'seq.fa', outfile='alignment.fasta') Infer Maximum-Likelihood tree ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Infer Maximum-Likelihood (ML) tree can be easily done in ProtParCon by using function ``mlt()``. Since this function provides a common interface for all supported ML programs, you can use this function to infer ML tree using all supported ML programs in the same manner. At this stage, ML tree inference via IQ-TREE, FastTree, RAxML, and PhyML are supported in ProtParCon. You are only required to pass the path to the executable of any supported MSA program and the path to an alignment file in FASTA format to function ``msa()``, ProtParCon will then take care of everything about ML tree inference for you. The following examples assume you have the needed ML program installed on your system and the path to its executable is the same as used here. Otherwise, you need to replace the path to the executable of a MSA program with its actual path. In our case, the executable of IQ-TREE is named `iqtree` and it is already in the system path, so we are able to directly use `iqtree` as the path to the executable of IQ-TREE software. All the examples also assume that the alignment file used is in the current work directory and it is named `msa.fa`. If this is not the case for you, you need to use either a relative or absolute path of the files accordingly to make ProtParCon works as expected. This Python session will automatically infer ML tree using IQ-TREE and save the best ML tree to a file named `msa.IQ-TREE.ML.newick` in the same directory of the multiple sequence alignment file: >>> from ProtParCon import mlt >>> mlt('iqtree', 'msa.fa') The default naming rule for ML tree output will be in the format of [basename].[mlter].ML.newick, where basename is the filename of the alignment file without known FASTA format file's extension, mlter is the name of the ML program (figured by ProtParCon according to the ML program's executable), ML denotes that the file contains a Maximum-Likelihood tree, and newick is the file extension for NEWICK file. Thus, the following session will infer ML tree using RAxML and save the ML tree to a file named 'msa.RAxML.ML.newick': >>> from ProtParCon import mlt >>> mlt('raxml', 'msa.fa') Since ``mlt()`` provides a common interface for inferring ML tree, the other two supported ML programs can also be used in the same way. This example will infer ML tree using PjyML and save the ML tree to a file named 'msa.PhyML.ML.newick': >>> from ProtParCon import mlt >>> mlt('phyml', 'msa.fa') And, of course, this example will infer ML tree using FastTree and save the ML tree to a file named 'msa.FastTree.ML.newick': >>> from ProtParCon import mlt >>> mlt('fasttree', 'msa.fa') If you want to save the resulted ML tree to a file using a customized name, you can pass a filename to argument ``outfile``. This session will infer ML tree using RAxML and save the tree to a file named `tree.newick` in the same directory of the alignment file (if you want to save the ancestral states output to a different directory, pass a relative or absolute path accordingly): >>> from ProtParCon import mlt >>> mlt('raxml', 'msa.fa', outfile='tree.newick') Function `mlt()` also allows you to specify a substitution model for inferring a ML tree. The model can be a name of empirical substitution name (e.g. JTT, WAG, LG, ...) or a name combined with a other options (e.g. JTT+G8, LG+G8+I, WAG+G4+I+F). For example, the following example will infer ML tree using LG model with 8 Gamma categories account for among-site rate variation and estimated ML base frequencies of 20 amino acids via PhyML: >>> from ProtParCon import mlt >>> mlt('raxml', 'msa.fa', outfile='tree.newick', model='LG+G8+F') If you do not want to specify the modeling process via argument `model`, there are four other arguments: `gamma`, `alpha`, `freq`, and `invp`, that you can use to specify additional modeling information, such as number of discrete Gamma categories, shape of discrete Gamma distribution, base frequencies of 20 amino acids, and proportion of invariable site. The value specified by these arguments have high priority than the ones coming with model argument. Therefore, the following example will do the exactly same things as the above example: >>> from ProtParCon import mlt >>> mlt('raxml', 'msa.fa', outfile='tree.newick', model='LG', gamma=9, freq='estimate') You also have the option to provide a start tree and/or constraint tree to control the way in which ML tree has been inferred via arguments `start_tree` and `constraint_tree`: >>> from ProtParCon import mlt >>> mlt('raxml', 'msa.fa', outfile='tree.newick', model='LG+G8+I', start_tree='/path/to/the/start/tree/file', constraint_tree='/path/to/the/constraint/tree/file') Reconstruct ancestral states ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Ancestral states reconstruction (ASR) can be easily done in ProtParCon by using function ``asr()``, and this function has a common interface for all supported ASR programs. At this stage, ASR via CODEML (inside PAML package), and RAxML are supported. You are only required to pass the path to the executable of any supported ASR program, the path to an alignment file in FASTA format, and a guide tree file in NEWICK format to function ``asr()``, ProtParCon will then take care of everything about ancestral states reconstruction and results parsing for you. The following examples asuume you have the needed ASR program installed on your system and the path to its executable is the same as used here. Otherwise, you need to replace the path to the executable of a ASR program with its actual path. In our case, the executable of CODEML is named `codeml` and it is already in the system path, so we are able to directly use `codeml` as the path to the CODEML executable. All the examples also assume that the alignment file and the tree file used here are in the current work directory and they are named `msa.fa` and `tree.newick`. If this is not the case for you, you need to use either a relative or absolute paths of these files accordingly to make ProtParCon works as expected. This Python session will automatically reconstruct ancestral states using CODEML and save the ancestral states output to a file named `msa.codeml.tsv` in the same directory of the sequence file: >>> from ProtParCon import ars >>> asr('codeml', 'msa.fa', 'tree.nwick') The resulted ancestral states file `seq.codeml.tsv` is TAB separated file, and the first line of the file will start with '#TREE' and followed by a TAB (\t) and then a NEWICK formatted tree string, the internal nodes are labeled. The second line of the tsv file is intentionally left as a blank line and the rest lines of the file are tab separated sequence IDs and amino acid sequences. The default naming rule for ancestral states output will be in the format of [basename].[asrer].tsv, where basename is the filename of the alignment file without known FASTA format file's extension, asrer is the name of the ASR program (figured by ProtParCon according to the MSA's executable) in lower case, and fasta is the file extension for FASTA file. Thus, the following session will reconstruct ancestral states using RAxML and save the ancestral states output to a file named 'msa.raxml.tsv': >>> from ProtParCon import asr >>> asr('raxml', 'msa.fa') If you want to save the ancestral states output to a file using a customized name, you can pass the filename to argument ``outfile``. This session will reconstruct ancestral states using RAxML and save the ancestral states output to a file named `ancestors.tsv` in the same directory of the alignment file (if you want to save the ancestral states output to a different directory, pass a relative or absolute path accordingly): >>> from ProtParCon import asr >>> asr('raxml', 'msa.fa', outfile='ancestors.tsv') The default reconstruction will use JTT model as substitution model, of course you can use any supported substitution models by passing the name of the model to argument ``model``. This session will reconstruct ancestral states via CODEML using WAG model: >>> from ProtParCon import ars >>> asr('codeml', 'msa.fa', 'tree.nwick', model='WAG') Since ``asr()`` function provides a common inteface for ancestral states reconstruction, the same rule also applies to other support ASR programs, like RAxML. Thus, this session will reconstruct ancestral states via RAxML using 'WAG' model: >>> from ProtParCon import ars >>> asr('codeml', 'msa.fa', 'tree.nwick', model='WAG') The argument `model` can also pass other information for guiding state reconstruction rather than just the name of a empirical substitution model. If the model argument combined name and Gamma category numbers, i.e. JTT+G4, WAG+G8, etc., a discrete Gamma model would be used to account for among-site rate variation. If the model argument combined name and frequencies, i.e. LG+G8+F, WAG+F, etc., a ML estimate of base freqeuencies of 20 amino acids would be used instead of empirical values associated with the specified substitution model. Thus, this session will reconstruct ancestral states using LG model with 8 Gamma categories and a ML estimate of base frequencies of 20 amino acids via RAxML: >>> from ProtParCon import ars >>> asr('raxml', 'msa.fa', 'tree.nwick', model='LG+G8+F') Another way for you to providing complicted modeling information is to use these four arguments: `gamma`, `alpha`, `freq`, and `invp`, along with argument `model`. Argument `gamma` will accept a integer of number of Gamma category, `alpha` will let you specify the shape parameter of the discrete Gamma distribution, and `freq` will accept either `empirical` or `estimate` to specify how the base frequencies of 20 amino acids will be handled. Thus, the following example will do the exactly same thing as the above example: >>> from ProtParCon import ars >>> asr('raxml', 'msa.fa', 'tree.nwick', model='LG', gamma=8, freq='estimate') Moreover, ProtParCon also allows you to use a customized substitution model (or matrix) instead of the built-in empirical models in ASR programs. You can pass the model (or matrix) file to argument `model`. In this case, if you still want to provide modeling information, such as Gamma categories and shape, base frequencies of amino acid, you are required to pass all these information through `gamma`, `alpha`, and `freq`. This example shows you how you can use a specified model (or matrix) file along with complicated modeling information for ancestral states reconstruction: >>> from ProtParCon import ars >>> asr('codeml', 'msa.fa', 'tree.nwick', model='/path/to/my/own/model', gamma=8, freq='estimate') .. note:: The model (or matrix) file needs to be in the right format required by ASR programs, before use the model file, check the manual for your ASR program to make sure you model file is in the right format. Simulate protein sequences ~~~~~~~~~~~~~~~~~~~~~~~~~~ ProtParCon supports simulate proteins sequences via `EVOLVER` (inside PAML package) and Seg-Gen in Python script or interactive session using a common interface. You are only required to provide an executable of any supported simulation program and a phylogenetic tree (with branch lengths) to the general use function ``sim()``, ProtParCon will then take care everything about simulation for you. The simplest example will look like this: >>> from ProtParCon import sim >>> sim('evolver', 'tree.nwick') The above code will use EVOLVER to simulate proteins sequences along the phylogenetic tree specified in tree file `tree.newick`. ProtParCon will automatically extract the number of leaf nodes that need to be simulated from the tree file. The default simulation procedure will set the substitution model to JTT model, the length of protein sequence to 100 amino acid sites, and the number of datasets (or duplicates) to 100. Thus, after run the above code, ProtParCon will simulate protein datasets and save simulated sequences to a tab separated file. The default naming rule for simulation output will be in the format of [simulator].simulations.tsv, where simulator is the name of the simulation program you used (this will be figured by ProtParCon automatically). The resulted simulation file is a TAB separated text file, and the first line of the file will start with '#TREE' and followed by a TAB (\t) and then a NEWICK formatted tree string, the internal nodes are labeled. The second line of the tsv file is intentionally left as a blank line and the rest lines of the file are blank line separated sequence blocks, in each sequence block, each sequence takes a whole line and the sequence IDs and amino acid sequences are separated by a TAB ('\t'). The function `sim()` also allows you to simulate sequences under various scenarios. For example, the following example will use Seq-Gen to simulate 200 protein datasets with the length set to 500 amino acids and substitution model set to LG with 8 Gamma categories to account for among sites rate variation: >>> from ProtParCon import sim >>> sim('seqgen', 'tree.newick', length=500, n=200, model='LG', gamma=8) The following example will use Seq-Gen to simulate 200 protein datasets with the length and base frequencies of 20 amino acids extracted from a multiple protein sequence alignment file: >>> from ProtParCon import sim >>> sim('seqgen', 'tree.newick', n=200, model='LG', gamma=8, msa='path/to/the/multiple/sequence/alignment/file', freq='estimate', outfile='path/to/the/simulation/output/file') Since you also passed a filename to argument `outfile`, in the above example, simulated sequences and the labeled tree will be saved to the file you specified. Topology test ~~~~~~~~~~~~~ For our own purpose, the only topology test supported in ProtParCon at this stage is AU test and the test need to use IQ-TREE. The test can be easily done via function `aut` inside ProtParCon. For example, assume we have multiple sequence alignment file and a hypothesis phylogenetic relationship specified in a NEWICK tree file, we want to know how big the differences are between the phylogenetic relationship specified by the tree file and the relationship specified by the best ML tree given the MSA file, thus we can do the following: >>> from ProtParCon import aut >>> aut('iqtree', 'msa.fa', 'tree.newick', model='WAG') Running the above code will conduct AU test implemented in IQ-TREE program without knowing how to use IQ-TREE. Identify molecular convergence in proteins ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The function ``imc()`` inside ProtParCon package provides a common and easy way to identify parallel and convergent amino acid replacements in orthologous proteins separately. It is able to take the following kinds of sequence data and identify parallel and convergent amino acid replacements for all comparable branch pairs within the phylogenetic tree: * sequences: raw protein sequence file, need to be in FASTA format (a NEWICK format tree, a multiple sequence alignment program, an ancestral states reconstruction program are also required. * msa: multiple sequence alignment file, need to be in FASTA format (a NEWICK format tree and an ancestral states reconstruction program are also required). * ancestors: reconstructed ancestral states file, need to be in tsv (tab separated) file, the first line needs to start with #TREE, second line need to be a blank line, and the rest lines in the file need to be tab separated sequence name (or ID) and amino acid sequences. * simulations: simulated sequences, need to be in tsv file, the first line needs to start with #TREE, second line need to be a blank line, each dataset need to be separated by a blank line and inside each dataset block, each line should consist of tab separated sequence name (or ID) and amino acid sequences. In the simplest way, if you pass a result file generated during ancestral states reconstruction to `imc()`, parallel and convergent amino acid replacements will be identified without requiring any other information: >>> from ProtParCon import imc >>> imc('path/to/the/ancestral/states/file') After running the above code, there are two TAB separated files saved to the current work directory: 'imc.counts.tsv' and 'imc.details.tsv'. The former file contains information about the number of parallel and convergent amino acid replacements among branch pairs, while the later file contains details of each identified parallel or convergent amino acid replacement. If you are interested in identifying parallel and convergent amino acid replacements in a protein orthologous group and you also want to identify the corresponding number of parallel changes in simulated datasets based on the protein orthologous group, you can manually do sequence alignment, ancestral states reconstruction, sequence simulation, and identify parallel and convergent changes step by step, or you can just let `imc()` do all the work for you: >>> from ProtParCon import imc >>> imc('path/to/the/orthologous/file', tree='path/to/the/tree/file', aligner='path/to/the/executable/of/a/MSA/program', ancestor='path/to/the/executable/of/a/ASR/program', anc_model='LG+G8+F', simulator='path/to/the/executable/of/a/simulation/program', sim_model='LG+G8+F', wd='path/to/the/work/directory') <file_sep> API Reference ============= This section documents the ProtParCon core API, and it is intended for developers and experienced users to extend ProtParCon. msa ~~~ .. automodule:: ProtParCon.msa :members: :private-members: asr ~~~ .. automodule:: ProtParCon.asr :members: :private-members: imc ~~~ .. automodule:: ProtParCon.imc :members: :private-members: detect ~~~~~~ .. automodule:: ProtParCon.detect :members: :private-members: sim ~~~ .. automodule:: ProtParCon.sim :members: :private-members: aut ~~~ .. automodule:: ProtParCon.aut :members: :private-members: mlt ~~~ .. automodule:: ProtParCon.mlt :members: :private-members: utilities ~~~~~~~~~ .. autofunction:: ProtParCon.utilities.basename .. autofunction:: ProtParCon.utilities.modeling .. autofunction:: ProtParCon.utilities.trim .. autoclass:: ProtParCon.utilities.Tree :members: :private-members: <file_sep>Test datasets ============= This directory contains all datasets needed for running test codes and their corresponding output datasets<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- from ProtParCon import msa, asr, imc, sim, detect CLEANUP = True sequence = 'lysozyme.fa' tree = 'lysozyme.newick' # Replace the path with real path on your system muscle = 'muscle' codeml = 'codeml' evolver = 'evolver' result = imc(sequence, tree, aligner=muscle, ancestor=codeml, simulator=evolver, verbose=True) comparisons = detect() <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import shutil import logging import unittest PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) wd = os.path.join(PATH, 'tests', 'data', 'imc') sys.path.insert(0, PATH) from ProtParCon.imc import imc sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import settings logger = logging.getLogger('[iMC]') logger.setLevel(logging.INFO if settings.VERBOSE else logging.ERROR) CLEANUP = settings.CLEANUP MUSCLE = settings.MUSCLE CODEML = settings.CODEML IQTREE = settings.IQTREE EVOLVER = settings.EVOLVER SEQGEN = settings.SEQGEN class TestIMC(unittest.TestCase): def setUp(self): self.seq = os.path.join(wd, 'sequence.fa') self.msa = os.path.join(wd, 'msa.fa') self.tree = os.path.join(wd, 'tree.newick') self.asr = os.path.join(wd, 'asr.tsv') self.sim = os.path.join(wd, 'sim.tsv') self.rms = [] def tearDown(self): if CLEANUP and self.rms: for rm in self.rms: try: os.remove(os.path.join(PATH, 'tests', 'data', 'imc', rm)) except OSError as err: logging.warning('Failed to cleanup testing data {} due to:' '\n\t{}'.format(rm, err)) @unittest.skipIf((MUSCLE is None) or (CODEML is None), 'No valid executable provided.') def test_imc_seq_muscle_codeml(self): outs = {'sequence.muscle.codeml.tsv', 'sequence.muscle.codeml.counts.tsv', 'sequence.muscle.codeml.details.tsv', 'sequence.muscle.fasta', 'sequence.muscle.trimmed.fasta'} pars, cons, divs, details, _ = imc(self.seq, self.tree, aligner=MUSCLE, ancestor=CODEML) self.assertIsNotNone(pars) self.assertIsNotNone(cons) self.assertIsNotNone(divs) self.assertIsNotNone(details) self.assertTrue(outs.issubset(set(os.listdir(wd)))) self.rms = outs @unittest.skipIf((MUSCLE is None) or (CODEML is None) or (EVOLVER is None), 'No valid executable provided.') def test_imc_seq_muscle_codeml_evolver_iqtree(self): outs = {'sequence.evolver.tsv', 'sequence.muscle.codeml.tsv', 'sequence.muscle.codeml.counts.tsv', 'sequence.muscle.codeml.details.tsv', 'sequence.muscle.fasta', 'sequence.muscle.trimmed.fasta'} pars, cons, divs, details, _ = imc(self.seq, tree=self.tree, aligner=MUSCLE, ancestor=CODEML, simulator=EVOLVER) self.assertIsNotNone(pars) self.assertIsNotNone(cons) self.assertIsNotNone(divs) self.assertIsNotNone(details) self.assertTrue(outs.issubset(set(os.listdir(wd)))) self.rms = outs @unittest.skipIf((CODEML is None) or (EVOLVER is None), 'No valid executable provided.') def test_imc_msa_codeml_evolver_iqtree(self): outs = {'msa.evolver.tsv', 'msa.codeml.tsv', 'msa.codeml.counts.tsv', 'msa.codeml.details.tsv', 'msa.trimmed.fasta'} pars, cons, divs, details, _ = imc(self.msa, tree=self.tree, ancestor=CODEML, simulator=EVOLVER) self.assertIsNotNone(pars) self.assertIsNotNone(cons) self.assertIsNotNone(divs) self.assertIsNotNone(details) self.assertTrue(outs.issubset(set(os.listdir(wd)))) self.rms = outs @unittest.skipIf(EVOLVER is None, 'No valid executable provided.') def test_imc_asr_evolver_iqtree(self): outs = {'asr.counts.tsv', 'asr.details.tsv'} pars, cons, divs, details, _ = imc(self.asr) self.assertIsNotNone(pars) self.assertIsNotNone(cons) self.assertIsNotNone(divs) self.assertIsNotNone(details) self.assertTrue(outs.issubset(set(os.listdir(wd)))) self.rms = outs def test_imc_threshold(self): outs = {'sequence.muscle.codeml.tsv', 'sequence.muscle.codeml.counts.tsv', 'sequence.muscle.codeml.details.tsv', 'sequence.muscle.fasta', 'sequence.muscle.trimmed.fasta'} pars, cons, divs, details, _ = imc(self.seq, self.tree, aligner=MUSCLE, ancestor=CODEML, threshold=0.5) self.assertIsNotNone(pars) self.assertIsNotNone(cons) self.assertIsNotNone(divs) self.assertIsNotNone(details) self.assertTrue(outs.issubset(set(os.listdir(wd)))) self.rms = outs if __name__ == '__main__': unittest.main(warnings='ignore') <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Providing a common interface for inferring phylogenetic trees from alignments of protein sequences using maximum-likelihood method. The minimum requirement for using this module is a multiple sequence alignment (MSA) file and an executable of a maximum-likelihood tree inference program. If user wants to take full control of the tree inference, optional parameters are also accepted depend on the program. Without providing an evolutionary model, the default model (JTT model for FastTree and LG model for PhyML) or a model decided by model selection procedure (RAxML and IQ-TREE) will be used. Users are recommended to only use function ``mlt()`` and avoid to use any private functions in this module. However, users are strongly recommended to implement new private functions for additional maximum-likelihood tree inference program that they are interested and incorporate them into the general use function ``mlt()``. .. TODO:: It seems FastTree does not accept FASTA format file which has a space between '>' and the sequence name (or ID), should check FASTA file before feed in. """ import os import re import sys import random import shutil import logging import tempfile import argparse try: from textwrap import indent except ImportError: from ProtParCon.utilities import indent from collections import namedtuple from subprocess import PIPE, Popen, DEVNULL from Bio import Phylo, AlignIO from ProtParCon.utilities import basename, modeling LEVEL = logging.INFO LOGFILE, LOGFILEMODE = '', 'w' HANDLERS = [logging.StreamHandler(sys.stdout)] if LOGFILE: HANDLERS.append(logging.FileHandler(filename=LOGFILE, mode=LOGFILEMODE)) logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=HANDLERS, level=LEVEL) logger = logging.getLogger('[iMC]') warn, info, error = logger.warning, logger.info, logger.error FASTTREE_MODELS = ['jtt', 'lg', 'wag'] IQTREE_MODELS = ['BLOSUM62', 'cpREV', 'Dayhoff', 'DCMut', 'FLU', 'HIVb', 'HIVw', 'JTT', 'JTTDCMut', 'LG', 'mtART', 'mtMAM', 'mtREV', 'mtZOA', 'mtMet', 'mtVer', 'mtInv', 'Poisson', 'PMB', 'rtREV', 'VT', 'WAG', 'GTR20'] RAXML_MODELS = ['DAYHOFF', 'DCMUT', 'JTT', 'MTREV', 'WAG', 'RTREV', 'CPREV', 'VT', 'BLOSUM62', 'MTMAM', 'LG', 'MTART', 'MTZOA', 'PMB', 'HIVB', 'HIVW', 'JTTD', 'CMUT', 'FLU', 'STMTREV', 'DUMMY', 'DUMMY2', 'AUTO', 'LG4M', 'LG4X', 'PROT_FILE', 'GTR_UNLINKED', 'GTR'] PHYML_MODELS = ['Blosum62', 'CpREV', 'DCMut', 'Dayhoff', 'HIVb', 'HIVw', 'JTT', 'MtArt', 'MtMam', 'MtREV', 'RtREV', 'VT', 'WAG'] MODEL = namedtuple('model', 'name frequency gamma rates invp type') def _guess(exe): """ Guess the name of a tree inference program according to its executable. :param exe: str, path to the executable of an maximum-likelihood tree inference program. :return: tuple, name of the program and the corresponding function. """ programs, func = {'FastTree': _fasttree, 'IQ-TREE': _iqtree, 'RAxML': _raxml, 'PhyML': _phyml}, None if exe: try: process = Popen([exe, '-h'], stdout=PIPE, stderr=PIPE, universal_newlines=True) outs, errs = process.communicate(timeout=10) out = outs or errs for name in programs.keys(): if name in out[:50]: return name, programs[name] error('Unknown exe: {}, the exe may not be an acceptable tree ' 'inference program, exited.') sys.exit(1) except OSError: error('Invalid exe: {}, exe does not exist, exited.'.format(exe)) sys.exit(1) else: error('The exe of a tree inference program is empty, exited.') sys.exit(1) def _fasttree(exe, msa, model, cat, gamma, alpha, freq, invp, start_tree, constraint_tree, seed, outfile): """ Infer ML phylogenetic tree using FastTree. """ if model.type == 'custom': error('Invalid model, FastTree does not accept custom model file ' '{}.'.format(model)) sys.exit(1) else: name = model.name if model.name else 'JTT' if name.lower() == 'jtt': info('Inferring ML tree using JTT model.') m = '' else: if name.lower in ['lg', 'wag']: info('Inferring ML tree using {} model.'.format( model.upper())) m = '-{}'.format(name) else: error('Invalid model {}, FastTree only accepts JTT, WAG, ' 'and LG model.'.format(name)) sys.exit(1) info('Inferring ML tree for {} using FastTree.'.format(msa)) args = [exe, '-quiet', '-nopr', '-seed', str(seed)] if start_tree and os.path.isfile(start_tree): args.extend(['-intree', start_tree]) if m: args.append(m) if gamma or model.gamma: args.append('-gamma') if cat: if cat != 20: args.extend(['-cat', str(cat)]) else: args.append('-nocat') args.append(os.path.basename(msa)) tree = outfile if outfile else '{}.FastTree.ML.newick'.format(basename(msa)) try: info('Running FastTree using the following command:\n\t' '{}'.format(' '.join(args))) with open(tree, 'w') as stdout: process = Popen(args, cwd=os.path.dirname(msa), stdout=stdout, stderr=PIPE, universal_newlines=True) code = process.wait() if code: msg = indent(process.stderr.read(), prefix='\t') print(msg) error('Inferring ML tree failed for {}\n{}'.format(msa, msg)) if os.path.isfile(tree): os.remove(tree) sys.exit(1) else: info('Successfully save inferred ML tree to {}.'.format(tree)) except OSError: error('Inferring ML tree failed for {}, executable (exe) {} of ' 'FastTree is empty or invalid.'.format(msa, exe)) if os.path.isfile(tree): os.remove(tree) sys.exit(1) return tree def _iqtree(exe, msa, model, cat, gamma, alpha, freq, invp, start_tree, constraint_tree, seed, outfile): """ Infer ML phylogenetic tree using IQ-TREE. """ wd = tempfile.mkdtemp(dir=os.path.dirname(os.path.abspath(msa))) shutil.copy(msa, os.path.join(wd, 'msa.fa')) if model.name: name = model.name.upper() if model.type == 'builtin': frequency = freq or model.frequency if frequency == 'estimate': frequency = 'FO' else: frequency = 'F' invpro = 'I' if (invp or model.invp) else '' gamma = gamma or model.gamma gamma = 'G{}'.format(gamma) if gamma else '' cat = cat if cat not in ('None', 'none', None) else 0 rates = cat or model.rates rates = 'R{}'.format(rates) if rates else '' m = ['-m', '+'.join((i for i in [name, frequency, invpro, gamma, rates] if i))] else: m = ['-mdef', model.name] else: m = ['-m', 'TEST'] info('Inferring ML tree for {} using IQ-TREE.'.format(msa)) # iqtree_cmd = 'exe -s seq -t user_tree -pre prefix -nt 1 -seed seed # -quiet -m MFP -g constraint_tree' args = [exe, '-s', 'msa.fa', '-nt', '1', '-pre', 'tmf', '-seed', str(seed)] args.extend(m) # args.append('-quiet') if gamma and alpha: args.extend(['-a', str(alpha)]) if invp: args.extend(['-i', str(invp)]) if constraint_tree: args.extend(['-g', constraint_tree]) try: # info('Running IQTree using the following command:\n\t' # '{}'.format(' '.join(args))) process = Popen(args, cwd=wd, stdout=PIPE, stderr=PIPE, universal_newlines=True) code = process.wait() if code: msg = indent(process.stderr.read(), prefix='\t') error('Inferring ML tree failed for {}\n{}'.format(msa, msg)) sys.exit(1) else: tree = outfile if outfile else '{}.IQ-TREE.ML.newick'.format( basename(msa)) try: tree = shutil.copy(os.path.join(wd, 'tmf.treefile'), tree) info('Successfully save inferred gene tree to {}.'.format( tree)) except OSError: error('Path of outfile {} is not writeable, saving tree to ' 'file failed.'.format(tree)) sys.exit(1) except OSError: error('Inferring tree failed for {}, executable (exe) {} of ' 'IQ-TREE is invalid.'.format(msa, exe)) sys.exit(1) finally: shutil.rmtree(wd) return tree def _raxml(exe, msa, model, cat, gamma, alpha, freq, invp, start_tree, constraint_tree, seed, outfile): """ Infer ML phylogenetic tree using RAxML. """ wd = tempfile.mkdtemp(dir=os.path.dirname(os.path.abspath(msa))) shutil.copy(msa, os.path.join(wd, 'msa.fa')) if model.type == 'builtin': frequency = freq or model.frequency frequency = 'X' if frequency == 'estimate' else 'F' gamma = gamma or model.gamma invpro = 'I' if (model.invp or invp) else '' gamma = 'GAMMA' if gamma else 'CAT' if model.name: mm = ''.join(['PROT', gamma, invpro, model.name.upper(), frequency]) model = ['-m', mm] else: model = ['-m', ''.join(['PROT', invpro, gamma, 'AUTO'])] else: model = ['-P', model.name] info('Inferring ML tree for {} using RAxML.'.format(msa)) args = [exe, '-s', 'msa.fa', '-n', 'RAxML', '-p', str(seed), '--silent'] args.extend(model) cat = cat if cat not in ('None', 'none', None) else 0 if cat: args.extend(['-c', str(cat)]) if start_tree: args.extend(['-t', start_tree]) if constraint_tree: args.extend(['-r', constraint_tree]) try: # info('Running FastTree using the following command:\n\t' # '{}'.format(' '.join(args))) process = Popen(args, cwd=wd, stdout=DEVNULL, stderr=PIPE, universal_newlines=True) code = process.wait() if code: msg = indent(process.stderr.read(), prefix='\t') error('Tree inferring failed for {}\n{}'.format(msa, msg)) tree = '' else: tree = outfile if outfile else '{}.RAxML.ML.newick'.format( basename(msa)) try: tree = shutil.copy(os.path.join(wd, 'RAxML_bestTree.RAxML'), tree) info('Successfully save inferred ML tree to {}.'.format( tree)) except OSError: error('Path of outfile {} is not writeable, saving tree to ' 'file failed.'.format(tree)) sys.exit(1) except OSError: error('Tree inferring failed for {}, executable (exe) {} is ' 'invalid.'.format(msa, exe)) sys.exit(1) finally: shutil.rmtree(wd) return tree def _phyml(exe, msa, model, cat, gamma, alpha, freq, invp, start_tree, constraint_tree, seed, outfile): """ Infer ML phylogenetic tree using PhyML. """ # cmd = 'exe -i seq -d aa -m JTT -f e|m -v invariable -c 4 -a gamma-alpha # --quiet --r_seed num -u user_tree_file' wd = tempfile.mkdtemp(dir=os.path.dirname(os.path.abspath(msa))) alignment = 'temporary.alignment.phylip' AlignIO.convert(msa, 'fasta', os.path.join(wd, alignment), 'phylip') if model.type == 'builtin': m = ['-m', model.name] if model.name else ['-m', 'LG'] else: m = ['-m', 'custom', '--aa_rate_file', model.name] info('Inferring ML tree for {} using PhyML.'.format(msa)) args = [exe, '-i', alignment, '-d', 'aa', '--r_seed', str(seed), '--quiet'] args.extend(m) cat = cat if cat not in ('None', 'none', None) else 0 if cat: args.extend(['--free_rates', cat]) gamma = gamma or model.gamma if gamma: args.extend(['-c', str(gamma)]) if alpha: args.extend(['-a', str(alpha)]) frequency = freq or model.frequency frequency = 'X' if frequency == 'estimate' else 'F' if frequency == 'estimate': args.extend(['-f', 'e']) else: args.extend(['-f', 'm']) if start_tree: args.extend(['-u', start_tree]) if constraint_tree: args.extend(['--constraint_file', constraint_tree]) if model.invp: if invp: args.extend(['-v', str(invp)]) else: args.extend(['-v', 'e']) else: if invp: args.extend(['-v', str(invp)]) try: # info('Running FastTree using the following command:\n\t' # '{}'.format(' '.join(args))) process = Popen(args, cwd=wd, stdout=PIPE, stderr=PIPE, universal_newlines=True) code = process.wait() if code: msg = process.stderr.read() or process.stdout.read() msg = indent(msg, prefix='\t') error('Tree inferring failed for {}\n{}'.format(msa, msg)) sys.exit(1) else: tree = outfile if outfile else '{}.PhyML.ML.newick'.format( basename(msa)) try: out = '{}{}'.format(os.path.join(wd, alignment), '_phyml_tree.txt') tree = shutil.copy(out, tree) info('Successfully save inferred ML tree to {}.'.format( tree)) except OSError: error('Path of outfile {} is not writeable, saving tree to ' 'file failed.'.format(tree)) sys.exit(1) except OSError: error('Tree inferring failed for {}, executable (exe) {} of PhyML ' 'is invalid.'.format(msa, exe)) sys.exit(1) finally: shutil.rmtree(wd) return tree def mlt(exe, msa, model='', cat=0, gamma=0, alpha=0.0, freq='empirical', invp=0.0, start_tree='', constraint_tree='', seed=0, outfile='', verbose=False): """ Common interface for inferring ML phylogenetic tree. :param msa: str, path of the multiple sequence alignment (FASTA) file. :param exe: str, path of the executable of the ML tree inference program. :param model: str, name of the model or path of the model file. :param cat: int, invoke rate heterogeneity (CAT) model and set the number of categories to the corresponding number cat, if CAT model is not in use, it will be ignored. When FastTree is in use, set cat=None to invoke nocat mode. :param gamma: int, 0 means discrete Gamma model not in use, any positive integer larger than 1 will invoke discrete Gamma model and set the number of categories to gamma. :param alpha: float, the Gamma shape parameter alpha, without setting, the value will be estimated by the program, in case an initial value is needed, the initial value of alpha will be set to 0.5. :param freq: str, the base frequencies of the twenty amino acids. Accept empirical, or estimate, where empirical will set frequencies use the empirical values associated with the specified substitution model, and estimate will use a ML estimate of base frequencies. :param invp: float, proportion of invariable site. :param start_tree: str, path of the starting tree file, the tree file must be in NEWICK format. :param constraint_tree: str, path of the constraint tree file, the tree file muse be in NEWICK format. :param seed: int, the seed used to initiate the random number generator. :param outfile: pathname of the output ML tree. If not set, default name [basename].[program].ML.newick, where basename is the filename of the sequence file without extension, program is the name of the ML inference program, and newick is the extension for NEWICK format tree file. :param verbose: bool, invoke verbose or silent process mode, default: False, silent mode. :return: path of the maximum-likelihood tree file. """ level = logging.INFO if verbose else logging.ERROR logger.setLevel(level) if not os.path.isfile(msa): error('Alignment {} is not a file or does not exist.'.format(msa)) sys.exit(1) program, func = _guess(exe) if program == 'FastTree': if cat in ('None', 'none', None): cat = 0 else: cat = 20 try: seed = int(seed) if seed else random.randint(0, 10000) except ValueError: warn('Invalid seed, generating seed using random number generator.') seed = random.randint(0, 10000) model = modeling(model) tree = func(exe, msa, model=model, cat=cat, gamma=gamma, alpha=alpha, freq=freq, invp=invp, start_tree=start_tree, seed=seed, constraint_tree=constraint_tree, outfile=outfile) return tree def main(): des = 'Infer maximum likelihood phylogenetic tree from protein alignments.' epilog = """ The minimum requirement for running iMC-mlt is a multiple sequence alignment (MSA) file and an executable of a maximum-likelihood tree inference program. If user want to take full control of the tree inference, optional parameters are also accepted depend on the program. Without provide an evolutionary model, the default model (JTT model for FastTree and LG model for PhyML) or a model decided by model selection procedure (RAxML and IQ-TREE) will be used. The model needs to be in the format of MODEL+<FreqType>+<RateType> or a model (text) file, where MODEL is a model name (e.g. JTT, WAG, ...), FreqType decides how the model will handle amino acid frequency (e.g. F, empirical AA frequencies from the data; FO, ML optimized AA frequencies from the data or FQ, Equal AA frequencies). Some options (e.g. start tree, constraint tree) may not supported by all of the four programs, they will be automatically ignored. """ formatter = argparse.RawDescriptionHelpFormatter parse = argparse.ArgumentParser(description=des, prog='ProtParCon-mlt', usage='%(prog)s EXECUTABLE MSA [OPTIONS]', formatter_class=formatter, epilog=epilog) parse.add_argument('EXECUTABLE', help='Pathname of the executable of the tree inference ' 'program.') parse.add_argument('MSA', help='Pathname of the alignment file in fasta format.') parse.add_argument('-m', '--model', help='Name of the evolutionary model or filename of the ' 'model file.') parse.add_argument('-c', '--category', help='Invoke CAT model and set the number of ' 'categories to value of cat.', default=0) parse.add_argument('-g', '--gamma', default=0, help='Invoke discrete Gamma model and set the number of ' 'categories to value of gamma.') parse.add_argument('-a', '--alpha', help='The Gamma shape parameter alpha.') parse.add_argument('-f', '--frequency', help='Amino acid frequency, either m or e.') parse.add_argument('-i', '--invp', help='Proportion of invariable sites.') parse.add_argument('-p', '--stree', help='Path of the starting tree file.') parse.add_argument('-q', '--ctree', help='Path of the constraint tree file.') parse.add_argument('-s', '--seed', help='The seed for initiating the random number ' 'generator.') parse.add_argument('-o', '--output', help='Pathname of the ML tree output file.') parse.add_argument('-v', '--verbose', action='store_true', help='Invoke verbose or silent (default) process mode.') args = parse.parse_args() msa, exe = args.MSA, args.EXECUTABLE mlt(exe, msa, model=args.model, cat=args.category, gamma=args.gamma, alpha=args.alpha, freq=args.frequency, invp=args.invp, start_tree=args.stree, constraint_tree=args.ctree, seed=args.seed, verbose=args.verbose) if __name__ == '__main__': main() <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import logging import unittest PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATA = os.path.join(PATH, 'tests', 'data', 'msa') sys.path.insert(0, PATH) from ProtParCon.msa import _guess, msa sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import settings CLEANUP = settings.CLEANUP MUSCLE = settings.MUSCLE MAFFT = settings.MAFFT CLUSTAL = settings.CLUSTAL ALIGNERS = {'muscle': MUSCLE, 'mafft': MAFFT, 'clustal': CLUSTAL} # It seems use PIPE in Popen will cause a warning: # ResourceWarning: unclosed file <_io.TextIOWrapper ... > # No best solution for now, will work on it in future. class MSATest(unittest.TestCase): def setUp(self): self.seq = os.path.join(DATA, 'sequence.fa') self.rm = '' def tearDown(self): if self.rm and os.path.isfile(self.rm): try: os.remove(self.rm) except OSError: logging.warning('MSA testing generated a output file: {} the ' 'file was not deleted.'.format(self.rm)) pass @unittest.skipIf(not all(ALIGNERS.values()), 'No aligners were provided.') def test_guess(self): aligners = set(ALIGNERS.keys()) self.assertSetEqual(aligners, set(_guess(a)[0] for a in ALIGNERS.values())) @unittest.skipIf(MUSCLE is None, 'No MUSCLE executable was provided.') def test_muscle_default(self): aln = msa(MUSCLE, self.seq) self.assertTrue(os.path.isfile(aln)) self.rm = aln @unittest.skipIf(MUSCLE is None, 'No MUSCLE executable was provided.') def test_muscle_outfile(self): out = self.seq.replace('sequence.fa', 'msa.out.muscle.fa') aln = msa(MUSCLE, self.seq, outfile=out) self.assertTrue(os.path.isfile(aln)) self.assertEqual(out, aln) self.rm = aln @unittest.skipIf(MAFFT is None, 'No MAFFT executable was provided.') def test_mafft_default(self): aln = msa(MAFFT, self.seq) self.assertTrue(os.path.isfile(aln)) self.rm = aln @unittest.skipIf(MAFFT is None, 'No MAFFT executable was provided.') def test_mafft_outfile(self): out = self.seq.replace('sequence.fa', 'msa.out.mafft.fa') aln = msa(MAFFT, self.seq, outfile=out) self.assertTrue(os.path.isfile(aln)) self.assertEqual(out, aln) self.rm = aln @unittest.skipIf(CLUSTAL is None, 'No CLUSTAL executable was provided.') def test_clustal_default(self): aln = msa(CLUSTAL, self.seq) self.assertTrue(os.path.isfile(aln)) self.rm = aln @unittest.skipIf(CLUSTAL is None, 'No CLUSTAL executable was provided.') def test_clustal_outfile(self): out = self.seq.replace('sequence.fa', 'msa.out.clustal.fa') aln = msa(CLUSTAL, self.seq, outfile=out) self.assertTrue(os.path.isfile(aln)) self.assertEqual(out, aln) self.rm = aln if __name__ == '__main__': unittest.main(warnings='ignore') <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import logging import unittest PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, PATH) from ProtParCon.asr import _guess, asr sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import settings CLEANUP = settings.CLEANUP CODEML = settings.CODEML RAXML = settings.RAXML ASR = {'codeml': CODEML, 'raxml': RAXML} class TestASR(unittest.TestCase): def setUp(self): self.msa = os.path.join(PATH, 'tests', 'data', 'asr', 'msa.fa') self.tree = os.path.join(PATH, 'tests', 'data', 'asr', 'tree.newick') self.rm = '' def tearDown(self): if CLEANUP and self.rm and os.path.isfile(self.rm): try: os.remove(self.rm) except OSError: logging.warning('MSA testing generated a output file: {} the ' 'file was not deleted.'.format(self.rm)) pass @unittest.skipIf(not all(ASR.values()), 'No ASR program provided.') def test__guess(self): aligners = set(ASR.keys()) aligner = set(_guess(a)[0] for a in ASR.values() if a) self.assertTrue(aligner.issubset(aligners)) @unittest.skipIf(CODEML is None, 'No CODEML executable was provided.') def test_codeml_dfault(self): out = asr(CODEML, self.msa, self.tree, 'JTT') self.assertTrue(os.path.isfile(out)) self.rm = out @unittest.skipIf(CODEML is None, 'No CODEML executable was provided.') def test_codeml_outfile(self): out = os.path.join(PATH, 'tests', 'data', 'asr', 'codeml.ancestors.tsv') outfile = asr(CODEML, self.msa, self.tree, 'JTT', outfile=out) self.assertTrue(os.path.isfile(outfile)) self.assertEqual(out, outfile) self.rm = out @unittest.skipIf(RAXML is None, 'No RAxML executable was provided.') def test_raxml_default(self): out = asr(RAXML, self.msa, self.tree, 'JTT') self.assertTrue(os.path.isfile(out)) self.rm = out @unittest.skipIf(RAXML is None, 'No RAxML executable was provided.') def test_raxml_outfile(self): out = os.path.join(PATH, 'tests', 'data', 'asr', 'raxml.ancestors.tsv') outfile = asr(RAXML, self.msa, self.tree, 'JTT', outfile=out) self.assertTrue(os.path.isfile(outfile)) self.assertEqual(out, outfile) self.rm = out if __name__ == '__main__': unittest.main(warnings='ignore') <file_sep>.. _topics-index: ================================== ProtParCon |version| documentation ================================== This documentation contains everything you need to know about ProtParCon. .. toctree:: :caption: Knowing ProtParCon overview .. toctree:: :caption: Installing ProtParCon install .. toctree:: :caption: Using ProtParCon usage-python usage-shell .. toctree:: :caption: Extending ProtParCon api <file_sep> <!DOCTYPE html> <!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>imc.utilities &mdash; ProtParCon 1.0 documentation</title> <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" /> <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> <link rel="index" title="Index" href="../../genindex.html" /> <link rel="search" title="Search" href="../../search.html" /> <script src="../../_static/js/modernizr.min.js"></script> </head> <body class="wy-body-for-nav"> <div class="wy-grid-for-nav"> <nav data-toggle="wy-nav-shift" class="wy-nav-side"> <div class="wy-side-scroll"> <div class="wy-side-nav-search"> <a href="../../index.html" class="icon icon-home"> ProtParCon </a> <div class="version"> 1.0 </div> <div role="search"> <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get"> <input type="text" name="q" placeholder="Search docs" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation"> <p class="caption"><span class="caption-text">Knowing ProtParCon</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../../overview.html">ProtParCon at a glance</a></li> <li class="toctree-l1"><a class="reference internal" href="../../overview.html#walk-through-of-an-example">Walk-through of an example</a></li> <li class="toctree-l1"><a class="reference internal" href="../../overview.html#what-just-happened">What just happened?</a></li> <li class="toctree-l1"><a class="reference internal" href="../../overview.html#what-else">What else?</a></li> <li class="toctree-l1"><a class="reference internal" href="../../overview.html#what-s-next">What’s next?</a></li> </ul> <p class="caption"><span class="caption-text">Installing ProtParCon</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../../install.html">Install ProtParCon</a></li> <li class="toctree-l1"><a class="reference internal" href="../../install.html#install-protparcon-to-a-virtual-environment-recommended">Install ProtParCon to a virtual environment (recommended)</a></li> <li class="toctree-l1"><a class="reference internal" href="../../install.html#things-that-are-good-to-know">Things that are good to know</a></li> </ul> <p class="caption"><span class="caption-text">Using ProtParCon</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../../usage-python.html">Use ProtParCon in Python</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../usage-python.html#import-protparcon">Import ProtParCon</a></li> <li class="toctree-l2"><a class="reference internal" href="../../usage-python.html#align-multiple-sequences">Align multiple sequences</a></li> <li class="toctree-l2"><a class="reference internal" href="../../usage-python.html#infer-maximum-likelihood-tree">Infer Maximum-Likelihood tree</a></li> <li class="toctree-l2"><a class="reference internal" href="../../usage-python.html#reconstruct-ancestral-states">Reconstruct ancestral states</a></li> <li class="toctree-l2"><a class="reference internal" href="../../usage-python.html#simulate-protein-sequences">Simulate protein sequences</a></li> <li class="toctree-l2"><a class="reference internal" href="../../usage-python.html#topology-test">Topology test</a></li> <li class="toctree-l2"><a class="reference internal" href="../../usage-python.html#identify-molecular-convergence-in-proteins">Identify molecular convergence in proteins</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../usage-shell.html">Using ProtParCon in terminal</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../usage-shell.html#check-protparcon-command-line-toolsets">Check ProtParCon command-line toolsets</a></li> <li class="toctree-l2"><a class="reference internal" href="../../usage-shell.html#using-toolsets-in-terminal">Using toolsets in terminal</a></li> </ul> </li> </ul> <p class="caption"><span class="caption-text">Extending ProtParCon</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../../api.html">API Reference</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../api.html#module-ProtParCon.msa">msa</a></li> <li class="toctree-l2"><a class="reference internal" href="../../api.html#module-ProtParCon.asr">asr</a></li> <li class="toctree-l2"><a class="reference internal" href="../../api.html#module-ProtParCon.imc">imc</a></li> <li class="toctree-l2"><a class="reference internal" href="../../api.html#module-ProtParCon.sim">sim</a></li> <li class="toctree-l2"><a class="reference internal" href="../../api.html#module-ProtParCon.aut">aut</a></li> <li class="toctree-l2"><a class="reference internal" href="../../api.html#module-ProtParCon.mlt">mlt</a></li> <li class="toctree-l2"><a class="reference internal" href="../../api.html#utilities">utilities</a></li> </ul> </li> </ul> </div> </div> </nav> <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"> <nav class="wy-nav-top" aria-label="top navigation"> <i data-toggle="wy-nav-top" class="fa fa-bars"></i> <a href="../../index.html">ProtParCon</a> </nav> <div class="wy-nav-content"> <div class="rst-content"> <div role="navigation" aria-label="breadcrumbs navigation"> <ul class="wy-breadcrumbs"> <li><a href="../../index.html">Docs</a> &raquo;</li> <li><a href="../index.html">Module code</a> &raquo;</li> <li>imc.utilities</li> <li class="wy-breadcrumbs-aside"> </li> </ul> <hr/> </div> <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article"> <div itemprop="articleBody"> <h1>Source code for imc.utilities</h1><div class="highlight"><pre> <span></span><span class="ch">#!/usr/bin/env python</span> <span class="c1"># -*- coding: utf-8 -*-</span> <span class="sd">&quot;&quot;&quot;</span> <span class="sd">Common utility functions for various iParCon submodules.</span> <span class="sd">&quot;&quot;&quot;</span> <span class="kn">import</span> <span class="nn">os</span> <span class="kn">import</span> <span class="nn">re</span> <span class="kn">import</span> <span class="nn">sys</span> <span class="kn">import</span> <span class="nn">shutil</span> <span class="kn">import</span> <span class="nn">logging</span> <span class="kn">from</span> <span class="nn">io</span> <span class="k">import</span> <span class="n">StringIO</span> <span class="kn">from</span> <span class="nn">copy</span> <span class="k">import</span> <span class="n">deepcopy</span> <span class="kn">from</span> <span class="nn">collections</span> <span class="k">import</span> <span class="n">namedtuple</span><span class="p">,</span> <span class="n">defaultdict</span> <span class="kn">from</span> <span class="nn">Bio</span> <span class="k">import</span> <span class="n">Phylo</span><span class="p">,</span> <span class="n">AlignIO</span> <span class="n">LEVEL</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">INFO</span> <span class="n">LOGFILE</span><span class="p">,</span> <span class="n">LOGFILEMODE</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span> <span class="n">HANDLERS</span> <span class="o">=</span> <span class="p">[</span><span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">)]</span> <span class="k">if</span> <span class="n">LOGFILE</span><span class="p">:</span> <span class="n">HANDLERS</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">FileHandler</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="n">LOGFILE</span><span class="p">,</span> <span class="n">mode</span><span class="o">=</span><span class="n">LOGFILEMODE</span><span class="p">))</span> <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="nb">format</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(levelname)-8s</span><span class="s1"> </span><span class="si">%(name)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">datefmt</span><span class="o">=</span><span class="s1">&#39;%Y-%m-</span><span class="si">%d</span><span class="s1"> %H:%M:%S&#39;</span><span class="p">,</span> <span class="n">handlers</span><span class="o">=</span><span class="n">HANDLERS</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="n">LEVEL</span><span class="p">)</span> <span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;[iMC]&#39;</span><span class="p">)</span> <span class="n">warn</span><span class="p">,</span> <span class="n">info</span><span class="p">,</span> <span class="n">error</span> <span class="o">=</span> <span class="n">logger</span><span class="o">.</span><span class="n">warning</span><span class="p">,</span> <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">,</span> <span class="n">logger</span><span class="o">.</span><span class="n">error</span> <span class="n">ENDINGS</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;fa&#39;</span><span class="p">,</span> <span class="s1">&#39;fan&#39;</span><span class="p">,</span> <span class="s1">&#39;fas&#39;</span><span class="p">,</span> <span class="s1">&#39;fasta&#39;</span><span class="p">,</span> <span class="s1">&#39;aln&#39;</span><span class="p">,</span> <span class="s1">&#39;clustal&#39;</span><span class="p">,</span> <span class="s1">&#39;clu&#39;</span><span class="p">,</span> <span class="s1">&#39;phy&#39;</span><span class="p">,</span> <span class="s1">&#39;phylip&#39;</span><span class="p">,</span> <span class="s1">&#39;phylip-relaxed&#39;</span><span class="p">,</span> <span class="s1">&#39;phylip-sequential&#39;</span><span class="p">,</span> <span class="s1">&#39;stockholm&#39;</span><span class="p">,</span> <span class="s1">&#39;mauve&#39;</span><span class="p">,</span> <span class="s1">&#39;mau&#39;</span><span class="p">,</span> <span class="s1">&#39;emboss&#39;</span><span class="p">,</span> <span class="s1">&#39;emb&#39;</span><span class="p">,</span> <span class="s1">&#39;nex&#39;</span><span class="p">,</span> <span class="s1">&#39;nexus&#39;</span><span class="p">,</span> <span class="s1">&#39;maf&#39;</span><span class="p">,</span> <span class="s1">&#39;xmfa&#39;</span><span class="p">,</span> <span class="s1">&#39;newick&#39;</span><span class="p">,</span> <span class="s1">&#39;new&#39;</span><span class="p">,</span> <span class="s1">&#39;text&#39;</span><span class="p">,</span> <span class="s1">&#39;tsv&#39;</span><span class="p">]</span> <span class="n">MODEL</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;model&#39;</span><span class="p">,</span> <span class="s1">&#39;name frequency gamma rates invp type&#39;</span><span class="p">)</span> <span class="n">AMINO_ACIDS</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="s1">&#39;ARNDCQEGHILKMFPSTWYV&#39;</span><span class="p">)</span> <div class="viewcode-block" id="basename"><a class="viewcode-back" href="../../api.html#imc.utilities.basename">[docs]</a><span class="k">def</span> <span class="nf">basename</span><span class="p">(</span><span class="n">name</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;</span> <span class="sd"> Removing file extension, if the extension is in ENDINGS.</span> <span class="sd"> </span> <span class="sd"> :param name: str, a filename.</span> <span class="sd"> :return: str, filename without known extensions for tsv, txt, FASTA, and</span> <span class="sd"> NEWICK as well as some alignment format files.</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">if</span> <span class="s1">&#39;.&#39;</span> <span class="ow">in</span> <span class="n">name</span><span class="p">:</span> <span class="n">names</span> <span class="o">=</span> <span class="n">name</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">)</span> <span class="k">if</span> <span class="n">names</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span> <span class="ow">in</span> <span class="n">ENDINGS</span><span class="p">:</span> <span class="k">return</span> <span class="s1">&#39;.&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">names</span><span class="p">[:</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="n">name</span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="n">name</span></div> <div class="viewcode-block" id="modeling"><a class="viewcode-back" href="../../api.html#imc.utilities.modeling">[docs]</a><span class="k">def</span> <span class="nf">modeling</span><span class="p">(</span><span class="n">model</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;</span> <span class="sd"> Parse evolutionary model.</span> <span class="sd"> The model needs to be in the format of MODEL+&lt;FreqType&gt;+&lt;RateType&gt; or a</span> <span class="sd"> model (text) file, where MODEL is a model name (e.g. JTT, WAG, ...),</span> <span class="sd"> FreqType is how the model will handle amino acid frequency (e.g. F, FO,</span> <span class="sd"> or FQ), and RateType is the rate heterogeneity type. Protein mixture</span> <span class="sd"> models are not supported.</span> <span class="sd"> </span> <span class="sd"> :param model: str, name of the model a pathname to the model file.</span> <span class="sd"> :return: namedtuple, in the order of name, frequency, gamma, rates, invp,</span> <span class="sd"> and type.</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">if</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">isfile</span><span class="p">(</span><span class="n">model</span><span class="p">):</span> <span class="k">return</span> <span class="n">MODEL</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">abspath</span><span class="p">(</span><span class="n">model</span><span class="p">),</span> <span class="s1">&#39;empirical&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="s1">&#39;custom&#39;</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="n">name</span> <span class="o">=</span> <span class="n">model</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;+&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span> <span class="n">invprop</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;\+I[+]*&#39;</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span> <span class="n">invprop</span> <span class="o">=</span> <span class="s1">&#39;estimate&#39;</span> <span class="k">if</span> <span class="n">invprop</span> <span class="k">else</span> <span class="mi">0</span> <span class="n">gamma</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;\+G([0-9])*\+*&#39;</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span> <span class="n">gamma</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">gamma</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span> <span class="k">if</span> <span class="n">gamma</span> <span class="k">else</span> <span class="mi">0</span> <span class="n">frequency</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;\+(F[OQ]?)\+*&#39;</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span> <span class="k">if</span> <span class="n">frequency</span><span class="p">:</span> <span class="n">fs</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;F&#39;</span><span class="p">:</span> <span class="s1">&#39;empirical&#39;</span><span class="p">,</span> <span class="s1">&#39;FO&#39;</span><span class="p">:</span> <span class="s1">&#39;estimate&#39;</span><span class="p">,</span> <span class="s1">&#39;FQ&#39;</span><span class="p">:</span> <span class="s1">&#39;equal&#39;</span><span class="p">}</span> <span class="n">frequency</span> <span class="o">=</span> <span class="n">fs</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">frequency</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="s1">&#39;empirical&#39;</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="n">frequency</span> <span class="o">=</span> <span class="s1">&#39;empirical&#39;</span> <span class="n">rates</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;\+R([0-9])*\+*&#39;</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span> <span class="n">rates</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">rates</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span> <span class="k">if</span> <span class="n">rates</span> <span class="k">else</span> <span class="mi">0</span> <span class="k">return</span> <span class="n">MODEL</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">frequency</span><span class="p">,</span> <span class="n">gamma</span><span class="p">,</span> <span class="n">rates</span><span class="p">,</span> <span class="n">invprop</span><span class="p">,</span> <span class="s1">&#39;builtin&#39;</span><span class="p">)</span></div> <div class="viewcode-block" id="Tree"><a class="viewcode-back" href="../../api.html#imc.utilities.Tree">[docs]</a><span class="k">class</span> <span class="nc">Tree</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">tree</span><span class="p">,</span> <span class="n">leave</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;</span> <span class="sd"> A class handles phylogenetic trees.</span> <span class="sd"> </span> <span class="sd"> :param tree: str, a newick tree file or tree string (must start with</span> <span class="sd"> &#39;(&#39; and end with &#39;;&#39;).</span> <span class="sd"> :param leave: bool, whether exit the process or not once an error</span> <span class="sd"> occurred.</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">tree</span><span class="p">,</span> <span class="nb">str</span><span class="p">):</span> <span class="k">if</span> <span class="n">tree</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">&#39;(&#39;</span><span class="p">)</span> <span class="ow">and</span> <span class="n">tree</span><span class="o">.</span><span class="n">endswith</span><span class="p">(</span><span class="s1">&#39;;&#39;</span><span class="p">):</span> <span class="n">tree</span> <span class="o">=</span> <span class="n">StringIO</span><span class="p">(</span><span class="n">tree</span><span class="p">)</span> <span class="k">elif</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">isfile</span><span class="p">(</span><span class="n">tree</span><span class="p">):</span> <span class="k">pass</span> <span class="k">else</span><span class="p">:</span> <span class="n">error</span><span class="p">(</span><span class="s1">&#39;Invalid tree: </span><span class="si">{}</span><span class="s1">, tree should be either a NEWICK format &#39;</span> <span class="s1">&#39;tree string or tree file.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">tree</span><span class="p">))</span> <span class="n">tree</span> <span class="o">=</span> <span class="kc">None</span> <span class="k">else</span><span class="p">:</span> <span class="n">error</span><span class="p">(</span><span class="s1">&#39;Invalid tree, tree should be a string.&#39;</span><span class="p">)</span> <span class="n">tree</span> <span class="o">=</span> <span class="kc">None</span> <span class="k">if</span> <span class="n">tree</span> <span class="ow">is</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">leave</span><span class="p">:</span> <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="n">tree</span> <span class="o">=</span> <span class="n">Phylo</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="n">tree</span><span class="p">,</span> <span class="s1">&#39;newick&#39;</span><span class="p">)</span> <span class="k">if</span> <span class="n">tree</span> <span class="k">else</span> <span class="kc">None</span> <span class="k">if</span> <span class="n">tree</span><span class="p">:</span> <span class="n">leaves</span> <span class="o">=</span> <span class="nb">len</span><span class="p">([</span><span class="n">c</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">tree</span><span class="o">.</span><span class="n">find_clades</span><span class="p">()</span> <span class="k">if</span> <span class="n">c</span><span class="o">.</span><span class="n">is_terminal</span><span class="p">()])</span> <span class="n">nodes</span> <span class="o">=</span> <span class="nb">len</span><span class="p">([</span><span class="n">c</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">tree</span><span class="o">.</span><span class="n">find_clades</span><span class="p">()</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">c</span><span class="o">.</span><span class="n">is_terminal</span><span class="p">()])</span> <span class="n">length</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">([</span><span class="n">c</span><span class="o">.</span><span class="n">branch_length</span> <span class="k">if</span> <span class="n">c</span><span class="o">.</span><span class="n">branch_length</span> <span class="k">else</span> <span class="mf">0.0</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">tree</span><span class="o">.</span><span class="n">find_clades</span><span class="p">()])</span> <span class="k">else</span><span class="p">:</span> <span class="n">leaves</span><span class="p">,</span> <span class="n">nodes</span><span class="p">,</span> <span class="n">length</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mf">0.0</span> <span class="bp">self</span><span class="o">.</span><span class="n">tree</span> <span class="o">=</span> <span class="n">tree</span> <span class="bp">self</span><span class="o">.</span><span class="n">leaves</span> <span class="o">=</span> <span class="n">leaves</span> <span class="bp">self</span><span class="o">.</span><span class="n">nodes</span> <span class="o">=</span> <span class="n">nodes</span> <span class="bp">self</span><span class="o">.</span><span class="n">length</span> <span class="o">=</span> <span class="n">length</span> <div class="viewcode-block" id="Tree.string"><a class="viewcode-back" href="../../api.html#imc.utilities.Tree.string">[docs]</a> <span class="k">def</span> <span class="nf">string</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">ic</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">ic2name</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">nodes</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">brlen</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;</span> <span class="sd"> Get a newick tree string for a tree after manipulating.</span> <span class="sd"> </span> <span class="sd"> :param ic: bool, whether to keep confidence of internal nodes.</span> <span class="sd"> :param ic2name: whether to convert confidence of internal nodes to</span> <span class="sd"> their names.</span> <span class="sd"> :param nodes: bool, discard or keep name of internal nodes.</span> <span class="sd"> :param brlen: bool, discard or keep branch lengths.</span> <span class="sd"> :return: str, a newick tree string.</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">tree</span><span class="p">:</span> <span class="n">tree</span> <span class="o">=</span> <span class="n">deepcopy</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">tree</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="n">s</span> <span class="n">n</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">leaves</span> <span class="k">for</span> <span class="n">clade</span> <span class="ow">in</span> <span class="n">tree</span><span class="o">.</span><span class="n">find_clades</span><span class="p">():</span> <span class="k">if</span> <span class="n">ic2name</span><span class="p">:</span> <span class="k">if</span> <span class="n">clade</span><span class="o">.</span><span class="n">confidence</span><span class="p">:</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">clade</span><span class="o">.</span><span class="n">is_terminal</span><span class="p">()</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">clade</span><span class="o">.</span><span class="n">name</span><span class="p">:</span> <span class="n">clade</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">clade</span><span class="o">.</span><span class="n">confidence</span><span class="p">)</span> <span class="n">clade</span><span class="o">.</span><span class="n">confidence</span> <span class="o">=</span> <span class="kc">None</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">ic</span><span class="p">:</span> <span class="n">clade</span><span class="o">.</span><span class="n">confidence</span> <span class="o">=</span> <span class="kc">None</span> <span class="k">if</span> <span class="n">nodes</span><span class="p">:</span> <span class="n">clade</span><span class="o">.</span><span class="n">confidence</span> <span class="o">=</span> <span class="kc">None</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">clade</span><span class="o">.</span><span class="n">is_terminal</span><span class="p">()</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">clade</span><span class="o">.</span><span class="n">name</span><span class="p">:</span> <span class="n">clade</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s1">&#39;NODE</span><span class="si">{}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">n</span><span class="p">)</span> <span class="n">n</span> <span class="o">+=</span> <span class="mi">1</span> <span class="k">else</span><span class="p">:</span> <span class="k">if</span> <span class="n">ic2name</span><span class="p">:</span> <span class="k">pass</span> <span class="k">else</span><span class="p">:</span> <span class="k">if</span> <span class="n">clade</span><span class="o">.</span><span class="n">name</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">clade</span><span class="o">.</span><span class="n">is_terminal</span><span class="p">():</span> <span class="n">clade</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="kc">None</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">brlen</span><span class="p">:</span> <span class="n">clade</span><span class="o">.</span><span class="n">branch_length</span> <span class="o">=</span> <span class="mf">0.0</span> <span class="n">s</span> <span class="o">=</span> <span class="n">tree</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;newick&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="c1"># Remove branch length if brlen set to False</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">brlen</span><span class="p">:</span> <span class="n">s</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s1">r&#39;:0\.\d+&#39;</span><span class="p">,</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span> <span class="c1"># Remove branch lengths if only unscaled tree (topology) was given</span> <span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">length</span><span class="p">:</span> <span class="n">s</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s1">r&#39;:0\.\d+&#39;</span><span class="p">,</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span> <span class="k">return</span> <span class="n">s</span></div> <div class="viewcode-block" id="Tree.file"><a class="viewcode-back" href="../../api.html#imc.utilities.Tree.file">[docs]</a> <span class="k">def</span> <span class="nf">file</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">filename</span><span class="p">,</span> <span class="n">ic</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">ic2name</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">nodes</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">brlen</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;</span> <span class="sd"> Write a tree to a file after manipulating.</span> <span class="sd"> </span> <span class="sd"> :param filename: str, the name of the tree output file</span> <span class="sd"> :param ic: bool, whether to keep confidence of internal nodes.</span> <span class="sd"> :param ic2name: whether to convert confidence of internal nodes to</span> <span class="sd"> their names.</span> <span class="sd"> :param nodes: bool, discard or keep name of internal nodes.</span> <span class="sd"> :param brlen: bool, discard or keep branch lengths.</span> <span class="sd"> :return: str, a newick tree string.</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="n">s</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">string</span><span class="p">(</span><span class="n">ic</span><span class="o">=</span><span class="n">ic</span><span class="p">,</span> <span class="n">ic2name</span><span class="o">=</span><span class="n">ic2name</span><span class="p">,</span> <span class="n">nodes</span><span class="o">=</span><span class="n">nodes</span><span class="p">,</span> <span class="n">brlen</span><span class="o">=</span><span class="n">brlen</span><span class="p">)</span> <span class="k">try</span><span class="p">:</span> <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">o</span><span class="p">:</span> <span class="n">o</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">{}</span><span class="se">\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">s</span><span class="p">))</span> <span class="k">except</span> <span class="ne">IOError</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span> <span class="n">error</span><span class="p">(</span><span class="n">err</span><span class="p">)</span> <span class="k">return</span> <span class="n">filename</span></div></div> <div class="viewcode-block" id="trim"><a class="viewcode-back" href="../../api.html#imc.utilities.trim">[docs]</a><span class="k">def</span> <span class="nf">trim</span><span class="p">(</span><span class="n">msa</span><span class="p">,</span> <span class="n">fmt</span><span class="o">=</span><span class="s1">&#39;fasta&#39;</span><span class="p">,</span> <span class="n">outfile</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;</span> <span class="sd"> Remove gaps and ambiguous characters from protein multiple sequence</span> <span class="sd"> alignment (MSA) file or a dictionary object of MSA records.</span> <span class="sd"> :param msa: str or dict, pathname of the protein (MSA) multiple sequence</span> <span class="sd"> alignment file or a dictionary object of of MSA records.</span> <span class="sd"> :param fmt: format of the MSA file, if msa is the pathname of a MSA file.</span> <span class="sd"> :param outfile: pathname for saving trimmed MSA to a file, if not set,</span> <span class="sd"> trimmed sequences will only be returned without saving to a file.</span> <span class="sd"> :param verbose: bool, invoke verbose or silent process mode,</span> <span class="sd"> default: False, silent mode.</span> <span class="sd"> :return: dict, trimmed MSA in a dictionary.</span> <span class="sd"> .. note::</span> <span class="sd"> </span> <span class="sd"> Ambiguous characters (characters not in ARNDCQEGHILKMFPSTWYV) will be</span> <span class="sd"> treated as gaps and removed. The trimmed alignment file will be saved</span> <span class="sd"> to outfile in FASTA format if outfile is not a empty string and there</span> <span class="sd"> are sites left after trimming. Whether the outfile is set or not,</span> <span class="sd"> `trim()` always returns trimmed MSA in a dictionary (even a empty dict).</span> <span class="sd"> </span> <span class="sd"> Careful with PHYLIP format MSA files, `trim()` use `Bio.AlignIO` to read</span> <span class="sd"> MSA file, users are responsible for given the right name for PHYLIP</span> <span class="sd"> format files, e.g. phylip-relaxed or phylip-sequential.</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="n">level</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">INFO</span> <span class="k">if</span> <span class="n">verbose</span> <span class="k">else</span> <span class="n">logging</span><span class="o">.</span><span class="n">ERROR</span> <span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">level</span><span class="p">)</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">msa</span><span class="p">,</span> <span class="nb">str</span><span class="p">):</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">isfile</span><span class="p">(</span><span class="n">msa</span><span class="p">):</span> <span class="n">error</span><span class="p">(</span><span class="s1">&#39;Alignment </span><span class="si">{}</span><span class="s1"> is not a file or does not exist.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">msa</span><span class="p">))</span> <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="k">try</span><span class="p">:</span> <span class="n">records</span> <span class="o">=</span> <span class="n">AlignIO</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="n">msa</span><span class="p">,</span> <span class="n">fmt</span><span class="p">)</span> <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span> <span class="n">error</span><span class="p">(</span><span class="s1">&#39;Alignment </span><span class="si">{}</span><span class="s1"> contains non equal length sequences.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span> <span class="n">msa</span><span class="p">))</span> <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="n">length</span><span class="p">,</span> <span class="n">label</span> <span class="o">=</span> <span class="n">records</span><span class="o">.</span><span class="n">get_alignment_length</span><span class="p">(),</span> <span class="n">msa</span> <span class="n">records</span> <span class="o">=</span> <span class="p">{</span><span class="n">a</span><span class="o">.</span><span class="n">id</span><span class="p">:</span> <span class="n">a</span><span class="o">.</span><span class="n">seq</span> <span class="k">for</span> <span class="n">a</span> <span class="ow">in</span> <span class="n">records</span><span class="p">}</span> <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">msa</span><span class="p">,</span> <span class="nb">dict</span><span class="p">):</span> <span class="n">length</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="nb">set</span><span class="p">([</span><span class="nb">len</span><span class="p">(</span><span class="n">v</span><span class="p">)</span> <span class="k">for</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">msa</span><span class="o">.</span><span class="n">values</span><span class="p">()]))</span> <span class="k">if</span> <span class="ow">not</span> <span class="nb">len</span><span class="p">(</span><span class="n">length</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span> <span class="n">error</span><span class="p">(</span><span class="s1">&#39;Alignment object contains non equal length sequences.&#39;</span><span class="p">)</span> <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="n">length</span><span class="p">,</span> <span class="n">label</span> <span class="o">=</span> <span class="n">length</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="s1">&#39;alignment record&#39;</span> <span class="n">records</span> <span class="o">=</span> <span class="n">msa</span> <span class="k">else</span><span class="p">:</span> <span class="n">error</span><span class="p">(</span><span class="s1">&#39;Invalid msa for trimming, msa should be a pathname of MSA file&#39;</span> <span class="s1">&#39;or a dictionary object of sequence name and sequence pairs.&#39;</span><span class="p">)</span> <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="n">info</span><span class="p">(</span><span class="s1">&#39;Trimming gaps and ambiguous characters for </span><span class="si">{}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">label</span><span class="p">))</span> <span class="n">trimmed</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">list</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">length</span><span class="p">):</span> <span class="n">column</span> <span class="o">=</span> <span class="nb">set</span><span class="p">([</span><span class="n">s</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">records</span><span class="o">.</span><span class="n">values</span><span class="p">()])</span> <span class="k">if</span> <span class="n">column</span><span class="o">.</span><span class="n">issubset</span><span class="p">(</span><span class="n">AMINO_ACIDS</span><span class="p">):</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">records</span><span class="o">.</span><span class="n">items</span><span class="p">():</span> <span class="n">trimmed</span><span class="p">[</span><span class="n">k</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">v</span><span class="p">[</span><span class="n">i</span><span class="p">])</span> <span class="k">if</span> <span class="nb">all</span><span class="p">(</span><span class="n">trimmed</span><span class="o">.</span><span class="n">values</span><span class="p">()):</span> <span class="n">trimmed</span> <span class="o">=</span> <span class="p">{</span><span class="n">k</span><span class="p">:</span> <span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">v</span><span class="p">)</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">trimmed</span><span class="o">.</span><span class="n">items</span><span class="p">()}</span> <span class="k">if</span> <span class="n">outfile</span><span class="p">:</span> <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">outfile</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">o</span><span class="p">:</span> <span class="n">o</span><span class="o">.</span><span class="n">writelines</span><span class="p">(</span><span class="s1">&#39;&gt;</span><span class="si">{}</span><span class="se">\n</span><span class="si">{}</span><span class="se">\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="n">v</span><span class="p">)</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">trimmed</span><span class="o">.</span><span class="n">items</span><span class="p">())</span> <span class="k">else</span><span class="p">:</span> <span class="n">trimmed</span> <span class="o">=</span> <span class="p">{</span><span class="n">k</span><span class="p">:</span> <span class="s1">&#39;&#39;</span> <span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">trimmed</span><span class="o">.</span><span class="n">keys</span><span class="p">()}</span> <span class="k">if</span> <span class="n">outfile</span><span class="p">:</span> <span class="n">warn</span><span class="p">(</span><span class="s1">&#39;Successfully removed all gaps and ambiguous characters, but &#39;</span> <span class="s1">&#39;no site was left after trimming, no outfile saved.&#39;</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="n">warn</span><span class="p">(</span><span class="s1">&#39;Successfully removed all gaps and ambiguous characters, but &#39;</span> <span class="s1">&#39;no site was left after trimming, empty dict returned.&#39;</span><span class="p">)</span> <span class="k">return</span> <span class="n">trimmed</span></div> <span class="k">def</span> <span class="nf">indent</span><span class="p">(</span><span class="n">text</span><span class="p">,</span> <span class="n">prefix</span><span class="p">,</span> <span class="n">predicate</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;</span> <span class="sd"> A copy of textwrap.indent() method introduce in Python 3.3.</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">if</span> <span class="n">predicate</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span> <span class="k">def</span> <span class="nf">predicate</span><span class="p">(</span><span class="n">line</span><span class="p">):</span> <span class="k">return</span> <span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">def</span> <span class="nf">prefixed_lines</span><span class="p">():</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">text</span><span class="o">.</span><span class="n">splitlines</span><span class="p">(</span><span class="kc">True</span><span class="p">):</span> <span class="k">yield</span> <span class="p">(</span><span class="n">prefix</span> <span class="o">+</span> <span class="n">line</span> <span class="k">if</span> <span class="n">predicate</span><span class="p">(</span><span class="n">line</span><span class="p">)</span> <span class="k">else</span> <span class="n">line</span><span class="p">)</span> <span class="k">return</span> <span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">prefixed_lines</span><span class="p">())</span> <span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span> <span class="k">pass</span> </pre></div> </div> </div> <footer> <hr/> <div role="contentinfo"> <p> &copy; Copyright 2018, FEI YUAN. </p> </div> Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. </footer> </div> </div> </section> </div> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT:'../../', VERSION:'1.0', LANGUAGE:'None', COLLAPSE_INDEX:false, FILE_SUFFIX:'.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="../../_static/jquery.js"></script> <script type="text/javascript" src="../../_static/underscore.js"></script> <script type="text/javascript" src="../../_static/doctools.js"></script> <script type="text/javascript" src="../../_static/js/theme.js"></script> <script type="text/javascript"> jQuery(function () { SphinxRtdTheme.Navigation.enable(true); }); </script> </body> </html><file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import shutil import logging import unittest from collections import namedtuple from Bio import AlignIO MODEL = namedtuple('model', 'name frequency gamma rates invp type') PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATA = os.path.join(PATH, 'tests', 'data', 'utilities') sys.path.insert(0, PATH) from ProtParCon.utilities import basename, modeling, Tree, trim sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import settings CLEANUP = settings.CLEANUP class TestBasename(unittest.TestCase): result = 'original name' def test_fa(self): self.assertEqual('a.name', basename('a.name.fa')) def test_fan(self): self.assertEqual('a.name', basename('a.name.fan')) def test_fas(self): self.assertEqual('a.name', basename('a.name.fas')) def test_fasta(self): self.assertEqual('a.name', basename('a.name.fasta')) def test_aln(self): self.assertEqual('a.name', basename('a.name.aln')) def test_clu(self): self.assertEqual('a.name', basename('a.name.clu')) def test_clustal(self): self.assertEqual('a.name', basename('a.name.clustal')) def test_phy(self): self.assertEqual('a.name', basename('a.name.phy')) def test_phylip(self): self.assertEqual('a.name', basename('a.name.phylip')) def test_phylip_relaxed(self): self.assertEqual('a.name', basename('a.name.phylip-relaxed')) def test_phy_sequential(self): self.assertEqual('a.name', basename('a.name.phylip-sequential')) def test_stockholm(self): self.assertEqual('a.name', basename('a.name.stockholm')) def test_mauve(self): self.assertEqual('a.name', basename('a.name.mauve')) def test_mau(self): self.assertEqual('a.name', basename('a.name.mau')) def test_emboss(self): self.assertEqual('a.name', basename('a.name.emboss')) def test_emb(self): self.assertEqual('a.name', basename('a.name.emb')) def test_nexus(self): self.assertEqual('a.name', basename('a.name.nexus')) def test_nex(self): self.assertEqual('a.name', basename('a.name.nex')) def test_maf(self): self.assertEqual('a.name', basename('a.name.maf')) def test_xmfa(self): self.assertEqual('a.name', basename('a.name.xmfa')) def test_newick(self): self.assertEqual('a.name', basename('a.name.newick')) def test_new(self): self.assertEqual('a.name', basename('a.name.new')) def test_text(self): self.assertEqual('a.name', basename('a.name.text')) def test_tsv(self): self.assertEqual('a.name', basename('a.name.tsv')) def test_name(self): self.assertEqual('a.name', basename('a.name')) class TestModeling(unittest.TestCase): def test_model_builtin(self): self.assertTupleEqual(MODEL('JTT', 'empirical', 0, 0, 0, 'builtin'), modeling('JTT')) def test_model_custom(self): self.assertTupleEqual(MODEL((os.path.join(DATA, 'jtt')), 'empirical', 0, 0, 0, 'custom'), modeling(os.path.join(DATA, 'jtt'))) def test_model_freq(self): self.assertTupleEqual(MODEL('JTT', 'empirical', 0, 0, 0, 'builtin'), modeling('JTT+F')) def test_model_freq_estimate(self): self.assertTupleEqual(MODEL('JTT', 'estimate', 0, 0, 0, 'builtin'), modeling('JTT+FO')) def test_model_freq_equal(self): self.assertTupleEqual(MODEL('JTT', 'equal', 0, 0, 0, 'builtin'), modeling('JTT+FQ')) def test_model_freq_gamma(self): self.assertTupleEqual(MODEL('JTT', 'empirical', 4, 0, 0, 'builtin'), modeling('JTT+F+G4')) def test_model_freq_estimate_gamma(self): self.assertTupleEqual(MODEL('JTT', 'estimate', 4, 0, 0, 'builtin'), modeling('JTT+FO+G4')) def test_model_freq_equal_gamma(self): self.assertTupleEqual(MODEL('JTT', 'equal', 4, 0, 0, 'builtin'), modeling('JTT+FQ+G4')) def test_model_gamma_rate(self): self.assertTupleEqual(MODEL('JTT', 'empirical', 4, 8, 0, 'builtin'), modeling('JTT+G4+R8')) def test_model_freq_gamma_invp_rate(self): self.assertTupleEqual(MODEL('JTT', 'empirical', 4, 4, 'estimate', 'builtin'), modeling('JTT+F+G4+I+R4')) def test_model_freq_estimate_gamma_invp_rate(self): self.assertTupleEqual(MODEL('JTT', 'estimate', 4, 8, 'estimate', 'builtin'), modeling('JTT+I+FO+G4+R8')) def test_model_freq_equal_gamma_invp_rate(self): self.assertTupleEqual(MODEL('JTT', 'equal', 4, 4, 'estimate', 'builtin'), modeling('JTT+FQ+G4+I+R4')) def test_model_gamma(self): self.assertTupleEqual(MODEL('JTT', 'empirical', 4, 0, 0, 'builtin'), modeling('JTT+G4')) def test_model_freq_gamma_invp(self): self.assertTupleEqual(MODEL('JTT', 'empirical', 4, 0, 'estimate', 'builtin'), modeling('JTT+F+G4+I')) def test_model_freq_estimate_gamma_invp(self): self.assertTupleEqual(MODEL('JTT', 'estimate', 4, 0, 'estimate', 'builtin'), modeling('JTT+I+FO+G4')) def test_model_freq_equal_gamma_invp(self): self.assertTupleEqual(MODEL('JTT', 'equal', 4, 0, 'estimate', 'builtin'), modeling('JTT+FQ+G4+I')) def _read(name): with open(name) as f: return f.readline().strip() class TestTree(unittest.TestCase): def setUp(self): self.top = os.path.join(DATA, 'topology.newick') self.top_nodes = os.path.join(DATA, 'topology_internal.newick') self.tree = os.path.join(DATA, 'tree.newick') self.tree_ic = os.path.join(DATA, 'tree_confidence.newick') self.tree_nodes = os.path.join(DATA, 'tree_internal.newick') self.s = '(A:0.2,(B:0.3,(C:0.4,''D:0.5):0.2):0.1):0.0;' self.s_ic = '(A:0.2,(B:0.3,(C:0.4,D:0.5)7:0.2)6:0.1)5:0.0;' self.s_nodes = '(A:0.2,(B:0.3,(C:0.4,D:0.5)E:0.2)F:0.1)root:0.0;' self.rm = '' def tearDown(self): if CLEANUP and self.rm and os.path.exists(self.rm): try: if os.path.isfile(self.rm): os.remove(self.rm) else: shutil.rmtree(self.rm) except OSError as err: logging.warning('Failed to cleanup testing data {} due to:' '\n\t{}'.format(self.rm, err)) def test_log(self): with self.assertLogs('[iMC]', level='INFO') as cm: Tree(self.s + 'abc') self.assertRegex(cm.output[0], r'ERROR.*Invalid tree:.*a NEWICK.*.') def test_leave(self): with self.assertRaises(SystemExit) as cm: Tree(self.s + 'abc', leave=True) self.assertEqual(cm.exception.code, 1) # Test read from file and return a string def test_topology_file(self): self.assertEqual('(A,(B,(C,D)));', Tree(self.top).string()) def test_topology_internal_file(self): self.assertEqual('(A,(B,(C,D)));', Tree(self.top_nodes).string()) def test_tree_file(self): self.assertEqual('(A:0.20000,(B:0.30000,(C:0.40000,D:0.50000):0.20000)' ':0.10000):0.00000;', Tree(self.tree).string()) def test_tree_brlen_file(self): self.assertEqual('(A,(B,(C,D)E)F)root;', Tree(self.tree_nodes).string(brlen=False, nodes=True)) def test_tree_internal_file(self): self.assertEqual('(A:0.20000,(B:0.30000,(C:0.40000,D:0.50000)' ':0.20000):0.10000):0.00000;', Tree(self.tree_nodes).string()) def test_tree_internal_brlen_file(self): self.assertEqual('(A,(B,(C,D)));', Tree(self.tree_nodes).string(brlen=False)) def test_tree_confidence_file(self): self.assertEqual('(A,(B,(C,D)7)6)5;', Tree(self.tree_ic).string(ic2name=True, brlen=False)) # Test read from string and return a string def test_topology_string(self): self.assertEqual('(A,(B,(C,D)));', Tree('(A,(B,(C,D)));').string()) def test_topology_internal_string(self): self.assertEqual('(A,(B,(C,D)));', Tree('(A,(B,(C,D)E)F)root;').string()) def test_tree_string(self): self.assertEqual('(A:0.20000,(B:0.30000,(C:0.40000,D:0.50000)' ':0.20000):0.10000):0.00000;', Tree(self.s).string()) def test_tree_brlen_string(self): self.assertEqual('(A,(B,(C,D)E)F)root;', Tree(self.s_nodes).string(brlen=False, nodes=True)) def test_tree_internal_string(self): self.assertEqual('(A:0.20000,(B:0.30000,(C:0.40000,D:0.50000):' '0.20000):0.10000):0.00000;', Tree(self.s_nodes).string()) def test_tree_internal_brlen_string(self): self.assertEqual('(A,(B,(C,D)));', Tree(self.s_nodes).string(brlen=False)) def test_tree_confidence_string(self): self.assertEqual('(A,(B,(C,D)7)6)5;', Tree(self.s_ic).string(ic2name=True, brlen=False)) # Test read from file and write to file def test_topology_file_to_file(self): name = os.path.join(DATA, 'a.newick') self.assertEqual('(A,(B,(C,D)));', _read(Tree(self.top).file(name))) self.rm = name def test_topology_internal_file_to_file(self): name = os.path.join(DATA, 'b.newick') self.assertEqual('(A,(B,(C,D)));', _read(Tree(self.top_nodes).file(name))) self.rm = name def test_tree_file_to_file(self): name = os.path.join(DATA, 'c.newick') self.assertEqual('(A:0.20000,(B:0.30000,(C:0.40000,D:0.50000):0.20000)' ':0.10000):0.00000;', _read(Tree(self.tree).file(name))) self.rm = name def test_tree_brlen_file_to_file(self): name = os.path.join(DATA, 'd.newick') self.assertEqual('(A,(B,(C,D)E)F)root;', _read(Tree(self.tree_nodes).file(name, brlen=False, nodes=True))) self.rm = name def test_tree_internal_file_to_file(self): name = os.path.join(DATA, 'e.newick') self.assertEqual('(A:0.20000,(B:0.30000,(C:0.40000,D:0.50000)' ':0.20000):0.10000):0.00000;', _read(Tree(self.tree_nodes).file(name))) self.rm = name def test_tree_internal_brlen_file_to_file(self): name = os.path.join(DATA, 'f.newick') self.assertEqual('(A,(B,(C,D)));', _read(Tree(self.tree_nodes).file(name, brlen=False))) self.rm = name def test_tree_confidence_file_to_file(self): name = os.path.join(DATA, 'g.newick') self.assertEqual('(A,(B,(C,D)7)6)5;', _read(Tree(self.tree_ic).file(name, ic2name=True, brlen=False))) self.rm = name class TestTrim(unittest.TestCase): def setUp(self): self.rm = '' def tearDown(self): if CLEANUP and self.rm and os.path.exists(self.rm): try: if os.path.isfile(self.rm): os.remove(self.rm) else: shutil.rmtree(self.rm) except OSError as err: logging.warning('Failed to cleanup testing data {} due to:' '\n\t{}'.format(self.rm, err)) def test_trim_default(self): msa = os.path.join(DATA, 'msa.fa') trimmed = {'A': 'ARGPSSSRILAILAVAFIL', 'B': 'ARGPSTSRFLVILAVAFIL', 'C': 'ARGPTNSRFLVILAVAFLL', 'D': 'VRVPSTSRFLVILAVAFLL'} self.assertDictEqual(trimmed, trim(msa)[0]) def test_trim_fmt(self): msa = os.path.join(DATA, 'msa.phylip') trimmed = {'A': 'ARGPSSSRILAILAVAFIL', 'B': 'ARGPSTSRFLVILAVAFIL', 'C': 'ARGPTNSRFLVILAVAFLL', 'D': 'VRVPSTSRFLVILAVAFLL'} self.assertDictEqual(trimmed, trim(msa, fmt='phylip-relaxed')[0]) def test_trim_outfile(self): msa = os.path.join(DATA, 'msa.phylip') name = os.path.join(DATA, 'trimmed.msa.fa') trimmed = {'A': 'ARGPSSSRILAILAVAFIL', 'B': 'ARGPSTSRFLVILAVAFIL', 'C': 'ARGPTNSRFLVILAVAFLL', 'D': 'VRVPSTSRFLVILAVAFLL'} out, outfile = trim(msa, fmt='phylip-relaxed', outfile=name) self.assertTrue(os.path.isfile(name)) self.assertDictEqual(trimmed, out) rs = AlignIO.read(name, 'fasta') out = {r.id: str(r.seq) for r in rs} self.assertDictEqual(trimmed, out) self.rm = name if __name__ == '__main__': unittest.main(warnings='ignore') <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import shutil import logging import unittest PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, PATH) from ProtParCon.sim import _guess, sim sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import settings CLEANUP = settings.CLEANUP EVOLVER = settings.EVOLVER SEQGEN = settings.SEQGEN ASR = {'evolver': EVOLVER, 'seq-gen': SEQGEN} class TestSim(unittest.TestCase): def setUp(self): self.msa = os.path.join(PATH, 'tests', 'data', 'sim', 'msa.fa') self.anc = os.path.join(PATH, 'tests', 'data', 'sim', 'asr.tsv') self.tree = os.path.join(PATH, 'tests', 'data', 'sim', 'tree.newick') self.out = os.path.join(PATH, 'tests', 'data', 'sim', 'sim.out') self.rm = '' def tearDown(self): if CLEANUP and self.rm and os.path.exists(self.rm): try: if os.path.isfile(self.rm): os.remove(self.rm) else: shutil.rmtree(self.rm) except OSError as err: logging.warning('Failed to cleanup testing data {} due to:' '\n\t{}'.format(self.rm, err)) @unittest.skipIf(not all(ASR.values()), 'No simulate program provided.') def test__guess(self): aligners = set(ASR.keys()) self.assertSetEqual(aligners, set(_guess(a)[0] for a in ASR.values())) @unittest.skipIf(EVOLVER is None, 'No EVOLVER executable provided.') def test_evolver_default(self): out = sim(EVOLVER, self.tree, length=100) self.assertTrue(os.path.isfile(out)) self.rm = out @unittest.skipIf(EVOLVER is None, 'No EVOLVER executable provided.') def test_evolver_out(self): out = sim(EVOLVER, self.tree, length=100, outfile=self.out) self.assertTrue(os.path.isfile(out)) self.assertEqual(out, self.out) self.rm = out @unittest.skipIf(EVOLVER is None, 'No EVOLVER executable provided.') def test_evolver_msa(self): out = sim(EVOLVER, self.tree, sequence=self.msa, outfile=self.out) self.assertTrue(os.path.isfile(out)) self.assertEqual(out, self.out) self.rm = out @unittest.skipIf(EVOLVER is None, 'No EVOLVER executable provided.') def test_evolver_anc(self): out = sim(EVOLVER, self.tree, sequence=self.anc, outfile=self.out) self.assertTrue(os.path.isfile(out)) self.assertEqual(out, self.out) self.rm = out @unittest.skipIf(SEQGEN is None, 'No Seq-Gen executable provided.') def test_seqgen_default(self): out = sim(SEQGEN, self.tree, length=100, outfile=self.out) self.assertTrue(os.path.isfile(out)) self.assertEqual(out, self.out) self.rm = out @unittest.skipIf(SEQGEN is None, 'No Seq-Gen executable provided.') def test_seqgen_out(self): out = sim(SEQGEN, self.tree, sequence=self.msa, outfile=self.out) self.assertTrue(os.path.isfile(out)) self.assertEqual(out, self.out) self.rm = out @unittest.skipIf(SEQGEN is None, 'No Seq-Gen executable provided.') def test_seqgen_msa(self): out = sim(SEQGEN, self.tree, sequence=self.msa, outfile=self.out, n=10) self.assertTrue(os.path.isfile(out)) self.assertEqual(out, self.out) self.rm = out @unittest.skipIf(SEQGEN is None, 'No Seq-Gen executable provided.') def test_seqgen_anc(self): outfile = os.path.join(PATH, 'tests', 'data', 'sim', 'seqgen.output.simulation.tsv') out = sim(SEQGEN, self.tree, sequence=self.anc, outfile=outfile, n=10) self.assertTrue(os.path.isfile(out)) self.assertEqual(outfile, out) self.rm = outfile if __name__ == '__main__': unittest.main(warnings='ignore') <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- from ProtParCon import msa, asr, imc, sim, detect sequence = 'lysozyme.fa' tree = 'lysozyme.newick' # Replace the path with real path on your system muscle = 'muscle' codeml = 'codeml' evolver = 'evolver' alignment = msa(muscle, sequence, trimming=True, verbose=True) ancestors = asr(codeml, alignment, tree, 'JTT', verbose=True) obs = imc(ancestors, verbose=True) simulations = sim(evolver, tree=tree, sequence=alignment, verbose=True) exp = imc(simulations, verbose=True) # If you choose to identify changes step by step, after get obs and exp, you # need to handel these results by your self. Each of them consists # of five objects: pars (dict), cons (dict), divs (dict), details (list), # and length (int). The three dicts have the same keys, and their values are # lists. See function imc() for details, refer function detect() to see an # example for handling pairwise comparison. <file_sep>#!/usr/bin/env bash imc lysozyme.fa -t lysozyme.newick -l muscle -a codeml -s evolver -v<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup, find_packages VERSION = '3.1' wd = os.path.abspath(os.path.dirname(__file__)) def readme(): with open(os.path.join(wd, 'README.rst')) as f: return f.read() setup(name='ProtParCon', version=VERSION, description="""ProtParCon - A framework for framework for processing molecular data and identifying parallel and convergent amino acid replacements.""", long_description=readme(), url='https://github.com/iBiology/ProtParCon', author='<NAME>', author_email='<EMAIL>', license='MIT', packages=find_packages(), install_requires=['biopython>=1.71'], entry_points={ 'console_scripts': ['imc=ProtParCon.imc:main', 'oma=ProtParCon.oma:main', 'msa=ProtParCon.msa:main', 'mlt=ProtParCon.mlt:main', 'asr=ProtParCon.asr:main', 'aut=ProtParCon.aut:main', 'sim=ProtParCon.sim:main', 'detect=ProtParCon.detect:main'] }, include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 3.4', 'Topic :: Scientific/Engineering :: Bio-Informatics', ], keywords='phylogeny tree alignment simulation biology bioinformatics' ) if __name__ == '__main__': pass <file_sep>TESTS ===== This directory contains codes for testing iMC. Before run any test, edit file `settings.py` in this directory to make necessary changes.<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Common utility functions for various iParCon submodules. """ import os import re import sys import shutil import logging from io import StringIO from copy import deepcopy from collections import namedtuple, defaultdict from Bio import Phylo, AlignIO LEVEL = logging.INFO LOGFILE, LOGFILEMODE = '', 'w' HANDLERS = [logging.StreamHandler(sys.stdout)] if LOGFILE: HANDLERS.append(logging.FileHandler(filename=LOGFILE, mode=LOGFILEMODE)) logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=HANDLERS, level=LEVEL) logger = logging.getLogger('[iMC]') warn, info, error = logger.warning, logger.info, logger.error ENDINGS = ['fa', 'fan', 'fas', 'fasta', 'aln', 'clustal', 'clu', 'phy', 'phylip', 'phylip-relaxed', 'phylip-sequential', 'stockholm', 'mauve', 'mau', 'emboss', 'emb', 'nex', 'nexus', 'maf', 'xmfa', 'newick', 'new', 'text', 'tsv'] MODEL = namedtuple('model', 'name frequency gamma rates invp type') AMINO_ACIDS = set('ARNDCQEGHILKMFPSTWYV') def basename(name): """ Removing file extension, if the extension is in ENDINGS. :param name: str, a filename. :return: str, filename without known extensions for tsv, txt, FASTA, and NEWICK as well as some alignment format files. """ if '.' in name: names = name.split('.') if names[-1].lower() in ENDINGS: return '.'.join(names[:-1]) else: return name else: return name def modeling(model): """ Parse evolutionary model. The model needs to be in the format of MODEL+<FreqType>+<RateType> or a model (text) file, where MODEL is a model name (e.g. JTT, WAG, ...), FreqType is how the model will handle amino acid frequency (e.g. F, FO, or FQ), and RateType is the rate heterogeneity type. Protein mixture models are not supported. :param model: str, name of the model a pathname to the model file. :return: namedtuple, in the order of name, frequency, gamma, rates, invp, and type. """ if os.path.isfile(model): return MODEL(os.path.abspath(model), 'empirical', 0, 0, 0, 'custom') else: name = model.split('+', 1)[0] invprop = re.search('\+I[+]*', model) invprop = 'estimate' if invprop else 0 gamma = re.search('\+G([0-9])*\+*', model) gamma = int(gamma.group(1)) if gamma else 0 frequency = re.search('\+(F[OQ]?)\+*', model) if frequency: fs = {'F': 'empirical', 'FO': 'estimate', 'FQ': 'equal'} frequency = fs.get(frequency.group(1), 'empirical') else: frequency = 'empirical' rates = re.search('\+R([0-9])*\+*', model) rates = int(rates.group(1)) if rates else 0 return MODEL(name, frequency, gamma, rates, invprop, 'builtin') class Tree(object): def __init__(self, tree, leave=False): """ A class handles phylogenetic trees. :param tree: str, a newick tree file or tree string (must start with '(' and end with ';'). :param leave: bool, whether exit the process or not once an error occurred. """ if isinstance(tree, str): if tree.startswith('(') and tree.endswith(';'): tree = StringIO(tree) elif os.path.isfile(tree): pass else: error('Invalid tree: {}, tree should be either a NEWICK format ' 'tree string or tree file.'.format(tree)) tree = None else: error('Invalid tree, tree should be a string.') tree = None if tree is None and leave: sys.exit(1) else: tree = Phylo.read(tree, 'newick') if tree else None if tree: leaves = len([c for c in tree.find_clades() if c.is_terminal()]) nodes = len([c for c in tree.find_clades() if not c.is_terminal()]) length = sum([c.branch_length if c.branch_length else 0.0 for c in tree.find_clades()]) else: leaves, nodes, length = 0, 0, 0.0 self.tree = tree self.leaves = leaves self.nodes = nodes self.length = length def string(self, ic=True, ic2name=False, nodes=False, brlen=True): """ Get a newick tree string for a tree after manipulating. :param ic: bool, whether to keep confidence of internal nodes. :param ic2name: whether to convert confidence of internal nodes to their names. :param nodes: bool, discard or keep name of internal nodes. :param brlen: bool, discard or keep branch lengths. :return: str, a newick tree string. """ s = '' if self.tree: tree = deepcopy(self.tree) else: return s n = self.leaves for clade in tree.find_clades(): if ic2name: if clade.confidence: if not clade.is_terminal() and not clade.name: clade.name = str(clade.confidence) clade.confidence = None if not ic: clade.confidence = None if nodes: clade.confidence = None if not clade.is_terminal() and not clade.name: clade.name = 'NODE{}'.format(n) n += 1 else: if ic2name: pass else: if clade.name and not clade.is_terminal(): clade.name = None if not brlen: clade.branch_length = 0.0 s = tree.format('newick').strip() # Remove branch length if brlen set to False if not brlen: s = re.sub(r':0\.\d+', '', s) # Remove branch lengths if only unscaled tree (topology) was given if not self.length: s = re.sub(r':0\.\d+', '', s) return s def file(self, filename, ic=True, ic2name=False, nodes=False, brlen=True): """ Write a tree to a file after manipulating. :param filename: str, the name of the tree output file :param ic: bool, whether to keep confidence of internal nodes. :param ic2name: whether to convert confidence of internal nodes to their names. :param nodes: bool, discard or keep name of internal nodes. :param brlen: bool, discard or keep branch lengths. :return: str, a newick tree string. """ s = self.string(ic=ic, ic2name=ic2name, nodes=nodes, brlen=brlen) try: with open(filename, 'w') as o: o.write('{}\n'.format(s)) except IOError as err: error(err) return filename def trim(msa, fmt='fasta', outfile='', verbose=False): """ Remove gaps and ambiguous characters from protein multiple sequence alignment (MSA) file or a dictionary object of MSA records. :param msa: str or dict, pathname of the protein (MSA) multiple sequence alignment file or a dictionary object of of MSA records. :param fmt: format of the MSA file, if msa is the pathname of a MSA file. :param outfile: pathname for saving trimmed MSA to a file, if not set, trimmed sequences will only be returned without saving to a file. :param verbose: bool, invoke verbose or silent process mode, default: False, silent mode. :return: dict, trimmed MSA in a dictionary. .. note:: Ambiguous characters (characters not in ARNDCQEGHILKMFPSTWYV) will be treated as gaps and removed. The trimmed alignment file will be saved to outfile in FASTA format if outfile is not a empty string and there are sites left after trimming. Whether the outfile is set or not, `trim()` always returns trimmed MSA in a dictionary (even a empty dict). Careful with PHYLIP format MSA files, `trim()` use `Bio.AlignIO` to read MSA file, users are responsible for given the right name for PHYLIP format files, e.g. phylip-relaxed or phylip-sequential. """ level = logging.INFO if verbose else logging.ERROR logger.setLevel(level) if isinstance(msa, str): if not os.path.isfile(msa): error('Alignment {} is not a file or does not exist.'.format(msa)) sys.exit(1) try: records = AlignIO.read(msa, fmt) except ValueError: error('Alignment {} contains non equal length sequences.'.format( msa)) sys.exit(1) length, label = records.get_alignment_length(), msa records = {a.id: a.seq for a in records} elif isinstance(msa, dict): length = list(set([len(v) for v in msa.values()])) if not len(length) == 1: error('Alignment object contains non equal length sequences.') sys.exit(1) length, label = length[0], 'alignment record' records = msa else: error('Invalid msa for trimming, msa should be a pathname of MSA file' 'or a dictionary object of sequence name and sequence pairs.') sys.exit(1) info('Trimming gaps and ambiguous characters for {}'.format(label)) trimmed = defaultdict(list) for i in range(length): column = set([s[i] for s in records.values()]) if column.issubset(AMINO_ACIDS): for k, v in records.items(): trimmed[k].append(v[i]) if all(trimmed.values()): trimmed = {k: ''.join(v) for k, v in trimmed.items()} if outfile: try: with open(outfile, 'w') as o: o.writelines('>{}\n{}\n'.format(k, v) for k, v in trimmed.items()) except IOError: outfile = '' warn('IOError, failed to save trimmed alignment.') else: trimmed = {} warn('Successfully removed all gaps and ambiguous characters, but ' 'no site was left after trimming.') if outfile: warn('No trimmed alignment was saved.') outfile = '' return trimmed, outfile def indent(text, prefix, predicate=None): """ A copy of textwrap.indent() method introduce in Python 3.3. """ if predicate is None: def predicate(line): return line.strip() def prefixed_lines(): for line in text.splitlines(True): yield (prefix + line if predicate(line) else line) return ''.join(prefixed_lines()) if __name__ == '__main__': pass <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import glob import logging import argparse from collections import namedtuple from scipy.stats import poisson LEVEL = logging.INFO LOGFILE, LOGFILEMODE = '', 'w' HANDLERS = [logging.StreamHandler(sys.stdout)] if LOGFILE: HANDLERS.append(logging.FileHandler(filename=LOGFILE, mode=LOGFILEMODE)) logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=HANDLERS, level=LEVEL) logger = logging.getLogger('[iTOL]') warn, info, error = logger.warning, logger.info, logger.error def _tester(obs, exp, values, alpha=0.05): """ One sample T-test to determine whether the observed value is statistically significantly different to the expected value. :param obs: int, observed value. :param exp: float, the expected value. :param values: list or tuple, a list of expected values where exp was calculated. :param alpha: float, significance level. :return: float, p value of the T-test. """ try: from scipy import stats except ImportError: warn('SciPy package not installed, statistical test aborted.') return None t = stats.ttest_1samp(values, obs) return t[1] def _poisson(obs, exp, values): p = poisson.cdf(obs, exp) if obs <= exp else 1 - poisson.cdf(obs, exp) return p def detect(branchpair=None, pars=None, cons=None, wd='', fn='', tester=None, printout=True, verbose=True): """ Pairwise comparison for parallel and convergent amino acid replacements in protein sequences. :param branchpair: list, a list of branch pairs need to be tested. :param pars: dict, a dict object stores parallel changes. :param cons: dict, a dict object stores convergent changes. :param wd: str, path to the work directory. Without specifying, it will be set to current work directory. A file ends with '.counts.tsv' in the work directory will be used if neither pars nor cons was provided. :param fn: str: path to the result file. :param tester: function, a function for test the differences. :param printout: bool, print out the test results (default) or only return the test result without printing them out. :param verbose: bool, invoke verbose or silent process mode, default: False, silent mode. :return: list, a list of test results. """ logger.setLevel(logging.INFO if verbose else logging.ERROR) if pars is None or cons is None: wd = wd if wd else os.getcwd() if wd and os.path.isdir(wd): fns = glob.glob(os.path.join(wd, '*.counts.tsv')) if fns: fn = fns[0] else: error('No result file was found, detect aborted.') sys.exit(1) elif fn: if not os.path.isfile(fn): error('Result {} is not a file or does not exist, detect ' 'aborted.'.format(fn)) sys.exit(1) else: error('The wd {} is not a directory or does not exist, detect ' 'aborted.'.format(wd)) sys.exit(1) pars, cons = {}, {} with open(fn) as f: for line in f: blocks = line.strip().split() if blocks[0] == 'P': pars[blocks[1]] = blocks[2:] elif blocks[0] == 'C': cons[blocks[1]] = blocks[2:] elif not isinstance(pars, dict) and not isinstance(cons, dict): error('Invalid pars and cons, they need to be dict objects, detect ' 'aborted.') sys.exit(1) if isinstance(branchpair, str): pairs = [branchpair] elif isinstance(branchpair, (list, tuple)): pairs = branchpair else: info('No interested branch branchpair assigned, doing test for all ' 'branch pairs.') pairs = list(pars.keys()) ps = [] for p in pairs: if p in pars: ps.append(p) else: pr = '-'.join(p.split('-')[::-1]) if pr in pars: ps.append(pr) else: warn('Invalid branch branchpair {} was ignored'.format(p)) R = namedtuple('result', 'bp po pe p1 co ce p2') results = [] for item in ps: p, c = pars[item], cons[item] tester = tester if tester else _poisson (po, pe, *pv), (co, ce, *cv) = p, c po, pe, pv = int(po), float(pe), [int(i) for i in pv] co, ce, cv = int(co), float(ce), [int(i) for i in cv] p1, p2 = tester(po, pe, pv), tester(co, ce, cv) results.append(R(*[item, po, pe, p1, co, ce, p2])) if printout and results: top = ''.join(['+', '-' * 78, '+']) h1 = ''.join(['|', ' ' * 34, '|', 'Parallelism'.center(21), '|', 'Convergence'.center(21), '|']) line1 = ''.join(['+', '-' * 34, '+', '------+', '------+', '-------+', '------+', '------+', '-------+']) h2 = ''.join(['|', 'Branch Pair'.center(34), '|'] + [ ' Obs. | Exp. |P-value|'] * 2) print('Parallel and convergent amino acid replacements among {} ' 'branch pairs'.format(len(results))) print(top) print(h1) print(line1) print(h2) for result in results: print(line1) bp = result.bp.center(34) empty = 'None'.center(7) po, pe = str(result.po).center(6), '{:5.4f}'.format(result.pe) p1 = '{:2.1E}'.format(result.p1) if result.p1 else empty co, ce = str(result.co).center(6), '{:5.4f}'.format(result.ce) p2 = '{:2.1E}'.format(result.p2) if result.p2 else empty print('|{}|'.format('|'.join([bp, po, pe, p1, co, ce, p2]))) print(top) output = os.path.join(wd, 'pairwise.comparison.tsv') with open(output, 'w') as o: o.write('branchpair\tP_Obs\tP_Exp\tp1\tC_Obs\tC_Exp\tp2\n') o.writelines( '{}\t{}\t{:.4f}\t{:2.1E}\t{}\t{:.4f}\t{:2.1E}\n'.format(*result) for result in results) info('Successfully saved comparison results to {}'.format(output)) return results def main(): des = """Pairwise comparison for parallel and convergent amino acid replacements in protein sequences""" epilog = """ Only support Poisson test or one-sample t test, if you expect other tests, please implement the test by yourself and using detect() in Python instead of command line. """ formatter = argparse.RawDescriptionHelpFormatter parse = argparse.ArgumentParser(description=des, prog='detect', usage='%(prog)s RESULT [OPTIONS]', formatter_class=formatter, epilog=epilog) parse.add_argument('RESULT', help='Path to the result file contains identified ' 'parallel and convergent changes.') parse.add_argument('-b', '--branchpair', help='Comma separated branch pairs.') parse.add_argument('-v', '--verbose', action='store_true', help='Invoke verbose or silent (default) process mode.') args = parse.parse_args() result, bp = args.RESULT, args.branchpair if bp: bp = bp.split(',') detect(branchpair=bp, fn=result, verbose=args.verbose) if __name__ == '__main__': main() <file_sep>biopython==1.73 numpy==1.16.1 scipy==1.2.0 Sphinx==1.8.4 <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Providing a common interface for aligning multiple sequences using various align programs. Users are only asked to provide an alignment programs's executable and an multiple sequence file in FASTA format. The general use function ``msa()`` will always return the pathname of the alignment output file or exit with an error code 1 and an error message logged. Users are recommended to only use function ``msa()`` and avoid to use any private functions inside the module. However, we strongly recommend users to implement new private functions for additional alignment programs that they are interested and incorporate them into the general use function ``msa()``. """ import os import sys import shutil import logging import argparse import tempfile try: from textwrap import indent except ImportError: from ProtParCon.utilities import indent from subprocess import PIPE, Popen from ProtParCon.utilities import basename, trim LEVEL = logging.INFO LOGFILE, LOGFILEMODE = '', 'w' HANDLERS = [logging.StreamHandler(sys.stdout)] if LOGFILE: HANDLERS.append(logging.FileHandler(filename=LOGFILE, mode=LOGFILEMODE)) logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=HANDLERS, level=LEVEL) logger = logging.getLogger('[iMC]') warn, info, error = logger.warning, logger.info, logger.error def _guess(exe): """ Guess the name of a multiple sequence alignment (MSA) program according to its executable. :param exe: str, path to the executable of a MSA program. :return: tuple, name of the MSA program and the corresponding function. """ aligner, func = None, None aligners = {'muscle': _muscle, 'mafft': _mafft, 'clustal': _clustal, 't-coffee': _tcoffee} try: process = Popen([exe, '--help'], stdout=PIPE, stderr=PIPE, universal_newlines=True) outs, errs = process.communicate(timeout=10) out = outs or errs out = out[:100] for a, f in aligners.items(): if a.upper() in out or a.title() in out: aligner, func = a, f break except OSError: error('The aligner exe: {} is empty or may not be an valid executable ' 'of a sequence align program.'.format(exe)) sys.exit(1) return aligner, func def _mafft(exe, seq, outfile): """ Align multiple sequences using MAFFT_. :param exe: str, path to the executable of a multiple sequence align program. :param seq: str, path to the multiple sequence file (must in FASTA format). :param seq: str, path to the aligned sequence output file (in FASTA format). :return: str, path to the aligned sequence output file (in FASTA format). .. _MAFFT: https://mafft.cbrc.jp/alignment/software/ """ args = [exe, '--quiet', seq] try: with open(outfile, 'w') as stdout: process = Popen(args, stdout=stdout, stderr=PIPE, universal_newlines=True) code = process.wait() except OSError: msg = 'Failed to write alignment to outfile {}'.format(outfile) error('Aligning sequence: {} via MUSCLE failed due to:\n\tIOError, ' 'failed to write alignment to outfile: {}.'.format(seq, outfile)) sys.exit(1) if code: if os.path.isfile(outfile): os.remove(outfile) msg = indent(process.stderr.read(), prefix='\t') process.stderr.close() error('Aligning sequence: {} via MAFFT failed due to:\n{}.'.format(seq, msg)) sys.exit(1) return outfile def _muscle(exe, seq, outfile): """ Align multiple sequences using MUSCLE_. :param exe: str, path to the executable of a multiple sequence align program. :param seq: str, path to the multiple sequence file (must in FASTA format). :param seq: str, path to the aligned sequence output file (in FASTA format). :return: str, path to the aligned sequence output file (in FASTA format). .. _MUSCLE: https://www.drive5.com/muscle/ """ args = [exe, '-in', seq, '-out', outfile, '-quiet'] process = Popen(args, stdout=PIPE, stderr=PIPE, universal_newlines=True) code = process.wait() if code: if os.path.isfile(outfile): os.remove(outfile) msg = process.stderr.read() or process.stdout.read() process.stdout.close(), process.stderr.close() error('Aligning sequence: {} via MUSCLE failed due to:\n{}.'.format( seq, indent(msg, prefix='\t'))) sys.exit(1) else: process.poll() return outfile def _clustal(exe, seq, outfile): """ Align multiple sequences using `CLUSTAL (OMEGA)`_. :param exe: str, path to the executable of a multiple sequence align program. :param seq: str, path to the multiple sequence file (must in FASTA format). :param seq: str, path to the aligned sequence output file (in FASTA format). :return: str, path to the aligned sequence output file (in FASTA format). .. _`CLUSTAL (OMEGA)`: http://www.clustal.org/omega/ """ args = [exe, '-i', seq, '-o', outfile] if os.path.isfile(outfile): args.append('--force') process = Popen(args, stdout=PIPE, stderr=PIPE, universal_newlines=True) code = process.wait() if code: if os.path.isfile(outfile): os.remove(outfile) msg = process.stderr.read() or process.stdout.read() process.stdout.close(), process.stderr.close() error('Aligning sequence: {} via CLUSTAL failed due to:\n{}.'.format( seq, indent(msg, prefix='\t'))) sys.exit(1) return outfile def _tcoffee(exe, seq, outfile): """ Align multiple sequences using `T-COFFEE`_. :param exe: str, path to the executable of a multiple sequence align program. :param seq: str, path to the multiple sequence file (must in FASTA format). :param seq: str, path to the aligned sequence output file (in FASTA format). :return: str, path to the aligned sequence output file (in FASTA format). .. _`T-COFFEE`: http://www.tcoffee.org/Projects/tcoffee/ """ wd = tempfile.mkdtemp(dir=os.path.dirname(seq)) args = [exe, '-in', seq, '-outfile', outfile, '-output', 'fasta_aln', '-run_name', 't-coffee-alignment', '-quiet'] try: process = Popen(args, stderr=PIPE, universal_newlines=True, cwd=wd) code = process.wait() if code: if os.path.isfile(outfile): os.remove(outfile) msg = process.stderr.read() or process.stdout.read() process.stderr.close() error('Aligning sequence: {} via T-COFFEE failed due to:\n{}.' .format(seq, indent(msg, prefix='\t'))) sys.exit(1) finally: shutil.rmtree(wd) return outfile def msa(exe, seq, outfile='', trimming=False, verbose=False): """ General use function for multiple sequence alignment (MSA). :param exe: str, path to the executable of a MSA program. :param seq: str, path to the multiple sequence file (must in FASTA format). :param outfile: str, path to the aligned sequence output (FASTA) file, default: [basename].[aligner].fasta, where basename is the filename of the sequence file without known FASTA file extension, aligner is the name of the aligner program in lowercase, and fasta is the extension for fasta format file. :param trimming: bool, trim gaps and ambiguous sites if True, otherwise, leave them untouched. :param verbose: bool, invoke verbose or silent process mode, default: False, silent mode. :return: str, path to the aligned sequence output file (in FASTA format). """ level = logging.INFO if verbose else logging.ERROR logger.setLevel(level) if os.path.isfile(seq): sequence = os.path.abspath(seq) if exe: aligner, func = _guess(exe) if func is None: error('Invalid or unsupported aligner executable (exe): {}, ' 'alignment aborted.'.format(exe)) sys.exit(1) else: error('Invalid aligner executable (exe), empty string, sequence ' 'alignment aborted.') sys.exit(1) if not outfile: outfile = '.'.join([basename(sequence), aligner, 'fasta']) if os.path.isfile(outfile): info('Found pre-existing alignment file.') else: info('Aligning sequence {} using {}.'.format(sequence, aligner.upper())) outfile = func(exe, sequence, outfile) info('Successfully aligned sequence, alignment was saved to ' '{}.'.format(outfile)) else: error('Sequence: {} is not a file or does not exist.'.format(seq)) sys.exit(1) if trimming: clean = ''.join([basename(outfile), '.trimmed.fasta']) if os.path.isfile(clean): outfile = clean info('Found pre-existing trimmed alignment.') else: _, outfile = trim(outfile, outfile=clean, verbose=verbose) return outfile def main(): des = 'Common interface for aligning multiple sequences.' epilog = """ In order to make this interface common and simple, only FASTA format is the acceptable sequence file format. Without specifying the alignment output, alignment will be saved to a file named in the format of [basename].[aligner].fasta, where basename is the filename of the sequence file without extension, aligner is the name of the align program (in lower case), and fasta is the extension for FASTA format file. Under silent process mode, only errors was logged, while under verbose mode, all errors, warnings and information about processing details will be logged. """ formatter = argparse.RawDescriptionHelpFormatter parse = argparse.ArgumentParser(description=des, prog='ProtParCon-msa', usage='%(prog)s EXECUTABLE SEQUENCE', formatter_class=formatter, epilog=epilog) parse.add_argument('EXECUTABLE', help='path to the executable of a multiple sequence ' 'align program.') parse.add_argument('SEQUENCE', help='Path to the multiple sequence input file ' '(must in FASTA format).') parse.add_argument('-o', '--output', help='Path to the aligned multiple sequence output' 'file (in FASTA format).') parse.add_argument('-t', '--trim', action='store_true', help='Trim gaps and ambiguous sites or leave them ' 'untouched (default).') parse.add_argument('-v', '--verbose', action='store_true', help='Invoke verbose or silent (default) process mode.') args = parse.parse_args() seq, exe, out = args.SEQUENCE, args.EXECUTABLE, args.output msa(exe, seq, outfile=out, verbose=args.verbose, trimming=args.trim) if __name__ == '__main__': main() <file_sep>Changelog ========= [3.1] - 2019-03-09 ================== Changed ~~~~~~~ - Fixed the wrong version number in docs. [3.0] - 2019-03-09 ================== Added ~~~~~ - Added module detect and command line tool detect Changed ~~~~~~~ - Fixed some bugs [2.0] - 2019-03-06 ================== Added ~~~~~ - Added option for identifying parallel and convergent amino acid replacements for both independent and all branch pairs. - Added method for identifying divergent amino acid replacements. - Added ancestral state probability for ASR using CODEML (PAML) - Added method for identifying parallel, convergent, and divergent amino acid replacements for sites with probability beyond a specified threshold. Changed ~~~~~~~ - Wrapped empirical amino acid replacement models to a Python module. - Simplified flags for command line arguments. Removed ~~~~~~~ - Removed text files of empirical amino acid replacements models. [1.0] - 2018-11-13 ================== Released ProtParCon Version 1.0 Deals attach_money Profile person Otto pets
9bd162a54e9861def588ffe37c10f90d19267129
[ "HTML", "reStructuredText", "Python", "Text", "Shell" ]
35
Python
iBiology/ProtParCon
ac0a7100a9c52c0412b579728f7a3821a9f074fc
153f1a326b8237ebd1b7e6a8ace4e09ace5fe625
refs/heads/main
<file_sep>local players = {} local playernames = {} local GuildID = 1000000000 -- : -- change this to your GuildID local DiscToken = <PASSWORD>." -- change this to your own discord token local FormattedToken = "Bot " .. DiscToken ESX = nil local loaded = false TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) CreateThread(function() Wait(200) playerinfo = Database(config.Mysql,'fetchAll','SELECT * FROM users', {}) for k,v in pairs(playerinfo) do playernames[v.identifier] = v end loaded = true print("SCOREBOARD LOADED") TriggerClientEvent("renzu_scoreboard:loaded",-1) end) function UploadAvatar(identifier, avatar) Database(config.Mysql,'execute','UPDATE users SET avatar = @avatar WHERE identifier = @identifier', { ['@avatar'] = avatar, ['@identifier'] = identifier }) end RegisterServerEvent('renzu_scoreboard:avatarupload') AddEventHandler('renzu_scoreboard:avatarupload', function(url) local source = tonumber(source) local xPlayer = ESX.GetPlayerFromId(source) if players[source] ~= nil then UploadAvatar(xPlayer.identifier, url) players[source].image = url end end) function GetAvatar(source,first,last) local source = source local image = nil local steamhex = GetPlayerIdentifier(source, 0) local initials = math.random(1,#config.RandomAvatars) local letters = config.RandomAvatars[initials] if steamhex ~= nil and steamhex ~= '' then local steamid = tonumber(string.gsub(steamhex, 'steam:', ''), 16) PerformHttpRequest('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' .. GetConvar('steam_webApiKey') .. '&steamids=' .. steamid, function(e, data, h) local data = json.decode(data) local avatar = data.response.players[1].avatarfull image = avatar end) local c = 0 while image == nil and c < 100 do c = c + 1 Wait(1) end if image == nil then image = 'https://ui-avatars.com/api/?name='..first..'+'..last..'&background='..letters.background..'&color='..letters.color..'' end return image else return 'https://ui-avatars.com/api/?name='..first..'+'..last..'&background='..letters.background..'&color='..letters.color..'' end end local loading = {} local qued = {} RegisterServerEvent('renzu_scoreboard:playerloaded') AddEventHandler('renzu_scoreboard:playerloaded', function() local source = tonumber(source) local xPlayer = ESX.GetPlayerFromId(source) local initials = math.random(1,#config.RandomAvatars) local letters = config.RandomAvatars[initials] if xPlayer ~= nil and playernames[xPlayer.identifier] ~= nil and playernames[xPlayer.identifier].firstname ~= nil and playernames[xPlayer.identifier].firstname ~= '' then CreatePlayer(source,xPlayer) elseif xPlayer ~= nil and playernames[xPlayer.identifier] == nil then CreatePlayer(source,xPlayer,true) else print('Xplayer is nil or player is not register in server table') end end) function CreatePlayer(source,xPlayer,quee) local initials = math.random(1,#config.RandomAvatars) local letters = config.RandomAvatars[initials] CreateThread(function() if quee then print("id# "..source.." QUED") if xPlayer ~= nil and playernames[xPlayer.identifier] == nil then playernames[xPlayer.identifier] = {} end while playernames[xPlayer.identifier].firstname == nil or playernames[v.identifier].firstname ~= nil and playernames[v.identifier].firstname:len() >= 3 do Wait(10000) print("id# "..source.." CHECKING PLAYER INFO") local playerinfo = Database(config.Mysql,'fetchAll','SELECT * FROM users WHERE identifier = @identifier', {['@identifier'] = xPlayer.identifier}) if #playerinfo > 0 and playerinfo[1] ~= nil and playerinfo[1].firstname ~= nil and playerinfo[1].firstname ~= '' and playerinfo[1].firstname ~= 'null' then for k,v in pairs(playerinfo) do playernames[v.identifier] = v end print("id# "..source.." PLAYER IS REGISTERED Successfully",playernames[xPlayer.identifier].firstname) -- you can pass any client events here once the player is loaded ex. playerloaded event break else print('id# '..source..' is requed, still creating character?') end end end if players[source] == nil and xPlayer ~= nil and loading[source] == nil then loading[source] = true playerdata = nil local f,l,v = '', '', false if playernames[xPlayer.identifier] ~= nil and playernames[xPlayer.identifier].firstname ~= nil then f = playernames[xPlayer.identifier].firstname l = playernames[xPlayer.identifier].lastname end if config.ShowVips and playernames[xPlayer.identifier] ~= nil then if playernames[xPlayer.identifier].vip ~= nil then v = playernames[xPlayer.identifier].vip ~= nil end end local name = GetPlayerName(source) if (name:find("src") ~= nil) then name = "Blacklisted name" end if (name:find("script") ~= nil) then name = "Blacklisted name" end if config.UseSelfUploadAvatar and playernames[xPlayer.identifier] ~= nil then if playernames[xPlayer.identifier].avatar ~= nil and playernames[xPlayer.identifier].avatar ~= '' then avatar = playernames[xPlayer.identifier].avatar else avatar = 'https://ui-avatars.com/api/?name='..f..'+'..l..'&background='..letters.background..'&color='..letters.color..'' end elseif config.UseDiscordAvatar then avatar = GetDiscordAvatar(source,f,l) else avatar = GetAvatar(source,f,l) end if players[source] == nil then players[source] = {id = source, image = avatar, first = f, last = l, name = name, discordname = GetDiscordName(source,f,l), vip = v} end end end) end local pings = {} ESX.RegisterServerCallback('renzu_scoreboard:playerlist', function (source, cb) local list = {} local whitelistedjobs = {} local source = tonumber(source) for k,v in pairs(players) do local xPlayer = ESX.GetPlayerFromId(tonumber(v.id)) for _, job in pairs(config.whitelistedjobs) do local job = job.name if whitelistedjobs[job] == nil then whitelistedjobs[job] = 0 end if xPlayer ~= nil and xPlayer.job.name == job then whitelistedjobs[job] = whitelistedjobs[job] + 1 break end end if xPlayer ~= nil then local ping = nil if pings[v.id] == nil and config.CheckpingOnce then pings[v.id] = GetPlayerPing(v.id) elseif not config.CheckpingOnce then ping = GetPlayerPing(v.id) end if config.CheckpingOnce and pings[v.id] ~= nil then ping = pings[v.id] end table.insert(list, {id = v.id, job = xPlayer.job.label, name = v.name, discordname = v.discordname, firstname = v.first, lastname = v.last, image = v.image, ping = ping, admin = xPlayer.getGroup() == 'superadmin', vip = v.vip}) end end local count = 0 for k,v in pairs(players) do count = count + 1 end xPlayer = ESX.GetPlayerFromId(source) if xPlayer ~= nil and players[source] ~= nil then cb(list, whitelistedjobs, count, xPlayer.getGroup() == 'superadmin',players[source].image) end end) RegisterServerEvent('playerDropped') AddEventHandler('playerDropped', function() local source = tonumber(source) players[source] = nil loading[source] = nil end) function Database(plugin,type,query,var) local query = query local type= type local var = var local plugin = plugin if type == 'fetchAll' and plugin == 'mysql-async' then return MySQL.Sync.fetchAll(query, var) end if type == 'execute' and plugin == 'mysql-async' then MySQL.Sync.execute(query,var) end if type == 'execute' and plugin == 'ghmattisql' then exports['ghmattimysql']:execute(query, var) end if type == 'fetchAll' and plugin == 'ghmattisql' then local data = nil exports.ghmattimysql:execute(query, var, function(result) data = result end) while data == nil do Wait(0) end return data end end function DiscordRequest(method, endpoint, jsondata) local data = nil PerformHttpRequest("https://discordapp.com/api/"..endpoint, function(errorCode, resultData, resultHeaders) data = {data=resultData, code=errorCode, headers=resultHeaders} end, method, #jsondata > 0 and json.encode(jsondata) or "", {["Content-Type"] = "application/json", ["Authorization"] = FormattedToken}) while data == nil do Citizen.Wait(0) end return data end function DiscordUserData(id) local member = DiscordRequest("GET", ("guilds/%s/members/%s"):format(GuildID, id), {}) if member.code == 200 then local Userdata = json.decode(member.data) return Userdata.user end end function GetDiscordAvatar(user,f,l) local id = string.gsub(ExtractIdentifiers(user).discord, "discord:", "") local Userdata = DiscordUserData(id) if Userdata ~= nil then if (Userdata.avatar:sub(1, 1) and Userdata.avatar:sub(2, 2) == "_") then imgURL = "https://cdn.discordapp.com/avatars/" .. id .. "/" .. Userdata.avatar .. ".gif"; else imgURL = "https://cdn.discordapp.com/avatars/" .. id .. "/" .. Userdata.avatar .. ".png" end else local initials = math.random(1,#config.RandomAvatars) local letters = config.RandomAvatars[initials] imgURL = 'https://ui-avatars.com/api/?name='..f..'+'..l..'&background='..letters.background..'&color='..letters.color..'' end return imgURL end function GetDiscordName(user,f,l) if config.useDiscordname then local id = string.gsub(ExtractIdentifiers(user).discord, "discord:", "") local Userdata = DiscordUserData(id) if Userdata ~= nil then return Userdata.username else return GetPlayerName(user) or ''..f..' '..l..'' -- default end else return GetPlayerName(user) -- default end end function ExtractIdentifiers(src) local identifiers = { steam = "", ip = "", discord = "", license = "", xbl = "", live = "" } --Loop over all identifiers for i = 0, GetNumPlayerIdentifiers(src) - 1 do local id = GetPlayerIdentifier(src, i) --Convert it to a nice table. if string.find(id, "steam") then identifiers.steam = id elseif string.find(id, "ip") then identifiers.ip = id elseif string.find(id, "discord") then identifiers.discord = id elseif string.find(id, "license") then identifiers.license = id elseif string.find(id, "xbl") then identifiers.xbl = id elseif string.find(id, "live") then identifiers.live = id end end return identifiers end
6de9a36d71e2ff0340ef858d2621e950e7306962
[ "Lua" ]
1
Lua
WhereiamL/renzu_scoreboard
57cf611a6abeb2c81bc61ca9cecd629cf20afafa
ad9c7ddf7bc50bbbd829c03e7a090c2b16dbfb86
refs/heads/master
<repo_name>krzysztofzablocki/Strongify<file_sep>/Package.swift // swift-tools-version:5.3 import PackageDescription let package = Package( name: "Strongify", platforms: [ .macOS(.v10_10), .iOS(.v9), .tvOS(.v9), .watchOS(.v2) ], products: [ .library(name: "Strongify", targets: ["Strongify"]), ], targets: [ .target(name: "Strongify", path: "Sources"), .testTarget(name: "StrongifyTests", dependencies: ["Strongify"]), ] ) <file_sep>/Sources/Strongify.swift // // Strongify.swift // Strongify // // Created by <NAME> on 03/04/2017. // Copyright © 2017 Strongify. All rights reserved. // /// This file is code-generated, don't modify. /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject>(weak context1: Context1?, closure: @escaping(Context1) -> Void) -> () -> Void { return { [weak context1] in guard let strongContext1 = context1 else { return } closure(strongContext1) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Argument1>(weak context1: Context1?, closure: @escaping(Context1, Argument1) -> Void) -> (Argument1) -> Void { return { [weak context1] argument1 in guard let strongContext1 = context1 else { return } closure(strongContext1, argument1) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Argument1, Argument2>(weak context1: Context1?, closure: @escaping(Context1, Argument1, Argument2) -> Void) -> (Argument1, Argument2) -> Void { return { [weak context1] argument1, argument2 in guard let strongContext1 = context1 else { return } closure(strongContext1, argument1, argument2) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Argument1, Argument2, Argument3>(weak context1: Context1?, closure: @escaping(Context1, Argument1, Argument2, Argument3) -> Void) -> (Argument1, Argument2, Argument3) -> Void { return { [weak context1] argument1, argument2, argument3 in guard let strongContext1 = context1 else { return } closure(strongContext1, argument1, argument2, argument3) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Argument1, Argument2, Argument3, Argument4>(weak context1: Context1?, closure: @escaping(Context1, Argument1, Argument2, Argument3, Argument4) -> Void) -> (Argument1, Argument2, Argument3, Argument4) -> Void { return { [weak context1] argument1, argument2, argument3, argument4 in guard let strongContext1 = context1 else { return } closure(strongContext1, argument1, argument2, argument3, argument4) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5>(weak context1: Context1?, closure: @escaping(Context1, Argument1, Argument2, Argument3, Argument4, Argument5) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5) -> Void { return { [weak context1] argument1, argument2, argument3, argument4, argument5 in guard let strongContext1 = context1 else { return } closure(strongContext1, argument1, argument2, argument3, argument4, argument5) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6>(weak context1: Context1?, closure: @escaping(Context1, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6) -> Void { return { [weak context1] argument1, argument2, argument3, argument4, argument5, argument6 in guard let strongContext1 = context1 else { return } closure(strongContext1, argument1, argument2, argument3, argument4, argument5, argument6) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7>(weak context1: Context1?, closure: @escaping(Context1, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7) -> Void { return { [weak context1] argument1, argument2, argument3, argument4, argument5, argument6, argument7 in guard let strongContext1 = context1 else { return } closure(strongContext1, argument1, argument2, argument3, argument4, argument5, argument6, argument7) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8>(weak context1: Context1?, closure: @escaping(Context1, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8) -> Void { return { [weak context1] argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8 in guard let strongContext1 = context1 else { return } closure(strongContext1, argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject>(weak context1: Context1?, _ context2: Context2?, closure: @escaping(Context1, Context2) -> Void) -> () -> Void { return { [weak context1, weak context2] in guard let strongContext1 = context1, let strongContext2 = context2 else { return } closure(strongContext1, strongContext2) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Argument1>(weak context1: Context1?, _ context2: Context2?, closure: @escaping(Context1, Context2, Argument1) -> Void) -> (Argument1) -> Void { return { [weak context1, weak context2] argument1 in guard let strongContext1 = context1, let strongContext2 = context2 else { return } closure(strongContext1, strongContext2, argument1) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Argument1, Argument2>(weak context1: Context1?, _ context2: Context2?, closure: @escaping(Context1, Context2, Argument1, Argument2) -> Void) -> (Argument1, Argument2) -> Void { return { [weak context1, weak context2] argument1, argument2 in guard let strongContext1 = context1, let strongContext2 = context2 else { return } closure(strongContext1, strongContext2, argument1, argument2) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Argument1, Argument2, Argument3>(weak context1: Context1?, _ context2: Context2?, closure: @escaping(Context1, Context2, Argument1, Argument2, Argument3) -> Void) -> (Argument1, Argument2, Argument3) -> Void { return { [weak context1, weak context2] argument1, argument2, argument3 in guard let strongContext1 = context1, let strongContext2 = context2 else { return } closure(strongContext1, strongContext2, argument1, argument2, argument3) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Argument1, Argument2, Argument3, Argument4>(weak context1: Context1?, _ context2: Context2?, closure: @escaping(Context1, Context2, Argument1, Argument2, Argument3, Argument4) -> Void) -> (Argument1, Argument2, Argument3, Argument4) -> Void { return { [weak context1, weak context2] argument1, argument2, argument3, argument4 in guard let strongContext1 = context1, let strongContext2 = context2 else { return } closure(strongContext1, strongContext2, argument1, argument2, argument3, argument4) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5>(weak context1: Context1?, _ context2: Context2?, closure: @escaping(Context1, Context2, Argument1, Argument2, Argument3, Argument4, Argument5) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5) -> Void { return { [weak context1, weak context2] argument1, argument2, argument3, argument4, argument5 in guard let strongContext1 = context1, let strongContext2 = context2 else { return } closure(strongContext1, strongContext2, argument1, argument2, argument3, argument4, argument5) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6>(weak context1: Context1?, _ context2: Context2?, closure: @escaping(Context1, Context2, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6) -> Void { return { [weak context1, weak context2] argument1, argument2, argument3, argument4, argument5, argument6 in guard let strongContext1 = context1, let strongContext2 = context2 else { return } closure(strongContext1, strongContext2, argument1, argument2, argument3, argument4, argument5, argument6) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7>(weak context1: Context1?, _ context2: Context2?, closure: @escaping(Context1, Context2, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7) -> Void { return { [weak context1, weak context2] argument1, argument2, argument3, argument4, argument5, argument6, argument7 in guard let strongContext1 = context1, let strongContext2 = context2 else { return } closure(strongContext1, strongContext2, argument1, argument2, argument3, argument4, argument5, argument6, argument7) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8>(weak context1: Context1?, _ context2: Context2?, closure: @escaping(Context1, Context2, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8) -> Void { return { [weak context1, weak context2] argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8 in guard let strongContext1 = context1, let strongContext2 = context2 else { return } closure(strongContext1, strongContext2, argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, closure: @escaping(Context1, Context2, Context3) -> Void) -> () -> Void { return { [weak context1, weak context2, weak context3] in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3 else { return } closure(strongContext1, strongContext2, strongContext3) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Argument1>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, closure: @escaping(Context1, Context2, Context3, Argument1) -> Void) -> (Argument1) -> Void { return { [weak context1, weak context2, weak context3] argument1 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3 else { return } closure(strongContext1, strongContext2, strongContext3, argument1) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Argument1, Argument2>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, closure: @escaping(Context1, Context2, Context3, Argument1, Argument2) -> Void) -> (Argument1, Argument2) -> Void { return { [weak context1, weak context2, weak context3] argument1, argument2 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3 else { return } closure(strongContext1, strongContext2, strongContext3, argument1, argument2) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Argument1, Argument2, Argument3>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, closure: @escaping(Context1, Context2, Context3, Argument1, Argument2, Argument3) -> Void) -> (Argument1, Argument2, Argument3) -> Void { return { [weak context1, weak context2, weak context3] argument1, argument2, argument3 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3 else { return } closure(strongContext1, strongContext2, strongContext3, argument1, argument2, argument3) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Argument1, Argument2, Argument3, Argument4>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, closure: @escaping(Context1, Context2, Context3, Argument1, Argument2, Argument3, Argument4) -> Void) -> (Argument1, Argument2, Argument3, Argument4) -> Void { return { [weak context1, weak context2, weak context3] argument1, argument2, argument3, argument4 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3 else { return } closure(strongContext1, strongContext2, strongContext3, argument1, argument2, argument3, argument4) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, closure: @escaping(Context1, Context2, Context3, Argument1, Argument2, Argument3, Argument4, Argument5) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5) -> Void { return { [weak context1, weak context2, weak context3] argument1, argument2, argument3, argument4, argument5 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3 else { return } closure(strongContext1, strongContext2, strongContext3, argument1, argument2, argument3, argument4, argument5) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, closure: @escaping(Context1, Context2, Context3, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6) -> Void { return { [weak context1, weak context2, weak context3] argument1, argument2, argument3, argument4, argument5, argument6 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3 else { return } closure(strongContext1, strongContext2, strongContext3, argument1, argument2, argument3, argument4, argument5, argument6) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, closure: @escaping(Context1, Context2, Context3, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7) -> Void { return { [weak context1, weak context2, weak context3] argument1, argument2, argument3, argument4, argument5, argument6, argument7 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3 else { return } closure(strongContext1, strongContext2, strongContext3, argument1, argument2, argument3, argument4, argument5, argument6, argument7) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, closure: @escaping(Context1, Context2, Context3, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8) -> Void { return { [weak context1, weak context2, weak context3] argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3 else { return } closure(strongContext1, strongContext2, strongContext3, argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, closure: @escaping(Context1, Context2, Context3, Context4) -> Void) -> () -> Void { return { [weak context1, weak context2, weak context3, weak context4] in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Argument1>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, closure: @escaping(Context1, Context2, Context3, Context4, Argument1) -> Void) -> (Argument1) -> Void { return { [weak context1, weak context2, weak context3, weak context4] argument1 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, argument1) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Argument1, Argument2>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, closure: @escaping(Context1, Context2, Context3, Context4, Argument1, Argument2) -> Void) -> (Argument1, Argument2) -> Void { return { [weak context1, weak context2, weak context3, weak context4] argument1, argument2 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, argument1, argument2) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Argument1, Argument2, Argument3>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, closure: @escaping(Context1, Context2, Context3, Context4, Argument1, Argument2, Argument3) -> Void) -> (Argument1, Argument2, Argument3) -> Void { return { [weak context1, weak context2, weak context3, weak context4] argument1, argument2, argument3 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, argument1, argument2, argument3) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Argument1, Argument2, Argument3, Argument4>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, closure: @escaping(Context1, Context2, Context3, Context4, Argument1, Argument2, Argument3, Argument4) -> Void) -> (Argument1, Argument2, Argument3, Argument4) -> Void { return { [weak context1, weak context2, weak context3, weak context4] argument1, argument2, argument3, argument4 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, argument1, argument2, argument3, argument4) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, closure: @escaping(Context1, Context2, Context3, Context4, Argument1, Argument2, Argument3, Argument4, Argument5) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5) -> Void { return { [weak context1, weak context2, weak context3, weak context4] argument1, argument2, argument3, argument4, argument5 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, argument1, argument2, argument3, argument4, argument5) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, closure: @escaping(Context1, Context2, Context3, Context4, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6) -> Void { return { [weak context1, weak context2, weak context3, weak context4] argument1, argument2, argument3, argument4, argument5, argument6 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, argument1, argument2, argument3, argument4, argument5, argument6) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, closure: @escaping(Context1, Context2, Context3, Context4, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7) -> Void { return { [weak context1, weak context2, weak context3, weak context4] argument1, argument2, argument3, argument4, argument5, argument6, argument7 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, argument1, argument2, argument3, argument4, argument5, argument6, argument7) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, closure: @escaping(Context1, Context2, Context3, Context4, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8) -> Void { return { [weak context1, weak context2, weak context3, weak context4] argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, closure: @escaping(Context1, Context2, Context3, Context4, Context5) -> Void) -> () -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5] in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Argument1>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Argument1) -> Void) -> (Argument1) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5] argument1 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, argument1) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Argument1, Argument2>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Argument1, Argument2) -> Void) -> (Argument1, Argument2) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5] argument1, argument2 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, argument1, argument2) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Argument1, Argument2, Argument3>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Argument1, Argument2, Argument3) -> Void) -> (Argument1, Argument2, Argument3) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5] argument1, argument2, argument3 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, argument1, argument2, argument3) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Argument1, Argument2, Argument3, Argument4>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Argument1, Argument2, Argument3, Argument4) -> Void) -> (Argument1, Argument2, Argument3, Argument4) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5] argument1, argument2, argument3, argument4 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, argument1, argument2, argument3, argument4) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Argument1, Argument2, Argument3, Argument4, Argument5) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5] argument1, argument2, argument3, argument4, argument5 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, argument1, argument2, argument3, argument4, argument5) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5] argument1, argument2, argument3, argument4, argument5, argument6 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, argument1, argument2, argument3, argument4, argument5, argument6) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5] argument1, argument2, argument3, argument4, argument5, argument6, argument7 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, argument1, argument2, argument3, argument4, argument5, argument6, argument7) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5] argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6) -> Void) -> () -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6] in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Argument1>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Argument1) -> Void) -> (Argument1) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6] argument1 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, argument1) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Argument1, Argument2>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Argument1, Argument2) -> Void) -> (Argument1, Argument2) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6] argument1, argument2 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, argument1, argument2) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Argument1, Argument2, Argument3>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Argument1, Argument2, Argument3) -> Void) -> (Argument1, Argument2, Argument3) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6] argument1, argument2, argument3 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, argument1, argument2, argument3) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Argument1, Argument2, Argument3, Argument4>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Argument1, Argument2, Argument3, Argument4) -> Void) -> (Argument1, Argument2, Argument3, Argument4) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6] argument1, argument2, argument3, argument4 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, argument1, argument2, argument3, argument4) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Argument1, Argument2, Argument3, Argument4, Argument5) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6] argument1, argument2, argument3, argument4, argument5 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, argument1, argument2, argument3, argument4, argument5) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6] argument1, argument2, argument3, argument4, argument5, argument6 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, argument1, argument2, argument3, argument4, argument5, argument6) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6] argument1, argument2, argument3, argument4, argument5, argument6, argument7 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, argument1, argument2, argument3, argument4, argument5, argument6, argument7) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6] argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7) -> Void) -> () -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7] in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Argument1>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Argument1) -> Void) -> (Argument1) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7] argument1 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, argument1) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Argument1, Argument2>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Argument1, Argument2) -> Void) -> (Argument1, Argument2) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7] argument1, argument2 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, argument1, argument2) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Argument1, Argument2, Argument3>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Argument1, Argument2, Argument3) -> Void) -> (Argument1, Argument2, Argument3) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7] argument1, argument2, argument3 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, argument1, argument2, argument3) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Argument1, Argument2, Argument3, Argument4>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Argument1, Argument2, Argument3, Argument4) -> Void) -> (Argument1, Argument2, Argument3, Argument4) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7] argument1, argument2, argument3, argument4 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, argument1, argument2, argument3, argument4) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Argument1, Argument2, Argument3, Argument4, Argument5) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7] argument1, argument2, argument3, argument4, argument5 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, argument1, argument2, argument3, argument4, argument5) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7] argument1, argument2, argument3, argument4, argument5, argument6 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, argument1, argument2, argument3, argument4, argument5, argument6) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7] argument1, argument2, argument3, argument4, argument5, argument6, argument7 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, argument1, argument2, argument3, argument4, argument5, argument6, argument7) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7] argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - context8: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Context8: AnyObject>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, _ context8: Context8?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Context8) -> Void) -> () -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7, weak context8] in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7, let strongContext8 = context8 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, strongContext8) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - context8: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Context8: AnyObject, Argument1>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, _ context8: Context8?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Context8, Argument1) -> Void) -> (Argument1) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7, weak context8] argument1 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7, let strongContext8 = context8 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, strongContext8, argument1) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - context8: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Context8: AnyObject, Argument1, Argument2>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, _ context8: Context8?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Context8, Argument1, Argument2) -> Void) -> (Argument1, Argument2) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7, weak context8] argument1, argument2 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7, let strongContext8 = context8 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, strongContext8, argument1, argument2) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - context8: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Context8: AnyObject, Argument1, Argument2, Argument3>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, _ context8: Context8?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Context8, Argument1, Argument2, Argument3) -> Void) -> (Argument1, Argument2, Argument3) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7, weak context8] argument1, argument2, argument3 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7, let strongContext8 = context8 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, strongContext8, argument1, argument2, argument3) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - context8: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Context8: AnyObject, Argument1, Argument2, Argument3, Argument4>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, _ context8: Context8?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Context8, Argument1, Argument2, Argument3, Argument4) -> Void) -> (Argument1, Argument2, Argument3, Argument4) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7, weak context8] argument1, argument2, argument3, argument4 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7, let strongContext8 = context8 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, strongContext8, argument1, argument2, argument3, argument4) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - context8: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Context8: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, _ context8: Context8?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Context8, Argument1, Argument2, Argument3, Argument4, Argument5) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7, weak context8] argument1, argument2, argument3, argument4, argument5 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7, let strongContext8 = context8 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, strongContext8, argument1, argument2, argument3, argument4, argument5) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - context8: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Context8: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, _ context8: Context8?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Context8, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7, weak context8] argument1, argument2, argument3, argument4, argument5, argument6 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7, let strongContext8 = context8 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, strongContext8, argument1, argument2, argument3, argument4, argument5, argument6) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - context8: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Context8: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, _ context8: Context8?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Context8, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7, weak context8] argument1, argument2, argument3, argument4, argument5, argument6, argument7 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7, let strongContext8 = context8 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, strongContext8, argument1, argument2, argument3, argument4, argument5, argument6, argument7) } } /// Creates a closure that automatically deals with weak-strong dance /// /// - Parameters: /// - context1: Any context object to weakify and strongify. /// - context2: Any context object to weakify and strongify. /// - context3: Any context object to weakify and strongify. /// - context4: Any context object to weakify and strongify. /// - context5: Any context object to weakify and strongify. /// - context6: Any context object to weakify and strongify. /// - context7: Any context object to weakify and strongify. /// - context8: Any context object to weakify and strongify. /// - closure: Closure to execute instead of the original one. public func strongify<Context1: AnyObject, Context2: AnyObject, Context3: AnyObject, Context4: AnyObject, Context5: AnyObject, Context6: AnyObject, Context7: AnyObject, Context8: AnyObject, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8>(weak context1: Context1?, _ context2: Context2?, _ context3: Context3?, _ context4: Context4?, _ context5: Context5?, _ context6: Context6?, _ context7: Context7?, _ context8: Context8?, closure: @escaping(Context1, Context2, Context3, Context4, Context5, Context6, Context7, Context8, Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8) -> Void) -> (Argument1, Argument2, Argument3, Argument4, Argument5, Argument6, Argument7, Argument8) -> Void { return { [weak context1, weak context2, weak context3, weak context4, weak context5, weak context6, weak context7, weak context8] argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8 in guard let strongContext1 = context1, let strongContext2 = context2, let strongContext3 = context3, let strongContext4 = context4, let strongContext5 = context5, let strongContext6 = context6, let strongContext7 = context7, let strongContext8 = context8 else { return } closure(strongContext1, strongContext2, strongContext3, strongContext4, strongContext5, strongContext6, strongContext7, strongContext8, argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8) } } <file_sep>/Tests/LinuxMain.swift import XCTest @testable import StrongifyTests XCTMain([ testCase(StrongifyTests.allTests), ]) <file_sep>/README.md # Strongify 1-file µframework that gets rid of weak-strong dancing in Swift. Basically allows you to go from this: ```swift target.closure = { [weak self, weak other] some, arguments in guard let strongSelf = self, let strongOther = other else { return } /// ... code } ``` To this: ```swift target.closure = strongify(weak: self, other) { strongSelf, strongOther, some, arguments in /// ... code } ``` [Read more](http://merowing.info/2017/04/stop-weak-strong-dance/) ## Installation ### Swift Package Manager Add `.Package(url: "https://github.com/krzysztofzablocki/Strongify.git", majorVersion: 1)` to your Package.swift file's dependencies. ### CocoaPods Add `pod 'Strongify'` to your Podfile. ### Carthage Add github `"krzysztofzablocki/Strongify"` to your Cartfile. ## License Strongify is available under the MIT license. See [LICENSE](LICENSE) for more information. ## Attributions I've used [SwiftPlate](https://github.com/JohnSundell/SwiftPlate) to generate xcodeproj compatible with SPM, CocoaPods and Carthage. <file_sep>/Tests/StrongifyTests/StrongifyTests.swift // // StrongifyTests.swift // Strongify // // Created by <NAME> on 03/04/2017. // Copyright © 2017 Strongify. All rights reserved. // import Foundation import XCTest import Strongify final class Target { var closure: ((_ number: Int, _ text: String) -> Void)? var deinitClosure: (() -> Void)? deinit { deinitClosure?() } } class StrongifyTests: XCTestCase { func testPropagation() { /// Arrange var received: (Target, Int, String)? let target = Target() /// Act target.closure = strongify(weak: target) { instance, number, text in received = (instance, number, text) } target.closure?(2, "61") guard let receivedTarget = received?.0, let receivedNumber = received?.1, let receivedText = received?.2 else { return XCTFail() } XCTAssertTrue(receivedTarget === target) XCTAssertTrue(receivedNumber == 2) XCTAssertTrue(receivedText == "61") } func testNoRetainCycle() { /// Arrange var targetDestroyed: Bool? /// Act autoreleasepool { let target = Target() target.closure = strongify(weak: target) { instance, number, text in } target.deinitClosure = { targetDestroyed = true } } XCTAssertTrue(targetDestroyed == true) } func testZeroArguments() { // Arrange let object = NSObject() var received: NSObject? // Act let closure: () -> Void = strongify(weak: object) { instance in received = instance } closure() guard let receivedObject = received else { return XCTFail() } XCTAssert(receivedObject === object) } } #if os(Linux) extension StrongifyTests { static var allTests : [(String, (StrongifyTests) -> () throws -> Void)] { return [ ("testExample", testExample), ] } } #endif
167ed0f0c625c50abb8ae6d43cc774e9aba59af5
[ "Swift", "Markdown" ]
5
Swift
krzysztofzablocki/Strongify
c8a151c2fdf77a1fef4143fad7999861609ef98d
309a37d05b9ba85d1bcc0a6a38d695ccc4dc5256
refs/heads/master
<file_sep>console.log("Hello World!"); // variable declaration var color; // variable assignment color = "blue"; // variable declaration & assignment var age = 35;
1e6046c3df59f18a039f85290cd2566d7ea9b282
[ "JavaScript" ]
1
JavaScript
jasonpaulso/JSD4
3c64d378136972b93105ec36e147251431ded5d0
4ef9c676227c4a0431b00dda792f1714e9855702
refs/heads/master
<repo_name>bcbankhead/angular-stuff-persist<file_sep>/lib/serverside.js require('dotenv').load(); var db = require('monk')(process.env.MONGOLAB_URI) var Post = db.get('posts') module.exports = { getPosts: function () { return Post.find({}) } }
8ffcf822ff12d2c35309b04e907e5324ddf9fdfd
[ "JavaScript" ]
1
JavaScript
bcbankhead/angular-stuff-persist
16b3293213a0e29b62327660cd0bf8bd40c9a531
ccc5a101f224329b37d12723109c929befda2f19
refs/heads/master
<file_sep>/* Part of the GUI for Processing library http://www.lagers.org.uk/g4p/index.html http://gui4processing.googlecode.com/svn/trunk/ Copyright (c) 2008-09 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package guicomponents; import java.awt.Point; import processing.core.PApplet; /** * The label component. * * @author <NAME> * */ public class GLabel extends GComponent { /** * * @param theApplet * @param text * @param x * @param y * @param width */ public GLabel(PApplet theApplet, String text, int x, int y, int width) { super(theApplet, x, y); labelCoreCtor(text, width, 0); } /** * * @param theApplet * @param text * @param x * @param y * @param width * @param height */ public GLabel(PApplet theApplet, String text, int x, int y, int width, int height) { super(theApplet, x, y); labelCoreCtor(text, width, height); } /** * * @param text * @param width * @param height */ private void labelCoreCtor(String text, int width, int height){ this.width = width; this.height = localFont.getSize() + 2 * PADV; if(height > this.height) this.height = height; opaque = false; if(text != null) setText(text); registerAutos_DMPK(true, false, false, false); } /** * Set the font & size for the label changing the height (+/-) * and width(+/-) of the label if necessary to display text. */ public void setFont(String fontname, int fontsize){ int tw = textWidth; int fs = (int) localFont.getSize(); localFont = GFont.getFont(winApp, fontname, fontsize); if(fontsize != fs) height += (fontsize - fs); setText(text); if(textWidth != tw) width += (textWidth - tw); calcAlignX(); calcAlignY(); } /** * Draw the label */ public void draw(){ if(!visible) return; winApp.pushStyle(); winApp.style(G4P.g4pStyle); Point pos = new Point(0,0); calcAbsPosition(pos); if(border != 0){ winApp.strokeWeight(border); winApp.stroke(localColor.lblBorder); } else winApp.noStroke(); if(opaque) winApp.fill(localColor.lblBack); else winApp.noFill(); winApp.rect(pos.x,pos.y, width, height); // Draw text winApp.noStroke(); winApp.fill(localColor.lblFont); winApp.textFont(localFont, localFont.getSize()); winApp.text(text, pos.x + alignX, pos.y + alignY, width, height); // winApp.text(text, pos.x + alignX, pos.y + (height - localFont.getFont().getSize())/2 - PADV, width - PADH - 2* border, height); winApp.popStyle(); } } <file_sep>/* Part of the GUI for Processing library http://www.lagers.org.uk/g4p/index.html http://gui4processing.googlecode.com/svn/trunk/ Copyright (c) 2010 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package guicomponents; import java.awt.Point; import java.awt.event.MouseEvent; import processing.core.PApplet; import processing.core.PImage; /** * Buttons create from this class use a number of images to represent it's * state. This means that buttons can have an irregular and/or discontinuous * shape. <br> * * The image button needs 1 to 3 image files to represent the button states <br> * OFF mouse is not over button <br> * OVER mouse is over the button <br> * DOWN the mouse is over the button and a mouse button is being pressed. <br> * * If you only provide one image then this will be used for all states, if you * provide two then the second image is used for both OVER and DOWN states. <br><br> * * Rather than separate files for the different image states you can provide a * single image file which is a composite of 1-3 images (tiled horizontally) * which are used for the different button states OFF, OVER and DOWN <br><br> * * * If you don't provide a mask file then the button 'hotspot' is represented by any * non-transparent pixels in the OFF image. If you do provide a mask file then the * hotspot is defined by any white pixels in the mask image. <br><br> * * * Three types of event can be generated :- <br> * <b> PRESSED RELEASED CLICKED </b><br> * * To simplify event handling the button only fires off CLICKED events * if the mouse button is pressed and released over the button face * (the default behaviour). <br> * * Using <pre>button1.fireAllEvents(true);</pre> enables the other 2 events * for button <b>button1</b>. A PRESSED event is created if the mouse button * is pressed down over the button face, the CLICKED event is then generated * if the mouse button is released over the button face. Releasing the * button off the button face creates a RELEASED event. <br> * * * @author <NAME> * */ public class GImageButton extends GComponent { // Button status values public static final int OFF = 0; public static final int OVER = 1; public static final int DOWN = 2; protected static PImage noImage[] = null; protected int status; protected PImage[] bimage = new PImage[3]; protected PImage mask; protected boolean reportAllButtonEvents = false; /** * Create an image button based on a composite image for the button states. * * @param theApplet * @param maskFile null if none is to be provided * @param imgFile composite image file for button sates * @param nbrImages number of images in composite image * @param x top-left horizontal distance for the buttun * @param y top left vertical position for the buttun */ public GImageButton(PApplet theApplet, String maskFile, String imgFile, int nbrImages, int x, int y){ super(theApplet, x, y); mask = getMask(maskFile); bimage = getImages(imgFile, nbrImages); width = bimage[0].width; height = bimage[0].height; z = Z_SLIPPY; createEventHandler(G4P.mainWinApp, "handleImageButtonEvents", new Class[]{ GImageButton.class }); registerAutos_DMPK(true, true, false, false); } /** * * @param theApplet * @param maskFile null if none is to be provided * @param imgFiles an array of filenames for button state images * @param x top-left horizontal distance for the button * @param y top left vertical position for the button */ public GImageButton(PApplet theApplet, String maskFile, String imgFiles[], int x, int y){ super(theApplet, x, y); mask = getMask(maskFile); bimage = getImages(imgFiles); width = bimage[0].width; height = bimage[0].height; z = Z_SLIPPY; createEventHandler(G4P.mainWinApp, "handleImageButtonEvents", new Class[]{ GImageButton.class }); registerAutos_DMPK(true, true, false, false); } /** * Get the images from a composite image file. * * @param imgFile * @param nbrImages * @return */ protected PImage[] getImages(String imgFile, int nbrImages){ nbrImages = PApplet.constrain(nbrImages, 1, 3); PImage[] imgs = new PImage[3]; PImage img = winApp.loadImage(imgFile); if(imgFile == null || img == null){ missingFile(imgFile); imgs = getErrorImage(); } else { int iw = img.width / nbrImages; for(int i = 0; i < nbrImages; i++){ imgs[i] = new PImage(iw, img.height, ARGB); imgs[i].copy(img, i * iw, 0, iw, img.height, 0, 0, iw, img.height); } // Re use images if less than 3 were provided for(int i = nbrImages; i < 3; i++){ imgs[i] = imgs[nbrImages - 1]; } } return imgs; } /** * Get the images specified in the file list * @param imgFiles * @return */ protected PImage[] getImages(String[] imgFiles){ PImage[] imgs = new PImage[3]; int imgCount = 0; if(imgFiles == null || imgFiles.length < 1){ if(G4P.messages) System.out.println("Error: you have not provided a list of image files for GImageButton"); } else { for(imgCount = 0; imgCount < imgFiles.length; imgCount++){ imgs[imgCount] = winApp.loadImage(imgFiles[imgCount]); if(imgs[imgCount] == null) missingFile(imgFiles[imgCount]); } //Make sure we have 3 images to work with for(int j = imgCount; j < 3; j++) imgs[j] = imgs[j - 1]; } if(imgs[0] == null) imgs = getErrorImage(); return imgs; } /** * Get the mask file. Report an error if the file cannot be found. * @param mfile * @return */ protected PImage getMask(String mfile){ PImage img = null; if(mfile != null){ img = winApp.loadImage(mfile); if(img == null) missingFile(mfile); } return img; } /** * Report a missing file * @param fname */ protected void missingFile(String fname){ if(G4P.messages) System.out.println("\nUnable to locate file '"+ fname+"' for GImageButton"); } /** * Get the the error button images * @return */ protected PImage[] getErrorImage(){ if(noImage == null) noImage = getImages("noimage3.png",3); return noImage; } /** * Determines whether the position ax, ay is over this component. * It will use a mask image if one has been provided otherwise * it will look for non-transparent pixels. * @param ax mouse x position * @param ay mouse y position * @return true if mouse is over the component else false */ public boolean isOver(int ax, int ay){ Point p = new Point(0,0); calcAbsPosition(p); if(ax >= p.x && ax <= p.x + width && ay >= p.y && ay <= p.y + height){ int dx, dy, pixel; dx = ax - p.x; dy = ay - p.y; if(mask != null){ // we have a mask file pixel = mask.get(dx, dy) & 0x00ffffff; // test for white (ignoring alpha value) if(pixel == 0x00ffffff) return true; } else { // no mask use transparency of off image pixel = bimage[0].get(dx, dy); // Not transparent? if(winApp.alpha(pixel) != 0) return true; } } return false; } /** * Draw the button */ public void draw(){ if(!visible) return; winApp.pushStyle(); winApp.imageMode(CORNER); Point pos = new Point(0,0); calcAbsPosition(pos); // Draw image if(bimage != null && bimage[status] != null){ winApp.image(bimage[status], pos.x, pos.y); } winApp.popStyle(); } /** * If the parameter is true all 3 event types are generated, if false * only CLICKED events are generated (default behaviour). * @param all */ public void fireAllEvents(boolean all){ reportAllButtonEvents = all; } /** * All GUI components are registered for mouseEvents. <br> * When a button is clicked on a GButton it generates 3 events (in this order) * mouse down, mouse up and mouse pressed. <br> * If you only wish to respond to button click events then you should test the * event type e.g. <br> * <pre> * void handleButtonEvents(GButton button) { * if(button == btnName && button.eventType == GButton.CLICKED){ * // code for button click event * } * </pre> <br> * Where <pre><b>btnName</b></pre> is the GButton identifier (variable name) * */ public void mouseEvent(MouseEvent event){ if(!visible || !enabled) return; boolean mouseOver = isOver(winApp.mouseX, winApp.mouseY); if(mouseOver) cursorIsOver = this; else if(cursorIsOver == this) cursorIsOver = null; switch(event.getID()){ case MouseEvent.MOUSE_PRESSED: if(focusIsWith != this && mouseOver && z > focusObjectZ()){ mdx = winApp.mouseX; mdy = winApp.mouseY; status = DOWN; takeFocus(); eventType = PRESSED; if(reportAllButtonEvents) fireEvent(); } break; case MouseEvent.MOUSE_CLICKED: // No need to test for isOver() since if the component has focus // and the mouse has not moved since MOUSE_PRESSED otherwise we // would not get the Java MouseEvent.MOUSE_CLICKED event if(focusIsWith == this){ status = OFF; loseFocus(null); eventType = CLICKED; fireEvent(); } break; case MouseEvent.MOUSE_RELEASED: // if the mouse has moved then release focus otherwise // MOUSE_CLICKED will handle it if(focusIsWith == this && mouseHasMoved(winApp.mouseX, winApp.mouseY)){ loseFocus(null); if(isOver(winApp.mouseX, winApp.mouseY)){ eventType = CLICKED; fireEvent(); } else { if(reportAllButtonEvents){ eventType = RELEASED; fireEvent(); } } status = OFF; } break; case MouseEvent.MOUSE_MOVED: // If dragged state will stay as DOWN if(isOver(winApp.mouseX, winApp.mouseY)) status = OVER; else status = OFF; } } } <file_sep>/* Part of the GUI for Processing library http://www.lagers.org.uk/g4p/index.html http://gui4processing.googlecode.com/svn/trunk/ Copyright (c) 2008-09 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package guicomponents; import java.awt.font.TextAttribute; /** * @author <NAME> * */ public interface GConstants { // 0x0??????? user can disable these messages // 0x8??????? always display these messages // ### Event constants ### // TextField component (GSlider also uses CHANGED) public final static int CHANGED = 0x00000101; // Text has changed public final static int ENTERED = 0x00000102; // Enter key pressed public final static int SET = 0x00000103; // setText() was used // GPanel component public final static int COLLAPSED = 0x00000201; // Panel has been collapsed public final static int EXPANDED = 0x00000202; // Panel has been expanded public final static int DRAGGED = 0x00000203; // Panel has been dragged // GButton public final static int CLICKED = 0x00000301; public final static int PRESSED = 0x00000302; public final static int RELEASED = 0x00000303; // GCheckbox & GOption public final static int SELECTED = 0x00000401; public final static int DESELECTED = 0x00000402; // GRoundControl public final static int CTRL_ANGULAR = 0x00000501; public final static int CTRL_HORIZONTAL = 0x00000502; public final static int CTRL_VERTICAL = 0x00000503; // GWindow public final static int EXIT_APP = 0x00000f01; public final static int CLOSE_WINDOW = 0x00000f02; public final static int KEEP_OPEN = 0x00000f03; // ### GUI build constants ### public final static int ADD_DUPLICATE = 0x00010101; public final static int USER_COL_SCHEME = 0x00010102; public final static int DISABLE_AUTO_DRAW = 0x00010103; // ### Scroll bar policy constants ### /** Do not create or display any scrollbars for the text area. */ public static final int SCROLLBARS_NONE = 0x0000; /** Create and display vertical scrollbar only. */ public static final int SCROLLBARS_VERTICAL_ONLY = 0x0001; /** Create and display horizontal scrollbar only. */ public static final int SCROLLBARS_HORIZONTAL_ONLY = 0x0002; /** Create and display both vertical and horizontal scrollbars. */ public static final int SCROLLBARS_BOTH = 0x0003; public static final int SCROLLBARS_AUTOHIDE = 0x1000; // ### Scroll bar type constants ### /** Create and display vertical scrollbar only. */ public static final int SCROLLBAR_VERTICAL = 1; /** Create and display horizontal scrollbar only. */ public static final int SCROLLBAR_HORIZONTAL = 2; // ### Error MessageTypes ### public final static int RUNTIME_ERROR = 0xf0000000; // Event method handler errors public final static int MISSING = 0x01000001; // Can't find standard handler public final static int NONEXISTANT = 0x01000002; public final static int EXCP_IN_HANDLER = 0x81000003; // Exception in event handler // PeasyCam errors public final static int NOT_PEASYCAM = 0x82000001; // Not a PeasyCam object public final static int HUD_UNSUPPORTED = 0x82000002; // HUD not supported public final static int INVALID_STATUS = 0x82000003; // HUD not supported // GTextField text scroll constants public final static int SCROLL_UP = 0x00000111; // Scroll text up public final static int SCROLL_DOWN = 0x00000112; // Scroll text down public final static int SCROLL_LEFT = 0x00000113; // Scroll text left public final static int SCROLL_RIGHT = 0x00000114; // Scroll text right public static final TextAttribute FAMILY = TextAttribute.FAMILY; // public static final TextAttribute FAMILY = new TextAttribute("family"); // public static final TextAttribute WEIGHT = new TextAttribute("weight"); public static final TextAttribute WEIGHT = TextAttribute.WEIGHT; public static final Float WEIGHT_EXTRA_LIGHT = new Float(0.5f); public static final Float WEIGHT_LIGHT = new Float(0.75f); public static final Float WEIGHT_DEMILIGHT = new Float(0.875f); public static final Float WEIGHT_REGULAR = new Float(1.0f); public static final Float WEIGHT_SEMIBOLD = new Float(1.25f); public static final Float WEIGHT_MEDIUM = new Float(1.5f); public static final Float WEIGHT_DEMIBOLD = new Float(1.75f); public static final Float WEIGHT_BOLD = new Float(2.0f); public static final Float WEIGHT_HEAVY = new Float(2.25f); public static final Float WEIGHT_EXTRABOLD = new Float(2.5f); public static final Float WEIGHT_ULTRABOLD = new Float(2.75f); // public static final TextAttribute WIDTH = new TextAttribute("width"); public static final TextAttribute WIDTH = TextAttribute.WIDTH; public static final Float WIDTH_CONDENSED = new Float(0.75f); public static final Float WIDTH_SEMI_CONDENSED = new Float(0.875f); public static final Float WIDTH_REGULAR = new Float(1.0f); public static final Float WIDTH_SEMI_EXTENDED = new Float(1.25f); public static final Float WIDTH_EXTENDED = new Float(1.5f); public static final TextAttribute POSTURE = TextAttribute.POSTURE; public static final Float POSTURE_REGULAR = new Float(0.0f); public static final Float POSTURE_OBLIQUE = new Float(0.20f); // Acceptable values - float public static final TextAttribute SIZE = TextAttribute.SIZE; public static final TextAttribute SUPERSCRIPT = TextAttribute.SUPERSCRIPT; public static final Integer SUPERSCRIPT_SUPER = new Integer(1); public static final Integer SUPERSCRIPT_SUB = new Integer(-1); // Any java.awt.Color object public static final TextAttribute FOREGROUND = TextAttribute.FOREGROUND; public static final TextAttribute BACKGROUND = TextAttribute.BACKGROUND; public static final TextAttribute STRIKETHROUGH = TextAttribute.STRIKETHROUGH; public static final Boolean STRIKETHROUGH_ON = new Boolean(true); public static final Boolean STRIKETHROUGH_OFF = new Boolean(false); public static final TextAttribute JUSTIFICATION = TextAttribute.JUSTIFICATION; public static final Float JUSTIFICATION_FULL = new Float(1.0f); public static final Float JUSTIFICATION_NONE = new Float(0.0f); } <file_sep>package guicomponents; abstract class HotSpot implements Comparable<HotSpot> { public final Integer id; abstract public boolean contains(float px, float py); protected HotSpot(int id){ this.id = Math.abs(id); } public int compareTo(HotSpot spoto) { return id.compareTo(spoto.id); } static class HSrect extends HotSpot { private final float x, y, w, h; /** * @param x * @param y * @param w * @param h */ public HSrect(int id, float x, float y, float w, float h) { super(id); this.x = x; this.y = y; this.w = w; this.h = h; } @Override public boolean contains(float px, float py) { return (px >= x && py >= y && px <= x + w && py <= y + h); } } } <file_sep>/* Part of the GUI for Processing library http://www.lagers.org.uk/g4p/index.html http://gui4processing.googlecode.com/svn/trunk/ Copyright (c) 2008-09 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package guicomponents; import java.util.HashMap; import processing.core.PApplet; import processing.core.PFont; /** * This class only has static methods and are used to create and return * PFont objects for use by the GUI components.<br> * * * @author <NAME> * */ public class GFont { // Keep track of all fonts made and prevent duplicates private static final HashMap<GFontKey, PFont> fontmap = new HashMap<GFontKey, PFont>(); /** * Create a font * * @param theApplet * @param fontname system name for font * @param fsize size of font to create (8 - 144 incl) * @return the matching PFont object */ public static PFont getFont(PApplet theApplet, String fontname, int fsize){ fsize = PApplet.constrain(fsize, 8, 144); GFontKey fkey = new GFontKey(fontname, fsize); PFont pfont = null; // See if the font has already been created // if so return it else make it if(fontmap.containsKey(fkey)) pfont = fontmap.get(fkey); else { // Attempt to make the this font pfont = theApplet.createFont(fontname, fsize, true); // if no such system font then make one using default sans-serif font of same size if(pfont != null){ fontmap.put(fkey, pfont); // remember it } else { // unable to make this font so make sans-serif font // at this size if not already done fkey = new GFontKey("SansSerif", fsize); if(fontmap.containsKey(fkey)) pfont = fontmap.get(fkey); else { pfont = theApplet.createFont("SansSerif", fsize, true); fontmap.put(fkey, pfont); } } } return pfont; } /** * A quick way to get the default Sans Serif font (11pt) * @param theApplet * @return the applet's default color scheme */ public static PFont getDefaultFont(PApplet theApplet){ return getFont(theApplet, "SansSerif", 11); } /** * This is a private class and is only used by the GFont class. * It defines a key to uniquely identify fonts created based on * their system font name and size. The purpose is to prevent * multiple PFont objects that represent the same font/size. * * @author <NAME> * */ private static class GFontKey implements Comparable<GFontKey>{ private final String fontKey; public GFontKey(String fontname, int fontsize){ fontKey = fontname + "-" + fontsize; } public boolean equals(Object o){ GFontKey fkey = (GFontKey) o; if(fkey == null) return false; return fontKey.equals(fkey.fontKey); } public int hashCode(){ return fontKey.hashCode(); } public int compareTo(GFontKey obj) { GFontKey fkey = (GFontKey) obj; if(fkey == null) return 1; return fontKey.compareTo(fkey.fontKey ); } } // /** // * Get the system default Serif font // * @param theApplet // * @param fsize the font size wanted // * @return // */ // public static PFont getSerifFont(PApplet theApplet, int fsize){ // fsize = PApplet.constrain(fsize, 8, 72); // GFontKey fkey = new GFontKey("Serif", fsize); // PFont pfont; // if(fontmap.containsKey(fkey)) // return fontmap.get(fkey); // else { // pfont = theApplet.createFont("Serif", fsize, true); // fontmap.put(fkey, pfont); // return pfont; // } // } // // /** // * Get the system Sans Serif font // * @param theApplet // * @param fsize the font size wanted // * @return // */ // public static PFont getSansSerifFont(PApplet theApplet, int fsize){ // fsize = PApplet.constrain(fsize, 8, 72); // GFontKey fkey = new GFontKey("SansSerif", fsize); // PFont pfont; // if(fontmap.containsKey(fkey)) // pfont = fontmap.get(fkey); // else { // pfont = theApplet.createFont("SansSerif", fsize, true); // fontmap.put(fkey, pfont); // } // return pfont; // } // // /** // * Get the system mono-spaced font // * @param theApplet // * @param fsize the font size wanted // * @return // */ // public static PFont getMonospacedFont(PApplet theApplet, int fsize){ // fsize = PApplet.constrain(fsize, 8, 72); // GFontKey fkey = new GFontKey("Monospaced", fsize); // PFont pfont; // if(fontmap.containsKey(fkey)) // pfont = fontmap.get(fkey); // else { // pfont = theApplet.createFont("Monospaced", fsize, true); // fontmap.put(fkey, pfont); // } // return pfont; // } } <file_sep>/* Part of the GUI for Processing library http://www.lagers.org.uk/g4p/index.html http://gui4processing.googlecode.com/svn/trunk/ Copyright (c) 2008-09 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package guicomponents; import java.awt.Point; import java.awt.event.MouseEvent; import processing.core.PApplet; /** * The horizontal slider component. * * @author <NAME> * */ public class GHorzSlider extends GSlider { /** * Create a horizontal slider. * Default values: * Range 0-100 * Initial value 50 * Use the setLimits method to customise these values. * * @param theApplet * @param x * @param y * @param width * @param height */ public GHorzSlider(PApplet theApplet, int x, int y, int width, int height){ super(theApplet, x, y, width, height); initThumbDetails(); z = Z_SLIPPY; } /** * Initialises the thumb details */ protected void initThumbDetails(){ thumbSize = (int) Math.max(20, width / 20); thumbMin = thumbSize/2; thumbMax = (int) (width - thumbSize/2); thumbTargetPos = thumbPos; } /** * Draw the slider */ public void draw(){ if(!visible) return; winApp.pushStyle(); winApp.style(G4P.g4pStyle); Point pos = new Point(0,0); calcAbsPosition(pos); winApp.noStroke(); winApp.fill(localColor.sdrTrack); winApp.rect(pos.x, pos.y, width, height); winApp.fill(localColor.sdrThumb); winApp.rect(pos.x + thumbPos - thumbSize/2, pos.y, thumbSize, height); if(border != 0){ winApp.strokeWeight(border); winApp.noFill(); winApp.stroke(localColor.sdrBorder); winApp.rect(pos.x, pos.y, width, height); } winApp.popStyle(); } /** * All GUI components are registered for mouseEvents */ public void mouseEvent(MouseEvent event){ if(!visible || !enabled) return; boolean mouseOver = isOver(winApp.mouseX, winApp.mouseY); if(mouseOver || focusIsWith == this) cursorIsOver = this; else if(cursorIsOver == this) cursorIsOver = null; switch(event.getID()){ case MouseEvent.MOUSE_PRESSED: if(focusIsWith != this && mouseOver && z > focusObjectZ()){ mdx = winApp.mouseX; mdy = winApp.mouseY; takeFocus(); } break; case MouseEvent.MOUSE_CLICKED: if(focusIsWith == this){ loseFocus(null); mdx = mdy = Integer.MAX_VALUE; } break; case MouseEvent.MOUSE_RELEASED: if(focusIsWith == this && mouseHasMoved(winApp.mouseX, winApp.mouseY)){ loseFocus(null); mdx = mdy = Integer.MAX_VALUE; } break; case MouseEvent.MOUSE_DRAGGED: if(focusIsWith == this){ isValueChanging = true; Point p = new Point(0,0); calcAbsPosition(p); thumbTargetPos = PApplet.constrain(winApp.mouseX - offset - p.x, thumbMin, thumbMax); } break; } } /** * Determines whether the position ax, ay is over the thumb * of this Slider. * * @return true if mouse is over the slider thumb else false */ public boolean isOver(int ax, int ay){ Point p = new Point(0,0); calcAbsPosition(p); if(ax >= p.x + thumbPos - thumbSize/2 && ax <= p.x + thumbPos + thumbSize/2 && ay >= p.y && ay <= p.y + height){ offset = ax - (p.x + thumbPos); return true; } else return false; } } // end of class <file_sep>/* Part of the GUI for Processing library http://www.lagers.org.uk/g4p/index.html http://gui4processing.googlecode.com/svn/trunk/ Copyright (c) 2011 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package guicomponents; import java.awt.Point; import processing.core.PApplet; /** * The provides an extremely configurable GUI knob controller. GKnobOval * inherits from GKnob which inherits from GRoundControl so you should * read the documentation for those classes as it also applies to * GKnobOval.<br> * <br> * * For circular knobs use GKnob rather than this class. <br> * To avoid inaccuracies when drawing the bezel arcs it is recommended that * the length of the major axis should not exceed 1.5 x the minor axis and/or * the bezel width is kept small. <br><br> * * Configurable options <br> * Knob height and width (should be oval) <br> * Start and end of rotation arc. <br> * Bezel width with tick marks <br> * <br> * Documentation for the following can be found in GRoundControl <br> * Range of values associated with rotating the knob <br> * Rotation is controlled by mouse movement - 3 modes available <br> * (a) angular - drag round knob center <br> * (b) horizontal - drag left or right <br> * (c) vertical - drag up or down <br> * User can specify mouse sensitivity for modes (b) and (c) * Use can specify level of inertia to give smoother rotation * * <b>Note</b>: Angles are measured clockwise starting in the positive x direction i.e. * <pre> * 270 * | * 180 --+-- 0 * | * 90 * </pre> * * @author <NAME> * */ public class GKnobOval extends GKnob { protected Point p = new Point(); /** * Create a GKnobOval control <br><br> * * Will ensure that width and height are >= 20 pixels <br> * * The arcStart and arcEnd represent the limits of rotation expressed in * degrees as shown above. For instance if you want a knob that rotates * from 7 o'clock to 5 o'clock (via 12 o'clock) then arcStart = 120 and * arcEnd = 60 degrees. * * @param theApplet * @param x left position of knob * @param y top position of knob * @param width width of knob * @param height height of knob (if different from width - oval knob) * @param arcStart start of rotation arc (in degrees) * @param arcEnd end of rotation arc (in degrees) */ public GKnobOval(PApplet theApplet, int x, int y, int width, int height, int arcStart, int arcEnd) { super(theApplet, x, y, width, height, arcStart, arcEnd); // Calculate the display angle start = convertRealAngleToOvalAngle(PApplet.radians(aLow), sizeRadX, sizeRadY); end = convertRealAngleToOvalAngle(PApplet.radians(aHigh), sizeRadX, sizeRadY); // Calculate ticks calcTickMarkerPositions(nbrTickMarks); } public void draw(){ if(!visible) return; p.move(0,0); calcAbsPosition(p); p.x += cx; p.y += cy; float rad = PApplet.radians(needleAngle), nrad; winApp.pushMatrix(); winApp.translate(p.x, p.y); winApp.pushStyle(); winApp.style(G4P.g4pStyle); // Draw bezel if(bezelWidth > 0){ winApp.noStroke(); if(rotArcOnly) winApp.fill(winApp.color(128,128)); else { winApp.fill(winApp.color(128,48)); winApp.ellipse(0, 0, 2*sizeRadX, 2*sizeRadY); winApp.fill(winApp.color(128,80)); } // draw darker arc for rotation range winApp.arc(0, 0, 2*sizeRadX, 2*sizeRadY, start, end); // Draw active value arc if(valueTrackVisible){ winApp.fill(localColor.knobTrack); winApp.noStroke(); nrad = convertRealAngleToOvalAngle(rad, sizeRadX, sizeRadY); winApp.arc(0, 0, 2*barRadX, 2*barRadY, start, nrad); } // Draw ticks winApp.stroke(localColor.knobBorder); winApp.stroke(1.2f); for(int i = 0; i < mark.length; i++){ if(i == 0 || i == mark.length-1) winApp.strokeWeight(1.5f); else winApp.strokeWeight(1.2f); winApp.line(mark[i][0].x, mark[i][0].y,mark[i][1].x, mark[i][1].y); } } if(knobRadX > 0 ){ // Draw knob centre winApp.stroke(localColor.knobBorder); winApp.strokeWeight(1.2f); winApp.fill(localColor.knobFill); if(rotArcOnly){ winApp.arc(0, 0, 2*knobRadX, 2*knobRadY, start, end); winApp.stroke(localColor.knobBorder); winApp.strokeWeight(1.2f); winApp.line(0, 0, mark[0][0].x, mark[0][0].y); winApp.line(0, 0, mark[mark.length-1][0].x, mark[mark.length-1][0].y); } else winApp.ellipse(0, 0, 2*knobRadX, 2*knobRadY); // Draw needle winApp.stroke(localColor.knobNeedle); winApp.strokeWeight(2.0f); nrad = convertRealAngleToOvalAngle(rad, sizeRadX, sizeRadY); float ox = (float) (sizeRadX * Math.cos(nrad)); float oy = (float) (sizeRadY * Math.sin(nrad)); calcCircumferencePosition(p, ox, oy, knobRadX, knobRadY); winApp.line(0, 0, p.x, p.y); } winApp.popStyle(); winApp.popMatrix(); } /** * Determines whether the position ax, ay is over any part of the round control. * * @param ax x coordinate * @param ay y coordinate * @return true if mouse is over the control else false */ public boolean isOver(int ax, int ay){ // Point p = new Point(0,0); p.move(0,0); calcAbsPosition(p); boolean inside; int dx = (int) (ax - p.x - cx); int dy = (int) (ay - p.y - cy); float ratioX = ((float)dx)/ sizeRadX; float ratioY = ((float)dy)/ sizeRadY; inside = (ratioX * ratioX + ratioY * ratioY < 1.0f); return inside; } /** * Determines if the position is over the round control and within the rotation range. * @param ax x coordinate * @param ay y coordinate * @return true if mouse is over the rotation arc of the control else false */ public boolean isOverRotArc(int ax, int ay){ p.move(0,0); calcAbsPosition(p); boolean inside; int dx = (int) (ax - p.x - cx); int dy = (int) (ay - p.y - cy); float ratioX = ((float)dx)/ sizeRadX; float ratioY = ((float)dy)/ sizeRadY; inside = (ratioX * ratioX + ratioY * ratioY < 1.0f); if(inside){ Point pm = new Point(Math.round(dx), Math.round(dy)); float eX = pm.x, eY = pm.y; calcCircumferencePosition(pm, eX, eY, sizeRadX, sizeRadY); // Get real angle to knob centre double angle = Math.atan2(dy,dx); double cosA = Math.cos(angle), sinA = Math.sin(angle); double h = Math.abs(sizeRadX - sizeRadY)/2.0; if(width > height){ eX -= h * cosA; eY += h * sinA; } else { eX += h * cosA; eY -= h * sinA; } int degs = Math.round(PApplet.degrees((float) Math.atan2(eY, eX))); degs = (degs < 0) ? degs + 360 : degs; inside = isInValidArc(degs); } return inside; } /** * Used to calculate the tick mark positions * @param nticks the number of actual markers */ protected void calcTickMarkerPositions(int nticks){ mark = new Point[nticks][2]; float ox, oy; float ang = PApplet.radians(aLow), deltaAng = PApplet.radians(aHigh - aLow)/(nticks-1); for(int i = 0; i < nticks ; i++){ mark[i][0] = new Point(); mark[i][1] = new Point(); float dang = convertRealAngleToOvalAngle(ang, sizeRadX, sizeRadY); ox = (float) (sizeRadX * Math.cos(dang)); oy = (float) (sizeRadY * Math.sin(dang)); calcCircumferencePosition(mark[i][0], ox, oy, knobRadX, knobRadY); if(i == 0 || i == nticks - 1){ mark[i][1].x = Math.round(ox); mark[i][1].y = Math.round(oy); } else calcCircumferencePosition(mark[i][1], ox, oy, barRadX, barRadY); ang += deltaAng; } nbrTickMarks = nticks; } } <file_sep>/* Part of the GUI for Processing library http://www.lagers.org.uk/g4p/index.html http://gui4processing.googlecode.com/svn/trunk/ Copyright (c) 2008-09 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package guicomponents; import java.util.ArrayList; import processing.core.PApplet; /** * This is used to group options together to provide single-selection * from 2 or more GOption buttons. * * @author <NAME> * */ public class GOptionGroup { protected GOption selected = null; protected GOption deselected = null; protected ArrayList<GOption> options = new ArrayList<GOption>();; /** * Use this constructor to create an option group. */ public GOptionGroup(){ } /** * This class does not need a reference to the applet class * @deprecated * @param theApplet */ public GOptionGroup(PApplet theApplet){ } public ArrayList<GOption> getOptions(){ return options; } /** * Enable or disable all the options in this group * @param enable */ public void setEnabled(boolean enable){ for(int i = 0; i < options.size(); i++){ options.get(i).setEnabled(enable); } } /** * INTERNAL USE ONLY * @param index * @return reference to an option based on it's index. */ public GOption get(int index){ return options.get(index); } /** * INTERNAL USE ONLY * @param option * @return true if option successfully added else false */ public boolean addOption(GOption option){ if(option != null){ options.add(option); option.setGroup(this); return true; } else return false; } /** * Add a new Option at the given position * @param pos * @param option * @return true if option successfully added else false */ public boolean addOption(int pos, GOption option){ if(option != null && pos >= 0 && pos <= options.size()){ options.add(pos, option); option.setGroup(this); return true; } return false; } /** * Remove an existing option * @param option * @return a reference to the option removed */ public GOption removeOption(GOption option){ options.remove(option); return option; } /** * Remove an option at the given position * @param index * @return a reference to the option removed */ public GOption removeOption(int index){ GOption option = null; if(index >= 0 && index < options.size()){ option = options.remove(index); } return option; } /** * Remove an option based on the option's text (this ignores case) * @param optText * @return a reference to the option removed */ public GOption removeOption(String optText){ System.out.println("REMOVE"); GOption option = null; int i = options.size() - 1; while(i >= 0){ if(options.get(i).getText().compareToIgnoreCase(optText) == 0){ option = options.get(i); break; } i--; } if(option != null) options.remove(option); return option; } /** * Make this option the selected one * * @param option */ public void setSelected(GOption option){ deselected = selected; selected = option; } /** * If index is in range make this one selected * * @param index */ public void setSelected(int index){ if(index >= 0 && index < options.size()){ deselected = selected; options.get(index).setSelected(true); } } /** * Set option selected based on the option text (this case insensitive) * @param optText the text of the option to select */ public void setSelected(String optText){ int i = options.size(); while(i-- >= 0){ if(options.get(i).getText().compareToIgnoreCase(optText) == 0) break; } if(i > 0) setSelected(options.get(i)); } /** * INTERNAL USE ONLY * Return the option that has just been selected * @return the option that has been selected */ public GOption selectedOption(){ return selected; } /** * INTERNAL USE ONLY * Return the option that has just been deselected * @return the option that has been deselected */ public GOption deselectedOption(){ return deselected; } /** * INTERNAL USE ONLY * @return the index of the currently selected option */ public int selectedIndex(){ return options.indexOf(selected); } /** * INTERNAL USE ONLY * Return the index of the option that has just been deselected * @return the index of the de-selected option */ public int deselectedIndex(){ return options.indexOf(deselected); } /** * INTERNAL USE ONLY * @return the text of the currently selected option */ public String selectedText(){ return selected.text; } /** * INTERNAL USE ONLY * Return the text of the option that has just been deselected * @return the text of the de-selected option */ public String deselectedText(){ return deselected.text; } /** * Get the number of options in this GOptionGroup */ public int size(){ return options.size(); } } <file_sep>Project-Sentry-Gun ================== Project Site: http://psg.rudolphlabs.com/ This is an open-scource code project from Rudolph Labs. See the website above for more information. Initiated by <NAME> (sentryGun53) <EMAIL> <EMAIL> My build of this project, fully functional breaks apart into two peices; the base and the gun: http://tinypic.com/r/6gk28j/9. <file_sep>/* -------------------- Project Sentry Gun -------------------- ============================================================ ----- An Open-Source Project, initiated by <NAME> ----- */ // Set your controller type here // type options: "Arduino_bare", "Shield_v4", "Shield_v6", "Shield_v7", "Standalone_v3", "Standalone_v5", "Standalone_v7", "Standalone_v8" #define type "Standalone_v8" /* Help & Reference: http://projectsentrygun.rudolphlabs.com/make-your-own Forum: http://projectsentrygun.rudolphlabs.com/forum ATTACHMENT INSTRUCTIONS: (for using an Arduino board) attach x-axis (pan) standard servo to digital I/O pin 8 attach y-axis (tilt) standard servo to digital I/O pin 9 attach trigger standard servo to digital I/O pin 10 attach USB indicator LED to digital pin 11 attach firing indicator LED to digital I/O pin 12 attach mode indicator LED to digital I/O pin 13 attach reloading switch to digital I/O pin 3 (low-active: when on, connects pin to GND) attach diable plate momentary button to digital I/O pin 2 (low-active: when on, connects pin to GND) attach electric trigger MOSFET circuit to digital I/O pin 7 adjust the values below to the values that work for your gun: */ // <=========================================================================> // Begin custom values - change these servo positions to work with your turret // <=========================================================================> // servo positions: #define panServo_scanningMin 0 // how far side to side you want the #define panServo_scanningMax 180 // gun to turn while 'scanning' #define scanningSpeed 2000 // total time for 1 sweep (in milliseconds) #define panServo_HomePosition 97 // 'centered' gun position #define tiltServo_HomePosition 65 // #define panServo_ReloadPosition 97 // convenient position for reloading gun #define tiltServo_ReloadPosition 150 // #define triggerServo_HomePosition 120 // trigger servo not-firing position #define triggerServo_SqueezedPosition 90 // trigger servo firing position // more trigger settings: #define triggerTravelMillis 1500 // how often should trigger be squeezed (in semi-auto firing) // higher value = slower firing, lower value = faster firing // disable plate settings: #define disablePlateDelay 5000 // how long to disable sentry when plate is pressed (in milliseconds) // ammunition magazine/clip settings: boolean useAmmoCounter = false; // if you want to use the shot counter / clip size feature, set this to true int clipSize = 5; // how many shots before the gun will be empty and the gun will be disabled (reload switch resets the ammo counter) // <=========================================================================> // End custom values // <=========================================================================> int panServoPin; // Arduino pin for pan servo int tiltServoPin; // Arduino pin for tilt servo int triggerServoPin; // Arduino pin for trigger servo, or output to trigger MOSFET int firingIndicatorLEDPin; // Arduino pin for firing indicator LED int USBIndicatorLEDPin; // Arduino pin for USB indicator LED int modeIndicatorLEDPin; // Arduino pin for Mode indicator LED int reloadSwitchPin; // Arduino pin for input from RELOAD switch int disablePlatePin; // Arduino pin for input from disable plate int electricTriggerPin; // Arduino pin for output to trigger MOSFET boolean invertInputs; // TRUE turns on internal pull-ups, use if closed switch connects arduino pin to ground // pin assignments for each hardware setup are set in the function assignPins() at bottom of code typedef struct config_t { // Booleans but int int controlMode; int safety; int firingMode; int scanWhenIdle; int trackingMotion; int trackingColor; int leadTarget; int safeColor; int showRestrictedZones; int showDifferentPixels; int showTargetBox; int showCameraView; int mirrorCam; int soundEffects; // Integers int camWidth; int camHeight; int nbDot; int antSens; int minBlobArea; int tolerance; int effect; int trackColorTolerance; int trackColorRed; int trackColorGreen; int trackColorBlue; int safeColorMinSize; int safeColorTolerance; int safeColorRed; int safeColorGreen; int safeColorBlue; int idleTime; // Floats double propX; double propY; double xRatio; double yRatio; double xMin; double xMax; double yMin; double yMax; } configuration; configuration configuration1; #include <Servo.h> Servo pan; // x axis servo Servo tilt; // y axis servo Servo trigger; // trigger servo int xPosition; // pan position int yPosition; // tilt position int fire = 0; // if 1, fire; else, don't fire int fireTimer = 0; int fireSelector = 1; // 1 - semi-automatic firing, auto/semi-auto gun // 3 - full automatic firing, full-auto gun int idleCounter = 0; int watchdog = 0; int watchdogTimeout = 2000; boolean idle = true; boolean scanning = false; boolean scanDirection = true; boolean disabled = false; unsigned long int disableEndTime; int scanXPosition = panServo_scanningMin; int shotCounter = 0; // number of shots fires since last reload boolean clipEmpty = false; // is the ammo magazine empty? byte indicator; // if 'a', continue, if 'z', idle byte x100byte; // some bytes used during serial communication byte x010byte; byte x001byte; byte y100byte; byte y010byte; byte y001byte; byte fireByte; byte fireSelectorByte; byte scanningByte; void setup(){ assignPins(); pan.attach(panServoPin); // set up the x axis servo pan.write(panServo_HomePosition); tilt.attach(tiltServoPin); // set up the y axis servo tilt.write(tiltServo_HomePosition); pinMode(electricTriggerPin, OUTPUT); // electric trigger, set as output digitalWrite(electricTriggerPin, LOW); trigger.attach(triggerServoPin); // servo for trigger, set that servo up trigger.write(triggerServo_HomePosition); pinMode(USBIndicatorLEDPin, OUTPUT); // set up USB indicator LED pinMode(modeIndicatorLEDPin, OUTPUT); // set up Mode indicator LED pinMode(firingIndicatorLEDPin, OUTPUT); // set up firing indicator LED pinMode(reloadSwitchPin, INPUT); // set up reload switch input pinMode(disablePlatePin, INPUT); // set up disable plate input if(invertInputs) { digitalWrite(reloadSwitchPin, HIGH); // turn on internal pull-up digitalWrite(disablePlatePin, HIGH); // turn on internal pull-up } Serial.begin(4800); // start communication with computer } void loop() { if (Serial.available() >= 10) { // check to see if a new set of commands is available watchdog = 0; indicator = Serial.read(); // read first byte in buffer if(indicator == 'a') { // check for 'a' (indicates start of message) idle = false; idleCounter = 0; digitalWrite(USBIndicatorLEDPin, HIGH); // light up the USB indicator LED x100byte = Serial.read(); // read the message, byte by byte x010byte = Serial.read(); // x001byte = Serial.read(); // y100byte = Serial.read(); // y010byte = Serial.read(); // y001byte = Serial.read(); // fireByte = Serial.read(); // fireSelectorByte = Serial.read(); // fireSelector = int(fireSelectorByte) - 48; // convert byte to integer scanningByte = Serial.read(); if((int(scanningByte) - 48) == 1) { scanning = true; } else{ scanning = false; } } else if(indicator == 'z'){ // check for command to go idle (sent by computer when program is ended) idle = true; } else if(indicator == 'b'){ // start backup backup(); } else if(indicator == 'r'){ // start restore restore(); } } else{ watchdog++; if(watchdog > watchdogTimeout) { idle = true; } } if(idle) { // when Arduino is not getting commands from computer... Serial.write('T'); // tell the computer that Arduino is here idleCounter++; // periodically blink the USB indicator LED if(idleCounter > 1000) { // sequenceLEDs(1, 100); delay(10); // digitalWrite(USBIndicatorLEDPin, HIGH); // // delay(250); // // digitalWrite(USBIndicatorLEDPin, LOW); // idleCounter = 0; // } // else{ // digitalWrite(USBIndicatorLEDPin, LOW); // } // xPosition = panServo_HomePosition; // keep x axis servo in its home position yPosition = tiltServo_HomePosition; // keep y axis servo in its home position fire = 0; // don't fire } else{ // when Arduino is getting commands from the computer... xPosition = (100*(int(x100byte)-48)) + (10*(int(x010byte)-48)) + (int(x001byte)-48); // decode those message bytes into two 3-digit numbers yPosition = (100*(int(y100byte)-48)) + (10*(int(y010byte)-48)) + (int(y001byte)-48); // fire = int(fireByte) - 48; // convert byte to integer } if(scanning) { digitalWrite(modeIndicatorLEDPin, HIGH); if(scanDirection) { scanXPosition += 1; if(scanXPosition > panServo_scanningMax) { scanDirection = false; scanXPosition = panServo_scanningMax; } } else{ scanXPosition -= 1; if(scanXPosition < panServo_scanningMin) { scanDirection = true; scanXPosition = panServo_scanningMin; } } xPosition = scanXPosition; yPosition = tiltServo_HomePosition; fire = 0; delay(scanningSpeed/abs(panServo_scanningMax-panServo_scanningMin)); } else{ digitalWrite(modeIndicatorLEDPin, LOW); } if((digitalRead(disablePlatePin) == HIGH && !invertInputs) || (digitalRead(disablePlatePin) == LOW && invertInputs)) { // check the disable plate to see if it is pressed disabled = true; disableEndTime = millis() + disablePlateDelay; } if(millis() > disableEndTime) { disabled = false; } if((digitalRead(reloadSwitchPin) == HIGH && !invertInputs) || (digitalRead(reloadSwitchPin) == LOW && invertInputs)) { // check the reload switch to see if it is flipped shotCounter = 0; xPosition = panServo_ReloadPosition; // if it is flipped, override computer commands, yPosition = tiltServo_ReloadPosition; // and send the servos to their reload positions fire = 0; // don't fire while reloading digitalWrite(modeIndicatorLEDPin, HIGH); delay(100); digitalWrite(modeIndicatorLEDPin, LOW); delay(100); } if(disabled) { xPosition = panServo_ReloadPosition; // if it is flipped, override computer commands, yPosition = tiltServo_ReloadPosition; // and send the servos to their reload positions fire = 0; // don't fire while reloading digitalWrite(modeIndicatorLEDPin, HIGH); delay(50); digitalWrite(modeIndicatorLEDPin, LOW); delay(50); } pan.write(xPosition); // send the servos to whatever position has been commanded tilt.write(yPosition); // if(useAmmoCounter && shotCounter >= clipSize) { clipEmpty = true; } else{ clipEmpty = false; } if(fire == 1 && !clipEmpty) { // if firing... Fire(fireSelector); // fire the gun in whatever firing mode is selected } else{ // if not firing... ceaseFire(fireSelector); // stop firing the gun } } void Fire(int selector) { // function to fire the gun, based on what firing mode is selected if(selector == 1) { fireTimer++; if(fireTimer >=0 && fireTimer <= triggerTravelMillis) { digitalWrite(electricTriggerPin, HIGH); trigger.write(triggerServo_SqueezedPosition); digitalWrite(firingIndicatorLEDPin, HIGH); } if(fireTimer > triggerTravelMillis && fireTimer < 1.5*triggerTravelMillis) { digitalWrite(electricTriggerPin, LOW); trigger.write(triggerServo_HomePosition); digitalWrite(firingIndicatorLEDPin, LOW); } if(fireTimer >= 1.5*triggerTravelMillis) { fireTimer = 0; if(useAmmoCounter) { shotCounter++; // increment the shot counter } } } if(selector == 3) { digitalWrite(electricTriggerPin, HIGH); trigger.write(triggerServo_SqueezedPosition); digitalWrite(firingIndicatorLEDPin, HIGH); } } void ceaseFire(int selector) { // function to stop firing the gun, based on what firing mode is selected if(selector == 1) { fireTimer = 0; digitalWrite(electricTriggerPin, LOW); trigger.write(triggerServo_HomePosition); digitalWrite(firingIndicatorLEDPin, LOW); } if(selector == 3) { // for my gun, both firing modes cease firing by simply shutting off. digitalWrite(electricTriggerPin, LOW); trigger.write(triggerServo_HomePosition); digitalWrite(firingIndicatorLEDPin, LOW); } } void sequenceLEDs(int repeats, int delayTime) { int startDelay; for(int i = 0; i < repeats; i++) { digitalWrite(USBIndicatorLEDPin, LOW); digitalWrite(modeIndicatorLEDPin, LOW); startDelay = millis(); while(millis()-startDelay < delayTime) { digitalWrite(firingIndicatorLEDPin, HIGH); } digitalWrite(firingIndicatorLEDPin, LOW); startDelay = millis(); while(millis()-startDelay < delayTime) { digitalWrite(USBIndicatorLEDPin, HIGH); } digitalWrite(USBIndicatorLEDPin, LOW); startDelay = millis(); while(millis()-startDelay < delayTime) { digitalWrite(modeIndicatorLEDPin, HIGH); } digitalWrite(modeIndicatorLEDPin, LOW); startDelay = millis(); while(millis()-startDelay < delayTime) { // chill } } } void assignPins() { if(type == "Arduino_bare" || type == "Arduino_Bare") { // pin attachments: panServoPin = 8; // Arduino pin for pan servo tiltServoPin = 9; // Arduino pin for tilt servo triggerServoPin = 10; // Arduino pin for trigger servo, or output to trigger MOSFET firingIndicatorLEDPin = 12; // Arduino pin for firing indicator LED USBIndicatorLEDPin = 11; // Arduino pin for USB indicator LED modeIndicatorLEDPin = 13; // Arduino pin for Mode indicator LED reloadSwitchPin = 3; // Arduino pin for input from RELOAD switch disablePlatePin = 2; // Arduino pin for input from disable plate electricTriggerPin = 7; // Arduino pin for output to trigger MOSFET invertInputs = true; // TRUE turns on internal pull-ups, use if closed switch connects arduino pin to ground } else if(type == "Shield_v4" || type == "Shield_v6") { // pin attachments: panServoPin = 9; // Arduino pin for pan servo tiltServoPin = 8; // Arduino pin for tilt servo triggerServoPin = 7; // Arduino pin for trigger servo, or output to trigger MOSFET electricTriggerPin = 6; // Arduino pin for output to trigger MOSFET firingIndicatorLEDPin = 11; // Arduino pin for firing indicator LED USBIndicatorLEDPin = 12; // Arduino pin for USB indicator LED modeIndicatorLEDPin = 13; // Arduino pin for Mode indicator LED reloadSwitchPin = 10; // Arduino pin for input from RELOAD switch disablePlatePin = 2; // Arduino pin for input from disable plate invertInputs = true; // TRUE turns on internal pull-ups, use if closed switch connects arduino pin to ground } else if(type == "Shield_v7") { // pin attachments: panServoPin = 8; // Arduino pin for pan servo tiltServoPin = 9; // Arduino pin for tilt servo triggerServoPin = 10; // Arduino pin for trigger servo, or output to trigger MOSFET electricTriggerPin = 7; // Arduino pin for output to trigger MOSFET firingIndicatorLEDPin = 12; // Arduino pin for firing indicator LED USBIndicatorLEDPin = 6; // Arduino pin for USB indicator LED modeIndicatorLEDPin = 13; // Arduino pin for Mode indicator LED reloadSwitchPin = 11; // Arduino pin for input from RELOAD switch disablePlatePin = 2; // Arduino pin for input from disable plate invertInputs = true; // TRUE turns on internal pull-ups, use if closed switch connects arduino pin to ground } else if(type == "Standalone_v3") { // pin attachments: panServoPin = 8; // Arduino pin for pan servo tiltServoPin = 9; // Arduino pin for tilt servo triggerServoPin = 10; // Arduino pin for trigger servo, or output to trigger MOSFET electricTriggerPin = 7; // Arduino pin for output to trigger MOSFET firingIndicatorLEDPin = 12; // Arduino pin for firing indicator LED USBIndicatorLEDPin = 14; // Arduino pin for USB indicator LED modeIndicatorLEDPin = 13; // Arduino pin for Mode indicator LED reloadSwitchPin = 11; // Arduino pin for input from RELOAD switch disablePlatePin = 2; // Arduino pin for input from disable plate invertInputs = true; // TRUE turns on internal pull-ups, use if closed switch connects arduino pin to ground } else if(type == "Standalone_v5") { // pin attachments: panServoPin = 8; // Arduino pin for pan servo tiltServoPin = 9; // Arduino pin for tilt servo triggerServoPin = 10; // Arduino pin for trigger servo, or output to trigger MOSFET electricTriggerPin = 7; // Arduino pin for output to trigger MOSFET firingIndicatorLEDPin = 12; // Arduino pin for firing indicator LED USBIndicatorLEDPin = 14; // Arduino pin for USB indicator LED modeIndicatorLEDPin = 13; // Arduino pin for Mode indicator LED reloadSwitchPin = 11; // Arduino pin for input from RELOAD switch disablePlatePin = 2; // Arduino pin for input from disable plate invertInputs = true; // TRUE turns on internal pull-ups, use if closed switch connects arduino pin to ground } else if(type == "Standalone_v7") { // pin attachments: panServoPin = 8; // Arduino pin for pan servo tiltServoPin = 9; // Arduino pin for tilt servo triggerServoPin = 10; // Arduino pin for trigger servo, or output to trigger MOSFET electricTriggerPin = 7; // Arduino pin for output to trigger MOSFET firingIndicatorLEDPin = 12; // Arduino pin for firing indicator LED USBIndicatorLEDPin = 14; // Arduino pin for USB indicator LED modeIndicatorLEDPin = 13; // Arduino pin for Mode indicator LED reloadSwitchPin = 11; // Arduino pin for input from RELOAD switch disablePlatePin = 2; // Arduino pin for input from disable plate invertInputs = true; // TRUE turns on internal pull-ups, use if closed switch connects arduino pin to ground } else if(type == "Standalone_v8") { // pin attachments: panServoPin = 8; // Arduino pin for pan servo tiltServoPin = 9; // Arduino pin for tilt servo triggerServoPin = 10; // Arduino pin for trigger servo, or output to trigger MOSFET electricTriggerPin = 7; // Arduino pin for output to trigger MOSFET firingIndicatorLEDPin = 12; // Arduino pin for firing indicator LED USBIndicatorLEDPin = 14; // Arduino pin for USB indicator LED modeIndicatorLEDPin = 13; // Arduino pin for Mode indicator LED reloadSwitchPin = 11; // Arduino pin for input from RELOAD switch disablePlatePin = 2; // Arduino pin for input from disable plate invertInputs = true; // TRUE turns on internal pull-ups, use if closed switch connects arduino pin to ground } } <file_sep>/* Part of the GUI for Processing library http://www.lagers.org.uk/g4p/index.html http://gui4processing.googlecode.com/svn/trunk/ Copyright (c) 2008-09 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package guicomponents; import java.io.IOException; import java.io.InputStream; import processing.core.PApplet; import processing.core.PImage; /** * Stores all the colour information for the GUI components into a scheme. * * Defines a set of predefined schemes covering the primary colours * * @author <NAME> * */ public class GCScheme implements GConstants { // Color scheme constants public static final int BLUE_SCHEME = 0; public static final int GREEN_SCHEME = 1; public static final int RED_SCHEME = 2; public static final int PURPLE_SCHEME = 3; public static final int YELLOW_SCHEME = 4; public static final int CYAN_SCHEME = 5; public static final int GREY_SCHEME = 6; protected static PApplet app; protected static PImage image = null; // Mask to get RGB public static final int COL_MASK = 0x00ffffff; // Mask to get alpha public static final int ALPHA_MASK = 0xff000000; public static int setAlpha(int col, int alpha){ alpha = (alpha & 0xff) << 24; col = (col & COL_MASK) | alpha; return col; } /** * Set the default color scheme * * @param theApplet * @return the applets color scheme */ public static GCScheme getColor(PApplet theApplet){ return getColor(theApplet, 0); } /** * Set the color scheme to one of the preset schemes * BLUE / GREEN / RED / PURPLE / YELLOW / CYAN / GREY * or if you have created your own schemes following the instructions * at gui4processing.lagers.org.uk/colorscheme.html then you can enter * the appropriate numeric value of the scheme. * * @param theApplet * @param schemeNo * @return the color scheme based on the scheme number */ public static GCScheme getColor(PApplet theApplet, int schemeNo){ app = theApplet; if(image == null){ InputStream is = app.createInput("user_col_schema.png"); if(is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } image = app.loadImage("user_col_schema.png"); GMessenger.message(USER_COL_SCHEME, null, null); } else { // User image not provided image = app.loadImage("default_col_schema.png"); } } GCScheme scheme = new GCScheme(schemeNo); populateScheme(scheme, schemeNo); return scheme; } protected static void populateScheme(GCScheme s, int schemeNo){ // Force the scheme number to be valid depending on size of image schemeNo = Math.abs(schemeNo) % image.height; s.pnlFont = image.get(0, schemeNo) | ALPHA_MASK; s.pnlTabBack = image.get(1, schemeNo) | ALPHA_MASK; s.pnlBack = image.get(2, schemeNo) | ALPHA_MASK; s.pnlBorder = image.get(3, schemeNo) | ALPHA_MASK; s.btnFont = image.get(5, schemeNo) | ALPHA_MASK; s.btnOff = image.get(6, schemeNo) | ALPHA_MASK; s.btnOver = image.get(7, schemeNo) | ALPHA_MASK; s.btnDown = image.get(8, schemeNo) | ALPHA_MASK; s.sdrTrack = image.get(10, schemeNo) | ALPHA_MASK; s.sdrThumb = image.get(11, schemeNo) | ALPHA_MASK; s.sdrBorder = image.get(12, schemeNo) | ALPHA_MASK; s.txfFont = image.get(15, schemeNo) | ALPHA_MASK; s.txfBack = image.get(16, schemeNo) | ALPHA_MASK; s.txfSelBack = image.get(17, schemeNo) | ALPHA_MASK; s.txfBorder = image.get(18, schemeNo) | ALPHA_MASK; s.txfCursor = s.txfBorder; s.lblFont = image.get(20, schemeNo) | ALPHA_MASK; s.lblBack = image.get(21, schemeNo) | ALPHA_MASK; s.lblBorder = image.get(22, schemeNo) | ALPHA_MASK; s.optFont = image.get(25, schemeNo) | ALPHA_MASK; s.optBack = image.get(26, schemeNo) | ALPHA_MASK; s.optBorder = image.get(27, schemeNo) | ALPHA_MASK; s.cbxFont = image.get(30, schemeNo) | ALPHA_MASK; s.cbxBack = image.get(31, schemeNo) | ALPHA_MASK; s.cbxBorder = image.get(32, schemeNo) | ALPHA_MASK; s.acbBorder = image.get(35, schemeNo) | ALPHA_MASK; s.acbTrack = image.get(36, schemeNo) | ALPHA_MASK; s.acbLast = image.get(37, schemeNo) | ALPHA_MASK; s.acbFirst = image.get(38, schemeNo) | ALPHA_MASK; s.knobBorder = image.get(40, schemeNo) | ALPHA_MASK; s.knobFill = image.get(41, schemeNo) | ALPHA_MASK; s.knobTrack = image.get(42, schemeNo) | ALPHA_MASK; s.knobTicks = image.get(43, schemeNo) | ALPHA_MASK; s.knobNeedle = image.get(44, schemeNo) | ALPHA_MASK; } // Class attributes and methods start here // Scheme number public int schemeNo = 0; // Panels public int pnlFont, pnlTabBack, pnlBack, pnlBorder; // Buttons public int btnFont, btnOff, btnOver, btnDown, btnBorder; // Sliders public int sdrTrack, sdrThumb, sdrBorder; // TextFields public int txfFont, txfBack, txfSelBack, txfBorder, txfCursor; // Label public int lblFont, lblBack, lblBorder; // Option public int optFont, optBack, optBorder; // Checkbox public int cbxFont, cbxBack, cbxBorder; // ActivityBar public int acbBorder, acbTrack, acbFirst, acbLast; // Knobs public int knobBorder, knobFill, knobTrack, knobTicks, knobNeedle; // Transparency level private int alpha = 255; /** * Create a default (blue) scheme */ public GCScheme(){ schemeNo = 0; populateScheme(this, schemeNo); } /** * Create a scheme for a given scheme number * @param csn */ public GCScheme (int csn){ schemeNo = csn; populateScheme(this, schemeNo); } /** * Copy ctor * @param gcScheme scheme to copy */ public GCScheme(GCScheme gcScheme){ schemeNo = gcScheme.schemeNo; populateScheme(this, schemeNo); } /** * Changes the alpha level for all elements of the scheme. * * @param alpha in the range 0 (fully transparent) to 255 (fully opaque) */ public void setAlpha(int alpha){ this.alpha = (alpha & 0xff); int a = this.alpha << 24; pnlFont = (pnlFont & 0x00ffffff) | a; pnlTabBack = (pnlTabBack & 0x00ffffff) | a; pnlBack = (pnlBack & 0x00ffffff) | a; pnlBorder = (pnlBorder & 0x00ffffff) | a; btnFont = (btnFont & 0x00ffffff) | a; btnOff = (btnOff & 0x00ffffff) | a; btnOver = (btnOver & 0x00ffffff) | a; btnDown = (btnDown & 0x00ffffff) | a; btnBorder = (btnBorder & 0x00ffffff) | a; sdrTrack = (sdrTrack & 0x00ffffff) | a; sdrThumb = (sdrThumb & 0x00ffffff) | a; sdrBorder = (sdrBorder & 0x00ffffff) | a; txfFont = (txfFont & 0x00ffffff) | a; txfBack = (txfBack & 0x00ffffff) | a; txfSelBack = (txfSelBack & 0x00ffffff) | a; txfBorder = (txfBorder & 0x00ffffff) | a; txfCursor = (txfCursor & 0x00ffffff) | a; lblFont = (lblFont & 0x00ffffff) | a; lblBack = (lblBack & 0x00ffffff) | a; lblBorder = (lblBorder & 0x00ffffff) | a; optFont = (optFont & 0x00ffffff) | a; optBack = (optBack & 0x00ffffff) | a; optBorder = (optBorder & 0x00ffffff) | a; cbxFont = (cbxFont & 0x00ffffff) | a; cbxBack = (cbxBack & 0x00ffffff) | a; cbxBorder = (cbxBorder & 0x00ffffff) | a; acbBorder = (acbBorder & 0x00ffffff | a); acbTrack = (acbTrack & 0x00ffffff | a); acbLast = (acbLast & 0x00ffffff | a); acbFirst = (acbFirst & 0x00ffffff | a); knobBorder = (knobBorder & 0x00ffffff | a); knobFill = (knobFill & 0x00ffffff | a); knobTrack = (knobTrack & 0x00ffffff | a); knobTicks = (knobTicks & 0x00ffffff | a); knobNeedle = (knobNeedle & 0x00ffffff | a); } /** * Get the transparency level * @return 0 - transparent; 255 - opaque */ public int getAlpha(){ return alpha; } } // end of class <file_sep>package guicomponents; import guicomponents.HotSpot.HSrect; import guicomponents.StyledString.TextLayoutHitInfo; import guicomponents.StyledString.TextLayoutInfo; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.font.TextHitInfo; import java.awt.font.TextLayout; import java.awt.geom.GeneralPath; import java.util.LinkedList; import processing.core.PApplet; import processing.core.PGraphicsJava2D; public class FTextArea extends FTextComponent { private static float pad = 6; public FTextArea(PApplet theApplet, float p0, float p1, float p2, float p3) { this(theApplet, p0, p1, p2, p3, SCROLLBARS_NONE); } public FTextArea(PApplet theApplet, float p0, float p1, float p2, float p3, int scrollbars) { super(theApplet, p0, p1, p2, p3, scrollbars); tx = ty = pad; tw = width - 2 * pad - ((sbPolicy & SCROLLBAR_VERTICAL) != 0 ? 18 : 0); th = height - 2 * pad - ((sbPolicy & SCROLLBAR_HORIZONTAL) != 0 ? 18 : 0); gpTextDisplayArea = new GeneralPath(); gpTextDisplayArea.moveTo( 0, 0); gpTextDisplayArea.lineTo( 0, th); gpTextDisplayArea.lineTo(tw, th); gpTextDisplayArea.lineTo(tw, 0); gpTextDisplayArea.closePath(); // The image buffer is just for the typing area buffer = (PGraphicsJava2D) winApp.createGraphics((int)width, (int)height, PApplet.JAVA2D); buffer.rectMode(PApplet.CORNER); buffer.g2.setFont(fLocalFont); hotspots = new HotSpot[]{ new HSrect(1, tx, ty, tw, th), // typing area new HSrect(9, 0, 0, width, height), // control surface }; if((sbPolicy & SCROLLBAR_HORIZONTAL) != 0){ hsb = new FScrollbar(theApplet, 0, 0, tw, 16); addCompoundControl(hsb, tx, ty + th + 2, 0); hsb.addEventHandler(this, "hsbEventHandler"); hsb.setAutoHide(autoHide); } if((sbPolicy & SCROLLBAR_VERTICAL) != 0){ vsb = new FScrollbar(theApplet, 0, 0, th, 16); addCompoundControl(vsb, tx + tw + 18, ty, PI/2); vsb.addEventHandler(this, "vsbEventHandler"); vsb.setAutoHide(autoHide); } setTextNew(" ", (int)tw); z = Z_STICKY; registerAutos_DMPK(true, true, false, true); } /** * Set the text to be used. The wrap width is determined by the size of the component. * @param text */ public void setTextNew(String text){ setText(text, (int)tw); } /** * Set the text to display and adjust any scrollbars * @param text * @param wrapWidth */ public void setTextNew(String text, int wrapWidth){ this.text = text; stext = new StyledString(buffer.g2, text, wrapWidth); float sTextHeight; if(vsb != null){ sTextHeight = stext.getTextAreaHeight(); ptx = pty = 0; if(sTextHeight < th) vsb.setValue(0.0f, 1.0f); else vsb.setValue(0, th/sTextHeight); } // If needed update the horizontal scrollbar if(hsb != null){ if(stext.getMaxLineLength() < tw) hsb.setValue(0,1); else hsb.setValue(0, tw/stext.getMaxLineLength()); } } /** * If the buffer is invalid then redraw it. */ protected void updateBuffer(){ if(bufferInvalid) { Graphics2D g2d = buffer.g2; TextLayoutHitInfo startSelTLHI = null, endSelTLHI = null; buffer.beginDraw(); // Whole control surface if opaque if(opaque) buffer.background(palette[6]); else buffer.background(buffer.color(255,0)); // Now move to top left corner of text display area buffer.translate(tx,ty); // Typing area surface buffer.noStroke(); buffer.fill(palette[7]); buffer.rect(-1,-1,tw+2,th+2); g2d.setClip(gpTextDisplayArea); buffer.translate(-ptx, -pty); // Translate in preparation for display selection and text // buffer.strokeWeight(1.5f); // Get latest version of styled text layouts LinkedList<TextLayoutInfo> lines = stext.getLines(g2d); boolean hasSelection = hasSelection(); if(hasSelection){ if(endTLHI.compareTo(startTLHI) == -1){ startSelTLHI = endTLHI; endSelTLHI = startTLHI; } else { startSelTLHI = startTLHI; endSelTLHI = endTLHI; } } // Display selection and text for(TextLayoutInfo lineInfo : lines){ TextLayout layout = lineInfo.layout; buffer.translate(0, layout.getAscent()); // Draw selection if any if(hasSelection && lineInfo.compareTo(startSelTLHI.tli) >= 0 && lineInfo.compareTo(endSelTLHI.tli) <= 0 ){ int ss = 0; ss = (lineInfo.compareTo(startSelTLHI.tli) == 0) ? startSelTLHI.thi.getInsertionIndex() : 0; int ee = endSelTLHI.thi.getInsertionIndex(); ee = (lineInfo.compareTo(endSelTLHI.tli) == 0) ? endSelTLHI.thi.getInsertionIndex() : lineInfo.nbrChars-1; g2d.setColor(jpalette[14]); Shape selShape = layout.getLogicalHighlightShape(ss, ee); g2d.fill(selShape); } // display text g2d.setColor(jpalette[2]); lineInfo.layout.draw(g2d, 0, 0); buffer.translate(0, layout.getDescent() + layout.getLeading()); } g2d.setClip(null); buffer.endDraw(); bufferInvalid = false; } } /** * See if the cursor is off screen if so pan the display * @return */ protected boolean keepCursorInDisplay(){ boolean horzScroll = false, vertScroll = false; if(endTLHI != null){ if(caretX < ptx ){ // LEFT? ptx--; if(ptx < 0) ptx = 0; horzScroll = true; } else if(caretX > ptx + tw - 2){ // RIGHT? ptx++; horzScroll = true; } if(caretY < pty){ // UP? pty--; if(pty < 0) pty = 0; vertScroll = true; } else if(caretY > pty + th + stext.getMaxLineHeight()){ // DOWN? pty++; vertScroll = true; } if(horzScroll && hsb != null) hsb.setValue(ptx / (stext.getMaxLineLength() + 4)); if(vertScroll && vsb != null) vsb.setValue(pty / (stext.getTextAreaHeight() + 1.5f * stext.getMaxLineHeight())); } // If we have scrolled invalidate the buffer otherwise forget it if(horzScroll || vertScroll) bufferInvalid = true; // Let the user know we have scrolled return horzScroll | vertScroll; } public void draw(){ if(!visible) return; // Uodate buffer if invalid updateBuffer(); winApp.pushStyle(); winApp.pushMatrix(); // Perform the rotation winApp.translate(cx, cy); winApp.rotate(rotAngle); winApp.pushMatrix(); // Move matrix to line up with top-left corner winApp.translate(-halfWidth, -halfHeight); // Draw buffer winApp.imageMode(PApplet.CORNER); winApp.image(buffer, 0, 0); // Draw caret if text display area if(showCaret && endTLHI != null){ float[] cinfo = endTLHI.tli.layout.getCaretInfo(endTLHI.thi); float x_left = - ptx + cinfo[0]; float y_top = - pty + endTLHI.tli.yPosInPara; float y_bot = y_top - cinfo[3] + cinfo[5]; if(x_left >= 0 && x_left <= tw && y_top >= 0 && y_bot <= th){ winApp.strokeWeight(1.9f); winApp.stroke(palette[15]); winApp.line(tx+x_left, ty+Math.max(0, y_top), tx+x_left, ty+Math.min(th, y_bot)); } } winApp.popMatrix(); if(children != null){ for(GComponent c : children) c.draw(); } winApp.popMatrix(); winApp.popStyle(); } protected boolean processKeyPressed(KeyEvent e, boolean shiftDown, boolean ctrlDown){ int keyCode = e.getKeyCode(); boolean caretMoved = false; switch(keyCode){ case KeyEvent.VK_LEFT: caretMoved = moveCaretLeft(endTLHI); break; case KeyEvent.VK_RIGHT: caretMoved = moveCaretRight(endTLHI); break; case KeyEvent.VK_UP: caretMoved = moveCaretUp(endTLHI); break; case KeyEvent.VK_DOWN: caretMoved = moveCaretDown(endTLHI); break; case KeyEvent.VK_HOME: if(ctrlDown){ // move to start of text caretMoved = moveCaretStartOfText(endTLHI); } else // Move to start of line caretMoved = moveCaretStartOfLine(endTLHI); break; case KeyEvent.VK_END: if(ctrlDown){ // move to end of text caretMoved = moveCaretEndOfText(endTLHI); } else // Move to end of line caretMoved = moveCaretEndOfLine(endTLHI); break; } calculateCaretPos(endTLHI); if(caretX > stext.getWrapWidth()){ switch(keyCode){ case KeyEvent.VK_LEFT: case KeyEvent.VK_UP: case KeyEvent.VK_DOWN: case KeyEvent.VK_END: moveCaretLeft(endTLHI); caretMoved = true; break; case KeyEvent.VK_RIGHT: if(!moveCaretRight(endTLHI)) moveCaretLeft(endTLHI); caretMoved = true; } // Calculate new caret position calculateCaretPos(endTLHI); } // After testing for cursor moving keys if(caretMoved){ if(!shiftDown) // Not extending selection startTLHI.copyFrom(endTLHI); else bufferInvalid = true; // Selection changed } return caretMoved; } public void keyEvent(KeyEvent e) { if(!visible || !enabled || !available) return; if(focusIsWith == this && endTLHI != null){ boolean shiftDown = ((e.getModifiersEx() & KeyEvent.SHIFT_DOWN_MASK) == KeyEvent.SHIFT_DOWN_MASK); boolean ctrlDown = ((e.getModifiersEx() & KeyEvent.CTRL_DOWN_MASK) == KeyEvent.CTRL_DOWN_MASK); if(e.getID() == KeyEvent.KEY_PRESSED) { processKeyPressed(e, shiftDown, ctrlDown); setScrollbarValues(ptx, pty); while(keepCursorInDisplay()); } else if(e.getID() == KeyEvent.KEY_TYPED && e.getKeyChar() != KeyEvent.CHAR_UNDEFINED){ processKeyTyped(e, shiftDown, ctrlDown); setScrollbarValues(ptx, pty); while(keepCursorInDisplay()); } } } /** * Move caret to home position * @return true if caret moved else false */ protected boolean moveCaretStartOfLine(TextLayoutHitInfo currPos){ if(currPos.thi.getCharIndex() == 0) return false; // already at start of line currPos.thi = currPos.tli.layout.getNextLeftHit(1); return true; } protected boolean moveCaretEndOfLine(TextLayoutHitInfo currPos){ if(currPos.thi.getCharIndex() == currPos.tli.nbrChars - 1) return false; // already at end of line currPos.thi = currPos.tli.layout.getNextRightHit(currPos.tli.nbrChars - 1); return true; } protected boolean moveCaretStartOfText(TextLayoutHitInfo currPos){ if(currPos.tli.lineNo == 0 && currPos.thi.getCharIndex() == 0) return false; // already at start of text currPos.tli = stext.getTLIforLineNo(0); currPos.thi = currPos.tli.layout.getNextLeftHit(1); return true; } protected boolean moveCaretEndOfText(TextLayoutHitInfo currPos){ if(currPos.tli.lineNo == stext.getNbrLines() - 1 && currPos.thi.getCharIndex() == currPos.tli.nbrChars - 1) return false; // already at end of text currPos.tli = stext.getTLIforLineNo(stext.getNbrLines() - 1); currPos.thi = currPos.tli.layout.getNextRightHit(currPos.tli.nbrChars - 1); return true; } protected boolean moveCaretUp(TextLayoutHitInfo currPos){ if(currPos.tli.lineNo == 0) return false; TextLayoutInfo ntli = stext.getTLIforLineNo(currPos.tli.lineNo - 1); TextHitInfo nthi = ntli.layout.hitTestChar(caretX, 0); currPos.tli = ntli; currPos.thi = nthi; return true; } protected boolean moveCaretDown(TextLayoutHitInfo currPos){ if(currPos.tli.lineNo == stext.getNbrLines() - 1) return false; TextLayoutInfo ntli = stext.getTLIforLineNo(currPos.tli.lineNo + 1); TextHitInfo nthi = ntli.layout.hitTestChar(caretX, 0); currPos.tli = ntli; currPos.thi = nthi; return true; } /** * Move caret left by one character. If necessary move to the end of the line above * @return true if caret was moved else false */ protected boolean moveCaretLeft(TextLayoutHitInfo currPos){ TextLayoutInfo ntli; TextHitInfo nthi = currPos.tli.layout.getNextLeftHit(currPos.thi); if(nthi == null){ // Move the caret to the end of the previous line if(currPos.tli.lineNo == 0) // Can't goto previous line because this is the first line return false; else { // Move to end of previous line ntli = stext.getTLIforLineNo(currPos.tli.lineNo - 1); nthi = ntli.layout.getNextRightHit(ntli.nbrChars-1); currPos.tli = ntli; currPos.thi = nthi; } } else { // Move the caret to the left of current position currPos.thi = nthi; } return true; } /** * Move caret left by one character. If necessary move to the end of the line above * @return true if caret was moved else false */ protected boolean moveCaretRight(TextLayoutHitInfo currPos){ TextLayoutInfo ntli; TextHitInfo nthi = currPos.tli.layout.getNextRightHit(currPos.thi); if(nthi == null){ // Move the caret to the end of the previous line if(currPos.tli.lineNo >= stext.getNbrLines() - 1) // Can't goto next line because this is the last line return false; else { // Move to start of next line ntli = stext.getTLIforLineNo(currPos.tli.lineNo + 1); nthi = ntli.layout.getNextLeftHit(1); currPos.tli = ntli; currPos.thi = nthi; } } else { // Move the caret to the right of current position currPos.thi = nthi; } return true; } public void mouseEvent(MouseEvent event){ if(!visible || !enabled || !available) return; calcTransformedOrigin(winApp.mouseX, winApp.mouseY); ox -= tx; oy -= ty; // Remove translation currSpot = whichHotSpot(ox, oy); if(currSpot == 1 || focusIsWith == this) cursorIsOver = this; else if(cursorIsOver == this) cursorIsOver = null; switch(event.getID()){ case MouseEvent.MOUSE_PRESSED: if(currSpot == 1){ if(focusIsWith != this && z > focusObjectZ()){ takeFocus(); } mdx = winApp.mouseX; mdy = winApp.mouseY; endTLHI = stext.calculateFromXY(buffer.g2, ox + ptx, oy + pty); startTLHI = new TextLayoutHitInfo(endTLHI); calculateCaretPos(endTLHI); bufferInvalid = true; } break; case MouseEvent.MOUSE_RELEASED: dragging = false; break; case MouseEvent.MOUSE_DRAGGED: if(focusIsWith == this){ dragging = true; endTLHI = stext.calculateFromXY(buffer.g2, ox + ptx, oy + pty); calculateCaretPos(endTLHI); bufferInvalid = true; keepCursorInDisplay(); } break; } } protected void calculateCaretPos(TextLayoutHitInfo tlhi){ float temp[] = tlhi.tli.layout.getCaretInfo(tlhi.thi); caretX = temp[0]; caretY = tlhi.tli.yPosInPara; } } <file_sep>/* Part of the GUI for Processing library http://www.lagers.org.uk/g4p/index.html http://gui4processing.googlecode.com/svn/trunk/ Copyright (c) 2008-09 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package guicomponents; import java.awt.event.MouseEvent; import processing.core.PApplet; /** * Abstract class to provide a slider - GHorzSlider and GVertSlider * inherit from this class. * * @author <NAME> * */ public abstract class GSlider extends GComponent { public static final int INTEGER = 0; public static final int DECIMAL = 1; public static final int EXPONENT = 2; /** * These are the values that are supplied back to the user */ protected float init; protected float maxValue = 0; protected float minValue = 100; protected float value; // Indicates the type of value used in the display protected int _valueType = 0; /** * Pixel values relative to slider top left */ protected int thumbMin, thumbMax; // The position to display the thumb protected int thumbPos; // The final position for the thumb protected int thumbTargetPos; protected int thumbSize = 10; protected int thumbInertia = 1; protected int offset; protected boolean isValueChanging = false; /** * Called by GHorzSlider and GVertSlider. * * @param theApplet * @param x * @param y * @param width * @param height */ public GSlider(PApplet theApplet, int x, int y, int width, int height){ super(theApplet, x, y); this.width = width; this.height = height; z = Z_SLIPPY; registerAutos_DMPK(true, true, true, false); createEventHandler(G4P.mainWinApp, "handleSliderEvents", new Class[]{ GSlider.class }); } public GSlider(PApplet theApplet, int x, int y) { super(theApplet, x, y); } /** * The user can change the range and initial value of the * slider from the default values of range 0-100 and * initial value of 50. * This method ignores inertia so the effect is immediate. * * @param init * @param min * @param max */ public void setLimits(int init, int min, int max){ minValue = Math.min(min, max); maxValue = Math.max(min, max); this.init = Math.round(PApplet.constrain((float)init, minValue, maxValue)); if(thumbMax - thumbMin < maxValue - minValue && G4P.messages){ System.out.println(getClass().getSimpleName()+".setLimits"); System.out.println(" not all values in the range "+min+" - "+max+" can be returned"); System.out.print(" either reduce the range or make the slider "); if(this.getClass().getSimpleName().equals("GHorzSlider")) System.out.print("width"); else System.out.print("height"); System.out.println(" at least " + (max-min+thumbSize)); } thumbTargetPos = thumbPos; // Set the value immediately ignoring inertia setValue(init, true); _valueType = INTEGER; } /** * Sets the limits of the slider as float values. Converted to floats or integer depending * on the type of the slider. */ public void setLimits(float init, float min, float max){ minValue = Math.min(min, max); maxValue = Math.max(min, max); this.init = PApplet.constrain(init, minValue, maxValue); thumbTargetPos = thumbPos; // Set the value immediately ignoring inertia setValue(this.init, true); if(_valueType == INTEGER) _valueType = DECIMAL; } /** * Override in child classes */ public void mouseEvent(MouseEvent event){ } /** * Override in child classes * * @return always false */ public boolean isOver(int ax, int ay){ return false; } /** * Get the minimum slider value * @return min value */ public int getMinValue() { return Math.round(minValue); } /** * Get the maximum slider value * @return max value */ public int getMaxValue() { return Math.round(maxValue); } /** * Sets the type of slider that this should be. <br> * INTEGER or DECIMAL or EXPONENT */ public void setValueType(int type){ _valueType = type; } /** * Get the type used for the slider value * @return GSlider.INTEGER or GSlider.DECIMAL or GSlider.EXPONENT */ public int getValueType(){ return _valueType; } /** * Get the current value represented by the slider * * @return current value */ public int getValue(){ return Math.round(value); } /** * Gets the current value of the slider. If the value type is integer * then the value is rounded. */ public float getValuef(){ if(_valueType == INTEGER) return Math.round(value); else return value; } /** * Is the value changing as a result of the slider thumb being * dragged with the mouse. * * @return true if value being changed at GUI */ public boolean isValueChanging() { return isValueChanging; } /** * Sets the target value of the slider, if setInertia(x) has been used * to implement inertia then the actual slider value will gradually * change until it reaches the target value. The slider thumb is * always in the right position for the current slider value. <br> * <b>Note</b> that events will continue to be generated so if this * causes unexpected behaviour then use setValue(newValue, true) * * @param newValue the value we wish the slider to become */ public void setValue(int newValue){ value = PApplet.constrain(newValue, minValue, maxValue); thumbTargetPos = (int) PApplet.map(value, minValue, maxValue, thumbMin, thumbMax); } /** * The same as setValue(newValue) except the second parameter determines * whether we should ignore any inertia value so the affect is immediate. <br> * <b>Note</b> if false then events will continue to be generated so if this * causes unexpected behaviour then use setValue(newValue, true) * * @param newValue the value we wish the slider to become * @param ignoreInteria if true change is immediate */ public void setValue(int newValue, boolean ignoreInteria){ setValue(newValue); if(ignoreInteria){ thumbPos = thumbTargetPos; } } /** * Sets the target value of the slider, if setInertia(x) has been * to implement inertia then the actual slider value will gradually * change until it reaches the target value. The slider thumb is * always in the right position for the current slider value. <br> * <b>Note</b> that events will continue to be generated so if this * causes unexpected behaviour then use setValue(newValue, true) * * @param newValue the value we wish the slider to become */ public void setValue(float newValue){ value = PApplet.constrain(newValue, minValue, maxValue); thumbTargetPos = (int) PApplet.map(value, minValue, maxValue, thumbMin, thumbMax); } /** * The same as setValue(newValue) except the second parameter determines * whether we should ignore any inertia value so the affect is immediate. <br> * <b>Note</b> if false then events will continue to be generated so if this * causes unexpected behaviour then use setValue(newValue, true) * * @param newValue the value we wish the slider to become * @param ignoreInteria if true change is immediate */ public void setValue(float newValue, boolean ignoreInteria){ setValue(newValue); if(ignoreInteria){ thumbPos = thumbTargetPos; } } /** * When dragging the slider thumb rapidly with the mouse a certain amount of * inertia will give a nice visual effect by trailing the thumb behind the * mouse. A value of 1 (default) means the thumb is always in step with * the mouse. Increasing values will increase the amount of trailing and the * length of time needed to reach the final value. * I have found values around 10 give quite nice effect but much over 20 and * you start to loose the gliding effect due to acceleration and deacceleration. * * @param inertia values passed is constrained to the range 1-50. */ public void setInertia(int inertia){ thumbInertia = PApplet.constrain(inertia, 1, 100); } /** * Move thumb if not at desired position */ public void pre(){ int change, inertia = thumbInertia; if(thumbPos == thumbTargetPos){ isValueChanging = false; } else { // Make sure we get a change value by repeatedly decreasing the inertia value do { change = (thumbTargetPos - thumbPos)/inertia; inertia--; } while (change == 0 && inertia > 0); // If there is a change update the current value and generate an event if(change != 0){ thumbPos += change; float newValue = PApplet.map(thumbPos, thumbMin, thumbMax, minValue, maxValue); boolean valueChanged = (newValue != value); value = newValue; if(valueChanged){ eventType = CHANGED; fireEvent(); } } else isValueChanging = false; } } /** * Override in child classes */ public void draw(){ } }
af038013aa1a7b93b8da68b66fc7279dbd0012c1
[ "Markdown", "Java", "C++" ]
13
Java
ryan-peirce/Project-Sentry-Gun
de688a6010fe9a316891e2bfbdc11d7d229365a9
3fe0250b88ca3f62a48254c7889e157d2de19592
refs/heads/master
<repo_name>ddl-aambekar/sharepoint<file_sep>/sharepoint/sharepoint/__init__.py from sharepoint.auth import manual_auth from sharepoint.api import get_api_client from sharepoint.SPObjects import site_login, get_new_site, SPSite <file_sep>/sharepoint/sharepoint/api.py # -*- coding: utf-8 -*- from datetime import datetime, timedelta import logging import os from json import JSONDecodeError from urllib.parse import urlsplit def get_api_client(url, auth, logging=False): return APIclient(url, auth, logging) def _remove_filename(path): """ Return _dirname only if last element is a file. Don't include trailing slash in return value. :param path: :return: """ parts = urlsplit(path) last = parts.path.split('/')[-1] if '.' in last: # If last part of path has . then this is a file return os.path.dirname(path) else: if path[-1] == '/': path = path[:-1] return path class APIclient(object): """ SPApi is used to make API calls to the SharePoint server. Each SPObject includes a copy of SPApi and the api_url attribute of each copy is altered to point to the uri of the parent SPObject. Copies are shallow so that only a single requests session exists in memory. Context management for requests session handled in SPSite object. """ def __init__(self, url, auth, logging=False): # Connect to SharePoint self.auth = auth if self.auth.logged_in: self._session = self.auth.session # If logged in, get requests session else: self._session = self.auth.login() # auth.login returns requests session # Return JSON instead of XML self._session.headers.update({ "Accept": "application/json; odata=verbose", "Content-type": "application/json; odata=verbose" }) url = _remove_filename(url) self.api_url = self._get_api_url(url) # Form digest expiration. An unexpired digest token is required for posting # Setting to now guarantees that a new digest token is requested upon the first post self.expire = datetime.now() # Configure Logging self.logger = self._create_logger(logging) def get(self, url, params=None): """ Call _http with GET """ r = self.http(url, 'GET', params) return r def post(self, url, data=None): """ Call _http with POST :param url: :param data: :return: """ r = self.http(url, 'POST', data) return r def _get_api_url(self, url): """ Determines sharepoint_url to SharePoint api by looking up contextinfo property. Preserves path to SharePoint sub-sites. :param url: URL to any resource in desired SharePoint site :return: String with api sharepoint_url """ # Get rid of all path items after and including "_layouts" path_items = url.split('/') try: layouts_idx = path_items.index('_layouts') url = '/'.join(path_items[:layouts_idx]) except ValueError: # _layouts does not exist pass req_url = url + '/_api/contextinfo' r = self._session.post(req_url) self._check_response(r) site = r.json()['d']['GetContextWebInformation']['WebFullUrl'] return "{}/_api".format(site) def _check_response(self, r): """ Check if status code is ok. :param r: requests.Response object :return: None """ # TODO Need to check if re-authentication is needed here? if not r.ok: try: err_msg = r.json()['error']['message']['value'], except (KeyError, JSONDecodeError) as _: err_msg = None err_str = '{code}: {reason}\n{message}\nRequest: {request}'.format( code=r.status_code, reason=r.reason, message=err_msg, request=r.request.method + ' ' + r.url ) raise Exception(err_str) def _create_logger(self, logging_on): if logging_on: handler = logging.FileHandler('log') else: handler = logging.NullHandler() # create logger logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) # create console handler and set level to debug handler.setLevel(logging.INFO) # create formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch handler.setFormatter(formatter) # add ch to logger logger.addHandler(handler) return logger def _digest(self): """ If digest token is expired, obtain new value and update session header :return: """ if self.expire <= datetime.now(): r = self._session.post(self.api_url + '/contextinfo') self._check_response(r) contextinfo = r.json()['d']['GetContextWebInformation'] self._session.headers['X-RequestDigest'] = contextinfo['FormDigestValue'] self.expire = datetime.now() + timedelta(seconds=contextinfo['FormDigestTimeoutSeconds']) def http(self, url, verb, payload=None): """ Make an http request :param url: :param verb: :return: """ self.logger.debug("{0} request to {1}".format(verb, url)) if verb.upper() == 'GET': r = self._session.get(url, params=payload) elif verb.upper() == 'POST': self._digest() r = self._session.post(url, data=payload) else: raise Exception('HTTP verb {} not supported'.format(verb)) self._check_response(r) return r <file_sep>/sharepoint/sharepoint/SPObjects.py # -*- coding: utf-8 -*- import os from urllib.parse import parse_qs, urlsplit import uuid from sharepoint import manual_auth from sharepoint import get_api_client import logging logger = logging.getLogger(__name__) def site_login(url, getpass, logging=False): auth = manual_auth(getpass) auth.login() api_client = get_api_client(url, auth, logging) site_url = api_client.api_url + '/Web' return SPSite(site_url, api_client) def get_new_site(url, old_site, logging=False): """ Reuse Authentication from old_site to create new site object """ api_client = get_api_client(url, old_site._api_client.auth, logging) site_url = api_client.api_url + '/Web' return SPSite(site_url, api_client) def _json_to_object(json, api_client): sp_type = json['__metadata']['type'].replace(".", "") logger.debug("Attribute is an object of type {}. Creating object.".format(sp_type)) try: # Check if class is implemented in python sp_class = globals()[sp_type] except KeyError: sp_class = SPObject return sp_class(json['__metadata']['uri'], api_client, json) def _stringify(obj): try: # If object is a string, encode apostrophe and place single quotes around it obj = obj.replace("'", "%27%27") # Encoding apostrophe prevents interference early termination of quotes return "'" + obj + "'" except AttributeError: # If object is not a string, convert it to a string without quotes if type(obj) == uuid.UUID: return "guid'{}'".format(str(obj)) else: return str(obj) class SPObject(object): @staticmethod def _make_call_string(method_name, *args, **kwargs): """ Call a method from the SharePoint API. :param endpoint_url: URL for SharePoint resource with desired method. URI should not contain actual method. :param method_name: Name of method. :param args: Unnamed arguments for method. :param payload: OData query string for GET or data for POST :param verb: 'GET' or 'POST' :param kwargs: named arguments :return: Dict for json response """ args = ', '.join([_stringify(arg) for arg in args]) kwargs = ', '.join(["{0}={1}".format(key, _stringify(val)) for key, val in kwargs.items()]) all_args = ', '.join([args, kwargs]).strip(', ') call_str = "/{name}({args})".format( name=method_name, args=all_args ) return call_str def __init__(self, url, api_client, json=None): # json is dict with attribute values. Don't include 'd' key with json logger.debug('Creating new object from {}'.format(url)) self._api_client = api_client self._endpoint_url = url self._attributes = {} if json: logger.debug('JSON was supplied. Parsing into attributes') json.pop('__metadata') for name, val in json.items(): logger.debug('Setting attribute {}'.format(name)) if type(val) is dict: # Attribute is deferred so ignore it pass else: self._attributes[name] = val def __repr__(self): return self._repr_text(self._endpoint_url) def _repr_text(self, path_text): return "{0} {1}".format(type(self), path_text) def attribute(self, name): logger.debug("Retrieving attribute: {}".format(name)) # Retrieve value if already stored if name in self._attributes.keys(): logger.debug("Attribute was already stored. Retrieving value.") return self._attributes[name] else: url = self._attribute_url(name) logger.debug("Getting attribute from: {}".format(url)) self._attributes[name] = LazyAttribute(url, self._api_client, name).value() return self._attributes[name] def lazy_attribute(self, name): url = self._attribute_url(name) logger.debug("Creating LazyAttribute for {0} from {1}".format(name, url)) attribute = LazyAttribute(url, self._api_client, name) return attribute def _attribute_url(self, name): return self._endpoint_url + '/' + name def _method_get(self, method_name, *args, **kwargs): req_string = self._make_call_string(method_name, *args, **kwargs) url = self._endpoint_url + req_string return SPObject(url, self._api_client) def _method_post(self, method_name, *args, data=None, **kwargs): req_string = self._make_call_string(method_name, *args, **kwargs) url = self._endpoint_url + req_string return LazyPost(url, self._api_client, data) class LazyAttribute(SPObject): def __init__(self, url, api_client, name, value=None): self._name = name self._value = self._parse_json(value) super(LazyAttribute, self).__init__(url, api_client) def value(self, query=None): if not self._value: json = self._api_client.get(self._endpoint_url, query).json()['d'] logger.debug("Response for attribute {0}:\n{1}".format(self._name, json)) self._value = self._parse_json(json) return self._value def _parse_json(self, json): logger.debug('Parsing json') if not json: logger.debug('Value is not json. Setting value to None') value = None elif self._name in json.keys(): logger.debug('Attribute found in json.') value = json[self._name] elif 'results' in json.keys(): # json is a list results = [result for result in json['results']] logger.debug('Attribute is a list with length {0}. Parsing each item.'.format(len(json['results']))) value = [_json_to_object(item, self._api_client) for item in results] else: # json represents object. Assign correct object class. value = _json_to_object(json, self._api_client) return value class LazyPost(SPObject): def __init__(self, url, api_client, data=None): self.data = data super(LazyPost, self).__init__(url, api_client) def send(self): return self._api_client.post(self._endpoint_url, data=self.data) class SPSite(SPObject): """ SPSite represents the "Web" core endpoint from the SharePoint API. Users should only directly make instances of this class. All other class instances will be ultimately created through methods from this class. """ def __repr__(self): return self._repr_text(self.attribute('Title')) def download_file(self, sp_file_path, destination='.'): """ Convenience method that combines SPSite.get_file and SPFile.download file. """ sp_file = self.get_file_by_path(sp_file_path) sp_file.download(destination) def get_file_by_path(self, file_path): file_path = self._append_site_path(file_path) file_url = self._method_get('GetFileByServerRelativeUrl', ServerRelativeUrl=file_path)._endpoint_url return SPFile(file_url, self._api_client) def get_file_by_id(self, file_id): file_url = self._method_get('GetFileById', uniqueId=file_id)._endpoint_url return SPFile(file_url, self._api_client) def get_file_by_url(self, url): """ Attempt to parse sharepoint_url and retrieve file resource. If file_path or file id is known other methods should be used since this method is less robust. """ parts = urlsplit(url) query = parse_qs(parts.query) keys = query.keys() if "sourcedoc" in keys: uid = query['sourcedoc'][0][1:-1] return self.get_file_by_id(uid) elif "SourceUrl" in keys: path = query['SourceUrl'][0] path = '/' + '/'.join(path.split('/')[3:]) # Check for invalid .xlsf extension base, ext = os.path.splitext(path) if ext == '.xlsf': path = base + '.xls' return self.get_file_by_path(path) else: # Assume sharepoint_url is valid and remove all query items return self.get_file_by_path(parts.path) def get_folder(self, folder_path): folder_path = self._append_site_path(folder_path) new_url = self._method_get('GetFolderByServerRelativeUrl', folder_path)._endpoint_url return SPFolder(new_url, self._api_client) def _append_site_path(self, path): """ :param path: :return: """ if not path.startswith(self.attribute('ServerRelativeUrl')): path = self.attribute('ServerRelativeUrl') + '/' + path.strip('/') return path class SPFolder(SPObject): def __repr__(self): return self._repr_text(self.attribute('ServerRelativeUrl')) def download_files(self, destination='.'): """ Download all files in given folder. Ignores sub-folders. :param destination: Destination path where files will be saved. :return: None """ for file in self.attribute('Files'): if os.path.splitext(file.attribute('Name'))[1] not in ['.aspx']: # Downloading .aspx results in 403 forbidden error file.download(destination) def download(self, destination='.', maxdepth=None): """ Download all files and sub-folders up to specified depth. :param destination: Top-level path where files will be saved. :param maxdepth: Number of sub-folder levels to retrieve. To get all subfolders, set level to -1. :return: None """ base_path = os.path.dirname(self.attribute('ServerRelativeUrl')) destination = destination.strip('/') logger.debug("Start download of {}".format(base_path)) for folder, _, _, in self.walk(maxdepth=maxdepth): logger.debug('Inside {}'.format(folder.attribute('Name'))) folder_path = folder.attribute('ServerRelativeUrl')[len(base_path):] logger.debug('Folder path: {}'.format(folder_path)) dest_folder = destination + '/' + folder_path folder.download_files(dest_folder) def listdir(self): return self.attribute('Files') + self.attribute('Folders') def walk(self, topdown=True, maxdepth=None): """ Analogous to os.walk :param topdown: :param maxdepth: Maximum recursion depth. :return: """ top = self folders = self.attribute('Folders') logger.debug("Inside walk. Folders retrieved.") files = self.attribute('Files') logger.debug("Inside walk. Files retrieved.") if topdown: logger.debug("Reached walk endpoint.") yield top, folders, files if maxdepth is None or maxdepth > 1: for folder in folders: if maxdepth: newdepth = maxdepth - 1 else: newdepth = None for x in folder.walk(topdown, newdepth): yield x if not topdown: yield top, folders, files def upload_file(self, filename, overwrite=True): """ Upload a file to SharePoint :param filename: String with path to local file :param overwrite: Overwrite existing file on SharePoint? :return: None """ file_size = os.path.getsize(filename) chunk_size = 1024*1024 file_base = os.path.split(filename)[1] stream = False if file_size <= chunk_size: with open(filename, 'rb') as f: file = f.read() else: file = None # Don't include data with add method. Send it via streaming. stream = True try: # This runs even if streaming upload is used because an empty file must be created before streaming starts r = self.lazy_attribute('Files')._method_post('add', data=file, url=file_base, overwrite=str(overwrite).lower(), ).send() file = _json_to_object(r.json()['d'], self._api_client) except: logger.exception("Upload Failed") return if stream: self._stream_upload(filename, file_size, chunk_size) print("Uploaded {0} to {1}".format(filename, self.attribute('ServerRelativeUrl'))) if file.attribute('CheckOutType') != 2: logger.debug("File {} is checked out. Checking in file.".format(file.attribute('Name'))) file._method_post('CheckIn', comment="", checkInType=0).send() # Check in type 0 is minor check in def _stream_upload(self, filename, file_size, chunk_size): """ For larger files, upload in chunks. :param filename: :param file_size: :param chunk_size: :return: """ guid = uuid.uuid4() first_chunk = True f = open(filename, 'rb') i = self._endpoint_url.find("Web") + 3 site_url = self._endpoint_url[:i] # Add empty file to folder relative_path = self.attribute('ServerRelativeUrl') file = (SPObject(site_url, self._api_client). # create site level object to access GetFileBy... method _method_get('GetFileByServerRelativeUrl', ServerRelativeUrl=relative_path + '/' + filename)) try: offset = 0 while True: data = f.read(chunk_size) if first_chunk: file._method_post('startupload', uploadId=guid, data=data).send() first_chunk = False elif offset >= file_size - chunk_size: file._method_post('finishupload', uploadId=guid, fileOffset=offset, data=data).send() break else: file._method_post('continueupload', uploadId=guid, fileOffset=offset, data=data).send() offset += len(data) except: f.close() logger.debug('Upload Failed') file._method_post('cancelupload', guid).send() class SPFile(SPObject): def __repr__(self): return self._repr_text(self.attribute('ServerRelativeUrl')) def download(self, destination='.'): """ Download single file from SharePoint. :param destination: String with path where file will be saved. :return: None """ # Download file # api_client is directly used instead of attribute because $value returns raw data rather than json logger.debug("Starting download: {}".format(self.attribute('Name'))) r = self._api_client.get(self._endpoint_url + '/$value') logger.debug("Download complete") destination = destination.strip('/') destination = os.path.abspath(destination) if not os.path.isdir(destination): os.makedirs(destination) destination = os.path.join(destination, self.attribute('Name')) logger.debug("Writing file to disk") with open(destination, 'wb') as f: for chunk in r.iter_content(chunk_size=128): f.write(chunk) print("Successfully downloaded file as {0}".format(destination))<file_sep>/sharepoint/sharepoint/auth.py # -*- coding: utf-8 -*- import re import requests from requests.exceptions import MissingSchema from urllib.parse import urlsplit from bs4 import BeautifulSoup import pdb # Suppress SSL verify warnings try: from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) except ModuleNotFoundError: pass def manual_auth(getpass): """ manual_auth is a factory function that chooses the correct Auth class based on the supplied sharepoint_url. """ return ManualSPAuth(getpass) class ManualSPAuth(object): """ Manual authentication using user name and password. Credentials are securely received using the getpass package and transmitted by an https post. Jupyter uses it's own version of getpass. Since this special getpass function can't be accessed from the package level, it is instead passed into this function from Jupyter. """ sharepoint_url = "https://fqdn.of.your.sharepoint" auth_failed_url = "https://fqdn.of.your.sharepoint/htdocs/public/auth_failed.html" def __init__(self, getpass): self.getpass = getpass self.logged_in = False self.session = requests.session() self.session.headers.update({'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko)' ' Chrome/61.0.3163.100 Safari/537.36'}) self.session.verify = False # Turn off SSL verification if using non-standard root CA def login(self): r = self._get_login_page() r = self._enter_credentials(r) # post credentials with login form # Follow redirect r = self._submit_form(r) # Avoid MS 'keep me signed in' form r = self.session.get(self.sharepoint_url) # Follow redirect r = self._submit_form(r) print("Login successful") self.logged_in = True return self.session def _enter_credentials(self, r): # Enter credentials try: user = input('Enter username: ') except EOFError: raise Exception("Not inside interactive session. Can't get user input.") pw = self.getpass('Enter password: ') r = self._submit_form(r, {'USER': user, 'PASSWORD': pw}) if r.url == self.auth_failed_url: raise Exception('Authentication Failed') return r def _get_login_page(self): # Request sharepoint_url. Server will redirect to auth page r = self.session.get(self.sharepoint_url) # Follow javascript redirect regex = re.compile('https://[^"]*') redirect = regex.findall(r.text)[1] r = self.session.get(redirect) return r def _submit_form(self, r, data=None): """ Used for authentication. Get hidden form values and submit form. User values to form can be supplied with data argument. _session: requests session object r: response object with form data: dict of any user form data """ # Add hidden values to payload post = re.compile('post', re.IGNORECASE) soup = BeautifulSoup(r.text, 'lxml') tags = soup.findAll('input', {'type': 'hidden'}) payload = {tag.attrs['name']: tag.attrs['value'] for tag in tags} # Add user data to payload try: payload.update(data) except TypeError: # No user supplied data pass # Get response sharepoint_url url = soup.findAll('form', method=post)[0].attrs['action'] try: r = self.session.post(url, data=payload) except MissingSchema: # If schema is missing, use domain from response sharepoint_url url_parts = urlsplit(r.url) url = '{url.scheme}://{url.netloc}{path}'.format(url=url_parts, path=url) r = self.session.post(url, data=payload) return r
dfee51487e7535cb5fc11d2b2b8b628a96f5d9cf
[ "Python" ]
4
Python
ddl-aambekar/sharepoint
41efc18953e7bf6741ff89b2caad83c216fd59f2
f0a7dce6a9a5bd98f41553066552e615390c2f46
refs/heads/master
<repo_name>rkmr039/core-java<file_sep>/DB/inventry.sql create database inventry; use inventory; create table stock ( stockid varchar(30) primary key, ItemName varchar(30), Price numeric(9,2), QuantityAvail INT ); Create table Orders ( OrderId INT, StockID varchar(30), QtyOrd INT, billAmt numeric(9,2) ); Create Table Amount ( Gamt numeric(9,2) ); insert into amount values(0); commit; insert into Stock values('S001','Phone',25000,30); insert into Stock values('S002','Phone',25000,30); insert into Stock values('S003','Phone',25000,30); insert into Stock values('S004','Phone',25000,30); insert into Stock values('S005','Phone',25000,30); <file_sep>/Day2/BoxingDemo/src/com/hcl/boxing/BoxDemo.java package com.hcl.boxing; public class BoxDemo{ public static void main(String[] args) { int a=12; double b = 12.5; String name = "Hcl"; // Boxing Code Object ob1 = a; Object ob2 = b; Object ob3 = name; // Unboxing Code int a1 = (Integer)ob1; double b1 = (Double)ob2; String str = (String)ob3; a1++; System.out.println("Integer Value "+a1); System.out.println("Double value "+b1); System.out.println("Name "+str); } } <file_sep>/Day5/PracticeDay5/src/com/hcl/scanner/SumDemo.java package com.hcl.scanner; import java.util.Scanner; public class SumDemo { /** * main() . * @param args . */ public static void main(String[] args) { System.out.print("Enter Two Number : "); Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); System.out.println("Sum : " + (a + b)); } } <file_sep>/Day6/.metadata/version.ini #Wed Aug 07 11:23:06 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/Day6/PracticeDay6/src/com/hcl/generics/SortStudent.java package com.hcl.generics; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Comparator; import java.util.Set; import java.util.TreeSet; public class SortStudent { /** * main(). * @param args . */ public static void main(String[] args) { Comparator<Student> c = new CgpComparator(); c = new CityComparator(); Set lstStudent = new TreeSet<Student>(c); lstStudent.add(new Student(1, "Rishab", "Delhi", 6.3)); lstStudent.add(new Student(2, "Amit", "Noida", 7.3)); lstStudent.add(new Student(3, "Amar", "Kanpur", 8.3)); lstStudent.add(new Student(4, "Anand", "Patna", 9.3)); lstStudent.add(new Student(5, "Tushar", "Mumbai", 5.3)); System.out.println("Student List : "); lstStudent.forEach(System.out::println); } } <file_sep>/Day11/HtmlDemo/src/P11.html <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <font size="12"> <p> This is a text with font size 12 </p> </font> <font size="30" color="blue"> <p> This is a text with font size 30 </p> </font> <font size="25" color="cyan" face="Arial,Garamond,Tahoma"> <p> This is a text with font size 25 </p> </font> </body> </html><file_sep>/Day25/.metadata/version.ini #Wed Sep 04 08:39:48 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/Day6/PracticeDay6/src/com/hcl/lambdaexpressions/ListReduceDemo.java package com.hcl.lambdaexpressions; import java.util.ArrayList; import java.util.List; public class ListReduceDemo { /** * main(). * @param args . */ public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(new Integer(1)); list.add(new Integer(2)); list.add(new Integer(3)); list.add(new Integer(4)); list.add(new Integer(5)); int sum = list.stream().reduce(0,(n1,n2) -> n1 + n2); System.out.println(sum); } } <file_sep>/Day21/CalDemo/src/main/java/com/hcl/caldemo/MainProg.java package com.hcl.caldemo; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainProg { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("Calc.xml"); Calc c = (Calc)ctx.getBean("b1"); System.out.println("Sum : " + c.sum()); System.out.println("Sub : " + c.sub()); System.out.println("Mult : " + c.mult()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); System.out.println(sdf.format(new Date())); System.out.println(new Date()); // System.out.println(Calendar.getInstance(aLocale)); // System.out.println( sdf.parse(new java.util.Date())); String startDate="27-08-2019"; SimpleDateFormat sdf1 = new SimpleDateFormat("dd-mm-yyyy"); java.util.Date date; try { date = sdf1.parse(startDate); java.sql.Date sqlStartDate = new java.sql.Date(date.getTime()); System.out.println(sqlStartDate); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>/Day11/HtmlDemo/src/Online.js /** * */ var i = 0; var ans = 0; questions = [ ['1. What is Object Oriented Programming?',['A1','A2','A3','A4'],1], ['2. Who Introduce Java', ['B1','B2','B3','B4'],3], ['3. How to declare Generics?', ['C1','C2','C3','C4'],2], ['4. String.format() is used for... ? ', ['D1','D2','D3','D4'],4] ]; function show() { document.getElementById("question").innerHTML = questions[i][0]; // options document.getElementById("opt1").innerHTML = questions[i][1][0]; document.getElementById("opt2").innerHTML = questions[i][1][1]; document.getElementById("opt3").innerHTML = questions[i][1][2]; document.getElementById("opt4").innerHTML = questions[i][1][3]; // answers document.getElementById("a1").value = 1; document.getElementById("a2").value = 2; document.getElementById("a3").value = 3; document.getElementById("a4").value = 4; } function chkAnswer() { var answer = questions[i][2]; var radio = frmOnline.elements["exam"]; if(radio[0].checked && answer == document.getElementById("a1").value) { ans++; } else if(radio[1].checked && answer == document.getElementById("a2").value) { ans++; } else if(radio[2].checked && answer == document.getElementById("a3").value) { ans++; } else if(radio[3].checked && answer == document.getElementById("a4").value) { ans++; } else { alert("Select any one option..."); } } function nextQuestion() { chkAnswer(); i = i + 1; if (i < 4) { show(); } else { alert("Exam Over...."); } if(i == 4) { document.getElementById("res").innerHTML = "Correct Answers : " + ans; } }<file_sep>/DB/sqlpractice_employ.sql -- MySQL dump 10.13 Distrib 8.0.16, for Win64 (x86_64) -- -- Host: localhost Database: sqlpractice -- ------------------------------------------------------ -- Server version 5.5.62 /*!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 */; SET NAMES utf8 ; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `employ` -- DROP TABLE IF EXISTS `employ`; /*!40101 SET @saved_cs_client = @@character_set_client */; SET character_set_client = utf8mb4 ; CREATE TABLE `employ` ( `Empno` int(11) NOT NULL DEFAULT '0', `Name` varchar(50) DEFAULT NULL, `Dept` varchar(30) DEFAULT NULL, `Desig` varchar(30) DEFAULT NULL, `Basic` int(11) DEFAULT NULL, PRIMARY KEY (`Empno`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `employ` -- LOCK TABLES `employ` WRITE; /*!40000 ALTER TABLE `employ` DISABLE KEYS */; INSERT INTO `employ` VALUES (1,'<NAME>','java','developer',42233),(2,'<NAME>','dotnet','programmer',42133),(3,'<NAME>','java','developer',82233),(4,'Kareem','dotnet','programmer',52234),(5,'<NAME>','dotnet','developer',42555); /*!40000 ALTER TABLE `employ` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2019-08-12 9:15:34 <file_sep>/Day11/HtmlDemo/src/Js6.js function show() { var radio = frmRadio.elements["gender"]; for (var i = 0;i< radio.length; i++) { if(radio[i].checked) { gen = radio[i].value; } } //document.getElementById("res").innerHTML = gen; alert(gen); } <file_sep>/Day7/.metadata/.plugins/org.eclipse.core.resources/.history/de/80cb33923bb800191f97cd9ab186dbfd added = Student Record Added Successfully delete = Student Record Deleted notfound = Student Record Not Found update = Student Record updated Successfully entername = Enter Student name entersno = Enter Student Serial No. entercgp = Enter CGP entercity = Enter City Name enterchoice = Enter your choice\n opt = Options dashes = ------- opt1 = 1. Add Student opt2 = 2. Show Student opt3 = 3. Search Student opt4 = 4. Update Student opt5 = 5. Delete Student opt6 = 6. Exit opt7 = Invalid Choice <file_sep>/Day8/StudentCrud/src/com/hcl/jdbcstudent/StudentInsert.java package com.hcl.jdbcstudent; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Scanner; public class StudentInsert { /** * main method . * @param args . */ public static void main(String[] args) { Connection con = new DaoConnection().getConnection(); Scanner sc = new Scanner(System.in); System.out.println("Enter Student Number"); int sno = Integer.parseInt(sc.nextLine()); System.out.println("Enter Student Name"); String name = sc.nextLine(); System.out.println("Enter Subject 1 Marks"); int sub1 = Integer.parseInt(sc.nextLine()); System.out.println("Enter Subject 2 Marks"); int sub2 = Integer.parseInt(sc.nextLine()); System.out.println("Enter Subject 3 Marks"); int sub3 = Integer.parseInt(sc.nextLine()); String cmd = "insert into Student(sno, name,sub1,sub2,sub3) values (?,?,?,?,?)"; try { PreparedStatement ps = con.prepareStatement(cmd); ps.setInt(1, sno); ps.setString(2, name); ps.setInt(3, sub1); ps.setInt(4, sub2); ps.setInt(5, sub3); ps.executeUpdate(); System.out.println("Inserted Sucessfully"); } catch (SQLException e) { e.printStackTrace(); } try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } <file_sep>/Day18/.metadata/.plugins/org.eclipse.core.resources/.history/35/204ac908cdc400191f8ed60268abd26c package com.hcl.bankjsp; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class UpdateAccountServlet */ public class UpdateAccount { private int accno; private String city; private String state; public int getAccno() { return accno; } public void setAccno(int accno) { this.accno = accno; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String updateAccount() { return AccountBal.updateAccountBal(accno, city, state); } } <file_sep>/Day1/DemoProject/src/com/hcl/java/EvenShow.java package com.hcl.java; public class EvenShow { public void show(int n) { int i = 0; while (i < n) { i = i + 2; System.out.println("Even " + i); } } public static void main(String[] args) { int n = 20; new EvenShow().show(n); } } <file_sep>/Day19/.metadata/version.ini #Tue Aug 27 19:11:45 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/Day13/.metadata/version.ini #Wed Aug 28 14:00:34 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/Day2/BoxingDemo/src/com/hcl/boxing/BoxEmploy.java package com.hcl.boxing; public class BoxEmploy { public void show(Object obj){ Employ e = (Employ)obj; System.out.println(e); } public static void main(String[] args) { Employ objEmploy = new Employ(); objEmploy.empno = 1; objEmploy.name="RISHAB"; objEmploy.basic=15005; new BoxEmploy().show(objEmploy); } } <file_sep>/DB/Mode2DB.sql create database modeTwoDB; use modeTwoDB; drop table Student; create table Student( id int not null auto_increment, rollNum int , sname varchar(30), age int, gender varchar(10), country varchar(15), DateOfJoin datetime, FinalScore float, primary key(id) ); select * from Student; create table PERSON( id int not null auto_increment, name varchar(30), country varchar(30), primary key(id) ); use modetwodb; CREATE TABLE `libusers` ( `Username` varchar(50) NOT NULL, `Password` varchar(50) NOT NULL, PRIMARY KEY (`Username`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; create table APP_USER ( id BIGINT NOT NULL AUTO_INCREMENT, sso_id VARCHAR(30) NOT NULL, password VARCHAR(100) NOT NULL, first_name VARCHAR(30) NOT NULL, last_name VARCHAR(30) NOT NULL, email VARCHAR(30) NOT NULL, PRIMARY KEY (id), UNIQUE (sso_id) ); create table USER_PROFILE( id BIGINT NOT NULL AUTO_INCREMENT, type VARCHAR(30) NOT NULL, PRIMARY KEY (id), UNIQUE (type) ); CREATE TABLE APP_USER_USER_PROFILE ( user_id BIGINT NOT NULL, user_profile_id BIGINT NOT NULL, PRIMARY KEY (user_id, user_profile_id), CONSTRAINT FK_APP_USER FOREIGN KEY (user_id) REFERENCES APP_USER (id), CONSTRAINT FK_USER_PROFILE FOREIGN KEY (user_profile_id) REFERENCES USER_PROFILE (id) ); INSERT INTO USER_PROFILE(type) VALUES ('USER'); INSERT INTO USER_PROFILE(type) VALUES ('ADMIN'); INSERT INTO USER_PROFILE(type) VALUES ('DBA'); INSERT INTO APP_USER(sso_id, password, first_name, last_name, email) VALUES ('samir','samir', 'Samir','Smith','<EMAIL>'); /* Populate JOIN Table */ INSERT INTO APP_USER_USER_PROFILE (user_id, user_profile_id) SELECT user.id, profile.id FROM app_user user, user_profile profile where user.sso_id='sam' and profile.type='ADMIN'; INSERT INTO APP_USER_USER_PROFILE (user_id, user_profile_id) SELECT user.id, profile.id FROM app_user user, user_profile profile where user.sso_id='samir' and profile.type='ADMIN'; /* Create persistent_logins Table used to store rememberme related stuff*/ CREATE TABLE persistent_logins ( username VARCHAR(64) NOT NULL, series VARCHAR(64) NOT NULL, token VARCHAR(64) NOT NULL, last_used TIMESTAMP NOT NULL, PRIMARY KEY (series) ); SELECT * FROM modetwodb.person; SELECT * FROM modetwodb.app_user; update app_user_user_profile set user_profile_id = 2 where user_id = 4; SELECT * FROM modetwodb.app_user_user_profile; SELECT * FROM modetwodb.user_profile; <file_sep>/HMS/BitwiseOperators/src/com/hcl/streams/MultipleFilters.java package com.hcl.streams; import java.util.Arrays; import java.util.function.IntConsumer; public class MultipleFilters { public static void main(String[] args) { int[] nums = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; IntConsumer icons = i -> System.out.println( i + " "); Arrays.stream(nums).filter(e -> e < 6 || e > 10) .filter(e -> e % 2 == 0 ).forEach(icons); } } <file_sep>/Day23/.metadata/version.ini #Thu Aug 29 08:25:30 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/Day1/DemoProject/src/com/hcl/java/ArrayDemo1.java package com.hcl.java; public class ArrayDemo1 { /** * main() . * @param args . */ public static void main(String[] args) { int[] a = new int[] { 12, 5, 77, 23, 76 }; System.out.println("Elements of Array are"); for (int j: a) { System.out.println(j); } } } <file_sep>/Day8/.metadata/version.ini #Thu Aug 08 09:11:31 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/Day2/BoxingDemo/src/com/hcl/boxing/Cricket.java package com.hcl.boxing; public class Cricket { static int score; public void incr(int x){ score+=x; } public static void main(String[] args) { Cricket b1 = new Cricket(); Cricket b2 = new Cricket(); Cricket b3 = new Cricket(); b1.incr(20); b2.incr(30); b3.incr(50); System.out.println(Cricket.score); } } <file_sep>/Day1/DemoProject/src/com/hcl/java/LoopDemo.java package com.hcl.java; public class LoopDemo { public void show(int n) { int i = 0; while (i < n) { System.out.println("Welcome"); i++; } } public static void main(String[] args) { int n = 5; new LoopDemo().show(n); } }<file_sep>/Day19/LibraryProjectJsp/src/com/hcl/library/LibraryDao.java package com.hcl.library; import java.sql.Connection; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.sql.PreparedStatement; public class LibraryDao { Connection con = null; ResultSet rs = null; String cmd = ""; PreparedStatement pst = null; public boolean loginDao(String userName, String passWord) { String cmd = "select username from libusers where username =? and password=?;"; con = DaoConnection.getConnection(); boolean result = false; try { pst = con.prepareStatement(cmd); pst.setString(1, userName); pst.setString(2, passWord); rs = pst.executeQuery(); if(rs.next()) { result = true; } } catch (Exception e) { } return result; } public List<Book> searchBooksDao(String criteria, String value) { String cmd = "SELECT * FROM books "; List<Book> books = new ArrayList<Book>(); Connection con = DaoConnection.getConnection(); try { pst = con.prepareStatement(cmd); if(!(criteria.equals("TotalBooks"))) { cmd += "where " + criteria + " = ? "; pst = con.prepareStatement(cmd); if(criteria.equals("Id")) { pst.setInt(1, Integer.parseInt(value)); } else { pst.setString(1, value); } } rs = pst.executeQuery(); while (rs.next()) { Book book = new Book(); book.setId(rs.getInt("Id")); book.setName(rs.getString("Name")); book.setAuthor(rs.getString("Author")); book.setDept(rs.getString("Dept")); book.setEdition(rs.getString("Edition")); book.setNos(rs.getInt("TotalBooks")); books.add(book); } return books; } catch (SQLException e) { } return null; } public boolean issueBookDao(String name,int Id){ boolean isIssued = false; con = DaoConnection.getConnection(); try { cmd = "SELECT Count(*) FROM tranbook WHERE Username = ?;"; pst = con.prepareStatement(cmd); pst.setString(1, name); rs = pst.executeQuery(); rs.next(); // don't issue more then three books if(rs.getInt("Count(*)") <= 3) { cmd = "SELECT COUNT(*) FROM tranbook WHERE Username = ? AND BookId = ?"; pst = con.prepareStatement(cmd); pst.setString(1, name); pst.setInt(2, Id); rs = pst.executeQuery(); if(rs.next() && rs.getInt("Count(*)") == 0) { cmd = "insert into tranbook(Username,BookId) values(?,?)"; pst = con.prepareStatement(cmd); pst.setString(1, name); pst.setInt(2, Id); pst.executeUpdate(); isIssued = true; cmd = "update books set TotalBooks = TotalBooks-1 where Id = ?"; pst = con.prepareStatement(cmd); pst.setInt(1, Id); pst.executeUpdate(); } } }catch (SQLException e1) { } return isIssued; } public String[][] showIssuedBooksDao(String username) { String[][] result; con = DaoConnection.getConnection(); try { cmd = "SELECT Count(*) FROM tranbook WHERE Username = ?;"; pst = con.prepareStatement(cmd); pst.setString(1, username); rs = pst.executeQuery(); rs.next(); result = new String[rs.getInt("Count(*)")][2]; cmd = "SELECT * FROM tranbook WHERE Username = ?;"; pst = con.prepareStatement(cmd); pst.setString(1, username); rs = pst.executeQuery(); int i=0; while(rs.next()) { result[i][0] = String.format("%d", rs.getInt("BookId")); result[i][1] = rs.getDate("Fromdate").toString(); i++; } return result; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public String returnBookDao(String username,int id) { String result = ""; con = DaoConnection.getConnection(); cmd = " select Fromdate from tranbook where Bookid = ? and username = ?;"; try { pst = con.prepareStatement(cmd); pst.setInt(1,id); pst.setString(2, username); rs = pst.executeQuery(); rs.next(); Date fromdate = rs.getDate("Fromdate"); cmd = " delete from tranbook where Bookid = ? and username = ?;"; pst = con.prepareStatement(cmd); pst.setInt(1,id); pst.setString(2, username); pst.executeUpdate(); cmd = "insert into transreturn values(?,?,?,default);"; pst = con.prepareStatement(cmd); pst.setInt(2,id); pst.setString(1, username); pst.setDate(3, fromdate); pst.executeUpdate(); cmd = "update books set TotalBooks = TotalBooks + 1 where Id = ?;"; pst = con.prepareStatement(cmd); pst.setInt(1, id); pst.executeUpdate(); result = "<br/>**********Returned Successfully**********"; } catch (SQLException e) { } return result; } public String showHistoryDao(String username) { String history = ""; con = DaoConnection.getConnection(); cmd = "select * from transreturn where Username = ?;"; try { pst = con.prepareStatement(cmd); pst.setString(1, username); rs = pst.executeQuery(); while(rs.next()) { history += "<br/>" +rs.getInt("BookId"); history += "&nbsp;&nbsp;&nbsp;&nbsp; " + rs.getDate("Fromdate").toString(); history += "&nbsp;&nbsp;&nbsp;&nbsp; " + rs.getDate("Todate").toString() ; } } catch (SQLException e) { } return history; } } <file_sep>/EMS/EMS/src/com/hcl/ems/EmsDao.java package com.hcl.ems; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; public class EmsDao { Connection con = null; ResultSet rs = null; PreparedStatement pst = null; String cmd=""; public boolean loginDao(int ID, String passWord) { String cmd = "select EMP_ID from EmployLogin where EMP_ID =? and SecretCode=?;"; con = DaoConnection.getConnection(); boolean result = false; try { pst = con.prepareStatement(cmd); pst.setInt(1, ID); pst.setString(2, passWord); rs = pst.executeQuery(); if(rs.next()) { result = true; } } catch (Exception e) { } return result; } public Employ getAccountInfoDao(Integer ID) { cmd = "select * from EMPLOYEE where EMP_ID = ?"; con = DaoConnection.getConnection(); Employ e = null; try { pst = con.prepareStatement(cmd); pst.setInt(1, ID); rs = pst.executeQuery(); if(rs.next()){ e = new Employ(); e.setEmpId(ID); e.setEmpName(rs.getString("EMP_NAME")); e.setEmpMail(rs.getString("EMP_EMAIL")); e.setEmpMobNo(rs.getBigDecimal("EMP_MOB_NO")); e.setEmpDateJoined(rs.getDate("EMP_DATE_JOINED")); e.setEmpDpeName(rs.getString("EMP_DPT_NAME")); e.setEmpLeaveBalance(rs.getInt("EMP_LEAVE_BALANCE")); e.setEmpMgrId(rs.getInt("EMP_MGR_ID")); } } catch (SQLException ex) { ex.printStackTrace(); } return e; } public String applyLeaveDao(Leaves leave) { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); String stDate=sdf.format(leave.getStartDate()); String endDate=sdf.format(leave.getEndDate()); LeaveTypes lt=LeaveTypes.EL; java.util.Date dt=new java.util.Date(); String leavAppliedOn=sdf.format(dt); Employ l=EmsBal.getAccountInfoBal(leave.getEmpId()); LeaveStatus ls; if(l.getEmpMgrId() == 0) { ls=LeaveStatus.APPROVED; } else { ls=LeaveStatus.PENDING; } String result=""; if(l.getEmpLeaveBalance() > 0 && !(leave.getNoDays() > l.getEmpLeaveBalance())) { String cmd="Insert into Leave_History(LEA_START_DATE,LEA_END_DATE,LEA_NO_OF_DAYS,LEA_REASON," + "LEA_TYPE,LEA_APPLIED_ON,EMP_ID,LEA_STATUS) VALUES(?,?,?,?,?,?,?,?)"; Connection con=DaoConnection.getConnection(); try { PreparedStatement pst=con.prepareStatement(cmd); pst.setString(1, stDate); pst.setString(2, endDate); pst.setInt(3, leave.getNoDays()); pst.setString(4, leave.getReason()); pst.setString(5, lt.toString()); pst.setString(6, leavAppliedOn); pst.setInt(7, leave.getEmpId()); pst.setString(8, ls.toString()); pst.executeUpdate(); result="Leave Applied Successfully..."; cmd = "update employee set EMP_LEAVE_BALANCE = EMP_LEAVE_BALANCE - 1 where EMP_ID =?"; pst = con.prepareStatement(cmd); pst.setInt(1,leave.getEmpId()); pst.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); result=e.getMessage(); } } else { result = "Insufficient Leave Balance"; } return result; } public Leaves getMyLeavesDao(int empId) { cmd = "select * from leave_history where EMP_ID =?;"; con = DaoConnection.getConnection(); Leaves l = new Leaves(); try { pst = con.prepareStatement(cmd); pst.setInt(1, empId); rs = pst.executeQuery(); if(rs.next()) { l.setEmpId(rs.getInt("EMP_ID")); l.setStartDate(rs.getDate("LEA_START_DATE")); l.setEndDate(rs.getDate("LEA_END_DATE")); l.setNoDays(rs.getInt("LEA_NO_OF_DAYS")); l.setLeaId(rs.getInt("LEA_ID")); l.setType(rs.getString("LEA_TYPE")); l.setStatus(rs.getString("LEA_STATUS")); l.setReason(rs.getString("LEA_REASON")); l.setAppliedOn(rs.getDate("LEA_APPLIED_ON")); l.setMgrComment(rs.getString("LEA_MGR_COMMENTS")); } else { l = null; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return l; } public List<Leaves> getEmployLeavesDao(int mgrId) { con = DaoConnection.getConnection(); List<Leaves> leaves = new ArrayList<Leaves>(); int empId = 0; try { cmd = "select EMP_ID from employee where EMP_MGR_ID = ?"; pst = con.prepareStatement(cmd); pst.setInt(1, mgrId); rs = pst.executeQuery(); while(rs.next()){ empId = rs.getInt("EMP_ID"); // Leaves leave = EmsBal.getMyLeavesBal(empId); List<Leaves> empLeaves = EmsBal.getMyLeavesBal2(empId); for (Leaves leave : empLeaves) { if(leave != null){ leaves.add(leave); } } } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return leaves; } public Leaves getLeaveByIdDao(int leaveId) { cmd = "select * from leave_history where LEA_ID = ?"; con = DaoConnection.getConnection(); Leaves leave = null; try { pst = con.prepareStatement(cmd); pst.setInt(1, leaveId); rs = pst.executeQuery(); while(rs.next()) { leave = new Leaves(); leave.setLeaId(rs.getInt("LEA_ID")); leave.setAppliedOn(rs.getDate("LEA_APPLIED_ON")); leave.setEndDate(rs.getDate("LEA_END_DATE")); leave.setStartDate(rs.getDate("LEA_START_DATE")); leave.setNoDays(rs.getInt("LEA_NO_OF_DAYS")); leave.setReason(rs.getString("LEA_REASON")); leave.setType(rs.getString("LEA_TYPE")); leave.setMgrComment(rs.getString("LEA_MGR_COMMENTS")); leave.setEmpId(rs.getInt("EMP_ID")); leave.setStatus(rs.getString("LEA_STATUS")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return leave; } public boolean approveDenyLeaveDao(int leaveId, String comments, String action) { boolean result = false; cmd = "update leave_history set LEA_STATUS = ?, LEA_MGR_COMMENTS=? where LEA_ID =?"; con = DaoConnection.getConnection(); try{ pst = con.prepareStatement(cmd); if(action.equals("Approve")){ pst.setString(1, LeaveStatus.APPROVED.toString()); } else { pst.setString(1, LeaveStatus.DENIED.toString()); } pst.setString(2, comments); pst.setInt(3, leaveId); pst.executeUpdate(); result = true; if(action.equals("DENIED")){ Leaves l = EmsBal.getLeaveByIdBal(leaveId); int empId = l.getEmpId(); int leaveBalance = l.getNoDays(); cmd = "update employee set EMP_LEAVE_BALANCE = EMP_LEAVE_BALANCE + ? where EMP_ID =? "; pst = con.prepareStatement(cmd); pst.setInt(1, leaveBalance); pst.setInt(2, empId); pst.executeUpdate(); cmd = "update leave_history set LEA_MGR_COMMENTS=? where LEA_ID =?"; pst = con.prepareStatement(cmd); pst.setString(1, comments); pst.setInt(2, leaveId); pst.executeUpdate(); } } catch(SQLException e) { } return result; } public List<Leaves> getMyLeaves(int empId){ List<Leaves> leaves = new ArrayList<Leaves>(); cmd = "select * from leave_history where EMP_ID =?;"; con = DaoConnection.getConnection(); try { pst = con.prepareStatement(cmd); pst.setInt(1, empId); rs = pst.executeQuery(); while(rs.next()) { Leaves l = new Leaves(); l.setEmpId(rs.getInt("EMP_ID")); l.setStartDate(rs.getDate("LEA_START_DATE")); l.setEndDate(rs.getDate("LEA_END_DATE")); l.setNoDays(rs.getInt("LEA_NO_OF_DAYS")); l.setLeaId(rs.getInt("LEA_ID")); l.setType(rs.getString("LEA_TYPE")); l.setStatus(rs.getString("LEA_STATUS")); l.setReason(rs.getString("LEA_REASON")); l.setAppliedOn(rs.getDate("LEA_APPLIED_ON")); leaves.add(l); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return leaves; } } <file_sep>/Day6/PracticeDay6/src/com/hcl/lambdaexpressions/LambdaDemo2.java package com.hcl.lambdaexpressions; public class LambdaDemo2 { /** * main() . * * @param args * . */ public static void main(String[] args) { IHello h1 = () -> { System.out.println("Say Hello from Rishab"); }; IHello h2 = () -> { System.out.println("Say Hello from Anand"); }; IHello h3 = () -> { System.out.println("Say Hello from Amit"); }; IHello h4 = () -> { System.out.println("Say Hello from Yahs"); }; IHello[] arr = new IHello[] {h1,h2,h3,h4}; for (IHello ihello : arr) { ihello.sayHello(); } } } <file_sep>/Day1/DemoProject/src/com/hcl/obj/Employ.java package com.hcl.obj; public class Employ { int empno; String name; double basic; public Employ[] showEmploy(){ Employ[] arrEmploy = new Employ[3]; arrEmploy[0] = new Employ(); arrEmploy[0].empno = 1; arrEmploy[0].name="PriyaDarshani"; arrEmploy[0].basic=52345; arrEmploy[1] = new Employ(); arrEmploy[1].empno = 2; arrEmploy[1].name="RISHABKUMAR"; arrEmploy[1].basic=52000; arrEmploy[2] = new Employ(); arrEmploy[2].empno = 3; arrEmploy[2].name="AnubhavAnand"; arrEmploy[2].basic=62345; return arrEmploy; } public static void main(String[] args) { Employ[] result = new Employ().showEmploy(); for(Employ e: result){ System.out.println("Employe Numbere "+e.empno +"\r\n" + "Employe Name "+ e.name +"\r\n" + "Basic Salery " +e.basic+"\r\n" ); } } } <file_sep>/DB/sqlpractice.sql SELECT * FROM sqlpractice.department; use sqlpractice; show tables; desc emp; -- Display all records of Employ table select * from employ; -- Display empno, name, basic from employ table select Empno,Name,Basic from employ; -- Display all records whose basic salary > 50000 select * from employ where Basic > 50000; -- Display all records who belong to 'java' dept select * from employ where dept = 'java'; -- display all records whose basic from 40000 to 60000 select * from employ where Basic >= 40000 and basic <= 60000 ; select * from employ where Basic between 40000 and 60000; -- Display all records whose name start with 'k' select * from employ where name like 'k%'; -- Display all records who belong to java or dotnet dept select * from employ where dept = 'java' or dept = 'dotnet'; -- Display all records who does not belong to java or dotnet dept -- select * from employ where dept not like 'java' and dept not like 'dotnet'; select * from employ where dept not in ('java' and 'dotnet'); -- Display all records on ascending order by dept select * from employ order by dept; -- Display all records on ascending order by dept and name select * from employ order by dept asc,name asc; -- Display all records on ascending order by dept and name wise descending select * from employ order by dept asc,name desc; -- SQL JOINS select Empno,name,basic from employ where basic between 40000 and 60000 UNION select Empno,name,basic from employ where basic between 50000 and 85000; select Empno,name,basic from employ where basic between 40000 and 60000 UNION ALL select Empno,name,basic from employ where basic between 50000 and 85000 ; desc dept; desc emp; select deptno from dept; select distinct deptno from emp; select dept.deptno,dname, empno,ename,sal from dept inner join emp where dept.deptno = emp.deptno; select D.deptno,dname, empno,ename,sal from dept D inner join emp E where D.deptno = E.deptno; select D.deptno, dname, empno,ename,sal from dept D left join emp E on D.deptno = E.deptno; <file_sep>/Day23/HelloWorld/src/main/java/com/hcl/hello/HelloWorldController.java package com.hcl.hello; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class HelloWorldController { @RequestMapping("/hello") public ModelAndView helloWorld(){ return new ModelAndView("result","message","Welcome To Spring MVC Programming"); } @RequestMapping("/rishab") public ModelAndView helloRishab() { return new ModelAndView("rishab","message","Welcome <NAME>"); } } <file_sep>/Day3/PracticeDay3/src/com/hcl/interfacepckg/InterfaceDemo.java package com.hcl.interfacePckg; interface ITraining{ void name(); void email(); } class Rishab implements ITraining{ @Override public void name() { System.out.println("Rishab"); } @Override public void email() { System.out.println("<EMAIL>"); } } class Anand implements ITraining{ @Override public void name() { System.out.println("Anand"); } @Override public void email() { System.out.println("<EMAIL>"); } } public class InterfaceDemo { public static void main(String[] args) { ITraining[] arr = new ITraining[]{ new Rishab(), new Anand() }; for (ITraining iTraining : arr) { iTraining.name(); iTraining.email(); } } } <file_sep>/Day9/BankProject/src/com/hcl/bank/CloseAccountMain.java package com.hcl.bank; import java.util.Scanner; public class CloseAccountMain { /** * before closing account check that account is activated or not. * @param args . */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter Account No "); int accno = sc.nextInt(); System.out.println(AccountBal.closeAccountBal(accno)); sc.close(); } } <file_sep>/Day2/BoxingDemo/src/com/hcl/boxing/EmployTest.java package com.hcl.boxing; public class EmployTest { public static void main(String[] args) { Employ e1 = new Employ(); e1.empno = 1; e1.name = "Yash"; e1.basic=27752; Employ e2 = new Employ(); e2.empno = 2; e2.name = "Anand"; e2.basic=63547; System.out.println(e1 == e2); // check for same hashcode System.out.println(e1.equals(e2)); // override for Custom object as required } } <file_sep>/Day6/PracticeDay6/src/com/hcl/lambdaexpressions/ICtoF.java package com.hcl.lambdaexpressions; @FunctionalInterface public interface ICtoF { double calc(double c); } <file_sep>/Day13/LibraryManagementProject/src/com/hcl/library/ReturnBookServlet.java package com.hcl.library; import java.io.IOException; import java.io.OutputStream; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class ReturnBookServlet */ public class ReturnBookServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ReturnBookServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher rd=request.getRequestDispatcher("MenuServlet"); rd.include(request, response); HttpSession session = request.getSession(); String name = (String) session.getAttribute("name"); OutputStream out = response.getOutputStream(); String[][] result = LibraryBal.showIssuedBooksBal(name); ((ServletOutputStream) out).println("<br/><br/>"); ((ServletOutputStream) out).println("<form method='post' action='ShowReturnedBooksServlet'>"); ((ServletOutputStream) out).println("<table border='1'>"); ((ServletOutputStream) out).println("<tr>"); ((ServletOutputStream) out).println("<th>ID</th>"); ((ServletOutputStream) out).println("<th>From Date</th>"); ((ServletOutputStream) out).println("<th>Return</th>"); ((ServletOutputStream) out).println("</tr>"); for (String[] res : result) { ((ServletOutputStream) out).println("<tr>"); ((ServletOutputStream) out).println("<td>" + res[0] + "</td>"); ((ServletOutputStream) out).println("<td>" + res[1] + "</td>"); ((ServletOutputStream) out).println("<td><input type='checkbox' name='returnBox' value='"+ res[0] +"' /></td>"); ((ServletOutputStream) out).println("</tr>"); } ((ServletOutputStream) out).println("</table>"); ((ServletOutputStream) out).println("<br/><br/><input type='submit' value='Return' />"); ((ServletOutputStream) out).println("</form>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } <file_sep>/Day2/BoxingDemo/src/com/hcl/boxing/SwithcDemo.java package com.hcl.boxing; public class SwithcDemo { public void show(int x) { switch (x) { case 1: System.out.println("Hello 1"); break; case 2: System.out.println("Hello 2"); break; case 3: System.out.println("Hello 3"); case 4: System.out.println("Hello 4"); case 5: System.out.println("Hello 5"); default: System.out.println("Hello Default"); break; } } public static void main(String[] args) { SwithcDemo obj = new SwithcDemo(); obj.show(3); } } <file_sep>/Day2/BoxingDemo/src/com/hcl/access_specifier/BaseClass.java package com.hcl.access_specifier; public class BaseClass { private int a; protected int b; public int c; int d; public static void main(String[] args) { BaseClass obj = new BaseClass(); System.out.println(obj.a); System.out.println(obj.b); System.out.println(obj.c); System.out.println(obj.d); } } <file_sep>/DB/HMS.sql create database hotel; use hotel; select * from room; drop table room; Create Table Room ( RoomID varchar(10) primary key, Type varchar(10), Status varchar(10) default 'Available', CostPerDay INT ); -- Type must be Single or Double Create Table Booking ( BookId varchar(10) primary key, RoomID varchar(10), CustName varchar(30), City varchar(30), BookDate TIMESTAMP, ChkDate TimeStamp ); select * from booking; -- truncate table booking Create Table Billing ( billId int primary key, BookID varchar(10), RoomID varchar(10), NoOfDays INT, BillAmt INT ); select * from room; select max(RoomId) from Room; update Room set Type='Double',CostPerDay=950, Status = 'Available' where RoomId = 'R001'; select * from booking; delete from Booking where BookId = 'B001'; drop table billing; select * from billing; alter table billing add column billId int primary key; <file_sep>/DB/EMP_EMS.sql create database EMS_DB; use EMS_DB; CREATE TABLE EMPLOYEE( EMP_ID INT PRIMARY KEY, EMP_NAME VARCHAR(20) NOT NULL, EMP_EMAIL VARCHAR(30) NOT NULL, EMP_MOB_NO BIGINT NOT NULL, EMP_DPT_NAME VARCHAR(20), EMP_DATE_JOINED DATE NOT NULL, EMP_MGR_ID INT , FOREIGN KEY (EMP_MGR_ID) REFERENCES EMPLOYEE(EMP_ID), EMP_LEAVE_BALANCE INT ); CREATE TABLE LEAVE_HISTORY( LEA_ID INT PRIMARY KEY NOT NULL AUTO_INCREMENT, LEA_START_DATE DATE NOT NULL, LEA_END_DATE DATE NOT NULL, LEA_NO_OF_DAYS INT, LEA_REASON VARCHAR(100), LEA_TYPE ENUM ('EL'), LEA_APPLIED_ON DATE, LEA_MGR_COMMENTS VARCHAR(100), EMP_ID INT(11), FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE(EMP_ID), LEA_STATUS ENUM('APPROVED','DENIED','PENDING') ); INSERT INTO EMPLOYEE (EMP_ID,EMP_NAME, EMP_EMAIL,EMP_MOB_NO,EMP_DPT_NAME,EMP_DATE_JOINED, EMP_MGR_ID, EMP_LEAVE_BALANCE) VALUES (1000,'<NAME>', '<EMAIL>', 8878339946,'CEO','2017-11-14', NULL,4), (2000,'<NAME>', '<EMAIL>',8883315009,'BI ', '2017-11-14',1000, 0), (3000,'<NAME>', '<EMAIL>',7064672738, 'HRM','2017-11-14',1000, 15), (4000,'ANKITA', '<EMAIL>', 8825792015,'BI','2017-11-14',2000, 5), (5000,'<NAME>', '<EMAIL>',9090505919,'HRM','2017-11-14',3000, 7); select * from Employee; update employee set EMP_LEAVE_BALANCE = 4 where EMP_ID = 2000; drop table EMP_LOGIN; create table EmployLogin( EMP_ID INT NOT NULL UNIQUE PRIMARY KEY, SecretCode varchar(50) NOT NULL, FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE(EMP_ID) ); insert into EmployLogin values (1000,'Rishab'), (2000,'Laxmi'), (3000,'Raghu'), (4000,'Bindu'), (5000,'SaiKiran'); alter table leave_history AUTO_INCREMENT =1; select * from leave_history; delete from leave_history where LEA_ID = 10; SELECT * FROM ems_db.employlogin; update leave_history set LEA_STATUS = 'PENDING',LEA_MGR_COMMENTS = '' where LEA_ID = 3; update employee set EMP_LEAVE_BALANCE = EMP_LEAVE_BALANCE - 1 where EMP_ID = 3000; select EMP_ID from employee where EMP_MGR_ID = 2000; select * from leave_history where EMP_ID = 2000; select * from employee;<file_sep>/Day23/SpringEmployShow/src/main/java/com/hcl/employ/EmployController.java package com.hcl.employ; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class EmployController { @RequestMapping("/employShow") public ModelAndView showEmp(HttpServletRequest req, HttpServletResponse res){ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dataSource = (DriverManagerDataSource)ctx.getBean("dataSource"); JdbcTemplate jt = new JdbcTemplate(dataSource); String sql = "select * from employ"; List emps = null; emps = jt.query(sql, new RowMapper(){ public Object mapRow(ResultSet rs, int arg1) throws SQLException { String empInfo = rs.getInt("empno")+"======"+ rs.getString("name")+"======="+ rs.getString("dept")+"======="+ rs.getString("desig")+"======="+ rs.getString("basic"); return empInfo; } }); return (new ModelAndView("ShowPage","emps",emps)); } @RequestMapping("/searchEmploy") public ModelAndView searchEmploy(HttpServletRequest req, HttpServletResponse res ) { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dataSource = (DriverManagerDataSource)ctx.getBean("dataSource"); JdbcTemplate jt = new JdbcTemplate(dataSource); String sql = "select * from employ where empno = ?"; int empno = Integer.parseInt(req.getParameter("empno")); List emp = jt.query(sql,new Object[] { empno },new RowMapper(){ public Object mapRow(ResultSet rs, int arg1) throws SQLException { String empInfo = rs.getInt("empno")+"======"+ rs.getString("name")+"======="+ rs.getString("dept")+"======="+ rs.getString("desig")+"======="+ rs.getString("basic"); return empInfo; } }); return (new ModelAndView("ShowPage","emp",emp)); } @RequestMapping("/insertEmploy") public ModelAndView employInsert(HttpServletRequest req, HttpServletResponse res) { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dataSource = (DriverManagerDataSource)ctx.getBean("dataSource"); JdbcTemplate jt = new JdbcTemplate(dataSource); String sql = "insert into employ values(?,?,?,?,?)"; int empno = Integer.parseInt(req.getParameter("empno")); String name = req.getParameter("name"); String dept = req.getParameter("dept"); String desig = req.getParameter("desig"); int basic = Integer.parseInt(req.getParameter("basic")); jt.update(sql, new Object[]{empno,name,dept,desig,basic}); return (new ModelAndView("ShowPage","message","Result Inserted")); } } <file_sep>/Day11/.metadata/version.ini #Mon Aug 19 17:33:06 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/DB/inventry_amount.sql -- MySQL dump 10.13 Distrib 8.0.16, for Win64 (x86_64) -- -- Host: localhost Database: inventry -- ------------------------------------------------------ -- Server version 5.5.62 /*!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 */; SET NAMES utf8 ; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `amount` -- DROP TABLE IF EXISTS `amount`; /*!40101 SET @saved_cs_client = @@character_set_client */; SET character_set_client = utf8mb4 ; CREATE TABLE `amount` ( `Gamt` decimal(9,2) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `amount` -- LOCK TABLES `amount` WRITE; /*!40000 ALTER TABLE `amount` DISABLE KEYS */; INSERT INTO `amount` VALUES (1450840.00); /*!40000 ALTER TABLE `amount` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2019-08-12 9:15:31 <file_sep>/Day13/LibraryManagementProject/src/com/hcl/library/ShowIssuedBooksServlet.java package com.hcl.library; import java.io.IOException; import java.io.OutputStream; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class ShowIssuedBooksServlet */ public class ShowIssuedBooksServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ShowIssuedBooksServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher rd=request.getRequestDispatcher("MenuServlet"); rd.include(request, response); HttpSession session = request.getSession(); String name = (String) session.getAttribute("name"); String[] checked = request.getParameterValues("issueBox"); String res=""; OutputStream out = response.getOutputStream(); try{ if(checked.length == 0) {} } catch(NullPointerException e) { rd = request.getRequestDispatcher("IssueBooks.html"); rd.forward(request, response); } for (String id : checked) { int Id = Integer.parseInt(id); boolean i = LibraryBal.issueBookBal(name,Id); if(i) { res +="<br/><h5>Book ID(" + Id + ") issued.</h5><br/>"; } else { res +="<br/><h5>Book ID(" + Id + ") already issued.</h5><br/>"; } } ((ServletOutputStream) out).println(res); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } <file_sep>/DB/CMS.sql create database college; use college; create table CourseList ( courseno varchar(15) primary key, duration int, startDate date, endDate date, HOD varchar(30) ); drop table if exists subjects; create table subjects ( subId INT primary key auto_increment, year int, instructor varchar(28), subject varchar(150), theory int, practical int ); Create Table Feedback ( fid varchar(15) primary key, studentName varchar(30), instructor varchar(30), subject varchar(30), fbvalue varchar(30) ); select * from feedback; SELECT * FROM college.feedback; select * from subjects; SELECT instructor from Subjects; SELECT * FROM college.courselist; SELECT subject from Subjects where instructor = 'Prasanna'; update subjects set instructor = 'Juhi ' where subId = 4; select subject,instructor from Subjects where instructor in (SELECT distinct instructor from Subjects); select fbvalue,count(*) from Feedback where instructor = 'Prasanna' and subject = 'SQL Server' group by fbvalue;<file_sep>/Day1/DemoProject/src/com/hcl/java/CalcDemo.java package com.hcl.java; public class CalcDemo { /** * calc method. * @param a number 1. * @param b number 2. */ public void calc(int a, int b) { int c = a + b; System.out.println("Sum is:" + c); } /** * main() . * @param args . */ public static void main(String[] args) { int a; int b; a = Integer.parseInt(args[0]); b = Integer.parseInt(args[1]); CalcDemo obj = new CalcDemo(); obj.calc(a, b); } }<file_sep>/Day2/BoxingDemo/src/com/hcl/boxing/StDemo.java package com.hcl.boxing; public class StDemo { public void show(){ StDemo.diplay(); System.out.println("INSTANCE METHOD"); } static void diplay(){ System.out.println("STATIC METHOD"); } public static void main(String[] args) { // display(); StDemo.diplay(); new StDemo().show(); } } <file_sep>/DB/sqlpractice_department.sql -- MySQL dump 10.13 Distrib 8.0.16, for Win64 (x86_64) -- -- Host: localhost Database: sqlpractice -- ------------------------------------------------------ -- Server version 5.5.62 /*!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 */; SET NAMES utf8 ; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `department` -- DROP TABLE IF EXISTS `department`; /*!40101 SET @saved_cs_client = @@character_set_client */; SET character_set_client = utf8mb4 ; CREATE TABLE `department` ( `deptno` int(11) NOT NULL, `dname` varchar(30) DEFAULT NULL, `loc` varchar(30) DEFAULT NULL, `head` varchar(30) DEFAULT NULL, PRIMARY KEY (`deptno`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `department` -- LOCK TABLES `department` WRITE; /*!40000 ALTER TABLE `department` DISABLE KEYS */; INSERT INTO `department` VALUES (1,'java','Delhi','matt'),(2,'dotnet','detroit','princ'),(3,'SAP','piscaptsway','scott'),(4,'HRM','Delaware','Adam'),(5,'SQL','Hoolywood','Steve'); /*!40000 ALTER TABLE `department` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2019-08-12 9:15:39 <file_sep>/Day24/.metadata/version.ini #Tue Sep 03 09:33:01 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/Day2/BoxingDemo/src/com/hcl/boxing/ConDemo.java package com.hcl.boxing; public class ConDemo { static int a; // get memory in heap area static { // runs before main System.out.println("STATIC Constructor...."); a = 5; show(a); } // default constructor is invoked by Object class /*public ConDemo() { // removed System.out.println("Default Constructor..."); }*/ public static void show(int a){ System.out.println("Hello Before Main..."+a); } public ConDemo() { showC(5); // TODO Auto-generated constructor stub } public void showC(int a){ System.out.println("Hello Before Main..."+a); } public static void main(String[] args) { new ConDemo();// this will run default constructor } } <file_sep>/Day5/PracticeDay5/src/com/hcl/files/WriteStudent.java package com.hcl.files; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class WriteStudent { /** * main() . * @param args . */ public static void main(String[] args) { try { FileOutputStream fout = new FileOutputStream("C:/files/student.txt"); ObjectOutputStream objout = new ObjectOutputStream(fout); Student obj = new Student(1, "RISHAB", "DELHI", 8.6); objout.writeObject(obj); objout.close(); fout.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/Day2/.metadata/version.ini #Tue Jul 30 14:43:50 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/CMS/.metadata/version.ini #Tue Sep 10 11:05:23 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/Day2/BoxingDemo/src/com/hcl/boxing/StudentSearch.java <<<<<<< HEAD package com.hcl.boxing; public class StudentSearch { public Student searchStudent(int sno){ Student obj = null; if(sno == 1){ obj = new Student(); obj.sno = 10017826; obj.name = "RISHAB"; obj.city = "Delhi"; obj.cgp = 7.5; } if(sno==2){ obj = new Student(); obj.sno = 1003455; obj.name = "YASH"; obj.city = "BANGALORE"; obj.cgp = 7.5; } return obj; } public static void main(String[] args) { StudentSearch obj = new StudentSearch(); Student student = obj.searchStudent(1); if(student != null){ System.out.println(student); }else{ System.out.println("Student Not Found..."); } } } ======= package com.hcl.boxing; public class StudentSearch { public Student searchStudent(int sno){ Student obj = null; if(sno == 1){ obj = new Student(); obj.sno = 10017826; obj.name = "RISHAB"; obj.city = "Delhi"; obj.cgp = 7.5; } if(sno==2){ obj = new Student(); obj.sno = 1003455; obj.name = "YASH"; obj.city = "BANGALORE"; obj.cgp = 7.5; } return obj; } public static void main(String[] args) { StudentSearch obj = new StudentSearch(); Student student = obj.searchStudent(1); if(student != null){ System.out.println(student); }else{ System.out.println("Student Not Found..."); } } } >>>>>>> branch 'master' of https://github.com/rkmr039/Java_Practice.git <file_sep>/README.md Mode 1 Training Projects <file_sep>/EMS/.metadata/version.ini #Thu Sep 05 12:36:10 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/DB/BankProject.sql create database bank; use bank; Create Table Accounts ( AccountNo INT primary key, FirstName varchar(30), LastName varchar(30), City varchar(30), State varchar(30), Amount INT, CheqFacil varchar(10), AccountType varchar(20), Status varchar(10) default 'active', DateOfOpen TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); Create Table Trans ( AccountNo int, TransAmount numeric(9,2), TransDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP, TransType varchar(10) ); select case when max(accountNo) IS NULL THEN 1 else max(accountNo)+1 END accno FROM Accounts; update accounts set Status ='active' where AccountNo = 1; select * from accounts;<file_sep>/Day13/BankProjectServlet/src/com/hcl/bank/CreateAccountServlet.java package com.hcl.bank; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class CreateAccountServlet */ public class CreateAccountServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CreateAccountServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher rd=request.getRequestDispatcher("MenuServlet"); rd.include(request, response); OutputStream out = response.getOutputStream(); Accounts objAccount = new Accounts(); int accno = new AccountDao().generateAccountNoDao(); objAccount.setAccountNo(accno); objAccount.setFirstName(request.getParameter("firstName")); objAccount.setLastName(request.getParameter("lastName")); objAccount.setCity(request.getParameter("city")); objAccount.setState(request.getParameter("state")); int amount = Integer.parseInt(request.getParameter("amount")); objAccount.setAmount(amount); objAccount.setCheqFacil(request.getParameter("cheqFacil")); objAccount.setAccountType(request.getParameter("accountType")); String result = AccountBal.createAcccountBal(objAccount); //System.out.println(result); ((ServletOutputStream) out).println("<br/>"+result); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } <file_sep>/Day13/LibraryManagementProject/src/com/hcl/library/MyAccountServlet.java package com.hcl.library; import java.io.IOException; import java.io.OutputStream; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class MyAccountServlet */ public class MyAccountServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MyAccountServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher rd=request.getRequestDispatcher("MenuServlet"); rd.include(request, response); HttpSession session = request.getSession(); String name = (String) session.getAttribute("name"); OutputStream out = response.getOutputStream(); String[][] result = LibraryBal.showIssuedBooksBal(name); for (String[] res : result) { ((ServletOutputStream) out).println("<br/><br/>===========================================<br/>" + " Book Id : " + res[0] + " Issued On " + res[1] + " <br/>"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } <file_sep>/Day6/PracticeDay6/src/com/hcl/generics/GenEmploy.java package com.hcl.generics; import java.util.ArrayList; import java.util.List; public class GenEmploy { /** * main() . * @param args . */ public static void main(String[] args) { List<Employ> lstEmploy = new ArrayList<Employ>(); lstEmploy.add(new Employ(1, "Rishab", 21343)); lstEmploy.add(new Employ(2, "Yash", 21343)); lstEmploy.add(new Employ(3, "Anand", 92674)); lstEmploy.add(new Employ(4, "Amit", 62454)); lstEmploy.add(new Employ(5, "Tushar", 343434)); System.out.println("Employ list : "); lstEmploy.forEach(System.out::println); } } <file_sep>/Day5/PracticeDay5/hclresources/hcltraining.properties welcome = Good Morning To All lunch = Lunch Time at 1 PM break = Two breaks for tea logout = 6:30 PM based on work extended <file_sep>/Day8/DepartmentCrud/src/com/hcl/jdbdepartment/DeleteDepartment.java package com.hcl.jdbdepartment; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Scanner; public class DeleteDepartment { /** * main. * @param args . */ public static void main(String[] args) { int deptno; Scanner sc = new Scanner(System.in); System.out.println("Enter Department No "); deptno = sc.nextInt(); Connection con = new DaoConnection().getConnection(); String cmd = "delete from department where deptno = ?"; try { PreparedStatement ps = con.prepareStatement(cmd); ps.setInt(1,deptno); ps.executeUpdate(); System.out.println("Deleted Successfully"); } catch (SQLException e) { e.printStackTrace(); } } } <file_sep>/Day13/BankProjectServlet/src/com/hcl/bank/AccountBal.java package com.hcl.bank; public class AccountBal { public static int generateAccountNoBal() { return new AccountDao().generateAccountNoDao(); } public static String createAcccountBal(Accounts objAccounts) { return new AccountDao().createACoount(objAccounts); } public static Accounts searchAccountBal(int accno) { return new AccountDao().searchAccountDao(accno); } public static String updateAccountBal(int accno, String city, String state) { return new AccountDao().updateAccountDao(accno, city, state); } public static String closeAccountBal(int accno) { return new AccountDao().closeAccountDao(accno); } public static String depositeAccountBal(int accno, int depositeAmount) { return new AccountDao().depositeAccountDao(accno, depositeAmount); } public static String withdrawnAccountBal(int accno, int amount) { return new AccountDao().withdrawAccountDao(accno, amount); } }<file_sep>/Day22/DeptShow/src/main/java/com/hcl/dept/MainProg.java package com.hcl.dept; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainProg { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("jdbc.xml"); DataQueryDao d = (DataQueryDao)ctx.getBean("myDao"); d.showDept(); /*System.out.println(new Date()); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); System.out.println(sdf.format(new Date()));*/ Date d1 = new Date(); System.out.println(d1.getDate()); /*SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); String sDate = sdf.format(d1); System.out.println(sDate);*/ } } <file_sep>/Day2/BoxingDemo/src/com/hcl/boxing/NullKeyword.java <<<<<<< HEAD package com.hcl.boxing; // comparing null keyword public class NullKeyword { public void check(){ if(null==null){ System.out.println("Welcome..."); }else{ System.out.println("Bye...."); } } public static void main(String[] args) { new NullKeyword().check(); } } ======= package com.hcl.boxing; // comparing null keyword public class NullKeyword { public void check(){ if(null==null){ System.out.println("Welcome..."); }else{ System.out.println("Bye...."); } } public static void main(String[] args) { new NullKeyword().check(); } } >>>>>>> branch 'master' of https://github.com/rkmr039/Java_Practice.git <file_sep>/Day13/LibraryManagementProject/src/com/hcl/library/IssueBooksServlet.java package com.hcl.library; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class SearchBooksServlet */ public class IssueBooksServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public IssueBooksServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher rd=request.getRequestDispatcher("MenuServlet"); rd.include(request, response); OutputStream out = response.getOutputStream(); // SEARCH LOGIC String searchType = request.getParameter("searchType"); String searchValue = request.getParameter("searchValue"); List<Book> books = LibraryBal.searchBookBal(searchType, searchValue); ((ServletOutputStream) out).println("<br/><br/>"); ((ServletOutputStream) out).println("<form method='post' action='ShowIssuedBooksServlet'>"); ((ServletOutputStream) out).println("<table border='1'>"); ((ServletOutputStream) out).println("<tr>"); ((ServletOutputStream) out).println("<th>ID</th>"); ((ServletOutputStream) out).println("<th>Name</th>"); ((ServletOutputStream) out).println("<th>Author</th>"); ((ServletOutputStream) out).println("<th>Edition</th>"); ((ServletOutputStream) out).println("<th>Dept</th>"); ((ServletOutputStream) out).println("<th>TotalBooks</th>"); ((ServletOutputStream) out).println("<th>Issue</th>"); ((ServletOutputStream) out).println("</tr>"); for (Book book : books) { ((ServletOutputStream) out).println("<tr>"); ((ServletOutputStream) out).println("<td>" + book.getId() + "</td>"); ((ServletOutputStream) out).println("<td>" + book.getName() + "</td>"); ((ServletOutputStream) out).println("<td>" + book.getAuthor() + "</td>"); ((ServletOutputStream) out).println("<td>" + book.getEdition() + "</td>"); ((ServletOutputStream) out).println("<td>" + book.getDept() + "</td>"); ((ServletOutputStream) out).println("<td>" + book.getNos() + "</td>"); if(book.getNos() == 0) { ((ServletOutputStream) out).println("<td><input type='checkbox' disabled name='issueBox' id='issue'></td>"); } else { ((ServletOutputStream) out).println("<td><input type='checkbox' name='issueBox' value='"+ book.getId() + "' /></td>"); } ((ServletOutputStream) out).println("</tr>"); } ((ServletOutputStream) out).println("</table>"); ((ServletOutputStream) out).println("<input type='submit' value='Issue' id='issueButton' />"); ((ServletOutputStream) out).println("</form>"); ((ServletOutputStream) out).println("<br/><br/><span><b><h1>Please Select Atleast One Book To Issue</h1></b></span>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } <file_sep>/Day7/CustomerProject/src/com/hcl/customer/CustomerDao.java package com.hcl.customer; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; public class CustomerDao { static List<Customer> lstCustomer = null; static ResourceBundle rb = ResourceBundle.getBundle("project"); static { lstCustomer = new ArrayList<Customer>(0); } // INSERT public String addCustomerDao(Customer customer) { lstCustomer.add(customer); return rb.getString("added"); } /** * search a Customer from list. * @param sno . * @return Customer if found. */ public Customer searchCustomerDao(int sno) { Customer obj = null; for (Customer customer : lstCustomer) { if (customer.getCustId() == sno) { obj = customer; } } return obj; } // SELECT * public List<Customer> showCustomerDao() { return lstCustomer; } /** * UPDATE operation for Customer class. * @param obj Customer to be deleted * @return resultant string. */ public String updateCustomerDao(Customer obj) { Customer customer = searchCustomerDao(obj.getCustId()); if (customer != null) { for (Customer s : lstCustomer) { if (s.getCustId() == obj.getCustId()) { s.setCustName(obj.getCustName()); s.setAnnualIncom(obj.getAnnualIncom()); s.setModalPremium(obj.getModalPremium()); s.setPaymentMode(obj.getPaymentMode()); } } return rb.getString("update"); } else { return rb.getString("notfound"); } } /** * this method is used for storing customer list into file. */ public static void storeCustomer() { try { FileOutputStream fos = new FileOutputStream("C:/files/customers.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(lstCustomer); oos.close(); fos.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * this method is used for display customer list from file. */ public List<Customer> displayCustomer() { try { FileInputStream fin = new FileInputStream("C:/files/customers.txt"); ObjectInputStream objin = new ObjectInputStream(fin); lstCustomer = (List<Customer>) objin.readObject(); return lstCustomer; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } /** * delete Customer method . * @param sno . * @return success or not found . */ public String deleteCustomerDao(int sno) { Customer customer = searchCustomerDao(sno); if (customer != null) { lstCustomer.remove(sno); return rb.getString("delete"); } else { return rb.getString("notfound"); } } } <file_sep>/EMS/EMS/src/com/hcl/ems/LeaveTypes.java package com.hcl.ems; public enum LeaveTypes { EL,RH,CH } <file_sep>/DB/StudentDB.sql create database modeTwoDB; use modeTwoDB; CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `rollNum` int(11) DEFAULT NULL, `sname` varchar(30) DEFAULT NULL, `age` int(11) DEFAULT NULL, `gender` varchar(10) DEFAULT NULL, `country` varchar(15) DEFAULT NULL, `DateOfJoin` datetime DEFAULT NULL, `finalScore` double DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; CREATE TABLE `exam` ( `eid` int(11) NOT NULL AUTO_INCREMENT, `subject` varchar(30) NOT NULL, `mark` double DEFAULT NULL, `sid` int(11) DEFAULT NULL, PRIMARY KEY (`eid`), KEY `sid` (`sid`), CONSTRAINT `exam_ibfk_1` FOREIGN KEY (`sid`) REFERENCES `student` (`id`) ON DELETE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1; select * from Student; select * from exam; alter table student modify column finalScore double; delete from exam; delete from student; ALTER TABLE student AUTO_INCREMENT = 1; ALTER TABLE exam AUTO_INCREMENT = 1; delete from Student where name = 'Vishali'; select avg(mark) from exam where sid = 8;<file_sep>/Day8/EmployCrud/resources/db.properties mysqldriver=com.mysql.jdbc.Driver mysqlurl=jdbc:mysql://localhost:3306/sqlpractice user=root password=<PASSWORD><file_sep>/Day6/PracticeDay6/src/com/hcl/lambdaexpressions/Product.java package com.hcl.lambdaexpressions; /** * Product Class. * @author <NAME> */ public class Product { int id; String name; double price; /** * toString(). */ @Override public String toString() { return "Product [id=" + id + ", name=" + name + ", price=" + price + "]"; } /** * Constructor. * @param id . * @param name . * @param price . */ public Product(int id, String name, double price) { this.id = id; this.name = name; this.price = price; } } <file_sep>/Day6/PracticeDay6/src/com/hcl/lambdaexpressions/IHello.java package com.hcl.lambdaexpressions; //FunctionalInterface can have only one method @FunctionalInterface public interface IHello { void sayHello(); }<file_sep>/Day18/.metadata/.plugins/org.eclipse.core.resources/.history/f6/102239d5a5c400191909d2b5c1a339cd package com.hcl.bank; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class AccountDao { PreparedStatement pst; Connection con; /** * createAccount will create a account in DB account table. * @param objAccounts . * @return successful or error message. */ public String createACoount(Accounts objAccounts) { con = DaoConnection.getConnection(); String cmd = "INSERT INTO accounts(AccountNo,FirstName,LastName,City," + "State,Amount,CheqFacil,AccountType) VALUES(?,?,?,?,?,?,?,?);"; String result = ""; try { pst = con.prepareStatement(cmd); pst.setInt(1, objAccounts.getAccountNo()); pst.setString(2, objAccounts.getFirstName()); pst.setString(3, objAccounts.getLastName()); pst.setString(4, objAccounts.getCity()); pst.setString(5, objAccounts.getState()); pst.setInt(6, objAccounts.getAmount()); pst.setString(7, objAccounts.getCheqFacil()); pst.setString(8, objAccounts.getAccountType()); pst.executeUpdate(); result = "Account Created Successfully"; // System.out.println(result); } catch (SQLException e) { e.printStackTrace(); } return result; } /** * generate a new account number every time and return same. * @return account number generated. */ public int generateAccountNoDao() { con = DaoConnection.getConnection(); int accno = 0; String cmd = "SELECT CASE WHEN MAX(accountNo) IS NULL " + " THEN 1 ELSE MAX(accountNo) + 1 END accno " + " FROM Accounts "; try { pst = con.prepareStatement(cmd); ResultSet rs = pst.executeQuery(); rs.next(); accno = rs.getInt("accno"); } catch (SQLException e) { e.printStackTrace(); } return accno; } /** * search for an account from DB accounts table. * @param accno from searching accounts. * @return Account object. */ public Accounts searchAccountDao(int accno) { con = DaoConnection.getConnection(); String cmd = "SELECT * FROM Accounts WHERE accountNo = ?;"; Accounts objAccount = null; try { pst = con.prepareStatement(cmd); pst.setInt(1, accno); ResultSet rs = pst.executeQuery(); if (rs.next()) { objAccount = new Accounts(); objAccount.setAccountNo(rs.getInt("accountNo")); objAccount.setFirstName(rs.getString("firstName")); objAccount.setLastName(rs.getString("lastName")); objAccount.setCity(rs.getString("city")); objAccount.setState(rs.getString("state")); objAccount.setAmount(rs.getInt("amount")); objAccount.setCheqFacil(rs.getString("CheqFacil")); objAccount.setAccountType(rs.getString("AccountType")); objAccount.setStatus(rs.getString("Status")); } } catch (SQLException e) { e.printStackTrace(); } return objAccount; } /** * update account details. * first check account number exist in table or not. * @param accno of client to be updated. * @param city Updated City info. * @param state Updated State info. * @return update status. */ public String updateAccountDao(int accno, String city, String state) { con = DaoConnection.getConnection(); String result = ""; Accounts obj = AccountBal.searchAccountBal(accno); if (obj != null) { String status = obj.getStatus(); if (!(status.equals("Inactive"))) { String cmd = "UPDATE Accounts set city = ?, state = ? WHERE AccountNo = ?;"; try { pst = con.prepareStatement(cmd); pst.setString(1, city); pst.setString(2, state); pst.setInt(3, accno); pst.executeUpdate(); result = "Account Updated"; } catch (SQLException e) { e.printStackTrace(); } } else { result = "Account is Inactive"; } } else { result = "Account Num. Not Found"; } return result; } /** * this method will change the status of account to inactive. * @param accno of account to be closed. * @return success message. */ public String closeAccountDao(int accno) { con = DaoConnection.getConnection(); Accounts objAccounts = searchAccountDao(accno); String result = null; if (objAccounts != null) { String cmd = "UPDATE Accounts set Status='Inactive' WHERE accountNo=?;"; try { pst = con.prepareStatement(cmd); pst.setInt(1, accno); pst.executeUpdate(); result = "Status Closed"; } catch (SQLException e) { e.printStackTrace(); } } else { result = "Account Num. Not Found"; } return result; } /** * this method will deposit depositedAmount in account and update the trans table. * before updating amount check account is activated or not. * @param accno of account to be deposited. * @param depositeAmount . * @return deposit message. */ public String depositeAccountDao(int accno,int depositeAmount) { con = DaoConnection.getConnection(); Accounts accounts = AccountBal.searchAccountBal(accno); String result = ""; if (accounts != null) { String status = accounts.getStatus(); if (status.equals("Inactive")) { result = "Account is Inactive"; } else { String cmd = "UPDATE Accounts SET amount=amount+? " + "WHERE accountNo=?;"; try { pst = con.prepareStatement(cmd); pst.setInt(1, depositeAmount); pst.setInt(2, accno); pst.executeUpdate(); cmd = "INSERT INTO trans(AccountNo, TransAmount," + "TransType) values(?,?,?);"; pst = con.prepareStatement(cmd); pst.setInt(1, accno); pst.setInt(2, depositeAmount); pst.setString(3, "C"); pst.executeUpdate(); result = "Amount Credited"; } catch (SQLException e) { e.printStackTrace(); } } } else { result = "Account Num. Not Found"; } return result; } public String withdrawAccountDao(int accno, int withdrawnAmount) { con = DaoConnection.getConnection(); String result = ""; Accounts objAccounts = searchAccountDao(accno); if (objAccounts != null) { String status = objAccounts.getStatus(); if (status.equals("Inactive")) { result = "Account is Inactive"; } else { int amount = objAccounts.getAmount(); if (amount - withdrawnAmount >= 1000) { String cmd = "UPDATE Accounts SET amount=amount-? " + "WHERE accountNo=?;"; try { pst = con.prepareStatement(cmd); pst.setInt(1, withdrawnAmount); pst.setInt(2, accno); pst.executeUpdate(); cmd = "INSERT INTO trans(AccountNo, TransAmount," + "TransType) values(?,?,?);"; pst = con.prepareStatement(cmd); pst.setInt(1, accno); pst.setInt(2, withdrawnAmount); pst.setString(3, "D"); pst.executeUpdate(); result = "Amount Debited"; } catch (SQLException e) { e.printStackTrace(); } } else { result = "Insufficient Balance"; }} } else { result = "Account Num. Not Found"; } return result; } } <file_sep>/Day5/PracticeDay5/src/com/hcl/collections/Emp.java package com.hcl.collections; public class Emp implements Comparable { int empno; String name; transient double basic; /** * constructor(). * @param empno . * @param name . * @param basic . */ public Emp(int empno, String name, double basic) { this.empno = empno; this.name = name; this.basic = basic; // to hide the data (minor security) } /** * toString() . */ @Override public String toString() { return "Employ [empno=" + empno + ", name=" + name + ", basic=" + basic + "]"; } @Override public int compareTo(Object o) { Emp e = (Emp)o; return name.compareTo(e.name); // this pointer comes into picture automatically } } <file_sep>/Day10/junitdemo/src/com/hcl/junitpractice/Data.java package com.hcl.junitpractice; import java.util.HashMap; import java.util.Map; public class Data { public int dev(int a, int b) { int c = 1; try { c= a / b; } catch (ArithmeticException e) { e.printStackTrace(); } return c; } public String getProperty(String key) { Map<String,String> m = new HashMap<String,String>(); m.put("Meena", "Java"); m.put("Bharhgav", "Reddy"); m.put("Harish", "K"); m.put("Sai", "Bharat"); return m.get(key); } public static boolean even(int x) { if (x % 2 == 0) { return true; } else { return false; } } public int minArray(int[] x) { int min = x[0]; for (int i = 0; i< x.length; i++) { if (min > x[i]) { min = x[i]; } } return min; } public String sayHello() { return "Welcome to JUnit"; } public int sum(int a, int b) { return a + b; } public int max3(int a, int b, int c) { int m = a; if (m < b) { m = b; } if ( m < c) { m = c; } return m; } }<file_sep>/Day25/DeptInsertAnnotation/src/main/java/com/hcl/emp/InsertDept.java package com.hcl.emp; import java.util.Iterator; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; public class InsertDept { public static void main(String[] args) { Configuration cfg = new AnnotationConfiguration(); cfg.configure("hibernate.cfg.xml"); SessionFactory sf = cfg.buildSessionFactory(); Session s = sf.openSession(); Department d = new Department(); int deptno = 0; Query q = s.createQuery("SELECT max(deptno) from Department"); for(Iterator it = q.iterate();it.hasNext();) { deptno = (Integer)it.next(); } deptno++; System.out.println("Deptno : " + deptno); d.setDeptno(111111); d.setDname("JAVA"); d.setLoc("Kolkata"); d.setHead("Guru"); s.save(d); Transaction t = s.getTransaction(); t.begin(); t.commit(); System.out.println("Inserted"); } } <file_sep>/Day23/SpringDeptShow/src/main/java/com/hcl/dept/DeptController.java package com.hcl.dept; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import org.apache.catalina.connector.Request; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class DeptController { @RequestMapping("/deptShow") public ModelAndView showDept(HttpServletRequest req, HttpServletResponse res){ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dataSource = (DriverManagerDataSource)ctx.getBean("dataSource"); JdbcTemplate jt = new JdbcTemplate(dataSource); String sql = "select * from department"; List depts = null; depts = jt.query(sql, new RowMapper(){ public Object mapRow(ResultSet rs, int arg1) throws SQLException { String deptInfo = rs.getInt("deptno")+"======"+ rs.getString("dname")+"======="+ rs.getString("loc")+"======="+ rs.getString("head"); return deptInfo; } }); return (new ModelAndView("ShowPage","depts",depts)); } @RequestMapping("/searchDept") public ModelAndView searchDept(HttpServletRequest req, HttpServletResponse res){ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dataSource = (DriverManagerDataSource)ctx.getBean("dataSource"); JdbcTemplate jt = new JdbcTemplate(dataSource); int deptno = Integer.parseInt(req.getParameter("deptno")); String sql = "select * from department where deptno = ?"; List dept = null; dept = jt.query(sql,new Object[]{ deptno }, new RowMapper(){ public Object mapRow(ResultSet rs, int arg1) throws SQLException { String deptInfo = rs.getInt("deptno")+"======"+ rs.getString("dname")+"======="+ rs.getString("loc")+"======="+ rs.getString("head"); return deptInfo; } }); return (new ModelAndView("ShowPage","result",dept)); } @RequestMapping("/insertDept") public ModelAndView deptInsert(HttpServletRequest req, HttpServletResponse res) { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dataSource = (DriverManagerDataSource)ctx.getBean("dataSource"); JdbcTemplate jt = new JdbcTemplate(dataSource); String sql = "insert into department values(?,?,?,?)"; int deptno = Integer.parseInt(req.getParameter("deptno")); String dname = req.getParameter("dname"); String loc = req.getParameter("loc"); String head = req.getParameter("head"); jt.update(sql, new Object[]{deptno,dname,loc,head}); return (new ModelAndView("ShowPage","message","Result Inserted")); } } <file_sep>/Day10/.metadata/version.ini #Mon Aug 12 08:51:49 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/Day1/DemoProject/src/com/hcl/obj/NumToWord.java package com.hcl.obj; import java.util.Scanner; public class NumToWord { public StringBuilder convertIntoWords(int num) { StringBuilder word = new StringBuilder(); int divider = 10; int times; int[] arrNum; if (num < 10) { times = 1; } else if (num > 9 && num < 99) { times = 2; } else if (num > 99 && num < 999) { times = 3; } else { times = 4; } arrNum = new int[times]; divider = divider * times; while (times > 0) { int n = 0; arrNum[times] = num % divider; times--; } for(int n: arrNum){ System.out.println(n); } return word; } public static void main(String[] args) { int num; Scanner sc = new Scanner(System.in); System.out.println("Enter Number : "); num = sc.nextInt(); System.out.println(new NumToWord().convertIntoWords(num)); } } <file_sep>/Day18/InventoryProjectJsp/src/com/hcl/inventory/AddStock.java package com.hcl.inventory; public class AddStock { private String itemName; private double price; private int qntyAvail; public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getQntyAvail() { return qntyAvail; } public void setQntyAvail(int qntyAvail) { this.qntyAvail = qntyAvail; } public String addStock() { Stock obj = new Stock(); obj.setStockId(InventryBal.generateStockIdBal()); obj.setItemName(itemName); obj.setPrice(price); obj.setQuantityAvail(qntyAvail); return InventryBal.addStockBal(obj); } } <file_sep>/Day1/DemoProject/src/com/hcl/java/MaxNum.java package com.hcl.java; public class MaxNum { public void getGreatest(int a, int b, int c) { int m = a; if (m < b) { m = b; } if (m < c) { m = c; } System.out.println("Max Value " + m); } public static void main(String[] args) { int a = 8, b = 9, c = 5; new MaxNum().getGreatest(a, b, c); } }<file_sep>/Day5/PracticeDay5/src/com/hcl/collections/ArrayListDemo.java package com.hcl.collections; import java.util.ArrayList; import java.util.List; public class ArrayListDemo { /** * main() . * @param args . */ public static void main(String[] args) { List lstName = new ArrayList(); lstName.add("RISHAB"); lstName.add("YAHS"); lstName.add("Anand"); lstName.add("Amit"); System.out.println("Name are : "); /*for (Object object : lstName) { System.out.println(object); }*/ System.out.println("JDK 1.8"); lstName.forEach(System.out::println); lstName.forEach(System.err::println); /* Edit */ lstName.set(1, "Yash"); lstName.forEach(System.out::println); // Removal System.out.println("list after removing by index..."); lstName.remove(3); lstName.forEach(System.out::println); System.out.println("list after removing by object..."); lstName.remove("Anand"); lstName.forEach(System.out::println); } } <file_sep>/Day2/BoxingDemo/src/com/hcl/a_s_p2/DerivedChild.java package com.hcl.a_s_p2; import com.hcl.access_specifier.BaseClass; public class DerivedChild extends BaseClass { public static void main(String[] args) { DerivedChild obj = new DerivedChild(); //System.out.println(obj.a); System.out.println(obj.b); System.out.println(obj.c); //System.out.println(obj.d); } } <file_sep>/Day2/BoxingDemo/src/com/hcl/boxing/ConTest.java package com.hcl.boxing; // constructors are used to initialize member variables public class ConTest { int a,b; public ConTest() { this.a = 12; this.b = 15; } public ConTest(int a, int b) { this.a = a; this.b = b; } @Override public String toString() { return "ConTest [a=" + a + ", b=" + b + "]"; } public static void main(String[] args) { ConTest obj = new ConTest(); System.out.println(obj); ConTest obj2 = new ConTest(77,44); System.out.println(obj2); } } <file_sep>/Day13/LibraryManagementProject/src/com/hcl/library/MenuServlet.java package com.hcl.library; import java.io.IOException; import java.io.OutputStream; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class MenuServlet */ public class MenuServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MenuServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { OutputStream out = response.getOutputStream(); HttpSession session = request.getSession(); RequestDispatcher dip = null; String name = (String)session.getAttribute("name"); if( name == null || name.isEmpty()) { // working //System.out.println("LoggedOut"); ((ServletOutputStream) out).println("Please Login First"); dip = request.getRequestDispatcher("login.html"); dip.forward(request, response); } else { ((ServletOutputStream) out).println("Welcome : " + name); dip = request.getRequestDispatcher("menu.html"); dip.include(request, response); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } <file_sep>/HMS/BitwiseOperators/src/com/hcl/operators/Demo.java package com.hcl.operators; public class Demo { public static void main(String[] args) { System.out.println(8>>3); } } <file_sep>/Day22/.metadata/version.ini #Wed Aug 28 12:16:18 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/Day7/.metadata/.plugins/org.eclipse.core.resources/.history/81/b0e5c755c6b8001916bcd59fadfe3fc0 package com.hcl.customer; import java.io.Serializable; public class Customer implements Serializable { private int custId; private String custName; private double annualIncom; private double modalPremium; private int paymentMode; public int getCustId() { return custId; } public void setCustId(int custId) { this.custId = custId; } public String getCustName() { return custName; } public void setCustName(String custName) { this.custName = custName; } public double getAnnualIncom() { return annualIncom; } public void setAnnualIncom(double annualIncom) { this.annualIncom = annualIncom; } public double getModalPremium() { return modalPremium; } public void setModalPremium(double modalPremium) { this.modalPremium = modalPremium; } public int getPaymentMode() { return paymentMode; } public void setPaymentMode(int paymentMode) { this.paymentMode = paymentMode; } public Customer() { } /** * Parameterized constructor. * @param custId Unique ID of Customer. * @param custName Name of Customer. * @param annualIncom Annual Income of Customer. * @param modalPremium Modal Premium pay by Customer. * @param paymentMode Payment Mode 1 or 2 or 3. */ public Customer(int custId, String custName, double annualIncom, double modalPremium, int paymentMode) { this.custId = custId; this.custName = custName; this.annualIncom = annualIncom; this.modalPremium = modalPremium; this.paymentMode = paymentMode; } /** * toString() method for Customer object. */ @Override public String toString() { return "Customer [custId=" + custId + ", custName=" + custName + ", annualIncom=" + annualIncom + ", modalPremium=" + modalPremium + ", paymentMode=" + paymentMode + "]"; } }<file_sep>/Day3/.metadata/version.ini #Wed Jul 31 09:46:49 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/Day18/BankProjectjsp/src/com/hcl/bankjsp/WithdrawalAccount.java package com.hcl.bankjsp; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class WithdrawlAccountServlet */ public class WithdrawalAccount{ private int accno; private int amount; public int getAccno() { return accno; } public void setAccno(int accno) { this.accno = accno; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public String withdrawalAccount() { return AccountBal.withdrawalAccountBal(accno, amount); } } <file_sep>/Day7/CustomerProject/src/com/hcl/customer/CustomerMain.java package com.hcl.customer; import java.util.List; import java.util.ResourceBundle; import java.util.Scanner; public class CustomerMain { static ResourceBundle rb = ResourceBundle.getBundle("project"); /** * delete Customer method(). */ public static void deleteCustomer() { int sno; Scanner sc = new Scanner(System.in); System.out.println(rb.getString("entersno")); sno = sc.nextInt(); CustomerBal obj = new CustomerBal(); String res = obj.deleteCustomerBal(sno); System.out.println(res); } /** * update Customer method(). */ public static void updateCustomer() { Customer objCustomer = new Customer(); Scanner sc = new Scanner(System.in); System.out.println(rb.getString("entersno")); objCustomer.setCustId(Integer.parseInt(sc.nextLine())); System.out.println(rb.getString("entername")); objCustomer.setCustName(sc.nextLine()); System.out.println(rb.getString("enterAnnIncome")); objCustomer.setAnnualIncom(Integer.parseInt(sc.nextLine())); System.out.println(rb.getString("enterModelPre")); objCustomer.setModalPremium(Double.parseDouble(sc.nextLine())); System.out.println(rb.getString("enterPayMode")); objCustomer.setPaymentMode(Integer.parseInt(sc.nextLine())); CustomerBal obj = new CustomerBal(); String res = obj.updateCustomerBal(objCustomer); System.out.println(res); } /** * show list of Customers available . */ public static void showCustomer() { CustomerBal obj = new CustomerBal(); List<Customer> lstCustomer = obj.showCustomerBal(); for (Customer customer : lstCustomer) { System.out.println(customer); } } /** * search Customer on the basis of sno. */ public static void searchCustomer() { int sno; System.out.println(rb.getString("entersno")); Scanner sc = new Scanner(System.in); sno = sc.nextInt(); CustomerBal obj = new CustomerBal(); Customer objCustomer = obj.searchCustomerBal(sno); if (objCustomer != null) { System.out.println(objCustomer); } else { System.out.println(rb.getString("notfound")); } } /** * method for inserting Customer into list. */ public static void addCustomer() { Customer objCustomer = new Customer(); Scanner sc = new Scanner(System.in); System.out.println(rb.getString("entersno")); objCustomer.setCustId(Integer.parseInt(sc.nextLine())); // NumberFormateException System.out.println(rb.getString("entername")); objCustomer.setCustName(sc.nextLine()); System.out.println(rb.getString("enterAnnIncome")); objCustomer.setAnnualIncom(Integer.parseInt(sc.nextLine())); System.out.println(rb.getString("enterModelPre")); objCustomer.setModalPremium(Double.parseDouble(sc.nextLine())); System.out.println(rb.getString("enterPayMode")); objCustomer.setPaymentMode(Integer.parseInt(sc.nextLine())); CustomerBal obj = new CustomerBal(); try { boolean res = obj.addCustomerBal(objCustomer); if (res == true) { System.out.println(rb.getString("added")); } } catch (CustomerExceptions e) { System.out.println(e.getMessage()); } } public static void storeCustomer() { new CustomerBal().storeCustomer(); } public static void displayCustomer() { List<Customer> lstCustomer = new CustomerBal().displayCustomer();; for (Customer customer : lstCustomer) { System.out.println(customer); } } /** * main(). * @param args . */ public static void main(String[] args) { int ch; Scanner sc = new Scanner(System.in); do { System.out.println(rb.getString("opt")); System.out.println(rb.getString("dashes")); System.out.println(rb.getString("opt1")); System.out.println(rb.getString("opt2")); System.out.println(rb.getString("opt3")); System.out.println(rb.getString("opt4")); System.out.println(rb.getString("opt5")); System.out.println(rb.getString("opt6")); System.out.println(rb.getString("opt7")); System.out.println(rb.getString("opt8")); System.out.println(rb.getString("enterchoice")); ch = sc.nextInt(); switch (ch) { case 1: addCustomer(); break; case 2: showCustomer(); break; case 3: searchCustomer(); break; case 4: updateCustomer(); break; case 5: deleteCustomer(); break; case 6: storeCustomer(); break; case 7: displayCustomer(); break; case 8: return; default: System.out.println(rb.getString("opt9")); } } while (ch != 8); } }<file_sep>/Day7/.metadata/version.ini #Wed Aug 07 08:53:02 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/Day2/BoxingDemo/src/com/hcl/boxing/Demo2.java package com.hcl.boxing; // value data type have higher priority then reference data type // data type of parameter have higher priority public class Demo2 { public void show(int x){ System.out.println("Int is..."+x); } public void show(double x){ System.out.println("double is..."+x); } public void show(Double x){ System.out.println("Double is..."+x); } public void show(Object x){ System.out.println("Object is..."+x); } public static void main(String[] args) { Demo2 obj = new Demo2(); obj.show(12); // it will print int obj.show(12.5); // it will print double } } <file_sep>/Day6/PracticeDay6/src/com/hcl/generics/Employ.java package com.hcl.generics; import java.io.Serializable; public class Employ { public int empno; public String name; public double basic; /** * constructor(). * @param empno . * @param name . * @param basic . */ public Employ(int empno, String name, double basic) { this.empno = empno; this.name = name; this.basic = basic; } /** * toString() . */ @Override public String toString() { return "Employ [empno=" + empno + ", name=" + name + ", basic=" + basic + "]"; } } <file_sep>/Day8/DepartmentCrud/src/com/hcl/jdbdepartment/DepartmentShow.java package com.hcl.jdbdepartment; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DepartmentShow { /** * main method . * @param args . */ public static void main(String[] args) { Connection con = new DaoConnection().getConnection(); String cmd = "Select * from department"; try { PreparedStatement ps = con.prepareStatement(cmd); ResultSet rs = ps.executeQuery(); while (rs.next()) { System.out.println("Dept No. : " + rs.getInt("deptno")); System.out.println("Dept Name : " + rs.getString("dname")); System.out.println("Dept Location : " + rs.getString("loc")); System.out.println("Dept Head : " + rs.getString("head")); System.out.println("------------------------------------------"); } } catch (SQLException e) { e.printStackTrace(); } } } <file_sep>/Day1/DemoProject/src/com/hcl/java/ArgsDemo.java package com.hcl.java; public class ArgsDemo { /** * main() . * @param args . */ public static void main(String[] args) { System.out.println("First Arg " + args[0]); System.out.println("First Arg " + args[1]); } }<file_sep>/CMS/CMS/src/main/java/com/hcl/cms/CollegeCrud.java package com.hcl.cms; import org.hibernate.Transaction; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; public class CollegeCrud { public boolean addSubject(Subjects subject){ boolean flag = false; SessionFactory sf = HibernateUtil.getConnection(); Session s = sf.openSession(); s.save(subject); Transaction t = s.beginTransaction(); t.commit(); flag = true; return flag; } public boolean addFeedback(Feedback f) { boolean flag = false; SessionFactory sf = HibernateUtil.getConnection(); Session s = sf.openSession(); s.save(f); Transaction t = s.beginTransaction(); t.commit(); flag = true; return flag; } public String getFeedbackId(){ String fid = ""; SessionFactory sf = HibernateUtil.getConnection(); Session s = sf.openSession(); Query q = s.createQuery("SELECT max(fid) from Feedback"); for(Iterator it = q.iterate(); it.hasNext();) { fid = (String) it.next(); if(fid == null) { fid = "C000"; } int temp = Integer.parseInt(fid.substring(1)); temp++; fid = String.format("C%03d", temp); } return fid; } public List<String> getInstructors() { List<String> instructors; SessionFactory sf = HibernateUtil.getConnection(); Session s = sf.openSession(); Query q = s.createQuery("select distinct instructor from Subjects"); instructors = q.list(); return instructors; } public Map<String, List<String>> getInstructorsAndSubjects() { List<String> instructors; SessionFactory sf = HibernateUtil.getConnection(); Session s = sf.openSession(); Query q = s.createQuery("select distinct instructor from Subjects"); instructors = q.list(); Map<String, List<String>> list = new HashMap<String, List<String>>(); for (String ins : instructors) { Query q2 = s.createQuery("select subject from Subjects where instructor = ?" ); q2.setParameter(0, ins); List subList = q2.list(); List<String> subListRes = new ArrayList<String>(); for (Object object : subList) { // System.out.println((String)object); subListRes.add((String)object); } list.put(ins, subListRes); } return list; } public List<String> getSubjectsByInstructor(String ins) { List<String> result; SessionFactory sf = HibernateUtil.getConnection(); Session s = sf.openSession(); Query q = s.createQuery("select subject from Subjects where instructor = ?" ); q.setParameter(0, ins); result = q.list(); /*for(Object obj : result) { System.out.println((String)obj); }*/ return result; } public List<FbCount> getFeedbackCount(String ins, String sub){ SessionFactory sf = HibernateUtil.getConnection(); Session s = sf.openSession(); Query q = s.createQuery("select fbvalue,count(*) from Feedback where instructor = ? and subject = ? group by fbvalue"); q.setParameter(0, ins); q.setParameter(1, sub); List list = q.list(); List<FbCount> res = new ArrayList<FbCount>();; Iterator it = list.iterator(); while(it.hasNext()) { FbCount fb = new FbCount(); Object[] o = (Object[])it.next(); // System.out.println(o[0].toString()); // System.out.println(Integer.parseInt(o[1].toString())); fb.setFbValue(o[0].toString()); fb.setCount(Integer.parseInt(o[1].toString())); res.add(fb); } return res; } } <file_sep>/Day15/.metadata/version.ini #Thu Aug 22 15:06:16 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/Day3/PracticeDay3/src/com/hcl/enums/Enum1.java package com.hcl.enums; enum Day{ SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY } public class Enum1 { public static void main(String[] args) { Day s = Day.SUNDAY; Day m = Day.valueOf("MONDAY"); Day[] t = Day.values(); for( Day z: t ){ System.out.println(z); } System.out.println(s); System.out.println(m); } } <file_sep>/Day10/junitdemo/src/com/hcl/junitpractice/DataTest.java package com.hcl.junitpractice; import static org.junit.Assert.*; import org.junit.Test; public class DataTest { @Test(expected = NullPointerException.class) public void testNullEx() { Data obj = null; assertEquals(5, obj.sum(3, 6)); } @Test public void testDev() { Data obj = new Data(); assertEquals(2,obj.dev(5, 2)); } @Test(expected = ArithmeticException.class) public void testDevEx() { Data obj = new Data(); obj.dev(5, 0); } @Test public void testGetProperty() { Data obj = new Data(); assertNotNull(obj.getProperty("Sai")); assertNull(obj.getProperty("StayaSai")); } @Test public void testEven() { Data obj = new Data(); assertTrue(obj.even(6)); assertFalse(obj.even(7)); } @Test public void testMinArray() { Data obj = new Data(); int[] x = {2,1,3,4,5}; assertEquals(1,obj.minArray(x)); } @Test public void testMax3() { Data obj = new Data(); assertEquals(5, obj.max3(5, 1, 1)); assertEquals(5, obj.max3(1, 5, 3)); assertEquals(5, obj.max3(1, 3, 5)); assertEquals(5, obj.max3(1, 1, 5)); } @Test public void testSum() { Data obj = new Data(); assertEquals(7, obj.sum(2, 5)); assertEquals(4, obj.sum(2, 2)); } @Test public void testSayHello() { Data obj = new Data(); assertEquals("Welcome to JUnit",obj.sayHello()); } } <file_sep>/EMS/EMS/src/com/hcl/ems/TestEms.java package com.hcl.ems; import static org.junit.Assert.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.junit.Test; public class TestEms { /*@Test public void getEmployLeavesTest() { List<Leaves> leaves = EmsBal.getEmployLeavesBal(1000); String result = ""; System.out.println(leaves.size()); for (Leaves leave : leaves) { result += " " + leave.getEmpId(); Employ e = EmsBal.getAccountInfoBal(leave.getEmpId()); System.out.println(e.getEmpName()); result += " " + e.getEmpLeaveBalance(); result += " " + leave.getLeaId(); result += " " + leave.getStartDate(); result += " " + leave.getEndDate(); result += " " + leave.getType(); result += " " + leave.getStatus(); result += " " + leave.getReason(); result += " " + leave.getNoDays(); System.out.println(result); } } */ /*@Test public void getMyLeavesTest(){ List<Leaves> leaves = EmsBal.getMyLeavesBal2(1000); for (Leaves leave : leaves) { String result = ""; result += " " + leave.getEmpId(); Employ e = EmsBal.getAccountInfoBal(leave.getEmpId()); result += " " + e.getEmpLeaveBalance(); result += " " + leave.getLeaId(); result += " " + leave.getStartDate(); result += " " + leave.getEndDate(); result += " " + leave.getType(); result += " " + leave.getStatus(); result += " " + leave.getReason(); result += " " + leave.getNoDays(); System.out.println(result); } }*/ /* @Test // working fine public void getMyLeaveDaoTest() { Leaves l = EmsBal.getMyLeavesBal2(1000).get(1); System.out.println(l.getReason()); }*/ /* @Test // working fine public void getMyLeavesDaoTest() { Leaves l = EmsBal.getMyLeavesBal(2000).get(0); System.out.println(l.getEmpId()); }*/ @Test public void testGetHolidays(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date startDate; try { startDate = sdf.parse("2019-08-12"); Date endDate = sdf.parse("2019-08-16"); Holidays obj = new Holidays(); System.out.println("Holidays : " + obj.getHolidays(startDate, endDate)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>/BankProject/src/com/hcl/bank/UpdateAccountMain.java package com.hcl.bank; import java.util.Scanner; public class UpdateAccountMain { /** * main() . * @param args . */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter Account No. "); int accno = Integer.parseInt(sc.nextLine()); System.out.println("Enter City "); String city = sc.nextLine(); System.out.println("Enter State "); String state = sc.nextLine(); AccountBal.updateAccountBal(accno, city, state); System.out.println("Updated Successfully"); sc.close(); } } <file_sep>/Day21/.metadata/version.ini #Tue Aug 27 13:13:05 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/Day15/ServletDemo/src/com/hcl/loginlogoutdemo/DashboardServlet.java package com.hcl.loginlogoutdemo; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class DashboardServlet */ public class DashboardServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DashboardServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); RequestDispatcher rd = request.getRequestDispatcher("Dashboard.html"); OutputStream out = response.getOutputStream(); try { ((ServletOutputStream) out).println("<p id='name'>Welcome user</p>"); rd.include(request, response); } finally { out.close(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } <file_sep>/DB/sqlpractice_employnew.sql -- MySQL dump 10.13 Distrib 8.0.16, for Win64 (x86_64) -- -- Host: localhost Database: sqlpractice -- ------------------------------------------------------ -- Server version 5.5.62 /*!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 */; SET NAMES utf8 ; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `employnew` -- DROP TABLE IF EXISTS `employnew`; /*!40101 SET @saved_cs_client = @@character_set_client */; SET character_set_client = utf8mb4 ; CREATE TABLE `employnew` ( `empno` int(11) NOT NULL, `name` varchar(30) NOT NULL, `dept` varchar(30) DEFAULT NULL, `desig` varchar(30) DEFAULT NULL, `basic` decimal(9,2) DEFAULT NULL, PRIMARY KEY (`empno`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `employnew` -- LOCK TABLES `employnew` WRITE; /*!40000 ALTER TABLE `employnew` DISABLE KEYS */; INSERT INTO `employnew` VALUES (1,'Rishab','Java','Programmer',40000.00),(2,'Rishab','Java','Programmer',90000.00),(3,'Rishab','Java','Programmer',90000.00); /*!40000 ALTER TABLE `employnew` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2019-08-12 9:15:40 <file_sep>/Day7/CustomerProject/resources/project.properties added = Customer Record Added Successfully\r\n delete = Customer Record Deleted\r\n notfound = Customer Record Not Found\r\n update = Customer Record updated Successfully\r\n entername = Enter Customer name\r\n entersno = Enter Customer Serial No.\r\n enterPayMode = Enter Payment Mode\r\n enterModelPre = Enter Model Premium\r\n enterAnnIncome = Enter Annual Income\r\n enterchoice = Enter your choice\r\n opt = Options\r\n dashes = -------\r\n opt1 = 1. Add Customer\r\n opt2 = 2. Show Customer\r\n opt3 = 3. Search Customer\r\n opt4 = 4. Update Customer\r\n opt5 = 5. Delete Customer\r\n opt6 = 6. Store Customer in File\r\n opt7 = 7. Display Customer From File\r\n opt8 = 8. Exit\r\n opt9 = Invalid Choice\r\n custId = Customer ID can't be negative and zero\r\n custName = Customer Name must be Greater the 4 characters\r\n custAnnIncome = Annual Income must Be Between 20000 and 1000000\r\n modelPayment = Model Payment must Be Between 1000 and 50000\r\n paymentMode = Payment Mode must be 1 or 2 or 3\r\n <file_sep>/Day18/.metadata/version.ini #Fri Aug 23 08:25:41 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/DB/sqlpractice_student.sql -- MySQL dump 10.13 Distrib 8.0.16, for Win64 (x86_64) -- -- Host: localhost Database: sqlpractice -- ------------------------------------------------------ -- Server version 5.5.62 /*!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 */; SET NAMES utf8 ; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `student` -- DROP TABLE IF EXISTS `student`; /*!40101 SET @saved_cs_client = @@character_set_client */; SET character_set_client = utf8mb4 ; CREATE TABLE `student` ( `sno` int(11) NOT NULL, `name` varchar(30) NOT NULL, `sub1` int(11) DEFAULT NULL, `sub2` int(11) DEFAULT NULL, `sub3` int(11) DEFAULT NULL, `total` decimal(9,2) DEFAULT NULL, `aveg` decimal(9,2) DEFAULT NULL, PRIMARY KEY (`sno`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `student` -- LOCK TABLES `student` WRITE; /*!40000 ALTER TABLE `student` DISABLE KEYS */; INSERT INTO `student` VALUES (1,'Prem',67,65,74,132.00,65.67),(2,'Lakshi',78,43,78,121.00,54.67),(4,'Deepa',88,56,75,144.00,66.67); /*!40000 ALTER TABLE `student` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2019-08-12 9:15:38 <file_sep>/DB/Students.sql create table Student ( sno int primary key, name varchar(30) not null, sub1 int, sub2 int, sub3 int, total numeric(9,2), aveg numeric(9,2) ); CREATE TABLE `exam` ( `eid` int(11) NOT NULL AUTO_INCREMENT, `subject` varchar(30) NOT NULL, `mark` double DEFAULT NULL, `sid` int(11) DEFAULT NULL, PRIMARY KEY (`eid`), KEY `sid` (`sid`), CONSTRAINT `exam_ibfk_1` FOREIGN KEY (`sid`) REFERENCES `student` (`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=latin1; drop table Student; insert into Student(sno, name,sub1,sub2,sub3) values (1,'Prem',67,65,74), (2,'Lakshi',78,43,78), (3,'Vishali',78,43,78), (4,'Deepa',88,56,75); use sqlpractice; update Student set TOTAL = sub1+sub2, Aveg = (sub1+sub2+sub2)/3; <file_sep>/HMS/HMS/src/main/java/com/hcl/hms/HotelCrud.java package com.hcl.hms; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import org.hibernate.Transaction; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; public class HotelCrud { public List<Booking> getAllBookings() { List<Booking> bookings = new ArrayList<Booking>(); SessionFactory sf = HibernateUtil.getConnection(); Session s = sf.openSession(); Query q = s.createQuery("from Booking"); List list = q.list(); for(Object obj : list) { Booking b = (Booking)obj; bookings.add(b); } return bookings; } public String generateRoomId (){ // working properly String rid = ""; SessionFactory sf = HibernateUtil.getConnection(); Session s = sf.openSession(); Query q = s.createQuery("select max(roomId) from Room"); for(Iterator it = q.iterate();it.hasNext();) { rid = (String)it.next(); if(rid == null) { rid = "R000"; } int id = Integer.parseInt(rid.substring(1)); id++; rid = String.format("R%03d", id); } return rid; } public String generateBookingId (){ // working properly String bid = ""; SessionFactory sf = HibernateUtil.getConnection(); Session s = sf.openSession(); Query q = s.createQuery("select max(bookId) from Booking"); for(Iterator it = q.iterate();it.hasNext();) { bid = (String)it.next(); if(bid == null) { bid = "B000"; } int id = Integer.parseInt(bid.substring(1)); id++; bid = String.format("B%03d", id); } return bid; } public boolean addRooms(Room room) { SessionFactory sf = HibernateUtil.getConnection(); Session s = sf.openSession(); room.setStatus("Available"); s.save(room); Transaction t = s.beginTransaction(); t.commit(); return true; } public List<Room> getAvailableRooms() { List<Room> rooms = new ArrayList<Room>(); SessionFactory sf = HibernateUtil.getConnection(); Session s = sf.openSession(); Query q = s.createQuery("from Room"); List res = q.list(); for(Object obj : res) { Room room = (Room)obj; if(room.getStatus().equals("Available")) { rooms.add(room); } } return rooms; } public Room getRoomByid(String rid) { Room room = new Room(); SessionFactory sf = HibernateUtil.getConnection(); Session s = sf.openSession(); Query q = s.createQuery("from Room where RoomId = ?"); q.setParameter(0, rid); List list = q.list(); for(Object obj : list) { room = (Room)obj; // System.out.println(room.getStatus()); } return room; } public boolean bookRoom(Booking obj) { SessionFactory sf = HibernateUtil.getConnection(); Session s = sf.openSession(); obj.setChkDate(new Date()); s.save(obj); Transaction t = s.beginTransaction(); t.commit(); updateRoomStatus(obj.getRoomId(), "Booked"); return true; } public boolean updateRoomStatus(String rid,String status) { SessionFactory sf = HibernateUtil.getConnection(); Session s = sf.openSession(); Room room = new Room(); Room tempRoom = getRoomByid(rid); String type = tempRoom.getType(); int cpd = tempRoom.getCostPerDay(); room.setRoomId(rid); room.setStatus(status); room.setCostPerDay(cpd); room.setType(type); s.update(room); Transaction t = s.beginTransaction(); t.commit(); return true; } } <file_sep>/Day22/DeptShow/src/main/java/com/hcl/dept/DeptSearchMain.java package com.hcl.dept; import java.util.Scanner; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class DeptSearchMain { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("jdbc.xml"); DataQueryDao d = (DataQueryDao)ctx.getBean("myDao"); Scanner sc = new Scanner(System.in); System.out.println("Enter Deptno : "); int deptno = Integer.parseInt(sc.nextLine()); d.searchDept(deptno); } } <file_sep>/Day5/.metadata/version.ini #Tue Aug 06 17:17:42 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/BankProject/src/com/hcl/bank/DepositeAccountMain.java package com.hcl.bank; import java.util.Scanner; public class DepositeAccountMain { /** * before depositing amount check account is activate or not. * @param args . */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter Account "); int accno = Integer.parseInt(sc.nextLine()); System.out.println("Enter Amount "); int depositeAmount = Integer.parseInt(sc.nextLine()); System.out.println(AccountBal.depositeAccountBal(accno, depositeAmount)); sc.close(); } } <file_sep>/Day11/HtmlDemo/src/NameForm.js function showFullName() { var fn = frmName.firstName.value; var ln = frmName.lastName.value; frmName.fullName.value = fn + " " +ln; }<file_sep>/Day22/InventoryDemo/src/main/java/com/hcl/inventorydemo/MainProg.java package com.hcl.inventorydemo; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainProg { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("Wire.xml"); OrderLogic ol = (OrderLogic)ctx.getBean("orderlogic"); ol.display(); } } <file_sep>/Day9/.metadata/version.ini #Fri Aug 23 12:22:19 IST 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/DB/inventry_orders.sql -- MySQL dump 10.13 Distrib 8.0.16, for Win64 (x86_64) -- -- Host: localhost Database: inventry -- ------------------------------------------------------ -- Server version 5.5.62 /*!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 */; SET NAMES utf8 ; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `orders` -- DROP TABLE IF EXISTS `orders`; /*!40101 SET @saved_cs_client = @@character_set_client */; SET character_set_client = utf8mb4 ; CREATE TABLE `orders` ( `OrderId` int(11) DEFAULT NULL, `StockID` varchar(30) DEFAULT NULL, `QtyOrd` int(11) DEFAULT NULL, `billAmt` decimal(9,2) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `orders` -- LOCK TABLES `orders` WRITE; /*!40000 ALTER TABLE `orders` DISABLE KEYS */; INSERT INTO `orders` VALUES (1,'S001',5,50000.00),(2,'S002',10,390000.00),(3,'S003',2,50120.00),(4,'S003',2,50120.00),(5,'S003',2,50120.00),(6,'S003',2,50120.00),(7,'S003',2,50120.00),(8,'S003',2,50120.00),(9,'S003',2,50120.00),(10,'S006',2,110000.00),(11,'S006',2,110000.00),(12,'S006',2,110000.00),(13,'S006',1,55000.00),(14,'S006',1,55000.00),(15,'S006',1,55000.00),(16,'S006',1,55000.00),(17,'S006',1,55000.00),(18,'S006',1,55000.00); /*!40000 ALTER TABLE `orders` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2019-08-12 9:15:32 <file_sep>/Day8/.metadata/.plugins/org.eclipse.core.resources/.history/7e/5043aa3a06b900191432f8c1b395eba6 package com.hcl.jdbcemploy; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Scanner; public class UpdateEmploy { /** * main method . * @param args . */ public static void main(String[] args) { Connection con = new DaoConnection().getConnection(); Scanner sc = new Scanner(System.in); System.out.println("Enter Employ Number"); int empno = Integer.parseInt(sc.nextLine()); System.out.println("Enter Designation"); String desig = sc.nextLine(); System.out.println("Enter Basic Salary"); int basic = Integer.parseInt(sc.nextLine()); String cmd = "update Employ set desig = ?, basic = ? where empno = ?"; try { PreparedStatement ps = con.prepareStatement(cmd); ps.setInt(3, empno); ps.setString(1, desig); ps.setInt(2, basic); ps.executeUpdate(); System.out.println("Updated Sucessfully"); } catch (SQLException e) { e.printStackTrace(); } try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } <file_sep>/Day3/PracticeDay3/src/com/hcl/inheritance/InhDemo.java package com.hcl.inheritance; class First { public void show(){ System.out.println("Base Class Show() method"); } } class Second extends First { public void show(){ //super.show(); System.out.println("Child Class Show() method"); } } public class InhDemo{ public static void main(String[] args) { Second s1 = new Second(); // base class object creation in this way is not suggested First f1 = new Second(); // up casting // new keyword is given high priority //f1.show(); //s2.show(); First f2 = new First(); Second s2 = new Second(); //s2.show(); First f3 = (First)s2; // f3.show(); First f4 = (Second)s2; // f4.show(); Second s3 = (Second)f1; // s3.show(); } }
609cb7ccea1d7fede525cd8c36f3baf9a4aae491
[ "SQL", "HTML", "JavaScript", "Markdown", "INI", "Java" ]
120
SQL
rkmr039/core-java
1b6f22c8ef2479a2a039b6c5cac25be3c345ad70
f740d82c5b0b5948eb7fd6bd9fc3fc512c943fcd
refs/heads/main
<file_sep>package com.example.notes101 import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
d21c94c3077af8e5d28f636fcedcd5893eb7b667
[ "Kotlin" ]
1
Kotlin
JeroenKnoops/notes101
c8ead5c04a23e7dd740ff10f322a3e5930d47453
1f7a13c6f73d45e5acbb86e8211af47f5b29d7c3
refs/heads/master
<file_sep>package com.xandme.springbootquickstart.googleapi.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import org.codehaus.jackson.annotate.*; import java.util.HashMap; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "text", "image" }) public class ReadingModes { /** * The Text Schema. * <p> * An explanation about the purpose of this instance. * */ @JsonProperty("text") @JsonPropertyDescription("An explanation about the purpose of this instance.") private Boolean text = false; /** * The Image Schema. * <p> * An explanation about the purpose of this instance. * */ @JsonProperty("image") @JsonPropertyDescription("An explanation about the purpose of this instance.") private Boolean image = false; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * The Text Schema. * <p> * An explanation about the purpose of this instance. * */ @JsonProperty("text") public Boolean getText() { return text; } /** * The Text Schema. * <p> * An explanation about the purpose of this instance. * */ @JsonProperty("text") public void setText(Boolean text) { this.text = text; } /** * The Image Schema. * <p> * An explanation about the purpose of this instance. * */ @JsonProperty("image") public Boolean getImage() { return image; } /** * The Image Schema. * <p> * An explanation about the purpose of this instance. * */ @JsonProperty("image") public void setImage(Boolean image) { this.image = image; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } } <file_sep>https://github.com/CosmicCosmos/xandme.git I developed this application as a SpringBoot Application (Maven project), since it is a standalone server with embedded tomcat, we don't have to deploy it in any server, just run it as plain "GoogleapiApplication.java" java application. i did not make it as a command line argumnet, i made it as url based. Once the server is started , hit the below url where it accepts 3 parameter in the url. http://localhost:8080/api/python/5/Price CSV file location is configured in the application.properties as "csvFilePath=/Users/dselvaraj/Documents/GoogleApiData.csv" Base Url : http://localhost:8080/api the first parameter is a search string the second parameter is a max result need to be displayed. the third paramter is the sort by fields based on Price,PublishedDate,MaturityRating,RatingCount,PageCount,AverageRating/ These are the different ways to access the url to get the results. http://localhost:8080/api/python -> this pulls 40 records matches the python string pattern http://localhost:8080/api/python/5 -> this pulls 5 records matches the python string pattern http://localhost:8080/api/python/5/Price -> this pulls 5 records matches the python string sort by price field http://localhost:8080/api/python/5/PublishedDate -> this pulls 5 records matches the python string sort by PublishedDate field http://localhost:8080/api/python/5/MaturityRating -> this pulls 5 records matches the python string sort by MaturityRating field http://localhost:8080/api/python/5/RatingCount -> this pulls 5 records matches the python string sort by RatingCount field http://localhost:8080/api/python/5/PageCount -> this pulls 5 records matches the python string sort by PageCount field <file_sep>package com.xandme.springbootquickstart.googleapi.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import org.codehaus.jackson.annotate.*; import java.util.HashMap; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "country", "saleability", "isEbook", "retailPrice" }) public class SaleInfo { /** * The Country Schema. * <p> * An explanation about the purpose of this instance. * */ @JsonProperty("country") @JsonPropertyDescription("An explanation about the purpose of this instance.") private String country = ""; /** * The Saleability Schema. * <p> * An explanation about the purpose of this instance. * */ @JsonProperty("saleability") @JsonPropertyDescription("An explanation about the purpose of this instance.") private String saleability = ""; /** * The Isebook Schema. * <p> * An explanation about the purpose of this instance. * */ @JsonProperty("isEbook") @JsonPropertyDescription("An explanation about the purpose of this instance.") private Boolean isEbook = false; @JsonProperty("retailPrice") private RetailPrice retailPrice; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * The Country Schema. * <p> * An explanation about the purpose of this instance. * */ @JsonProperty("country") public String getCountry() { return country; } /** * The Country Schema. * <p> * An explanation about the purpose of this instance. * */ @JsonProperty("country") public void setCountry(String country) { this.country = country; } /** * The Saleability Schema. * <p> * An explanation about the purpose of this instance. * */ @JsonProperty("saleability") public String getSaleability() { return saleability; } /** * The Saleability Schema. * <p> * An explanation about the purpose of this instance. * */ @JsonProperty("saleability") public void setSaleability(String saleability) { this.saleability = saleability; } /** * The Isebook Schema. * <p> * An explanation about the purpose of this instance. * */ @JsonProperty("isEbook") public Boolean getIsEbook() { return isEbook; } /** * The Isebook Schema. * <p> * An explanation about the purpose of this instance. * */ @JsonProperty("isEbook") public void setIsEbook(Boolean isEbook) { this.isEbook = isEbook; } @JsonProperty("retailPrice") public RetailPrice getRetailPrice() { return this.retailPrice; } @JsonProperty("retailPrice") public void setRetailPrice(RetailPrice retailPrice) { this.retailPrice = retailPrice; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } } <file_sep>csvFilePath=/Users/dselvaraj/Documents/GoogleApiData.csv<file_sep>package com.xandme.springbootquickstart.googleapi.controller; import org.apache.commons.csv.CSVRecord; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.xandme.springbootquickstart.googleapi.service.GoogleApiService; import java.util.List; @RestController @RequestMapping("api/") public class GoogleApiController { @Autowired GoogleApiService googleApiService; @RequestMapping(value="{book}/{maxResults}/{orderBy}" , method =RequestMethod.GET) public List<String> getInfoOnBooks(@PathVariable String book,@PathVariable String maxResults,@PathVariable String orderBy) { return googleApiService.getBooks(book,maxResults,orderBy); } @RequestMapping(value="{book}/{maxResults}" , method =RequestMethod.GET) public List<String> getInfoOnBooksMaxResults(@PathVariable String book,@PathVariable String maxResults) { return googleApiService.getBooks(book,maxResults,""); } @RequestMapping(value="{book}" , method =RequestMethod.GET) public List<String> getInfoOnBooks(@PathVariable String book) { return googleApiService.getBooks(book,"",""); } }
9c99b501f43584706189c6ccc8489a2e773a35e0
[ "Markdown", "Java", "INI" ]
5
Java
dilipdiwakar/xandme
5cf1d8a70d668db3ea0c288eaac7ae28d1ad1f95
c61debdddbfc41278ee8d9258440abf911b04476
refs/heads/main
<repo_name>choll03/go-fundamental<file_sep>/slice/main.go package main import "fmt" func main() { var fruits = []string{"apple", "grape", "banana", "melon"} var newFruit = fruits[0:2] fmt.Println(newFruit) fmt.Println(fruits) } <file_sep>/map/main.go package main import "fmt" func main() { // 1. deklarasi map var chiken = map[string]int{ "januari": 10, "maret": 5, "april": 9, } looping(chiken) // 3. Menghapus Item Map delete(chiken, "januari") looping(chiken) // 4. Deteksi keberadaan item dengan key tertentu var value, isExist = chiken["tes"] if isExist { fmt.Println(value) } else { fmt.Println("item not exists") } // 5. Kombinasi slice & map var chickens = []map[string]string{ {"name": "chicken blue", "gender": "male"}, {"name": "chicken pink", "gender": "female"}, } for key, chicken := range chickens { fmt.Println(key, chicken["name"]) fmt.Println(key, chicken["gender"]) } } // 2. Iterasi Item Map Menggunakan for - range func looping(chicken map[string]int) { fmt.Println("----------------------------------") for key, val := range chicken { fmt.Println(key, val) } } <file_sep>/variable/main.go package main import "fmt" func main() { var firsName string = "jonh" var lastName string lastName = "wick" fmt.Printf("helo %s %s!\n", firsName, lastName) name := new(string) fmt.Println(name) fmt.Println(*name) } <file_sep>/coba/go.mod module coba go 1.15 <file_sep>/hello-world/go.mod module hello-wolrd go 1.15 <file_sep>/struct/main.go package main import "fmt" type Mahasiswa struct { nim string nama string kelas string } func main() { var mahasiswas = []Mahasiswa{ {nim: "2016141807", nama: "ismail", kelas: "09TPLE005"}, {nim: "2016141389", nama: "<NAME>", kelas: "09TPLE006"}, } for _, mahasiswa := range mahasiswas { fmt.Println(mahasiswa) } } <file_sep>/gorutine/go.mod module gorutine go 1.15 <file_sep>/kondisi/go.mod module kondisi go 1.15 <file_sep>/fungsi/main.go package main import ( "fmt" "strings" ) type FilterCallback func(string) bool func filters(data []string, callback FilterCallback) []string { var result []string for _, each := range data { if filtered := callback(each); filtered { result = append(result, each) } } return result } func main() { var data = []string{"is", "mail", "ndut"} var dataFilter = filters(data, func(each string) bool { return strings.Contains(each, "u") }) fmt.Println("Data asli", data) fmt.Println("Data filter", dataFilter) }
1214c2a84fc0c6d7e5121c4a79d9a17b78b3023d
[ "Go Module", "Go" ]
9
Go
choll03/go-fundamental
0a6dd6ccb639df51a0722a59a145c4db3869ce8f
2a822d788330357eb7e5742c237ad0243b50bdab
refs/heads/master
<file_sep>import styled from 'styled-components'; export const Wrapper = styled.section` display: flex; justify-content: flex-start; background-image: linear-gradient(to right, #00F260, #0575E6); box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); color: #fff; margin:10px 10px 10px 10px; padding: 10px; `; export const Img = styled.section` padding-top: 20px; `; export const Table = styled.table` border-collapse: collapse; width: 100%; `; export const Tr = styled.tr` text-align: left; padding: 8px; `; export const Td = styled.td` text-align: left; padding: 8px; `; export const Card = styled.section` text-align: left; padding: 8px; `; export const Button = styled.button` /* Adapt the colors based on primary prop */ background: ${props => props.primary ? "palevioletred" : "white"}; color: ${props => props.primary ? "white" : "palevioletred"}; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; `;<file_sep>import React from 'react'; import PropTypes from 'prop-types'; import './avatar1.css'; const Avatar1 = ({ src, alt }) => { return ( <img src={src} alt={alt} className="avatar1"/> ); } Avatar1.propTypes = { src: PropTypes.string.isRequired, } export default Avatar1;<file_sep>import React from 'react'; import CardMeetUp from './components/CardMeetUp/CardMeetUp'; import MeetUp from './components/NextMeetUp/MeetUp'; import Members from './components/Members/Members'; import PastMeet from './components/PastMeetUp/PastMeet'; import './App.css'; function App() { const dataPastMeet = [ { date: '27 Nov 2017', deskripsi: '#39 JakartaJS April Meetup with Kumparan', went:'137', btn :'primary', }, { date: '27 Oct 2018', deskripsi: '#38 JakartaJS April Meetup with Blibli', went:'137', btn :'success', }, { date: '27 Jam 2019', deskripsi: '#37 JakartaJS April Meetup with Hacktiv8', went:'137', btn :'warning', }, ] return ( <div className="App"> <div className="menu"> <ul> <li><a class="active" href="#home">Home</a></li> <li><a href="#news">News</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#about">About</a></li> </ul> </div> {/* Call component */} <CardMeetUp location="Medan, Indonesia" members="180" organizer="ReactJs"/> <h2>Next MeetUp</h2> <MeetUp title="Awesome Meetup and event"/> <h2>About Meetup</h2> <div className="text1"> <p> Come and meet other developers interested in the JavaScript and its library in the Greater Jakarta area<br /><br /> Twitter: @JakartaJS and we user the hashtag #jakartajs </p> <br /> </div> <div> <h2>Members</h2> <text className="SeeAll">See all</text><br /> </div> < Members name="<NAME>" sum="105 .others" /> <h2>Past Meetup</h2> <text className="SeeAll">See all</text><br /> <div className="cartPastMeet"> <PastMeet data={dataPastMeet}/> </div> </div> ); } export default App; <file_sep>import React from 'react'; import AvatarImages from '../../assets/avatar.jpg'; import Avatar1 from '../Avatar1/Avatar1'; import {Wrapper, Card} from './members.style.js'; const Members = ({name, sum}) => { return( <div > <Wrapper> <div > <Avatar1 src={AvatarImages} alt={AvatarImages} /></div> <Card> <h2>Organizers</h2> <table> <tr> <td>{name}</td> <td></td> <td>{sum}</td> </tr> </table> </Card> </Wrapper> </div> ) } export default Members;<file_sep>import React from 'react'; import Avatar from '../Avatar/Avatar'; // import Button from '../Button/Button'; import AvatarImage from '../../assets/avatar.jpg'; import {Button, Wrapper, Table, Tr, Td, Card, Img} from './cardMeetUp.style.js'; const CardMeetUp = ({location, members, organizer}) => { const thanksForJoin = () => { alert('Terima kasih sudah join meetup'); } return ( <Wrapper> <Img> <Avatar src={AvatarImage} alt="img avatar" /> </Img> <Card> <h2>Hacktiv 8 Meetup</h2> <Table> <Tr> <Td>Location</Td><Td>{location}</Td> </Tr> <Tr> <Td>Members</Td><Td>{members}</Td> </Tr> <Tr> <Td>Organizer</Td><Td>{organizer}</Td> </Tr> </Table> <Button onClick={thanksForJoin}>JOINT US</Button> <Button primary onClick={thanksForJoin}>START</Button> </Card> </Wrapper> ); } export default CardMeetUp;<file_sep>import styled from 'styled-components'; export const Wrapper = styled.section` display: flex; justify-content: flex-start; background-image: linear-gradient(to right, #78ffd6, #a8ff78); box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); padding-block: 20px; width: 400px; margin-left: 10px; padding-left: 10px; margin-top: 10px; transition: 0.3s; `; export const Div = styled.section` padding-left: 30px; `; export const Btn = styled.section` padding: 10px; `;<file_sep>import React from 'react'; import Button from '../Button/Button'; import {Wrapper, Div, Btn} from './pastMeet.style.js'; const PastMeet = ({data}) => { return( <> { data.map((item) => ( <Wrapper> <Div> <b>{item.date}</b><br /> <hr></hr> <b>{item.deskripsi}</b> <br></br> <p>{item.went} &nbsp;<text>went</text></p> <Btn> <Button textButton="View"/> </Btn> </Div> </Wrapper> )) } </> ) } export default PastMeet;
ef1aec8c3f66e8fc79985a9e031e04ac510704a0
[ "JavaScript" ]
7
JavaScript
agus-pra/react-component
f3632b6da1592d915a31404d0889bba35f41c916
16ee8bcc227d1d41bcefd7a494d279dbe2e44cef
refs/heads/master
<repo_name>AcidumJust/RSA_WPF<file_sep>/RSA_WPF/MainWindow.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace RSA_WPF { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } Random r = new Random(); string alfabetRU = " абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ0123456789"; BigInteger p, q, n, exp, d, func; (BigInteger, BigInteger, BigInteger) NOD(BigInteger a, BigInteger b) { if (b == 0) return (a, 1, 0); else { (BigInteger c, BigInteger x, BigInteger y) = NOD(b, a % b); return (c, y, x - y * (a / b)); } } BigInteger Converter01ToInt(string s) { BigInteger res = 0; for (int i = s.Length - 1, j = 0; i >= 0; --i, ++j) if (s[i] == '1') res += BigInteger.Pow(2, j); return res; } string ConverterIntTo01(BigInteger s) { Stack<int> st = new Stack<int>(); string res = ""; while (s > 0) { st.Push((int)(s % 2)); s = (s - s % 2) / 2; } while (st.Count > 0) res += st.Pop(); return res; } BigInteger RandBigIntByLen(int len) //Возвращает случайное нечетное число { string res = "1"; while (res.Length < len) { res += r.Next(2).ToString(); } var v = Converter01ToInt(res); return v % 2 == 0 ? v + 1 : v; //если четное то +1 } BigInteger ExpModN(BigInteger a, BigInteger exp, BigInteger n) { if (exp == 0) return new BigInteger(1); string e = ConverterIntTo01(exp); BigInteger res = a % n; for (int j = 1; j < e.Length; ++j) { if (e[j] == '1') res = ((res * res) * a) % n; else res = (res * res) % n; } return res; } bool TestMR(BigInteger R) { if (R == 2 || R == 3) return true; if (R < 2 || R % 2 == 0) return false; //Разложение на s и t BigInteger t = R - 1, s = 0; while (t % 2 == 0) { t /= 2; s += 1; } BigInteger a; for (int k = 0; k < 20; ++k) { //Случайное число размера BigInt (подглядел в интернете) RNGCryptoServiceProvider r = new RNGCryptoServiceProvider(); byte[] arrb = new byte[R.ToByteArray().Length]; do { r.GetBytes(arrb); a = new BigInteger(arrb); } while (a < 2 || a >= R - 2); // далее тест согласно методичке if (R % a == 0) return false; BigInteger b = ExpModN(a, t, R); if (b == 1 || b == R - 1) { continue; } else { for (int i = 1; i < s; ++i) { b = ExpModN(b, 2, R); if (b == R - 1) break; if (b == 1) return false; } if (b != R - 1) return false; } } return true; } BigInteger PrimeGenerator(int len) //длина в битах { var res = RandBigIntByLen(len); while (!TestMR(res)) { res = RandBigIntByLen(len); } return res; } void GenerateKeys(int len) //длина в битах { p = PrimeGenerator(len / 2); q = PrimeGenerator(len / 2); while (p == q) q = PrimeGenerator(len / 2); n = p * q; func = (p - 1) * (q - 1); exp = PrimeGenerator(len / 3); while (exp == p || exp == q || func % exp == 0) exp = PrimeGenerator(len / 3); d = NOD(func, exp).Item3; if (d < 0) d += func; } string StringToBigint(string txt, string alf) { string res = ""; foreach (var a in txt) { if (!alf.Contains(a)) { MessageBox.Show("Не все символы можно закодировать"); return ""; } res += (alf.IndexOf(a) + 10).ToString(); } return res; } string BigintToString(BigInteger txt, string alf) { string res = ""; string r = txt.ToString(); int i = 0; while (i < r.Length) { res += alf[(int.Parse((r[i++].ToString() + r[i++].ToString())) - 10) % alf.Length]; } return res; } string ShifrRSA(BigInteger txt, BigInteger exp, BigInteger n) { return ExpModN(txt, exp, n).ToString(); } BigInteger DeShifrRSA(BigInteger txt, BigInteger exp, BigInteger d)//если значение txt больше n, то преобразование невозможно { if (txt >= d) { throw new Exception(); } return ExpModN(txt, exp, d); } private void btn_Generate_Click(object sender, RoutedEventArgs e) { int len; if (int.TryParse(txtB_Len.Text,out len) && len < 1100 && len > 100) { GenerateKeys(len); round.ToolTip = $"p = {p}\nq = {q}\nn = {n}\nfunc = {func}\nexp = {exp}\nd = {d}"; round.Fill = Brushes.Green; return; } round.ToolTip = ""; round.Fill = Brushes.Red; MessageBox.Show("Введите целое число"); } private void btn_Shifr_Click(object sender, RoutedEventArgs e) { if(round.Fill!= Brushes.Red) { if (BigInteger.TryParse(StringToBigint(txtB_Orig.Text, alfabetRU), out BigInteger msg)) { txtB_Shifr.Text = ShifrRSA(msg,exp,n); } return; } MessageBox.Show("Сгенерируйте ключ"); } private void btn_DeShifr_Click(object sender, RoutedEventArgs e) { if(BigInteger.TryParse(txtB_Shifr.Text, out BigInteger msg)) { try { txtB_DeShifr.Text = BigintToString(DeShifrRSA(msg, d, n), alfabetRU); } catch { MessageBox.Show("Преобразование невозможно"); } } } } }
8c0ed7067ac0c99fdc441575b11fb6374f144e69
[ "C#" ]
1
C#
AcidumJust/RSA_WPF
c6d8e554b2f99405f2f97571e95b18898c0a25ba
6c779c4adf807baf67cfc67027ab1a8e55da56c8
refs/heads/master
<repo_name>Kimsihwan/MyLocation<file_sep>/MyLocation/ViewController.swift // // ViewController.swift // MyLocation // // Created by test on 2018. 11. 6.. // Copyright © 2018년 ksh. All rights reserved. // import UIKit import MapKit class ViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var myMap: MKMapView! var locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() myMap.showsUserLocation = true if CLLocationManager.locationServicesEnabled() == true { if CLLocationManager.authorizationStatus() == .restricted || CLLocationManager.authorizationStatus() == .denied || CLLocationManager.authorizationStatus() == .notDetermined { locationManager.requestWhenInUseAuthorization() } locationManager.desiredAccuracy = 1.0 locationManager.delegate = self locationManager.startUpdatingHeading() } else { print("GPS를 켜주세요") } } //MARK:- CLLocationManager Delegates func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: locations[0].coordinate.latitude, longitude: locations[0].coordinate.longitude), span: MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002)) self.myMap.setRegion(region, animated: true) } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("") } }
5778a9c4006db1550383c0a6c31d0e3300505da4
[ "Swift" ]
1
Swift
Kimsihwan/MyLocation
2baeb3ae0f1c4daea9c7bed8d1c347de8f2734df
7b2bd5eb3d24561e9be3e05e8f9a7bf2b7e95235
refs/heads/main
<repo_name>Jhoysbou/FragmentVideoDownloader<file_sep>/main.py from typing import Optional from loguru import logger import os import sys import platform from src.FragmentVideoDownloader import FragmentVideoDownloader from src.view.AppWindow import AppWindow def callback(video_url: Optional[str], audio_url: Optional[str], from_: int, to_: int): downloader: FragmentVideoDownloader = FragmentVideoDownloader(CURRENT_DIR, video_url, audio_url, from_=int(from_), to_=int(to_)) downloader.download() downloader.concat() if __name__ == '__main__': if platform.system() == "Darwin": CURRENT_DIR = os.sep.join(sys.argv[0].split("/")[:-1]) else: CURRENT_DIR = os.getcwd() logger.add(f'{CURRENT_DIR + os.sep}log{os.sep}FragmentVideoDownloader.log', format="{time} {level} {message}", rotation="1 MB", level="DEBUG") logger.info("starting app") app_window = AppWindow(callback=callback) app_window.show() <file_sep>/requirements.txt altgraph==0.17 certifi==2020.12.5 chardet==4.0.0 idna==2.10 loguru==0.5.3 macholib==1.14 pyinstaller==4.2 pyinstaller-hooks-contrib==2021.1 requests==2.25.1 urllib3==1.26.3 <file_sep>/build.sh #!/bin/bash pyinstaller --onefile --hidden-import loguru --clean --name FragmentVideoDownloader main.py <file_sep>/README.md # FragmentVideoDownloader Download and concatenate fragmented videos from any website with ease! ### Tired concatenating fragments of a video? This app will help you! #### Content [How to use](#how-to-use) \ [Info](#info) ## How to use 1. Go to a website where you want to download a video. 2. Open the web inspector (Safari and Chrome: COMMAND + OPTION + I or CTRL + ALT + I). Go to the Network tab ![](img/1.png) 3. Find something that looks like that `media_*.ts`. File name can be different, but it should have numbers in it. Click on a file. ![](img/2.png) 4. Copy the url of the file. 5. Then determine what number refers to the first fragment of the video. In my case its `0`. The same thing goes for the last part. Run through the video to the end and find the last number. In my case it is `2404` ![](img/3.png) 6. Open the app and paste the url you copied earlier. ![](img/4.png) 7. Replace digits that unique for every fragment with `{i}`. Then enter the numbers that refers to the first part of the video and the last part. Should look like this: ![](img/5.png) 8. Press `start` and watch for the directory when you opened the app. The app generates two folders: the one for logs, and the other one for output file. ![](img/6.png) Your concatenated file is `temp/output.{YOUR_FILE_EXTENSION}`. The raw fragments placed at `temp/videos` ![](img/7.png) ### Info - **No quality loss!** - **Requires FFMPEG!** [Get it here](https://ffmpeg.org/download.html) <file_sep>/src/view/AppWindow.py import tkinter as tk from typing import Callable class AppWindow: def __init__(self, callback: Callable): self.callback = callback self.__main: tk.Tk = tk.Tk() self.__main.title("FragmentVideoDownloader") self.__main.geometry("350x150+10+20") self.__main.resizable(False, False) def show(self): self.__render() self.__main.mainloop() def __render(self): tk.Label(self.__main, text="Video URL").grid(row=0, pady=10, padx=10) self.__is_audio_separated = tk.IntVar(value=0) # TODO: implement separate audio # audio_checkbox = tk.Checkbutton(self.__main, { # "variable": self.__is_audio_separated, # "text": "Audio URL", # "command": lambda: self.__change_visibility(audio_input) # }) # audio_checkbox.grid(row=1, column=0, padx=10) video_input = tk.Entry(self.__main, width=20) video_input.grid(row=0, column=1) tk.Label(self.__main, text="From").grid(row=1, pady=10, padx=10) from_input = tk.Entry(self.__main, width=5) from_input.grid(row=1, column=1) tk.Label(self.__main, text="To").grid(row=2, pady=10, padx=10) to_input = tk.Entry(self.__main, width=5) to_input.grid(row=2, column=1) # audio_input = tk.Entry(self.__main, width=20) tk.Button( self.__main, text='start', command=lambda: self.callback(video_input.get(), None, from_=from_input.get(), to_=to_input.get()) ).grid(row=2, column=1, sticky="e") def __change_visibility(self, entry): if self.__is_audio_separated.get() == 1: entry.grid(row=1, column=1) else: entry.grid_forget() <file_sep>/src/test/downlod_test.py import unittest from src.FragmentVideoDownloader import FragmentVideoDownloader class DownloadTest(unittest.TestCase): @staticmethod def test_simple_download(): downloader: FragmentVideoDownloader = FragmentVideoDownloader(".", "", None, from_=0, to_=50) downloader.download() downloader.concat() <file_sep>/src/FragmentVideoDownloader.py import os from typing import Optional import requests from loguru import logger from requests import Response from pathlib import Path class FragmentVideoDownloader: def __init__(self, path: str, video_url: Optional[str], audio_url: Optional[str], to_: int, from_: int = 0): self.to_ = to_ self.from_ = from_ self.audio_url = audio_url self.video_url = video_url self._path: str = path + os.sep + "temp" @logger.catch def download(self): if self.video_url is None: raise ValueError("video_url is none") logger.info("starting downloading") path = self._path + os.sep + "video" self._download(self.video_url, path, self.from_, self.to_) logger.info("finished downloading video files") if self.audio_url is not None: path = self._path + os.sep + "audio" self._download(self.audio_url, path, self.from_, self.to_) logger.info("finished downloading video files") def concat(self): self._prepare() logger.info("starting videos concatenation") os.system( f'ffmpeg -f concat -i {self._path + os.sep + "video" + os.sep + "videos.list"}' f' -c copy {self._path + os.sep}output.{self.video_url.split(".")[-1]} -y' ) def _prepare(self): name = self.video_url.split("/")[-1] result = [f"file '{name.replace('{i}', str(i))}'" for i in range(self.from_, self.to_)] with open(self._path + os.sep + "video" + os.sep + "videos.list", "w") as file: file.write("\n".join(result)) @staticmethod def _download(dirty_url, path, from_, to_): Path(path).mkdir(parents=True, exist_ok=True) for i in range(from_, to_): url = dirty_url.replace("{i}", str(i)) name = url.split("/")[-1] logger.info(f"downloading {name}") with open(path + os.sep + name, "wb") as file: data: Response = requests.get(url, allow_redirects=True) file.write(data.content)
85959f0138557163b1c14216a1b10fa9b446754f
[ "Markdown", "Python", "Text", "Shell" ]
7
Python
Jhoysbou/FragmentVideoDownloader
507eee2213adf7905dc2b2e7abffe4e9f832e4c3
94372e3a28bb19491517fc09228e06a9362c1352
refs/heads/master
<repo_name>OlesyaAstahova/SimpleClassExample<file_sep>/SimpleClassExample/SimpleClassExample/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SimpleClassExample { class Program { static void Main(string[] args) { //Усадим на мотоцикл байкера по имени Tiny. Motorcycle c = new Motorcycle(5); c.SetDriverName("Tiny"); c.PopAwheely(); Console.WriteLine("rider name is {0}", c.name);//name=NULL Console.WriteLine("Thanks ..."); /* Console.WriteLine("***** Fun with Class Bike *****\n"); Bike sony = new Bike(); sony.PrintState(); Bike pony = new Bike("Pony",2); pony.PrintState(); Bike tony = new Bike("Tony", 6); tony.PrintState(); */ /* // Console.WriteLine("***** Fun with Class Types *****\n"); //Разместить в памяти и сконфигурировать объект Car. Car myCar = new Car(); myCar.petName = "Henry"; myCar.currSpeed = 10; Car chuck = new Car(); chuck.PrintState(); Car mary = new Car("Mary"); mary.PrintState(); Car daisy = new Car("Daisy", 75); daisy.PrintState(); Car myCar; myCar = new Car(); myCar.petName = "Fred"; // Увиличить скорость автомобиля в несколько раз и вывести новое состояние. for (int i = 0; i <= 10; i++) { myCar.SpeedUp(5); myCar.PrintState(); }*/ Console.ReadLine(); } } } <file_sep>/SimpleClassExample/SimpleClassExample/Bike.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SimpleClassExample { class Bike { //'Состояние ' объект Bike. public string bikeName; public int bikeSpeed; public Bike(int Speed = 0, string name = "") { /* //Связывание конструктора в цепочку public Bike(int Speed) : this(Speed, "") { } public Bike(string name) : this(0, name) { } // Специальный стандартный конструктор. public Bike() { bikeName = "Sony"; bikeSpeed = 4; } public Bike(int Speed, string name) {*/ if (Speed > 10) { Speed = 10; } bikeSpeed = Speed; bikeName = name; } public string name; public void SetDriverName(string name) { this.name = name; } //Стандартное значение для типа int (0) // Установка кодом полного состояния Bike. public Bike(string pn, int cs) { bikeName = pn; bikeSpeed = cs; } // Функциональность Bike. public void PrintState() { Console.WriteLine("{0} is going {1} MPH.", bikeName, bikeSpeed); } public void SpeedUp(int delta) { bikeSpeed += delta; } } }
e3396a341c67459064b1a320b7e7d8780fcabb57
[ "C#" ]
2
C#
OlesyaAstahova/SimpleClassExample
77d60ad8d722b4bd6b58dfdcd64a557db80ccb8e
2a554e4de97bea1fbbf6f93df9b372e99f816e3e
refs/heads/main
<file_sep>import numpy as np def Fibonacci(n): if n < 2: return 1 return Fibonacci(n-1) + Fibonacci(n-2) rango = np.arange(0 , 35) valores = np.array(rango) for k in rango: valores[k] = Fibonacci(k) print(Fibonacci(k)) if k > 0: print('Golden Ratio = ', valores[k] / valores[k-1])<file_sep>import numpy as np import matplotlib.pyplot as plt Dx = 1e-6 f = lambda x : x**2 + np.log(2*x + 7)*np.cos(3*x) + 0.1 df = lambda x : (f(x + Dx) - f(x - Dx)) / (2*Dx) d2f = lambda x : (f(x + 2*Dx) - 2*f(x) + f(x - 2*Dx)) / (2*Dx)**2 def NewtonRap(x0): tol = 1e-4; err = 1000 while err > tol: x1 = x0 - f(x0)/df(x0) #Metodo de Newton Primera Derivada err = np.abs(x1-x0) # Calcula las raices de la funcion x0 = x1 return x0 def NewtonRap2(x0): tol = 1e-4 err = 1000 while err > tol: x1 = x0 - df(x0)/d2f(x0) #Metodo de Newton err = np.abs(x1-x0) #Calcula los maximos y minimos de la funcion x0 = x1 return x0 x0 = np.array([-0.5, 0.5, 2, 1.2]) #Creamos un array con los valores de x0 para el método de Newton Rapson y su primera derivada x2 = np.array([-1, 1, 0]) #Creamos un array con los valores de x2 para el método de Newton Rapson y su segunda derivada x = np.arange(-1.5 , 2.0, 0.01) xo = np.array([]) xm = np.array([]) for i in x0: xo = np.append(xo,[NewtonRap(i)]) #En estos ciclos, realizamos la función de NewtonRap mientras iteramos los valores de x0 y x2 for j in x2: # para el segundo método. xm = np.append(xm,[NewtonRap2(j)]) print(xo) print(xm) plt.grid() plt.figure(1) plt.plot(x, f(x)) plt.plot(xo, xo*0, 'ro') plt.plot(xm, f(xm), 'bo') plt.show() <file_sep>import matplotlib.pyplot as plt import numpy as np f = lambda x , y : (y + 1) * (x + 1) * np.cos(x**2 + 2*x) #Función lambda donde tenemos la ecuación que evaluaremos. def rk(x,y,h,xf): xarr = np.array([]) #Creamos un par de arreglos vacíos donde guardaremos los valores correspondientes en cada iteración. yarr = np.array([]) for i in np.arange(x, xf+h, h): #Ciclo for que va desde x: valor inicial de X, xf+h: el valor final de X + el aumento h para realizar las iteraciones correctas. print('x[',i,'] = ',x,' y[',i,'] = ', y) #Imprime los valores de X y Y en cada iteración. k1 = f(x , y) k2 = f(x + h/2 , y + k1 * h/2) k3 = f(x + h/2 , y + k2 * h/2) #Calculo de los valores K usando la función lambda. k4 = f(x + h , y + k3 * h) print('k1 = ',k1,' k2 = ',k2,' k3 = ',k3,' k4 = ',k4) #Imprime los valores de K. xarr = np.append(xarr,x) #Agrega los valores de X y Y al final de su respectivo arreglo. yarr = np.append(yarr,y) y += ((k1 + 2*k2 + 2*k3 + k4) / 6) * h #Sustitución del valor de Y para la siguiente iteración. x += h #Aumento de x en h return np.array([xarr, yarr]) #Regresa un arreglo creado a partir del arreglo xarr y yarr, divididos para uso individual. t = rk(0, 4, 0.01, 2) #Llamado de la función rk usando x: valor inicial x - y: valor inicial y - h: aumento - xf: valor final x plt.grid() plt.figure(1) plt.plot(t[0], t[1]) plt.show()<file_sep>import matplotlib.pyplot as plt import numpy as np """ f2 = lambda x: x**5 - 3*x*x + 1.6 def f(x): return x**5 - 3*x*x + 1.6 x = np.arange(-1 , 1.5 , 0.1) plt.grid() plt.figure(1) plt.plot(x, f2(x)) plt.show() """ """ f = lambda x : x**5 - 3*x*x +1.6 df = lambda x : 5*x**4 - 6*x + 1e-4 d2f = lambda x : 20*x**3 - 6 + 1e-8 def NewtonRap(x0): tol = 1e-4; err = 1000 while err > tol: x1 = x0 - f(x0)/df(x0) #Metodo de Newton Primera Derivada err = np.abs(x1-x0) # Calcula las raices de la funcion x0 = x1 return x0 def NewtonRap2(x0): tol = 1e-4; err = 1000 while err > tol: x1 = x0 - df(x0)/d2f(x0) #Metodo de Newton err = np.abs(x1-x0) #Calcula los maximos y minimos de la funcion x0 = x1 return x0 x0 = NewtonRap(0) x1 = NewtonRap(1) x2 = NewtonRap(2) x3 = NewtonRap2(-1) x4 = NewtonRap2(1) x = np.arange(-1 , 1.5, 0.01) xo = np.array([x0,x1,x2]) xm = np.array([x3,x4]) print(x0,x1,x2) print(x3,x4) plt.grid() plt.figure(1) plt.plot(x, f(x)) plt.plot(xo, xo*0, 'ro') plt.plot(xm, f(xm), 'bo') plt.show() """ Dx = 1e-6 f = lambda x : x**2 + np.log(2*x + 7)*np.cos(3*x) + 0.1 df = lambda x : (f(x + Dx) - f(x - Dx)) / (2*Dx) d2f = lambda x : (f(x + 2*Dx) - 2*f(x) + f(x - 2*Dx)) / (2*Dx)**2 def NewtonRap(x0): tol = 1e-4; err = 1000 while err > tol: x1 = x0 - f(x0)/df(x0) #Metodo de Newton Primera Derivada err = np.abs(x1-x0) # Calcula las raices de la funcion x0 = x1 return x0 def NewtonRap2(x0): tol = 1e-4 err = 1000 while err > tol: x1 = x0 - df(x0)/d2f(x0) #Metodo de Newton err = np.abs(x1-x0) #Calcula los maximos y minimos de la funcion x0 = x1 return x0 x0 = NewtonRap(-0.5) x1 = NewtonRap(0.5) x2 = NewtonRap(2) x3 = NewtonRap(1.2) x4 = NewtonRap2(-1) x5 = NewtonRap2(1) x6 = NewtonRap2(0) x = np.arange(-1.5 , 2.0, 0.01) xo = np.array([x0,x1,x2,x3]) xm = np.array([x4,x5,x6]) print(x0 ,x1 ,x2 ,x3) print(x4 ,x5 ,x6) plt.grid() plt.figure(1) plt.plot(x, f(x)) plt.plot(xo, xo*0, 'ro') plt.plot(xm, f(xm), 'bo') plt.show() <file_sep>import matplotlib.pyplot as plt import numpy as np #Función : dy/dt = y - t^2 + 1 t 0 a 2 ||| y0 = 0.5 f = lambda x , y : 1/x**2 - y/x - y**2 #f = lambda x , y : (y + 1) * (x + 1) * np.cos(x**2 + 2*x) #Función lambda donde tenemos la ecuación que evaluaremos. def rk(x,y,h,xf): xarr = np.array([]) #Creamos un par de arreglos vacíos donde guardaremos los valores correspondientes en cada iteración. yarr = np.array([]) for i in np.arange(x, xf+h, h): #Ciclo for que va desde x: valor inicial de X, xf+h: el valor final de X + el aumento h para realizar las iteraciones correctas. print('x[',i,'] = ',x,' y[',i,'] = ', y) #Imprime los valores de X y Y en cada iteración. k1 = f(x , y) k2 = f(x + h/2 , y + k1 * h/2) k3 = f(x + h/2 , y + k2 * h/2) #Calculo de los valores K usando la función lambda. k4 = f(x + h , y + k3 * h) print('k1 = ',k1,' k2 = ',k2,' k3 = ',k3,' k4 = ',k4) #Imprime los valores de K. xarr = np.append(xarr,x) #Agrega los valores de X y Y al final de su respectivo arreglo. yarr = np.append(yarr,y) y += ((k1 + 2*k2 + 2*k3 + k4) / 6) * h #Sustitución del valor de Y para la siguiente iteración. x += h #Aumento de x en h return np.array([xarr, yarr]) #Regresa un arreglo creado a partir del arreglo xarr y yarr, divididos para uso individual. t = rk(1, -1, 0.05, 4) #Llamado de la función rk usando x: valor inicial x | y: valor inicial y | h: aumento | xf: valor final x xx = np.arange(1,4,0.1) plt.grid() plt.figure(1) plt.plot(t[0], t[1], xx, -1/xx, 'ro') plt.show()<file_sep>import math #Función de elevar al cuadrado def sqr(x): return(x*x) #Potencia al cubo def cubo(x): return(x*x*x) #Raíz Cúbica def rcub(x): if(x<0): return -(-x)**(1/3) return x**(1/3) # y = sqr(5-7) print("y=", y) z = rcub(0) print("z=", z) print("z =", z , "......" , cubo(z)) #Definir mi propio factorial def fact(n): f = 1 for k in range(2,n+1): f *= k return f print("F = ", fact(5)) #Funcion exponencial def exp(x): f = 1 s = 1 for k in range (1,20): f *= (x/k) s += f return s print("Exp = ", exp(5)) #Funcion seno def seno(x): f = x s = x for k in range(3, 20, 2): f *= -(sqr(x)/(k*(k-1))) s += f return s print("Seno = ", seno(.25)) #Funcion coseno def coseno(x): f = 1 s = 1 for k in range(2, 20, 2): f *= -(sqr(x)/(k*(k-1))) s += f return s print("Coseno = ", coseno(.25)) #Definicion SQRT def sqrt(n): x1 = 1 err = 10 while err > 1e-8: x2 = (x1+n/x1)/2 err = abs(x2-x1) x1 = x2 return x1 print("Raiz = ", sqrt(1.25))
716fca9ce910e105ac1afa0622231bb2b386dca8
[ "Python" ]
6
Python
Ekuuin/Codigos_matematicos
7556ded777a79f3f94d30ae735aebe71e75b7407
6b7261048c0b0c8df241c0d955f53a7a6f32f766
refs/heads/master
<repo_name>gaoyiyang/SimpleETL<file_sep>/src/main/java/org/se/SimpleEtlApplication.java package org.se; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) @RestController public class SimpleEtlApplication { public static void main(String[] args) { SpringApplication.run(SimpleEtlApplication.class, args); } @RequestMapping("/") public ModelAndView index(){ return new ModelAndView("index"); } } <file_sep>/README.md # SimpleETL 一个基于java的简单ETL工具
c9c6139ca4a463dcab47d2c2999f4ad82c308ef4
[ "Markdown", "Java" ]
2
Java
gaoyiyang/SimpleETL
3da4fdee716ccd0c72c6cedef14282763b7a67b3
546214741bb37cfde3cec80f5289b9f12de13cfa
refs/heads/master
<repo_name>michaelmorrisg/phppractice<file_sep>/Site2/Random_info.php <?php $people = ["Kerry", "Ted", "Chris"] ?><file_sep>/Site2/index.php <?php include "./Random_info.php" ?> <?php if(isset($_GET["name"])){ echo $_GET["name"]; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h1>My Friends</h1> <?php foreach($people as $person): ?> <li> <?php echo $person . " is cool"; ?> </li> <?php endforeach; ?> <form method="GET" action="index.php"> <input name="name"/> <input type="submit" value="Submiter"/> </form> <?php $randomThings = [1,3, "3", "december", "crazy", " "]; foreach($randomThings as $randomThing){ if (is_string($randomThing)){ echo $randomThing . "is a string <br/>"; } } ?> <?php $loggedIn = false ?> <?php if($loggedIn) { ?> <h1>Welcome Man!</h1> <?php }?> <?php $email = $_POST['email']; $newName = $_POST['name']; echo $email; echo $newName; ?> <form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>"> <input type="text" name="email"/> <input type="text" name="name"/> <input value="Submit" type="submit"/> </form> </body> </html><file_sep>/arrays.php <?php $people = array('Doggo', 'Froggo', 'Todd'); echo $people[0]; $people[] = "add me"; //adds to the end of the array (like .push in js) echo $people[3]; $associative = array('Key' => 'value', "Another Key" => 'another value'); echo $associative['Key'] ?><file_sep>/variables.php <?php //echo just prints stuff to the screen echo "Hey there <br/>"; $output = "Sup sup"; echo $output . "<br/>"; $first = "Hi "; $second = "guys."; $greeting = $first . $second; echo "$greeting $second"; ?>
47123cf48505708c48555345c8397ac591623459
[ "PHP" ]
4
PHP
michaelmorrisg/phppractice
7477d0061f959b69200e0c48126c53713ac4479e
19469552739ea881f629e35e472e083c2bdac6c1
refs/heads/master
<repo_name>tworespect/freemarket_sample_38a<file_sep>/app/models/product.rb class Product < ApplicationRecord belongs_to :order, optional: true belongs_to :user has_many :images, dependent: :destroy has_many :product_sizes, dependent: :destroy has_many :product_brands, dependent: :destroy has_many :product_categories, dependent: :destroy has_many :product_page_comments, dependent: :destroy has_many :sizes, through: :product_sizes has_many :brands, through: :product_brands has_many :categories, through: :product_categories accepts_nested_attributes_for :images, allow_destroy: true accepts_nested_attributes_for :product_sizes, allow_destroy: true accepts_nested_attributes_for :product_brands, allow_destroy: true accepts_nested_attributes_for :product_categories, allow_destroy: true validates :user_id, presence: true validates :images, presence: true validates :name, presence: true, length: { maximum: 40 } validates :price, presence: true, numericality: { greater_than_or_equal_to: 300, less_than_or_equal_to: 9999999 } validates :status, presence: true validates :freight, presence: true, numericality: { greater_than: 0 } validates :state_of_goods, presence: true, numericality: { greater_than: 0 } validates :description, presence: true, length: { maximum: 1000 } validates :ship_method, presence: true, numericality: { greater_than: 0 } validates :ship_from_location, presence: true, numericality: { greater_than: 0 } validates :ship_day, presence: true, numericality: { greater_than: 0 } end <file_sep>/spec/factories/products.rb FactoryBot.define do factory :product do price 30000 freight 1 state_of_goods 1 description "aaa" name "bbb" status 0 ship_method 1 ship_from_location 1 ship_day 1 user created_at { Faker::Time.between(2.days.ago, Time.now, :all) } end end <file_sep>/app/models/payment.rb class Payment < ApplicationRecord belongs_to :user validates :payjp_customer_id, uniqueness: true, presence: true end <file_sep>/app/controllers/concerns/charge.rb module Charge extend ActiveSupport::Concern def create_charge(price, customer_id) Payjp.api_key = ENV["PAYJP_PRIVATE_KEY"] charge = Payjp::Charge.create( :amount => price, :customer => customer_id, :currency => 'jpy', ) end end <file_sep>/spec/models/user_spec.rb require 'rails_helper' RSpec.describe User, type: :model do describe '#create' do context 'can save' do it 'is valid with a name, email, password, password_confirmation' do user = build(:user) expect(user).to be_valid end end context 'can not save' do it "is invalid without a name" do user = build(:user, name: nil) user.valid? expect(user.errors[:name]).to include("can't be blank") end it "is invalid without a email" do user = build(:user, email: nil) user.valid? expect(user.errors[:email]).to include("can't be blank") end it "is invalid without a password" do user = build(:user, password: nil) user.valid? expect(user.errors[:password]).to include("can't be blank") end it "is invalid without a password_confirmation" do user = build(:user, password_confirmation: nil) user.valid? expect(user.errors[:password_confirmation]).to include("can't be blank") end it "is invalid with a duplicate email address" do User.create( name: "Joe", email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", ) another_user = User.new( name: "Jane", email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", ) another_user.valid? expect(another_user.errors[:email]).to include("has already been taken") end it "is Invalid if it is 5 characters or less password" do user = build(:user, password: "<PASSWORD>", password_confirmation: "<PASSWORD>") user.valid? expect(user.errors[:password]).to include("is too short (minimum is 6 characters)") end it "is Invalid if it is 129 characters or over password" do over = "a" * 129 user = build(:user, password: <PASSWORD>, password_confirmation: <PASSWORD>) user.valid? expect(user.errors[:password]).to include("is too long (maximum is 128 characters)") end it "is Invalid if Including at least alphanumeric characters" do user = build(:user, password: "<PASSWORD>", password_confirmation: "<PASSWORD>") user.valid? expect(user.errors[:password]).to include("is invalid") end it "is invalid without a password_confirmation" do user = build(:user, password: "<PASSWORD>",password_confirmation: "" ) user.valid? expect(user.errors[:password_confirmation]).to include("doesn't match Password") end end end end <file_sep>/config/breadcrumbs.rb crumb :root do link "メルカリ", root_path end crumb :users do link "マイページ", user_path(current_user) parent :root end crumb :users_logout do link "ログアウト" parent :users end crumb :users_card do link "支払い方法",new_user_card_path parent :users end crumb :users_card_new do link "クレジットカード情報入力" parent :users_card end crumb :products do |product| link "#{ product.name }" parent :root end <file_sep>/app/models/brand.rb class Brand < ApplicationRecord has_many :product_brands has_many :products, through: :product_brands end <file_sep>/db/migrate/20181116054618_create_images.rb class CreateImages < ActiveRecord::Migration[5.2] def change create_table :images do |t| t.references :product, foreign_key: true t.string :first_image, null: false t.string :second_image t.string :third_image t.string :forth_image t.timestamps end end end <file_sep>/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) # coding: utf-8 Category.create(:name => '衣服', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'ホビー', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => '家電', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'レディース', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'メンズ', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'キッズ', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'おもちゃ', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'スポーツ', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => '乗り物', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'PC', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => '生活家電', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'カメラ', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'トップス', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'パンツ', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => '小物', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'ドール・プラモ', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'ラジコン', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => '楽器', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => '野球', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'サッカー', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'バスケ', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => '自動車', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => '自転車', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'バイク', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'タブレット', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'ノートPC', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'パーツ', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => '電子レンジ', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'TV', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => '洗濯機', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'デジカメ', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'ビデオカメラ', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Category.create(:name => 'レンズ', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Brand.create(:name => 'シャネル', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Brand.create(:name => 'ナイキ', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Brand.create(:name => 'ルイヴィトン', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Brand.create(:name => 'シュプリーム', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Brand.create(:name => 'ユニクロ', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Brand.create(:name => 'ZARA', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Brand.create(:name => 'アディダス', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Brand.create(:name => 'ミズノ', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Brand.create(:name => 'アシックス', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Brand.create(:name => 'Butterfly', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') Brand.create(:name => 'その他', :created_at => '0000-00-00 00:00:00', :updated_at => '0000-00-00 00:00:00') <file_sep>/app/controllers/concerns/card.rb module Card extend ActiveSupport::Concern def create_customer Payjp.api_key = ENV['PAYJP_PRIVATE_KEY'] year = "20" + params[:exp_year] token = Payjp::Token.create({ card: { number: params[:number], cvc: params[:cvc], exp_month: params[:exp_month], exp_year: year, name: params[:name] }}, { 'X-Payjp-Direct-Token-Generate': 'true' } ) Payjp::Customer.create(card: token.id).id end end <file_sep>/spec/controllers/products_controller_spec.rb require 'rails_helper' describe ProductsController, type: :controller do describe 'GET #index' do it "populates an array of products ordered by id DESC" do products = create_list(:product,4) get :index expect(assigns(:products)).to match(products.sort{ |a, b| b.id <=> a.id }) end it "renders the :index template" do get :index expect(response).to render_template :index end end end <file_sep>/app/assets/javascripts/error.js $(function() { var list = $('li').text(); if(list.includes("Name can't be blank")){ $('.name-error').css('display','inherit'); } if(list.includes("Email can't be blank")){ $('.email-error').css('display','inherit'); } if(list.includes("Password can't be blank")){ $('.password-error').css('display','inherit'); $('.password-error-message').css('display','inherit'); } if(list.includes("Password is too short (minimum is 6 characters)")){ $('.password-error-message').css('display','inherit'); } if(list.includes("Password confirmation can't be blank")){ $('.password_confirmation-error').css('display','inherit'); } if(list.includes("Password confirmation doesn't match Password")){ $('.no-match-error').css('display','inherit'); } if(list.includes("Email has already been taken")){ $('.already-taken').css('display','inherit'); } if(list.includes("Password is invalid")){ $('.no-number-only').css('display','inherit'); } if($('div').hasClass('email-pass-error')){ $('.email-login-error').css('display','inherit'); $('.password-login-error').css('display','inherit'); $('.password-login-error-message').css('display','inherit'); } }); <file_sep>/app/controllers/card_controller.rb class CardController < ApplicationController include Card def index @payment = Payment.find_by(user_id: current_user.id) Payjp.api_key = ENV['PAYJP_PRIVATE_KEY'] @mycard = Payjp::Customer.retrieve(current_user.payments.first.payjp_customer_id).cards.data[0] if current_user.payments.present? end def new end def create unless current_user.payments.present? customer_id = create_customer @payment = Payment.find_or_initialize_by(user_id: current_user.id) @payment.payjp_customer_id = customer_id if @payment.save redirect_to user_path(current_user.id) else render :new end else render :index end end def destroy @payment = Payment.find_by(user_id: current_user.id) @payment.destroy redirect_to user_path(current_user.id) end private def payment_params params.permit(:payment).permit(:user_id, :customer_id) end end <file_sep>/README.md # README ## social_profilesテーブル |column|Type|Options| |------|----|-------| |provider|string|null: false| |uid|string|null: false, unique: true| |token|string|| |nickname|string|| |email|varchar|| ### Association - belongs_to :user ## usersテーブル |column|Type|Options| |------|----|-------| |nickname|string|null: false, unique: true, index: true| |image|text|| |text|text|| ### Association - belongs_to :social_profile - belongs_to :user_detail - belongs_to :point - belongs_to :credit_card - belongs_to :deposit - belongs_to :rate - belongs_to :address - belongs_to :birthday - has_many :products - has_many :users_news - has_many :notices - has_many :todos - has_many :news - has_many :transaction_comments - has_many :product_page_comments - has_many :likes - has_many :orders ## noticesテーブル |column|Type|Options| |------|----|-------| |from_user_id|integer|null: false, foreign_key: true| |to_user_id|integer|null: false, foreign_key: true| |text|text|null: false| ### Association - belongs_to :user ## todosテーブル |column|Type|Options| |------|----|-------| |user_id|integer|null: false, foreign_key: true| |text|text|null: false| ### Association - belongs_to :user ## news_usersテーブル |column|Type|Options| |------|----|-------| |user_id|integer|null: false, foreign_key: true| |news_id|integer|null: false, foreign_key: true| ### Association - belongs_to :user - belongs_to :news ## newsテーブル |column|Type|Options| |------|----|-------| |title|text|null: false| |text|text|null: false| |personal|integer|| ### Association - has_many :users, through: news_users - has_many :news_users - accepts_nested_attributes_for :news_users ## ratesテーブル |column|Type|Options| |------|----|-------| |user_id|integer|null: false, foreign_key: true| |user_detail_id|integer|null: false, foreign_key: true| |rating|integer|null: false| ### Association - belongs_to :user - belongs_to :user_detail ## user_detailsテーブル |column|Type|Options| |------|----|-------| |user_id|integer|null: false, foreign_key: true| |first_name_kanji|string|null: false| |last_name_kanji|string|null: false| |first_name_kana|string|null: false| |last_name_kana|string|null: false| |payment|integer|| ### Association - belongs_to :user ## depositsテーブル |column|Type|Options| |------|----|-------| |user_id|integer|null: false, foreign_key: true| |proceeds|integer|| ### Association - belongs_to :user - belongs_to :banks ## banksテーブル |column|Type|Options| |------|----|-------| |deposit_id|integer|null: false, foreign_key: true| |bank_name|string|null: false| |type|string|null: false| |branch_code|string|null: false| |account_number|string|null: false| |first_name_kana|string|null: false| |last_name_kana|string|null: false| ### Association - belongs_to :deposit ## credit_cardsテーブル |column|Type|Options| |------|----|-------| |user_id|integer|null: false, foreign_key: true| |main_number|string|null: false| |month|integer|null: false| |year|integer|null: false| |security_code|integer|null: false| ### Association - belongs_to :user ## pointsテーブル |column|Type|Options| |------|----|-------| |user_id|integer|null: false, foreign_key: true| |point_365|integer|| |point_180|integer|| |effective_term|string|null: false| ### Association - belongs_to :user ## addressesテーブル |column|Type|Options| |------|----|-------| |user_id|integer|null: false, foreign_key: true| |postal_code|string|null: false| |prefecture|text|null: false| |city|text|null: false| |street_address|text|null: false| |building|text|| |phone|string|| ### Association - belongs_to :user ## birthdaysテーブル |column|Type|Options| |------|----|-------| |user_id|integer|null: false, foreign_key: true| |birth_year|integer|| |birth_month|integer|| |birth_year|integer|| ### Association - belongs_to :user ## productsテーブル |column|Type|Options| |------|----|-------| |user_id|integer|null: false, unique: true, index: true| |name|string|null: false| |price|integer|null: false| |satatus|string|null: false| ### Association - belongs_to :product_detail - belongs_to :order - belongs_to :user - belongs_to :delivery - belongs_to :image - belongs_to :product_detail_brand - belongs_to :product_detail_category - has_many :transaction_comments - has_many :product_page_comments - has_many :likes ## product_detailsテーブル |column|Type|Options| |------|----|-------| |product_id|integer|null: false, foreign_key: true| |state_of_goods|text|null: false| |freight|integer|null: false| |description|text|null: false| |size|string|| ### Association - belongs_to :product ## imagesテーブル |column|Type|Options| |------|----|-------| |product_id|integer|null: false, foreign_key: true| |first_image|text|null: false| |second_image|text|| |third_image|text|| |forth_image|text|| ### Association - belongs_to :product ## deliveriesテーブル |column|Type|Options| |------|----|-------| |product_id|integer|null: false, foreign_key: true| |ship_method|string|null: false| |ship_form_location|string|null: false| |ship_day|string|null: false| ### Association - belongs_to :product ## products_brandsテーブル |column|Type|Options| |------|----|-------| |product_detail_id|integer|null: false, foreign_key: true| |brand_id|integer|null: false, foreign_key: true| ### Association - belongs_to :product - belongs_to :brand ## brandsテーブル |column|Type|Options| |------|----|-------| |name|string|null: false, index: true| ### Association - has_many :products_brands ## products_categoriesテーブル |column|Type|Options| |------|----|-------| |product_id|integer|null: false, foreign_key: true| |category_id|integer|null: false, foreign_key: true| ### Association - belongs_to :product - belongs_to :category ## categoriesテーブル |column|Type|Options| |------|----|-------| |name|string|null: false, index: true| ### Association - has_many :products_categories ## transaction_commentsテーブル |column|Type|Options| |------|----|-------| |product_id|integer|null: false, foreign_key: true| |user_id|integer|null: false, foreign_key: true| |text|text|null: false| ### Association - belongs_to :product - belongs_to :user ## product_page_commentsテーブル |column|Type|Options| |------|----|-------| |product_id|integer|null: false, foreign_key: true| |user_id|integer|null: false, foreign_key: true| |text|text|null: false| ### Association - belongs_to :product - belongs_to :user ## likesテーブル |column|Type|Options| |------|----|-------| |product_id|integer|null: false, foreign_key: true| |user_id|integer|null: false, foreign_key: true| ### Association - belongs_to :product - belongs_to :user ## ordersテーブル |column|Type|Options| |------|----|-------| |product_id|integer|null: false, foreign_key: true| |user_id|integer|null: false, foreign_key: true| ### Association - belongs_to :product - belongs_to :user This README would normally document whatever steps are necessary to get the application up and running. Things you may want to cover: * Ruby version * System dependencies * Configuration * Database creation * Database initialization * How to run the test suite * Services (job queues, cache servers, search engines, etc.) * Deployment instructions * ... <file_sep>/app/assets/javascripts/channels/exhibit_page/exhibit_page_columns.js $(function(){ $('.block--product_detail--right__categories--first').on('change', function(){ $('.block--product_detail--right__categories--second').css('display','inherit'); if($('#product_product_categories_attributes_0_category_id').val() == "0" ){ $('.block--product_detail--right__categories--second').css('display','none'); $('.block--product_detail--right__categories--third').css('display','none'); $('.block--product_detail--right__size').css('display','none'); $('.block--product_detail--right__brand').css('display','none'); } $('.block--product_detail--right__categories--second').on('change', function(){ $('.block--product_detail--right__categories--third').css('display','inherit'); if($('#product_product_categories_attributes_1_category_id').val() == "0" ){ $('.block--product_detail--right__categories--third').css('display','none'); $('.block--product_detail--right__size').css('display','none'); $('.block--product_detail--right__brand').css('display','none'); } $('.block--product_detail--right__categories--third').on('change', function(){ $('.block--product_detail--right__size').css('display','inherit'); $('.block--product_detail--right__brand').css('display','inherit'); if($('#product_product_categories_attributes_2_category_id').val() == "0" ){ $('.block--product_detail--right__size').css('display','none'); $('.block--product_detail--right__brand').css('display','none'); } }); }); }); $('#product_freight').on('change', function(){ $('.block--about_ship--right__method').css('display','inherit'); if($('#product_freight').val() == "0"){ $(".block--about_ship--right__method").css('display','none'); } }); }) <file_sep>/app/controllers/products_controller.rb class ProductsController < ApplicationController include Charge before_action :set_product, only: [:show, :destroy, :completion] before_action :set_product, only: [:show, :edit, :update, :destroy] def index @products = Product.order("id DESC").includes(:images, :categories) end def new @product = Product.new @product.product_sizes.build @product.product_brands.build @product.product_categories.build @product.images.build end def create @product = Product.new(product_params) if @product.save redirect_to products_path else @products = @product render :new end end def show @pre_product = Product.order("RAND()").limit(1) @post_product = Product.order("RAND()").limit(1) @page_host_products = Product.where(user_id: @product.user_id) end def edit @product_categories = @product.product_categories end def update if @product.update(product_params) redirect_to products_path else redirect_to edit_product_path end end def destroy if @product.destroy redirect_to products_path else redirect_to product_path end end def buy @product = Product.find(params[:product_id]) Payjp.api_key = ENV['PAYJP_PRIVATE_KEY'] @mycard = Payjp::Customer.retrieve(current_user.payments.first.payjp_customer_id).cards.data[0] if current_user.payments.present? end def pay @product = Product.find(params[:product_id]) @payment = Payment.find_by(user_id: current_user.id) create_charge(@product.price, @payment.payjp_customer_id) @product.update(status: 1) end private def product_params params.require(:product).permit(:name, :price, :freight, :state_of_goods, :description, :ship_method, :ship_from_location, :ship_day, product_sizes_attributes:[:id, :size_id], product_brands_attributes:[:id, :brand_id], product_categories_attributes:[:id, :category_id], images_attributes:[:id, :first_image, :second_image, :third_image, :forth_image]).merge(status: 0, user_id: current_user.id) end def set_product @product = Product.find(params[:id]) end end <file_sep>/app/models/size.rb class Size < ApplicationRecord has_many :product_sizes has_many :products, through: :product_sizes end <file_sep>/app/assets/javascripts/channels/exhibit_page/auto_calculation.js $(function(){ function getOthers(num){ if ( num >= 300 && num < 10000000){ num_01 = Number(num * 0.1) num_01_floor = Math.floor( num_01 ) num_09 = Number( num - num_01_floor ) num_09_floor = Math.floor( num_09 ) $('.block--price--right__commissions--right').empty(); $('.block--price--right__commissions--right').prepend("¥").append(num_01_floor.toLocaleString()); $('.block--price--right__proceeds--right').empty(); $('.block--price--right__proceeds--right').prepend("¥").append(num_09_floor.toLocaleString()); } if ( num < 300 || num >= 10000000){ $('.block--price--right__commissions--right').empty(); $('.block--price--right__commissions--right').append("-"); $('.block--price--right__proceeds--right').empty(); $('.block--price--right__proceeds--right').append("-"); } } $('#product_price').on('keyup', function(){ var num = $('#product_price').val(); getOthers(num) }) $('#product_price').on('blur', function(){ var num = $('#product_price').val(); num = num.replace( /[0-9]/g, function(s) { return String.fromCharCode(s.charCodeAt(0) - 65248); }); $('#product_price').val(num); getOthers(num) }).change(); }) <file_sep>/app/models/product_brand.rb class ProductBrand < ApplicationRecord belongs_to :product belongs_to :brand end <file_sep>/app/assets/javascripts/channels/exhibit_page/exhibit_page_brand.js $(function(){ var input = $(".medium_box__text").val(); var search = $('.block--product_detail--right__brand__candidate'); var register = $('.block--product_detail--right__brand'); function appendName(brand){ var html = `<div class="block--product_detail--right__brand__candidate__list" id="candidate${ brand.id }"> <a class="brand-search-add${ brand.id } block--product_detail--right__brand__candidate__list__each" data-brand-id="${ brand.id }"> ${ brand.name } </a> </div>` search.append(html); } function appendNoName(text){ var html = `<div class="block--product_detail--right__brand__candidate__list"> <a class="brand-search-add block--product_detail--right__brand__candidate__list__each"> ${ text } </a> </div>` search.append(html); } function registerName(brand){ var brand_name = $(`.brand-search-add${ brand.id }`).text() var brand_id = $(`.brand-search-add${ brand.id }`).attr('data-brand-id') $('.medium_box__text').val(''); $('.medium_box__text').val( brand_name ) $('.medium_box__input').val( brand_id ) $('.block--product_detail--right__brand__candidate').css('display','none'); } $(".medium_box__text").on('keyup', function(brand){ $('.medium_box--brand__input').val('') var input = $(".medium_box__text").val(); $.ajax({ type: 'GET', url: ('/brands/index'), data: { keyword: input }, dataType: 'json', }) .done(function(brands){ $('.block--product_detail--right__brand__candidate').css('display','inherit'); $(`.block--product_detail--right__brand__candidate__list`).remove(); if ( brands.length !== 0 ) { brands.forEach(function(brand){ appendName(brand); $(`#candidate${ brand.id }`).on('mouseover', function(){ $(`.brand-search-add${ brand.id }`).css('font-weight','bold').css('color','white') $(`#candidate${ brand.id }`).css('background-color','#0099e8') $(`#candidate${ brand.id }`).on('mouseout', function(){ $(`.brand-search-add${ brand.id }`).css('font-weight','normal').css('color','black') $(`#candidate${ brand.id }`).css('background-color','white') }) }) $(`#candidate${ brand.id }`).on('click', function(){ registerName(brand) }) }) } else { appendNoName("一致するブランドはありません"); } }) .fail(function() { alert('ブランド検索に失敗しました'); }) }) }) <file_sep>/app/models/image.rb class Image < ApplicationRecord belongs_to :product mount_uploader :first_image, ImageUploader mount_uploader :second_image, ImageUploader mount_uploader :third_image, ImageUploader mount_uploader :forth_image, ImageUploader end <file_sep>/config/routes.rb Rails.application.routes.draw do devise_for :users root "products#index" get "users/logout" => "users#logout" get "brands/index" => "brands#index" resources :users, only: [:index, :show, :edit, :update, :new] do resources :card, only: [:index, :new, :create, :destroy] end resources :products do resources :page_comments, only: [:create] get "buy" => "products#buy" post "buy" => "products#pay", as: 'pay' get "completion" => "products#completion" end end <file_sep>/db/migrate/20181121033314_create_product_brands.rb class CreateProductBrands < ActiveRecord::Migration[5.2] def change create_table :product_brands do |t| t.references :product, foreign_key: true t.references :brand, foreign_key: true t.timestamps end end end <file_sep>/app/models/user.rb class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :products has_many :payments validates :name, presence: true VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/ validates :email, presence: true, uniqueness: true, format: { with: VALID_EMAIL_REGEX } VALID_PASSWORD_REGEX = /\A(?=.*?[a-z])(?=.*?\d)[a-z\d]{6,128}+\z/i validates :password, presence: true, format: { with: VALID_PASSWORD_REGEX } validates :password_confirmation, presence: true end
dbb5401ebef50228494a896b8784fb6f2178f5ad
[ "JavaScript", "Ruby", "Markdown" ]
24
Ruby
tworespect/freemarket_sample_38a
67d065f122442accb8b22c222ae7f1e8b914b27e
e013db58fa39610214989fb69b1abb5dee6309f4
refs/heads/master
<file_sep><?php echo "Hello World"; echo "local"; ?> <file_sep># hello-world use for test git connect to github first branch and first commit. 加油! README.md 文件的内容 会自动显示在仓库的首页当中。因此,人们一般会在这个文件中标明本 仓库所包含的软件的概要、使用流程、许可协议等信息。如果使用 Markdown 语法进行描述,还可以添加标记,提高可读性。 - fix-B - feature-C
5bde5e0ca40d3f782b0ffc2dfedb5569de0ab006
[ "Markdown", "PHP" ]
2
PHP
guobool/hello-world
47a7aed8f0bbfd1a3b4861c6a4260b153a1c7a06
cfee912cad0b94b873ce9ee8d915c8b6f01e9723
refs/heads/master
<repo_name>bs1in/backend<file_sep>/src/main/java/de/bs1/Inventarisierung/Controller/TicketController.java package de.bs1.Inventarisierung.Controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import de.bs1.Inventarisierung.Repos.DeviceRepository; import de.bs1.Inventarisierung.Repos.TicketRepository; import de.bs1.Inventarisierung.model.Device; import de.bs1.Inventarisierung.model.Ticket; import de.bs1.Inventarisierung.model.TicketDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.Optional; @RestController public class TicketController { private final TicketRepository ticketRepository; private final DeviceRepository deviceRepository; private final ObjectMapper objectMapper = new ObjectMapper(); @Autowired public TicketController(TicketRepository ticketRepository, DeviceRepository deviceRepository) { this.ticketRepository = ticketRepository; this.deviceRepository = deviceRepository; objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } @ResponseBody @RequestMapping(value = "/api/tickets", method = RequestMethod.GET) private List<TicketDTO> getAllTicket() { List<Ticket> tickets = ImmutableList.copyOf(ticketRepository.findAll()); List<TicketDTO> dtos = new ArrayList<>(); for (Ticket t : tickets) { dtos.add(new TicketDTO(t.getId(), t.getDevice().getId(), t.getDescription(), t.isDone())); } return dtos; } @RequestMapping(value = "/api/tickets/{id}", method = RequestMethod.GET) @ResponseBody public TicketDTO getTicketByID(@PathVariable("id") Long id) { Optional<Ticket> ticket = ticketRepository.findById(id); if (ticket.isPresent()) { Ticket t = ticket.get(); return new TicketDTO(t.getId(), t.getDevice().getId(), t.getDescription(), t.isDone()); } return null; } @RequestMapping(value = "/api/tickets/{id}", method = RequestMethod.PUT) @ResponseBody public TicketDTO updateTicketByID(@PathVariable("id") Long id, @RequestBody TicketDTO requestTicket) { Optional<Ticket> ticket = ticketRepository.findById(id); Optional<Device> device = deviceRepository.findById(requestTicket.getDevice()); if (ticket.isPresent() && device.isPresent()) { Ticket t = new Ticket(device.get(), requestTicket.getDescription(), requestTicket.isDone()); t = ticketRepository.save(t); return new TicketDTO(t.getId(), t.getDevice().getId(), t.getDescription(), t.isDone()); } return null; } @RequestMapping(value = "/api/tickets", method = RequestMethod.POST) private TicketDTO insertTicket(@RequestBody TicketDTO requestTicket) { Optional<Device> device = deviceRepository.findById(requestTicket.getDevice()); if (device.isPresent()) { Ticket ticket = new Ticket(device.get(), requestTicket.getDescription(), requestTicket.isDone()); ticket = ticketRepository.save(ticket); requestTicket.setId(ticket.getId()); return requestTicket; } return null; // try { //Ticket ticket = null; //ticket = objectMapper.readValue(requestTicket, Ticket.class); // return ticketRepository.save(requestTicket); // } catch (IOException e) { // e.printStackTrace(); // return null; // } } } <file_sep>/src/main/java/de/bs1/Inventarisierung/Repos/DeviceRepository.java package de.bs1.Inventarisierung.Repos; import de.bs1.Inventarisierung.model.Device; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.Repository; import java.util.List; public interface DeviceRepository extends CrudRepository<Device, Long>{ } <file_sep>/src/main/java/de/bs1/Inventarisierung/InventarisierungApplication.java package de.bs1.Inventarisierung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class InventarisierungApplication { public static void main(String[] args) { SpringApplication.run(InventarisierungApplication.class, args); } } <file_sep>/src/main/java/de/bs1/Inventarisierung/model/Device.java package de.bs1.Inventarisierung.model; import javax.persistence.*; import java.util.HashMap; import java.util.Map; import java.util.Set; @Entity public class Device { @Id @Column(name = "id",nullable = false, unique = true) @GeneratedValue(strategy = GenerationType.AUTO, generator = "default_gen") private long id; @Column(name = "name", nullable = false) private String name = ""; @Column(name = "description", nullable = false) private String description = ""; /*@Column(name = "attributes", nullable = false) private Map<String, String> attributes = new HashMap<String, String>();*/ @ManyToOne private Location location = new Location("Kein Ort", ""); public Device(long id, String name, String description, /*Map<String, String> attributes,*/ Location location) { this.id = id; this.name = name; this.description = description; /*this.attributes = attributes;*/ this.location = location; } public Device() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } /* public Map<String, String> getAttributes() { return attributes; } public void setAttributes( Map<String, String> attributes) { this.attributes = attributes; }*/ public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } } <file_sep>/src/main/java/de/bs1/Inventarisierung/model/TicketDTO.java package de.bs1.Inventarisierung.model; public class TicketDTO { private long device; private long id; private String description; private boolean done; public TicketDTO() { } public TicketDTO(long id, long device, String description, boolean done) { this.device = device; this.id = id; this.description = description; this.done = done; } public long getDevice() { return device; } public void setDevice(long device) { this.device = device; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isDone() { return done; } public void setDone(boolean done) { this.done = done; } } <file_sep>/src/main/resources/data.sql Insert into devices (name, description) values ("test", "description"); Insert into devices (name, description) values ("test1", "description1"); Insert into devices (name, description) values ("test2", "description2");<file_sep>/src/main/java/de/bs1/Inventarisierung/Repos/LocationRepository.java package de.bs1.Inventarisierung.Repos; import de.bs1.Inventarisierung.model.Location; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.Repository; public interface LocationRepository extends CrudRepository<Location, Long> { }
5e45df14b6b88f24f75fe62c42118d67ed266752
[ "Java", "SQL" ]
7
Java
bs1in/backend
238ff77faab64c2797a63a9ec16e0cab6eb4d197
0c011e8a824736746aed372b25fd482834f846c3
refs/heads/master
<file_sep>public struct Engine { public var model:String public init(model:String){ self.model = model } } <file_sep>import XCTest @testable import EngineTests XCTMain([ testCase(EngineTests.allTests), ])
c058a47d9455ecf251fbbeb42ab729ed7b89944e
[ "Swift" ]
2
Swift
SwwGit/Engine
8a2fa784c4524657c5875f1d6746ec07b82ad347
9be17e01330ec9800540e7fbd6aad80d618845f0
refs/heads/master
<file_sep>import RPi.GPIO as GPIO import time GPIO.setmode (GPIO.BOARD) GPIO.setup (12, GPIO.OUT) GPIO.output (12, 0) GPIO.output (12, 1) time.sleep(10) GPIO.cleanup()
3c70d878ab4cda8550a8bd181d4b15f551b54bcb
[ "Python" ]
1
Python
rfair404/WP-REST-RASPBERRY-PI
967ccde0c4a178067795aaebcdeccfe2d057c525
6926efb1524b2fab307882690e98ea6c7a1dd891
refs/heads/master
<repo_name>fishfather/service<file_sep>/MavenPro/KafkaSpringboot/src/main/java/com/jw/kafka/Consumer.java package com.jw.kafka; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.kafka.support.Acknowledgment; import org.springframework.kafka.support.KafkaHeaders; import org.springframework.messaging.handler.annotation.Header; import org.springframework.stereotype.Component; import java.util.Optional; @Component public class Consumer { @KafkaListener(topics = "test-topic1", groupId="group3") public void consumer(ConsumerRecord<String, Object> consumerRecord) { System.out.println("Start to consumer..........."); Optional<Object> kafkaMassage = Optional.ofNullable(consumerRecord.value()); if (kafkaMassage.isPresent()) { Object o = kafkaMassage.get(); System.out.println("Consume:"+ o); } } } <file_sep>/MavenPro/Java-Test/src/main/java/com/thread/lock/TicketTest.java package com.thread.lock; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; public class TicketTest { public static void main(String[] args) { Ticket ticket = new Ticket(); Thread t1 = new Thread(ticket); Thread t2 = new Thread(ticket); Thread t3 = new Thread(ticket); Thread t4 = new Thread(ticket); Thread t5 = new Thread(ticket); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); } } class Ticket implements Runnable { private int tickets = 1000; private ReentrantLock lock = new ReentrantLock(); @Override public void run() { for (; ; ) { lock.lock(); try { if (tickets == 0) break; try { TimeUnit.MICROSECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " Sale ticket " + tickets); tickets--; } finally { lock.unlock(); } } } }<file_sep>/MavenPro/Java-Test/src/main/java/com/thread/wait/NotifyAllTest.java package com.thread.wait; public class NotifyAllTest { public static void main(String[] args) throws InterruptedException { Object obj = new Object(); Container c = new Container(2); new Thread(()->{ synchronized (obj){ System.out.println(Thread.currentThread().getName() + ": start."); try { obj.wait(); System.out.println(Thread.currentThread().getName() + ": get notified with len:"+c.len); if(c.len>=0){ c.len--; } } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ": end."); } }).start(); new Thread(()->{ synchronized (obj){ System.out.println(Thread.currentThread().getName() + ": start."); try { obj.wait(); System.out.println(Thread.currentThread().getName() + ": get notified with len:"+c.len); if(c.len>=0){ c.len--; } } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ": end."); } }).start(); new Thread(()->{ synchronized (obj){ System.out.println(Thread.currentThread().getName() + ": start."); // obj.notify(); c.len --; obj.notifyAll(); System.out.println(Thread.currentThread().getName() + ": end."); } }).start(); Thread.sleep(10000); System.out.println("Complete"); } static class Container{ int len = 0; Container(int len){ this.len = len; } } } <file_sep>/MavenPro/Java-Test/src/main/java/com/datastructure/AVLTree.java package com.datastructure; class Node{ Node left, right; int data; int height = 0; Node(){} Node(int data){ this.data = data; } @Override public String toString() { return "Node{" + "data=" + data + ", height=" + height + '}'; } } public class AVLTree { Node root; public AVLTree(){ this.root = null; } public Node getRoot(){ return root; } public int treeHeight(){ if(root == null) return 0; return root.height + 1; } public void insert(int data){ //insert always start from root this.root = insert(root, data); } public Node search(int data){ Node findNode = root; while(findNode!=null && findNode.data != data){ if(data < findNode.data){ findNode = findNode.left; }else{ findNode = findNode.right; } } return findNode; } private Node insert(Node n, int data){ if(n == null){ n = new Node(data); return n; } if(data < n.data){ //insert node to left n.left = insert(n.left, data); if(height(n.left) - height(n.right) == 2){ if(data < n.left.data){ n = rightRotate(n); }else{ n = doubleLeftRotateRightRotate(n); } } }else if( data > n.data){ n.right = insert(n.right, data); if(height(n.right) - height(n.left) == 2){ if(data > n.right.data){ n = leftRotate(n); }else{ n = doubleRightRotateLeftRotate(n); } } }else{ //insert a exist data, do nothing } resetNodeHeight(n); return n; } private Node doubleRightRotateLeftRotate(Node n) { Node right = rightRotate(n.right); n.right = right; return leftRotate(n); } // private Node shiftRigthChild(Node n) { // Node left = n.left; // n.left = left.right; // left.right = n; // resetNodeHeight(n); // resetNodeHeight(left); // return left; // } private Node leftRotate(Node n) { Node right = n.right; n.right = right.left; right.left = n; resetNodeHeight(n); resetNodeHeight(right); return right; } private Node doubleLeftRotateRightRotate(Node n) { Node left = leftRotate(n.left); n.left = left; return rightRotate(n); } // private Node shiftLeftChild(Node n) { // Node right = n.right; // n.right = right.left; // right.left = n; // resetNodeHeight(n); // resetNodeHeight(right); // return right; // } private Node rightRotate(Node n) { Node leftChild = n.left; n.left = leftChild.right; leftChild.right = n; resetNodeHeight(n); resetNodeHeight(leftChild); return leftChild; } private void resetNodeHeight(Node n){ n.height = Math.max(height(n.left) , height(n.right)) + 1; } private int height(Node n) { return n == null ? -1: n.height; } public void preSort(){ preSort(this.root); } private void preSort(Node node) { if(node != null){ System.out.print(" "+node.data); preSort(node.left); preSort(node.right); } } public void delete(int data){ if(root == null) return; this.root = _deleteNode(root, data); } private Node _deleteNode(Node n, int data){ if(n == null) return null; if (data < n.data) { //delete left n.left = _deleteNode(n.left, data); if(height(n.right) - height(n.left) == 2){ Node rotateNode = n.right; if(height(rotateNode.left)>height(rotateNode.right)){ n = doubleRightRotateLeftRotate(n); }else{ n = leftRotate(n); } } }else if(data > n.data){ n.right = _deleteNode(n.right, data); if(height(n.left) - height(n.right) == 2){ Node rotateNode = n.left; if(height(rotateNode.right)>height(rotateNode.left)){ n = doubleLeftRotateRightRotate(n); }else{ n = rightRotate(n); } } }else { if(n.left!=null && n.right!=null){ //find delete int minDataOfRightChild = findMinData(n.right); n.data = minDataOfRightChild; System.out.println("Find Min Data:"+minDataOfRightChild); n.right = _deleteNode(n.right, minDataOfRightChild); }else{ n = n.left!=null?n.left:n.right; } } if(n!=null) resetNodeHeight(n); return n; } private int findMinData(Node n) { if(n.left!=null) return findMinData(n.left); else return n.data; } public static void main(String[] args) { AVLTree tree = new AVLTree(); // tree.insert(14); // tree.insert(12); // tree.insert(16); // tree.insert(10); // tree.insert(8); // tree.insert(6); tree.insert(60); tree.insert(37); tree.insert(58); tree.insert(39); tree.insert(26); tree.insert(18); tree.insert(73); tree.insert(62); // System.out.println(tree.getRoot()); System.out.println("tree height:" + tree.treeHeight()); System.out.print("PreSort: "); tree.preSort(); System.out.println(); System.out.println(tree.findMinData(tree.getRoot())); System.out.println(tree.search(37)); tree.delete(37); // System.out.println(tree.getRoot()); System.out.print("PreSort: "); tree.preSort(); tree.delete(58); System.out.print("PreSort: "); tree.preSort(); } } <file_sep>/MavenPro/SpringbootNoDB/src/main/java/com/jw/test/user/UserEntitlement.java package com.jw.test.user; import org.springframework.beans.factory.annotation.Autowired; public abstract class UserEntitlement { @Autowired protected UserService userService; public void getUser(){ System.out.println("UserEntitlement getUser / "+userService); } public abstract void getClient(); } <file_sep>/MavenPro/SpringbootNoDB/src/main/java/com/jw/test/user/UserInternalEntitlement.java package com.jw.test.user; import org.springframework.stereotype.Component; @Component public class UserInternalEntitlement extends UserEntitlement { @Override public void getClient() { System.out.println("UserInternalEntitlement getClient /"+userService); } } <file_sep>/MavenPro/Java-Test/src/main/java/com/thread/countdown/CountDownTest.java package com.thread.countdown; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class CountDownTest { public static void main(String[] args) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(10); for (int i = 0; i < 10; i++) { new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + " 运行"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } finally { latch.countDown(); } } }).start(); } System.out.println("等待子线程运行结束"); // latch.await(10, TimeUnit.SECONDS); latch.await(); System.out.println("子线程运行结束"); } } <file_sep>/MavenPro/SpringbootGraphQL/src/main/java/org/jw/graphqljw/resolver/Query.java package org.jw.graphqljw.resolver; import graphql.kickstart.tools.GraphQLQueryResolver; import org.jw.graphqljw.model.Book; import org.jw.graphqljw.repositories.BookRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; @Component public class Query implements GraphQLQueryResolver { @Autowired private BookRepository bookRepository; public Query() { // this.bookRepository = bookRepository; } public List<Book> books() { System.out.println("get all books."); return bookRepository.findAll(); } } <file_sep>/Spring4Project/demo1/src/main/java/com/jw/spring4/demo1/f_aspectsjaop/MyAspect.java package com.jw.spring4.demo1.f_aspectsjaop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; @Aspect //申明为切面类 public class MyAspect { @Before("execution(* com.jw.spring4.demo1.f_aspectsjaop.UserService6.*(..))") public void before(){ System.out.println("前置通知-------------"); } @AfterReturning(value = "execution(* com.jw.spring4.demo1.f_aspectsjaop.UserService6.get(..))", returning = "returnValue") public void afterReturning(Object returnValue){ //这里returnValue必须和标签里一样 System.out.println("后置通知------------- 返回值:"+returnValue); } @Around("execution(* com.jw.spring4.demo1.f_aspectsjaop.UserService6.*(..))") public Object around(ProceedingJoinPoint pj) throws Throwable { //这里returnValue必须和标签里一样 System.out.println("环绕通知-------------开始"); Object retObj = pj.proceed(); //执行目标对象的方法 System.out.println("环绕通知-------------结束 --- 返回值:"+retObj); return retObj; } @AfterThrowing(value="execution(* com.jw.spring4.demo1.f_aspectsjaop.UserService6.throwMethod(..))", throwing = "selfE") public void afterThrowing(Throwable selfE){ System.out.println("异常捕获--------------"+selfE.getMessage()); } //最终通知,不管方法有没错都会执行,类似finally @After("execution(* com.jw.spring4.demo1.f_aspectsjaop.UserService6.*(..))") public void finallyMethod(){ System.out.println("最终通知--------------"); } } <file_sep>/MavenPro/SwaggerCodeGen/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jw.gen</groupId> <artifactId>SwaggerCodeGen</artifactId> <version>1.0-SNAPSHOT</version> <build> <plugins> <plugin> <groupId>io.swagger</groupId> <artifactId>swagger-codegen-maven-plugin</artifactId> <version>2.3.1</version> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${project.basedir}/src/main/resources/swagger-api2.yaml</inputSpec> <language>spring</language> <skip>false</skip> <!-- <output>${project.basedir}/target/generated-sources/swagger</output>--> <output>${project.build.directory}/generated-sources/swagger</output> <modelPackage>com.ssc.dsp.api.model</modelPackage> <apiPackage>com.ssc.dsp.api.controller</apiPackage> <generateApis>true</generateApis> <generateApiTests>false</generateApiTests> <generateModels>true</generateModels> <generateModelTests>false</generateModelTests> <generateSupportingFiles>false</generateSupportingFiles> <generateApiDocumentation>false</generateApiDocumentation> <addCompileSourceRoot>false</addCompileSourceRoot> <configOptions> <sourceFolder>src/gen/java/main</sourceFolder> </configOptions> </configuration> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/MavenPro/QuartzSpringboot/src/main/java/com/jw/quartz/controller/StuController.java package com.jw.quartz.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Controller; @Controller public class StuController { @Autowired private JdbcTemplate jdbcTemplate; } <file_sep>/MavenPro/TestSpringboot/src/main/java/com/jw/test/repo/UserRepository.java package com.jw.test.repo; import com.jw.test.entity.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import javax.transaction.Transactional; import java.util.List; //不需要加这个注解 //@Repository public interface UserRepository extends JpaRepository<User,Integer> { User findByName(String name); @Query(value = "select * from user",nativeQuery = true) Page<User> findPageUsers(Pageable pageable); @Query(value = "select * from user",nativeQuery = true) List<User> findAllUsers(); @Transactional @Modifying @Query("update User set name = ?1 where id = ?2") //JPQL int modifyById(String userName, Integer id); } <file_sep>/MavenPro/Java-Test/src/main/java/com/io/RandomAccessFileTest.java package com.io; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; class User { int id; String name; int age; public User() { } public User(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } } public class RandomAccessFileTest { public static void main(String[] args) throws Exception { String value = "中国"; System.out.println((int)value.charAt(0)); System.out.println((int)value.charAt(1)); // System.out.println(value.length()); // testWriteReadBuffer(); int v1=20013; int v2=22269; char c = (char)v1; System.out.println(c); } public static void testWriteReadBuffer() throws Exception { final int BUFFERED_SIZE = 10 * 512; byte[] buffer = new byte[BUFFERED_SIZE]; String[] dataFormat = {"int", "String", "int"}; List<User> list = new ArrayList<>(); list.add(new User(1, "Sam", 18)); list.add(new User(2, "Jack", 20)); list.add(new User(3, "Lucy", 19)); list.add(new User(4, "Lily", 17)); int rowSize = 4 + 8 + 4; int start = 0; for(User u: list){ start = saveUser(u, rowSize, buffer, start); } System.out.println("Final position is:"+start); System.out.println(getUser(buffer, 32)); } private static int saveUser(User u, int rowSize, byte[] buffer, int start) throws Exception { byte[] tmp = new byte[rowSize]; writeInt(tmp, 0, u.id); writeString(tmp, 4, u.name); writeInt(tmp, 12, u.age); System.arraycopy(tmp, 0, buffer, start, rowSize); start += rowSize; return start; } private static User getUser(byte[] buffer, int start) throws Exception { User u = new User(); u.id = readInt(buffer, start); u.name = readString(buffer, start + 4); u.age = readInt(buffer, start + 12); return u; } //4 bytes for int private static void writeInt(byte[] buffer, int start, int value) { buffer[start + 0] = (byte) ((value >>> 24) & 0xff); buffer[start + 1] = (byte) ((value >>> 16) & 0xff); buffer[start + 2] = (byte) ((value >>> 8) & 0xff); buffer[start + 3] = (byte) ((value) & 0xff); } private static int readInt(byte[] buffer, int start) { int ch1 = (buffer[start + 0] & 0xff) << 24; int ch2 = (buffer[start + 1] & 0xff) << 16; int ch3 = (buffer[start + 2] & 0xff) << 8; int ch4 = (buffer[start + 3] & 0xff); return ch1 + ch2 + ch3 + ch4; } //8 bytes for int private static void writeLong(byte[] buffer, int start, long value) { buffer[start + 0] = (byte) ((value >>> 56) & 0xff); buffer[start + 1] = (byte) ((value >>> 48) & 0xff); buffer[start + 2] = (byte) ((value >>> 40) & 0xff); buffer[start + 3] = (byte) ((value >>> 32) & 0xff); buffer[start + 4] = (byte) ((value >>> 24) & 0xff); buffer[start + 5] = (byte) ((value >>> 16) & 0xff); buffer[start + 6] = (byte) ((value >>> 8) & 0xff); buffer[start + 7] = (byte) ((value) & 0xff); } private static long readLong(byte[] buffer, int start) { long ch1 = (long) (buffer[start + 0] & 0xff) << 56; long ch2 = (long) (buffer[start + 1] & 0xff) << 48; long ch3 = (long) (buffer[start + 2] & 0xff) << 40; long ch4 = (long) (buffer[start + 3] & 0xff) << 32; long ch5 = (long) (buffer[start + 4] & 0xff) << 24; long ch6 = (long) (buffer[start + 5] & 0xff) << 16; long ch7 = (long) (buffer[start + 6] & 0xff) << 8; long ch8 = (long) (buffer[start + 7] & 0xff) << 0; return ch1 + ch2 + ch3 + ch4 + ch5 + ch6 + ch7 + ch8; } //string limited to length 7 bytes, last byte use to save string length private static void writeString(byte[] buffer, int start, String value) throws Exception { if (value.length() > 7) throw new Exception("length can't bigger than 7 bytes"); int len = value.length(); long v = 0L; for (int i = 0; i < len; i++) { char c = value.charAt(i); if ((int) c < 127) {//only handle 1 byte v += (c & 0xff); v = v << 8; //in order to save last byte with string length } else { throw new Exception("Only handle ascii code char"); } } v += len; //save last byte with length writeLong(buffer, start, v); } private static String readString(byte[] buffer, int start) { long v = readLong(buffer, start); // System.out.println("Read long value:"+v); int len = (int)(v & 0xff); v = v >>> 8; // System.out.println("String length is:"+len); StringBuilder sb = new StringBuilder(); for(int i=0;i<len; i++){ char c1 = (char)(v & 0xff); sb.append(c1); v = v >>> 8; } return sb.reverse().toString(); } public static void test(String[] args) throws Exception { // int i = 1; // int v = i << 2; // System.out.println(Integer.toBinaryString(v)); byte[] bytes = new byte[1]; RandomAccessFile file = new RandomAccessFile("D:\\code\\github\\service\\MavenPro\\Java-Test\\src\\main\\java\\com\\io\\file.txt", "rw"); long p = file.getFilePointer(); int v = 33333; byte[] b = new byte[4]; //write to b b[3] = (byte) ((v >>> 24) & 0xFF); b[2] = (byte) ((v >>> 16) & 0xFF); b[1] = (byte) ((v >>> 8) & 0xFF); b[0] = (byte) ((v >>> 0) & 0xFF); System.out.println(b); //read from b int nextV = ((b[3] & 0xFF) << 24) + ((b[2] & 0xFF) << 16) + ((b[1] & 0xFF) << 8) + (int) (b[0] & 0xFF); System.out.println(nextV); // file.seek(100000); // file.write("k".getBytes()); // file.write("a".getBytes()); // file.write("b".getBytes()); // file.write("c".getBytes()); // file.seek(2); // file.write("d".getBytes()); // file.seek(3); // file.read(bytes); // System.out.println(file.length()); // System.out.println(new String(bytes)); file.close(); } } <file_sep>/MavenPro/TestSpringboot/src/main/java/com/jw/test/service/PrimaryService.java package com.jw.test.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; @Service public class PrimaryService { @Autowired JdbcTemplate jdbcTemplate; public String getStuName(){ String sql = "SELECT NAME FROM STU WHERE ID = ?"; return jdbcTemplate.queryForObject(sql, String.class, 1); } } <file_sep>/MavenPro/SpringbootGraphQL/src/main/java/org/jw/graphqljw/resolver/BookResolver.java package org.jw.graphqljw.resolver; import graphql.kickstart.tools.GraphQLResolver; import org.jw.graphqljw.model.Author; import org.jw.graphqljw.model.Book; import org.jw.graphqljw.repositories.AuthorRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class BookResolver implements GraphQLResolver<Book> { private AuthorRepository authorRepository; @Autowired public BookResolver(AuthorRepository authorRepository) { System.out.println("************ bookresolver initiallized. " + authorRepository); this.authorRepository = authorRepository; } public Author author(Book book) { System.out.println("find author with book "+ book.getName()); return authorRepository.findById(book.getAuthorId()); } } <file_sep>/MavenPro/TestSpringboot/src/main/java/com/jw/test/Starter.java package com.jw.test; import com.jw.test.service.PrimaryService; import com.jw.test.service.SecondService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class Starter implements CommandLineRunner { @Autowired PrimaryService primaryService; @Autowired SecondService secondService; @Override public void run(String... args) throws Exception { System.out.println("start"); System.out.println("First DB data is:"+primaryService.getStuName()); System.out.println("Second DB data is:"+secondService.getStuName()); Nothing n1 = new Nothing(); Nothing n2 = new Nothing(); System.out.println(n1.get()); System.out.println(n2.get()); } } <file_sep>/Spring4Project/demo1/src/main/java/com/jw/spring4/demo1/a_simplebean/UserService2ImplB.java package com.jw.spring4.demo1.a_simplebean; public class UserService2ImplB implements UserService2 { public void get() { System.out.println("UserService2ImplB get"); } } <file_sep>/MavenPro/SpringbootNoDB/src/main/java/com/jw/test/user/UserFactory.java package com.jw.test.user; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class UserFactory { @Autowired UserInternalEntitlement userInternalEntitlement; @Autowired UserExternalEntitlement userExternalEntitlement; public UserEntitlement get(String type){ TYPE uType = null; try { uType = TYPE.valueOf(type); } catch (IllegalArgumentException e) { throw new RuntimeException("User type is not valid."); } if(uType == TYPE.I){ return userInternalEntitlement; }else{ return userExternalEntitlement; } } enum TYPE{ I, E } // public static UserEntitlement create(String type){ // if("I".equals(type)){ // return new UserInternalEntitlement(); // }else{ // return new UserExternalEntitlement(); // } // } } <file_sep>/MavenPro/SwaggerSpringboot/src/main/java/com/jw/quartz/controller/UserController.java package com.jw.quartz.controller; import com.jw.quartz.model.User; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @Api(tags="User Manager") @RestController @RequestMapping("user") public class UserController { @ApiOperation("用户详情") @RequestMapping(value = "getuser", method = RequestMethod.GET) public User hello(){ System.out.println("Enter user."); User user = new User(18, "Jw", "M"); return user; } } <file_sep>/MavenPro/Java-Test/src/main/java/com/threadlocal/ThreadLocalOOM.java package com.threadlocal; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * vm params: -Xms50M -Xmx50M */ public class ThreadLocalOOM { private static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 5, 10, TimeUnit.SECONDS ,new LinkedBlockingDeque<>()); public static void main(String[] args) throws InterruptedException { System.out.println("Start."); for (int i=0; i< 100; i++){ int k = i; poolExecutor.execute(()->{ System.out.println("Number ["+k+"] Thread is:"+Thread.currentThread().getName()); ThreadLocal<BigObject> thl = new ThreadLocal<>(); thl.set(new BigObject()); }); TimeUnit.SECONDS.sleep(1); } System.out.println("Complete."); } static class BigObject{ // 5M private byte[] bytes = new byte[5 * 1024 * 1024]; } } <file_sep>/MavenPro/SpringbootNoDB/src/main/java/com/jw/test/cache/UserCache.java package com.jw.test.cache; import com.jw.test.vo.UserDetails; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class UserCache { @Cacheable(value = "user_details", key = "#uid", unless="#result == null") public UserDetails getUserDetailsByUid(int uid){ System.out.println(" Cacheable enter..."+uid); UserDetails userDetails = new UserDetails(uid, "User"+uid); if(uid == 5) return null; return userDetails; } @CachePut(value = "user_details", key = "#user.id") public UserDetails updateUserInfo(UserDetails user){ System.out.println(" CachePut enter..."+user.getId()); UserDetails userDetails = new UserDetails(user.getId(), "User New "+user.getId()); if(user.getId() == 3) return null; return userDetails; } @CacheEvict(value = "user_details", key = "#uid") public int delUserInfoById(int uid){ System.out.println(" CacheEvict enter..."+uid); return 1; } } <file_sep>/MavenPro/Java-Test/src/main/java/com/stream/StreamTest.java package com.stream; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class StreamTest { public static void main(String[] args) { createStream(); streamToOtherDataStructure(); peekStream(); java8Optional("test"); Map<String, Integer > map; // map.computeIfAbsent() } private static void java8Optional(String text) { // Java 8 Optional.ofNullable(text).ifPresent(System.out::println); // Pre-Java 8 if (text != null) { System.out.println(text); } } private static void peekStream() { Stream.of("one", "two", "three", "four") .filter(e -> e.length() > 3) .peek(e -> System.out.println("Filtered value: " + e)) .map(String::toUpperCase) .peek(e -> System.out.println("Mapped value: " + e)) .collect(Collectors.toList()); } private static void streamToOtherDataStructure() { Stream<String> stream = Stream.of("a", "b", "c"); // 1. Array String[] strArray1 = stream.toArray(String[]::new); // 2. Collection stream = Stream.of("a", "b", "c"); List<String> list1 = stream.collect(Collectors.toList()); stream = Stream.of("a", "b", "c"); List<String> list2 = stream.collect(Collectors.toCollection(ArrayList::new)); stream = Stream.of("a", "b", "c"); Set set1 = stream.collect(Collectors.toSet()); stream = Stream.of("a", "b", "c"); Stack stack1 = stream.collect(Collectors.toCollection(Stack::new)); // 3. String stream = Stream.of("a", "b", "c"); String str = stream.collect(Collectors.joining()).toString(); } private static void createStream() { // 1. Individual values Stream stream = Stream.of("a", "b", "c"); // 2. Arrays String [] strArray = new String[] {"a", "b", "c"}; stream = Stream.of(strArray); stream = Arrays.stream(strArray); // 3. Collections List<String> list = Arrays.asList(strArray); stream = list.stream(); stream.forEach(System.out::print); System.out.println(); IntStream.of(new int[]{1, 2, 3}).forEach(System.out::print); System.out.println(); IntStream.range(1, 3).forEach(System.out::print); System.out.println(); IntStream.rangeClosed(1, 3).forEach(System.out::print); separator(); } private static void separator() { System.out.println(); System.out.println("-----------------------"); } } <file_sep>/MavenPro/TestSpringboot/src/main/java/com/jw/test/config/WebConfigure.java package com.jw.test.config; import com.jw.test.interceptor.TestInterceptor; import com.jw.test.interceptor.TestInterceptor2; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfigure implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { // registry.addInterceptor(new TestInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login","/index.html", "/js/**","/css/**","/images/**"); registry.addInterceptor(new TestInterceptor2()).addPathPatterns("/**").excludePathPatterns("/user/**","/js/**","/css/**","/images/**"); } } <file_sep>/Spring4Project/demo1/src/main/java/com/jw/spring4/demo1/g_aspectsjaoppointcut/MyPointcut.java package com.jw.spring4.demo1.g_aspectsjaoppointcut; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; @Aspect public class MyPointcut { @Pointcut(value = "execution(* com.jw.spring4.demo1.g_aspectsjaoppointcut.UserService7.*(..))") public void userService7Pointcut(){ //方法名就是切入点名称 } } <file_sep>/MavenPro/Java-Test/src/main/java/com/stream/OptionalTest.java package com.stream; import java.util.Optional; public class OptionalTest { public static void main(String[] args) { String str = "null"; Optional<String> s1 = Optional.ofNullable(str).map(s -> s + "_append"); if(s1.isPresent()){ System.out.println("str is not null"); }else{ System.out.println("str is null"); } //if str is null and not empty, return str, else return default String val2 = Optional.ofNullable(str).map(s -> s.isEmpty()?null:s).orElse("default"); System.out.println(val2); } } <file_sep>/MavenPro/QuartzSpringboot/src/main/java/com/jw/quartz/MyStartupRunner.java package com.jw.quartz; import com.jw.quartz.model.Student; import com.jw.quartz.repo.StuService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import java.util.List; @Component public class MyStartupRunner implements CommandLineRunner { // @Autowired // StuService service; @Override public void run(String... args) throws Exception { System.out.println(">>>>>>>>>>>>>>>MyStartupRunner start<<<<<<<<<<<<<"); } } <file_sep>/MavenPro/SpringbootGraphQL/src/main/java/org/jw/graphqljw/repositories/BookRepository.java package org.jw.graphqljw.repositories; import org.jw.graphqljw.model.Book; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; @Component public class BookRepository { public List<Book> findAll() { List<Book> list = new ArrayList<>(); list.add(new Book(1, "Java" , 1)); list.add(new Book(2, "Data Base" , 1)); list.add(new Book(3, "JavaScript" , 1)); return list; } } <file_sep>/Spring4Project/demo1/src/main/java/com/jw/spring4/demo1/f_aspectsjaop/UserService6.java package com.jw.spring4.demo1.f_aspectsjaop; public class UserService6 { public String get(){ System.out.println("UserService6 get()"); return "testUser"; } public void update(){ System.out.println("UserService6 update()"); } public void throwMethod(){ System.out.println("UserService6 throwMethod"); throw new RuntimeException("error happens for throwMethod"); } } <file_sep>/MavenPro/TestSpringboot/src/main/java/com/jw/test/App.java package com.jw.test; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication @EntityScan(basePackages={"com.jw.test.entity"}) @EnableJpaRepositories(basePackages={"com.jw.test.repo"}) public class App { public static void main(String[] args) { System.out.println("App starting...."); SpringApplication.run(App.class, args); } }<file_sep>/MavenPro/TestSpringboot/src/main/java/com/jw/test/Nothing.java package com.jw.test; import com.jw.test.service.PrototypeService; import com.jw.test.util.ApplicationContextUtil; /** * Just to test if non-ioc class can access spring ioc beans * from ApplicationContextUtil */ public class Nothing { public PrototypeService get(){ return ApplicationContextUtil.getBean(PrototypeService.class); } }
e0adc266f9581e0e3bee99a5274b2b7529acf0c5
[ "Java", "Maven POM" ]
30
Java
fishfather/service
086a310976f18c4c131e65c6d62a66e5d0c2db75
15942eae489bf9b3e2ac9323a6e3b34bd04d3409
refs/heads/master
<repo_name>AyrtonLucasSR/AtividadeAula6<file_sep>/app_evento/admin.py from django.contrib import admin from .models import Evento, Pessoa, PessoaFisica, Inscricao, Ingresso @admin.register(Evento) class EventoAdmin(admin.ModelAdmin): pass @admin.register(Pessoa) class PessoaAdmin(admin.ModelAdmin): pass @admin.register(PessoaFisica) class PessoaFisicaAdmin(admin.ModelAdmin): pass @admin.register(Inscricao) class InscricaoAdmin(admin.ModelAdmin): pass @admin.register(Ingresso) class IngressoAdmin(admin.ModelAdmin): pass # Register your models here. <file_sep>/app_evento/migrations/0004_auto_20200313_2113.py # Generated by Django 3.0.3 on 2020-03-14 00:13 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app_evento', '0003_auto_20200313_2037'), ] operations = [ migrations.DeleteModel( name='Evento', ), migrations.DeleteModel( name='Ingresso', ), migrations.RemoveField( model_name='pessoafisica', name='pessoa_ptr', ), migrations.DeleteModel( name='Pessoa', ), migrations.DeleteModel( name='PessoaFisica', ), ] <file_sep>/app_evento/migrations/0007_auto_20200313_2120.py # Generated by Django 3.0.3 on 2020-03-14 00:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app_evento', '0006_auto_20200313_2115'), ] operations = [ migrations.AlterField( model_name='ingresso', name='descricao', field=models.CharField(max_length=128, verbose_name='nome'), ), ] <file_sep>/app_evento/models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Pessoa(models.Model): nome= models.CharField('Nome',max_length=128) email= models.EmailField('E-mail', null=True, blank=True) def _str_(self): return self.nome class PessoaFisica(models.Model): pessoa=models.ForeignKey(Pessoa, on_delete=models.CASCADE,blank=True,null=True) cpf=models.CharField('CPF', max_length=15, help_text='Número do cpf no formato 00000000000',null=True, blank=True,) def _str_(self): return self.cpf class Evento(models.Model): nome = models.CharField('nome',max_length = 50) sigla = models.CharField('Sigla',max_length = 50) data_icinio = models.DateTimeField(default=timezone.now) realizador=models.ForeignKey(Pessoa, on_delete=models.CASCADE,blank=True,null=True) descricao = models.TextField() def _str_(self): return self.sigla class Ingresso(models.Model): descricao = models.CharField('nome',max_length=128) valor=models.TextField() evento= models.ForeignKey(Evento, on_delete=models.CASCADE,blank=True, null=True) def _str_(self): return self.descricao class Inscricao(models.Model): pessoa = models.ForeignKey(Pessoa, on_delete=models.CASCADE,blank=True, null=True) evento = models.ForeignKey(Evento, on_delete=models.CASCADE,blank=True, null=True) ingresso= models.ForeignKey(Ingresso, on_delete=models.CASCADE,blank=True, null=True) # Create your models here. <file_sep>/app_evento/migrations/0005_auto_20200313_2113.py # Generated by Django 3.0.3 on 2020-03-14 00:13 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('app_evento', '0004_auto_20200313_2113'), ] operations = [ migrations.CreateModel( name='Evento', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nome', models.CharField(max_length=50, verbose_name='nome')), ('sigla', models.CharField(max_length=50, verbose_name='Sigla')), ('data_icinio', models.DateTimeField(default=django.utils.timezone.now)), ('descricao', models.TextField()), ], ), migrations.CreateModel( name='Ingresso', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('descricao', models.CharField(max_length=128, verbose_name='Nome')), ('valor', models.TextField()), ('evento', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='app_evento.Evento')), ], ), migrations.CreateModel( name='Pessoa', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nome', models.CharField(max_length=128, verbose_name='Nome')), ('email', models.EmailField(blank=True, max_length=254, null=True, verbose_name='E-mail')), ], ), migrations.CreateModel( name='PessoaFisica', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('cpf', models.CharField(blank=True, help_text='Número do cpf no formato 1111111111', max_length=15, null=True, verbose_name='CPF')), ('pessoa', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='app_evento.Pessoa')), ], ), migrations.CreateModel( name='Inscricao', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('evento', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='app_evento.Evento')), ('ingresso', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='app_evento.Ingresso')), ('pessoa', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='app_evento.Pessoa')), ], ), migrations.AddField( model_name='evento', name='realizador', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='app_evento.Pessoa'), ), ] <file_sep>/app_evento/migrations/0003_auto_20200313_2037.py # Generated by Django 3.0.3 on 2020-03-13 23:37 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app_evento', '0002_ingresso_pessoa_pessoafisica'), ] operations = [ migrations.RemoveField( model_name='ingresso', name='data_icinio', ), migrations.RemoveField( model_name='ingresso', name='realizador', ), migrations.RemoveField( model_name='ingresso', name='sigla', ), ] <file_sep>/app_evento/migrations/0006_auto_20200313_2115.py # Generated by Django 3.0.3 on 2020-03-14 00:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app_evento', '0005_auto_20200313_2113'), ] operations = [ migrations.AlterField( model_name='pessoafisica', name='cpf', field=models.CharField(blank=True, help_text='Número do cpf no formato 00000000000', max_length=15, null=True, verbose_name='CPF'), ), ]
4120c2adb86fe986a3560ac047a525e51244f105
[ "Python" ]
7
Python
AyrtonLucasSR/AtividadeAula6
ef3415393f9c38d400645a9a56586c557daed0e3
6d568df115177d2b06e97df906ec8f6d5338a6e8
refs/heads/master
<repo_name>AngieD8615/HRSprint_chatterbox<file_sep>/client/scripts/messagesView.js var MessagesView = { $chats: $('#chats'), initialize: function () { }, render: function () { _.each(Messages, (message) => { if (!message.username) { message.username = 'unknown'; } if (message.text) { var $message = MessageView.render(message); MessagesView.$chats.append($message); } }); }, };<file_sep>/client/scripts/roomsView.js var RoomsView = { $button: $('#rooms button'), $select: $('#rooms select'), initialize: function() { }, render: function() { _.each(Rooms, (room) => { RoomsView.$select.append('<select><%= room %></select>'); }); } }; <file_sep>/client/scripts/formView.js var FormView = { $form: $('form'), initialize: function () { FormView.$form.on('submit', FormView.handleSubmit); }, handleSubmit: function (event) { // Stop the browser from submitting the form event.preventDefault(); var message = { username: '', text: $( "input" ).first().val(), roomname: 'lobby', }; console.log('click!', $( "input" ).first().val(), Messages); Parse.create(message, () => { Messages = [message, ...Messages]; MessagesView.render(); }); }, setStatus: function (active) { var status = active ? 'true' : null; FormView.$form.find('input[type=submit]').attr('disabled', status); } };
8fa673dca60b756b4638c15b4b06eca8a0a0d058
[ "JavaScript" ]
3
JavaScript
AngieD8615/HRSprint_chatterbox
eebd21cb1978dbbb17663ddf37c4203f3e88ee87
134a0383ebe644369f9a6e573eedd24cf6872848
refs/heads/master
<file_sep><?php ///////////////////////////////////////////////////////////////////// // WHOIS Script // Copyright (c) 2017 <NAME> ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // find_whois_server // Returns the whois server based on the domain TLD / ccTLD // You can add more whois servers by expanding the array. ///////////////////////////////////////////////////////////////////// function find_whois_server($ext) { $WHOIS_SERVERS = Array( "com" => "whois.crsnic.net", "net" => "whois.crsnic.net", "org" => "whois.pir.org", "edu" => "whois.crsnic.net", "biz" => "whois.neulevel.biz", "info" => "whois.afilias.info", "us" => "whois.nic.us", "uk" => "whois.nic.uk", "ca" => "whois.cira.ca", "de" => "whois.nic.de", "ws" => "whois.nic.ws", "au" => "whois.ausregistry.net.au", "nu" => "whois.nic.nu", "in" => "whois.registry.in", "tel" => "whois.nic.tel", "ie" => "whois.iedr.ie", "tw" => "whois.twnic.net.tw", "tv" => "whois.nic.tv", "ch" => "whois.nic.ch", "eu" => "whois.eu", "it" => "whois.nic.it", "cn" => "whois.cnnic.net.cn", "mobi" => "whois.dotmobiregistry.net", "cc" => "whois.nic.cc", "asia" => "whois.nic.asia", "pro" => "whois.registrypro.pro", "hk" => "whois.hknic.net.hk", "me" => "whois.meregistry.net", "be" => "whois.dns.be", "se" => "whois.nic.se", "ca" => "whois.cira.ca", "nz" => "whois.domainz.net.nz", "nl" => "whois.sidn.nl", 'ventures' => 'whois.donuts.co', 'singles' => 'whois.donuts.co', 'bike' => 'whois.donuts.co', 'holdings' => 'whois.donuts.co', 'plumbing' => 'whois.donuts.co', 'guru' => 'whois.donuts.co', 'clothing' => 'whois.donuts.co', 'camera' => 'whois.donuts.co', 'equipment' => 'whois.donuts.co', 'estate' => 'whois.donuts.co', 'gallery' => 'whois.donuts.co', 'graphics' => 'whois.donuts.co', 'lighting' => 'whois.donuts.co', 'photography' => 'whois.donuts.co', 'contractors' => 'whois.donuts.co', 'land' => 'whois.donuts.co', 'technology' => 'whois.donuts.co', 'construction' => 'whois.donuts.co', 'directory' => 'whois.donuts.co', 'kitchen' => 'whois.donuts.co', 'today' => 'whois.donuts.co', 'diamonds' => 'whois.donuts.co', 'enterprises' => 'whois.donuts.co', 'tips' => 'whois.donuts.co', 'voyage' => 'whois.donuts.co', 'shoes' => 'whois.donuts.co', 'careers' => 'whois.donuts.co', 'photos' => 'whois.donuts.co', 'recipes' => 'whois.donuts.co', 'limo' => 'whois.donuts.co', 'domains' => 'whois.donuts.co', 'cab' => 'whois.donuts.co', 'company' => 'whois.donuts.co', 'computer' => 'whois.donuts.co', 'center' => 'whois.donuts.co', 'systems' => 'whois.donuts.co', 'academy' => 'whois.donuts.co', 'management' => 'whois.donuts.co', 'training' => 'whois.donuts.co', 'solutions' => 'whois.donuts.co', 'support' => 'whois.donuts.co', 'builders' => 'whois.donuts.co', 'email' => 'whois.donuts.co', 'education' => 'whois.donuts.co', 'institute' => 'whois.donuts.co', 'repair' => 'whois.donuts.co', 'camp' => 'whois.donuts.co', 'glass' => 'whois.donuts.co', 'solar' => 'whois.donuts.co', 'coffee' => 'whois.donuts.co', 'international' => 'whois.donuts.co', 'house' => 'whois.donuts.co', 'florist' => 'whois.donuts.co', 'holiday' => 'whois.donuts.co', 'marketing' => 'whois.donuts.co', 'viajes' => 'whois.donuts.co', 'farm' => 'whois.donuts.co', 'codes' => 'whois.donuts.co', 'cheap' => 'whois.donuts.co', 'zone' => 'whois.donuts.co', 'agency' => 'whois.donuts.co', 'bargains' => 'whois.donuts.co', 'boutique' => 'whois.donuts.co', 'tienda' => 'whois.donuts.co', 'watch' => 'whois.donuts.co', 'works' => 'whois.donuts.co', 'cool' => 'whois.donuts.co', 'expert' => 'whois.donuts.co', 'menu' => 'whois.nic.menu', 'club' => 'whois.nic.club', 'photo' => 'whois.uniregistry.net', 'gift' => 'whois.uniregistry.net', 'guitars' => 'whois.uniregistry.net', 'pics' => 'whois.uniregistry.net', 'link' => 'whois.uniregistry.net', 'sexy' => 'whois.uniregistry.net', 'tattoo' => 'whois.uniregistry.net', 'reviews' => 'whois.unitedtld.com', 'ms' => 'whois.nic.ms', 'uno' => 'whois.nic.uno', 'buzz' => 'whois.nic.buzz', 'berlin' => 'whois.nic.berlin' ); $ext = strtolower($ext); if(array_key_exists($ext, $WHOIS_SERVERS)) return $WHOIS_SERVERS[$ext]; else return ""; } ///////////////////////////////////////////////////////////////////// function do_whois($domainname, $server, $port=43) { $output = "Unable to connect to " . $server; if(($ns = fsockopen($server,$port)) == true) { $output = ""; fputs($ns,"$domainname\r\n"); while(!feof($ns)) $output .= fgets($ns,128); fclose($ns); } return $output . "\r\n" . '<hr><p>Simple PHP WHOIS script, copyright (c) <a href="https://lonerangerweb.wordpress.com/">Lone-Ranger</a></p>'; } ///////////////////////////////////////////////////////////////////// function get_registrar_server($string) { $lookfor = array("Registrar WHOIS Server:", "Whois Server:"); foreach($lookfor as $fstr) { if(strstr($string, $fstr)) { $string = str_ireplace($fstr, "", $string); return trim($string); } } return false; } ///////////////////////////////////////////////////////////////////// function domain_whois($domainname, $port=43) { $domainname = trim($domainname); $domparts = explode(".", $domainname); $count = count($domparts); if(!$count) return "Invalid domain name"; $server = find_whois_server($domparts[$count-1]); if($server == "") return "Don't know the whois server for domain " . $domainname; $lookupname = $domainname; if(preg_match("/.(com|.net|.edu)$/i", $domainname)) $lookupname = "domain " . $domainname; $output = do_whois($lookupname, $server); if(preg_match("/.(com|.net|.edu|.cc|.tv|.ws)$/i", $domainname)) { $pieces = explode("\n", $output); $count = count($pieces); $c = 0; for($c = 0; $c < $count; $c++) { $line = $pieces[$c]; $registrar_server = get_registrar_server($line); if($registrar_server !== false) $output = do_whois($domainname, $registrar_server); } } if(!strlen($output)) $output = "There was error connecting to the whois server [" . $server . "]"; return $output; } ///////////////////////////////////////////////////////////////////// $domain = ""; $server = ""; if(isset($_GET["domain"])) $domain = strip_tags(stripslashes($_GET["domain"])); if(isset($_GET["server"])) $server = strip_tags(stripslashes($_GET["server"])); if($domain != "") { if($server != "") echo "<pre>" . do_whois($domain, $server) . "</pre>"; else echo "<pre>" . domain_whois($domain) . "</pre>"; } else echo "Domain Name Not Specified."; ///////////////////////////////////////////////////////////////////// ?> </br> </br> Note: put "?domain=domain.com" , replace domain.com with you domain.
b5ae8ccd9be120ada2cdbdddcf34ebee4ae0a07f
[ "PHP" ]
1
PHP
5l1v3r1/Asgard
9c26f021b70a84d6ee4a8b728a10d7debed6be1a
15e0c20afcfd6f71d75a74b69cd7a2f06690fb3d
refs/heads/main
<repo_name>xiyuximing/StudySpringBoot<file_sep>/blog-demo/src/main/java/com/cy/blogdemo/service/ArticleService.java package com.cy.blogdemo.service; import com.cy.blogdemo.pojo.Article; import com.cy.blogdemo.pojo.QryArticleInfo; import org.springframework.data.domain.Page; public interface ArticleService { /** * 根据条件查询分页信息 * @param cond 查询条件 * @return */ Page<Article> qryPageInfo(QryArticleInfo cond); } <file_sep>/blog-demo/src/main/java/com/cy/blogdemo/service/impl/ArticleServiceImpl.java package com.cy.blogdemo.service.impl; import com.cy.blogdemo.dao.ArticleDao; import com.cy.blogdemo.pojo.Article; import com.cy.blogdemo.pojo.QryArticleInfo; import com.cy.blogdemo.service.ArticleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.*; import org.springframework.stereotype.Service; @Service public class ArticleServiceImpl implements ArticleService { @Autowired private ArticleDao articleDao; @Override public Page<Article> qryPageInfo(QryArticleInfo cond) { PageRequest page = PageRequest.of(cond.getPage(), cond.getSize()); return articleDao.findAll(page); } } <file_sep>/blog-demo/src/main/java/com/cy/blogdemo/pojo/QryArticleInfo.java package com.cy.blogdemo.pojo; import java.io.Serializable; public class QryArticleInfo extends Article implements Serializable { private Integer page; private Integer size; public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } public QryArticleInfo() { } @Override public String toString() { return "QryArticleInfo{" + "page=" + page + ", size=" + size + '}'; } } <file_sep>/blog-demo/src/main/resources/application.properties spring.datasource.url=jdbc:mysql://192.168.123.198:13306/jpa?charset=utf-8 spring.datasource.username=root spring.datasource.password=<PASSWORD> spring.jpa.show-sql=true spring.thymeleaf.cache=false spring.redis.host=192.168.123.198 spring.redis.port=16379 spring.cache.redis.time-to-live=60000 <file_sep>/blog-demo/src/main/java/com/cy/blogdemo/dao/ArticleDao.java package com.cy.blogdemo.dao; import com.cy.blogdemo.pojo.Article; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.PagingAndSortingRepository; public interface ArticleDao extends JpaRepository<Article, Integer>, PagingAndSortingRepository<Article, Integer> { }
f26bc5609cb8bcf0c77fedb114b2760ab191d799
[ "Java", "INI" ]
5
Java
xiyuximing/StudySpringBoot
2beaa85c3f9d9864176c9c9d11da6bb7e2e323c9
5e7ab6cfc4b1445be9249b6bea679b25b4f68f2a
refs/heads/master
<file_sep>package hatim.dhuliawala.addressbook; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import hatim.dhuliawala.addressbook.R; public class EditDataMain extends Activity implements OnClickListener { Button edittonext, editBacktomain, getRowIdforEdit; EditText getrowidvianickname, rowidforedit; TextView displayrowidforedit; String bread; boolean row; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.editdata); initialize(); } private void initialize() { // TODO Auto-generated method stub edittonext = (Button) findViewById(R.id.bEditdatawithRowid123); editBacktomain = (Button) findViewById(R.id.bEditDataBacktoMain); getRowIdforEdit = (Button) findViewById(R.id.bGetDataforEdit); getrowidvianickname = (EditText) findViewById(R.id.etGetEditNickname); rowidforedit = (EditText) findViewById(R.id.etGetRowidforEdit); displayrowidforedit = (TextView) findViewById(R.id.tvGetEditRowId); edittonext.setOnClickListener(EditDataMain.this); editBacktomain.setOnClickListener(EditDataMain.this); getRowIdforEdit.setOnClickListener(EditDataMain.this); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.bGetDataforEdit: row = true; try { String rowidedit = getrowidvianickname.getText().toString(); if (getrowidvianickname.equals("")) { row = false; Toast err1 = Toast.makeText(getBaseContext(), "Enter A nickname", Toast.LENGTH_LONG); err1.show(); } else { AddressDatabase getrowiddata = new AddressDatabase(EditDataMain.this); getrowiddata.open(); String data = getrowiddata.getDeleteRowId(rowidedit); getrowiddata.close(); if (data.equals("")) { Toast err = Toast.makeText(getBaseContext(), "Enter Valid Nickname", Toast.LENGTH_LONG); err.show(); } else displayrowidforedit.setText(data); } } catch (Exception e) { row = false; e.printStackTrace(); Toast err = Toast.makeText(getBaseContext(), "Please Enter all Value", Toast.LENGTH_LONG); err.show(); } break; case R.id.bEditdatawithRowid123: try{ bread = rowidforedit.getText().toString(); if (bread.equals("")) { row = false; Toast err1 = Toast.makeText(getBaseContext(), "Please Enter Rowid ", Toast.LENGTH_LONG); err1.show(); } else { Bundle basket = new Bundle(); basket.putString("key", bread); Intent a = new Intent(EditDataMain.this,EditDataWork.class); a.putExtras(basket); startActivity(a); this.finish(); // Hiding Keyboard InputMethodManager i = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); i.hideSoftInputFromInputMethod(rowidforedit.getWindowToken(), 0); }}catch(Exception e){ e.printStackTrace(); Toast t = Toast.makeText(getBaseContext(), "some error", Toast.LENGTH_LONG); t.show(); } //Intent a = new Intent("com.example.addressbook.EDITDATA"); //a.putExtras(basket); //startActivity(a);*/ //Intent mainactivity1 = new Intent("com.example.addressbook.EDITDATAWORK"); //startActivity(mainactivity1); break; case R.id.bEditDataBacktoMain: Intent mainactivity = new Intent("hatim.dhuliawala.addressbook.ADDRESSACTIVITY"); startActivity(mainactivity); this.finish(); break; } } } <file_sep>package hatim.dhuliawala.addressbook; import android.app.Activity; import android.app.Dialog; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.widget.TextView; import android.widget.Toast; public class AddressDatabase extends Activity { public static final String KEY_ROWID = "_id"; public static final String KEY_FNAME = "person_firstName"; public static final String KEY_LNAME = "person_lastName"; public static final String KEY_NICKNAME = "person_nickname"; public static final String KEY_ADDRESS = "person_address"; private static final String DATABASE_NAME = "Addressdb"; private static final String DATABASE_TABLE = "peopleTable"; private static final int DATABASE_VERSION = 1; private final Context ourContext; private DBHelper ourHelper; private SQLiteDatabase ourDatabase; private static class DBHelper extends SQLiteOpenHelper { public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_FNAME + " TEXT NOT NULL, " + KEY_LNAME + " TEXT NOT NULL, " + KEY_NICKNAME + " TEXT NOT NULL, " + KEY_ADDRESS + " TEXT NOT NULL);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXIST " + DATABASE_TABLE); onCreate(db); } } public AddressDatabase(Context c) { ourContext = c; } public AddressDatabase open() throws SQLException { ourHelper = new DBHelper(ourContext); ourDatabase = ourHelper.getWritableDatabase(); return this; } public void close() { ourHelper.close(); } public long createEntry(String fname, String lname, String nickname, String address) { // TODO Auto-generated method stub ContentValues cv = new ContentValues(); cv.put(KEY_FNAME, fname); cv.put(KEY_LNAME, lname); cv.put(KEY_NICKNAME, nickname); cv.put(KEY_ADDRESS, address); return ourDatabase.insert(DATABASE_TABLE, null, cv); } public String getData() throws SQLException { // TODO Auto-generated method stub String[] column = new String[] { KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_NICKNAME, KEY_ADDRESS }; Cursor c = ourDatabase.query(DATABASE_TABLE, column, null, null, null, null, null); String result = ""; int iFName = c.getColumnIndex(KEY_FNAME); int iLName = c.getColumnIndex(KEY_LNAME); int iNickname = c.getColumnIndex(KEY_NICKNAME); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { result = result + "First Name = " + c.getString(iFName) + "\nLast Name = " + c.getString(iLName) + "\nNick Name = " + c.getString(iNickname) + "\n\n"; } return result; } public String searchdata(String l) throws SQLException { // TODO Auto-generated method stub String[] column = new String[] { KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_NICKNAME, KEY_ADDRESS }; Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_NICKNAME + " = " + "'" + l + "'", null, null, null, null); String result = ""; if (c != null) { // c.moveToFirst(); int iFName = c.getColumnIndex(KEY_FNAME); int iLName = c.getColumnIndex(KEY_LNAME); int iAddress = c.getColumnIndex(KEY_ADDRESS); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { result = result + "First Name = " + c.getString(iFName) + "\nLast Name = " + c.getString(iLName) + "\nAddress = " + c.getString(iAddress) + "\n\n"; } return result; } return null; } public void deleteEntry(long lRowDelete) throws SQLException { // TODO Auto-generated method stub ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + lRowDelete, null); } public String getDeleteRowId(String rowiddelete) throws SQLException { // TODO Auto-generated method stub String[] column = new String[] { KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_NICKNAME, KEY_ADDRESS }; Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_NICKNAME + "=" + "'" + rowiddelete + "'", null, null, null, null); String result = ""; int iFName = c.getColumnIndex(KEY_FNAME); int iLName = c.getColumnIndex(KEY_LNAME); int iRowid = c.getColumnIndex(KEY_ROWID); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { result = result + "Row ID = " + c.getString(iRowid) + "\nFirst Name = " + c.getString(iFName) + "\nLast Name = " + c.getString(iLName) + "\n\n"; } return result; } public String getFName(long l) throws SQLException { // TODO Auto-generated method stub String[] column = new String[] { KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_NICKNAME, KEY_ADDRESS }; Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); if (c != null) { c.moveToFirst(); String fname = c.getString(1); return fname; } return null; } public String getLName(long l) throws SQLException { // TODO Auto-generated method stub String[] column = new String[] { KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_NICKNAME, KEY_ADDRESS }; Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); if (c != null) { c.moveToFirst(); String lname = c.getString(2); return lname; } return null; } public String getNName(long l) throws SQLException { // TODO Auto-generated method stub String[] column = new String[] { KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_NICKNAME, KEY_ADDRESS }; Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); if (c != null) { c.moveToFirst(); String nname = c.getString(3); return nname; } return null; } public String getAddress(long l) throws SQLException { // TODO Auto-generated method stub String[] column = new String[] { KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_NICKNAME, KEY_ADDRESS }; Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); if (c != null) { c.moveToFirst(); String addressdata = c.getString(4); return addressdata; } return null; } public void getUpdate(long lRow, String mFName, String mLName,String mNName, String mAddress) throws SQLException { // TODO Auto-generated method stub ContentValues modify = new ContentValues(); modify.put(KEY_FNAME, mFName); modify.put(KEY_LNAME, mLName); modify.put(KEY_NICKNAME, mNName); modify.put(KEY_ADDRESS, mAddress); ourDatabase.update(DATABASE_TABLE, modify, KEY_ROWID + "=" + lRow, null); } } <file_sep>package hatim.dhuliawala.addressbook; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import hatim.dhuliawala.addressbook.R; public class ViewData extends Activity implements OnClickListener { TextView displaydata; Button done; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.view); initialize(); try{ AddressDatabase info = new AddressDatabase(ViewData.this); info.open(); String data = info.getData(); info.close(); displaydata.setText(data); }catch(Exception e){ e.printStackTrace(); Toast err = Toast.makeText(getBaseContext(), "ERR", Toast.LENGTH_LONG); err.show(); } } private void initialize() { // TODO Auto-generated method stub displaydata =(TextView) findViewById(R.id.tvDisplay); done = (Button) findViewById(R.id.bViewDone); done.setOnClickListener(ViewData.this); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()){ case R.id.bViewDone: Intent mainactivity = new Intent ("hatim.dhuliawala.addressbook.ADDRESSACTIVITY"); startActivity (mainactivity); this.finish(); } } } <file_sep>package hatim.dhuliawala.addressbook; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import hatim.dhuliawala.addressbook.R; public class DeleteData extends Activity implements OnClickListener { Button delete, deleteBack , getRowId; EditText deleteNickName, getrowiddelete; TextView displayrowid; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.delete); initialize(); } private void initialize() { // TODO Auto-generated method stub delete = (Button) findViewById(R.id.bDeleteData); deleteBack = (Button) findViewById(R.id.bDeleteBack); getRowId = (Button) findViewById(R.id.bDeleteRowId); deleteNickName = (EditText) findViewById(R.id.etDeleteNickname); getrowiddelete = (EditText) findViewById(R.id.etGetRowidforDeletion); displayrowid = (TextView) findViewById(R.id.tvDeleteRowId); getRowId.setOnClickListener(DeleteData.this); delete.setOnClickListener(DeleteData.this); deleteBack.setOnClickListener(DeleteData.this); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.bDeleteData: boolean del = true; try { String sRowDelete = getrowiddelete.getText().toString(); long lRowDelete = Long.parseLong(sRowDelete); if (getrowiddelete.equals("")) { del = false; Toast err1 = Toast.makeText(getBaseContext(), "Please Enter Row Id ", Toast.LENGTH_LONG); err1.show(); } else { AddressDatabase hdelete = new AddressDatabase(DeleteData.this); hdelete.open(); hdelete.deleteEntry(lRowDelete); hdelete.close(); } } catch (Exception e) { del = false; e.printStackTrace(); Toast err = Toast.makeText(getBaseContext(), "Record Not Found", Toast.LENGTH_LONG); err.show(); } finally { if (del == true) { Toast show = Toast.makeText(getBaseContext(), "Deleted", Toast.LENGTH_LONG); show.show(); Intent mainactivity1 = new Intent("hatim.dhuliawala.addressbook.ADDRESSACTIVITY"); startActivity(mainactivity1); // Hiding Keyboard InputMethodManager i = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); i.hideSoftInputFromInputMethod(deleteNickName.getWindowToken(), 0); this.finish(); } } break; case R.id.bDeleteRowId: boolean rowdel = true; try { String rowiddelete = deleteNickName.getText().toString(); if (deleteNickName.equals("")) { del = false; Toast err1 = Toast.makeText(getBaseContext(), "Please Enter NickName ", Toast.LENGTH_LONG); err1.show(); } else { AddressDatabase getrowiddata = new AddressDatabase(DeleteData.this); getrowiddata.open(); String data = getrowiddata.getDeleteRowId(rowiddelete); getrowiddata.close(); if(data.equals("")){ Toast err = Toast.makeText(getBaseContext(), "Enter Valid Nickname", Toast.LENGTH_LONG); err.show(); }else displayrowid.setText(data); } } catch (Exception e) { rowdel = false; e.printStackTrace(); Toast err = Toast.makeText(getBaseContext(), "Please Enter all Value", Toast.LENGTH_LONG); err.show(); } break; case R.id.bDeleteBack: Intent mainactivity = new Intent("hatim.dhuliawala.addressbook.ADDRESSACTIVITY"); startActivity(mainactivity); this.finish(); } } }
ed1c3ba49aea8334d0052b9fa00e7d0c5a7cb8a6
[ "Java" ]
4
Java
hatimsdhuliawala/Address-Book
3fbb23b94a9306832bc0c738c091149f5301e957
3f6adcd19417d5f0343a6321ff802ae1a818e5a3
refs/heads/master
<repo_name>taurus366/footProjectDinner<file_sep>/src/main/java/com/dinner/foot/data/entities/Supplement.java package com.dinner.foot.data.entities; import javax.persistence.*; import java.util.List; @Entity @Table(name = "Supplements") public class Supplement extends BaseEntity{ private String name; @ManyToMany() private List<Food> foods; @ManyToMany(mappedBy = "supplement") private List<Order> orders; public List<Order> getOrders() { return orders; } public void setOrders(List<Order> orders) { this.orders = orders; } public Supplement() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Food> getFoods() { return foods; } public void setFoods(List<Food> foods) { this.foods = foods; } } <file_sep>/src/main/java/com/dinner/foot/data/repositories/CityRepository.java package com.dinner.foot.data.repositories; import com.dinner.foot.data.entities.City; import org.springframework.data.jpa.repository.JpaRepository; public interface CityRepository extends JpaRepository<City,Integer> { City findByName(String name); } <file_sep>/src/main/java/com/dinner/foot/data/repositories/UserRepository.java package com.dinner.foot.data.repositories; import com.dinner.foot.data.entities.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User,Integer> { }
1d5abf1c71d9d18d0d7e0ebcefac3d0463c1817f
[ "Java" ]
3
Java
taurus366/footProjectDinner
8ff44d0bad21f042729b91bfff17f9f260c4486a
58398f248500ea505e25c4a218ddabc8f414f90f
refs/heads/master
<file_sep>#******* #* Read input from STDIN #* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line. #* Use: sys.stderr.write() to display debugging information to STDERR #* ***/ import sys from operator import itemgetter def toto (): tmp_res = '' a = input() nb_cab = int(a.split(' ')[0]) nb_req = int(a.split(' ')[1]) dat = [] for i in range (0,nb_req): a = input() dat.append ([int(a.split(' ')[0]), int(a.split(' ')[1]) ]) #sorted (dat) dat.sort (key=itemgetter(0)) free_cbl = [] for i in range (1,nb_cab+1): free_cbl.append (-1) for i in range (0,2500): for x in range (0,nb_req): if dat[x][1]==i: cab_nb = free_cbl.index (x) free_cbl[cab_nb] = -1 for x in range (0,nb_req): if dat[x][0]==i: try : cab_nb = free_cbl.index (-1) free_cbl[cab_nb] = x tmp_res += str (cab_nb+1) + ' ' except: print ("pas possible") return 0 print (tmp_res[:-1]) toto()<file_sep># b-dev-test Python Wrapper for B dev ## Init your PC : You can do it manually or via VSCODE Task : **Manually :** From root folder on the repo : * create a venv ``` python3.7 -m venv python3.7-venv ``` * install colored plugin ``` ./python3.7-venv/bin/activate pip install colored ``` **From VSCODE Task :** Ctrl+alt+T ==> "Init VENV" Then select the new venv as venv for the project, and install linter. after done : Ctrl+alt+T ==> "Install modules" ## Setup a new exercice for each exercice, create a folder and a python script inside with the same name. Exemple : ./my_exo1/my_exo1.py Inside the exercice folder create a "sample" folder and put in it the input/output files from battle dev. ## Launch your code Write your code in the exercice file, exemple in ./my_exo1/my_exo1.py, as it is in the web interface of battle Dev. In Wrapper.py, change the settings with the exercice you working on : ```python ################################ SETTINGS ex_to_launch = "M2016-ex1" input_to_open = "input1.txt" output_to_compare = "output1.txt" ################################ ``` Then simply launch wrapper.py **If using VSCODE**, launch.json is set to always launching ./wrapper.py with the current openned script, so you can F5 directly from exercice tab to launch it with wrapper :) <file_sep>#******* #* Read input from STDIN #* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line. #* Use: sys.stderr.write() to display debugging information to STDERR #* ***/ import sys my_place = int(input ()) for i in range (42): perte, gain = map (int,input().split()) my_place -= gain-perte gain = 0 if my_place<=100: gain += 1000 elif my_place<=10000: gain += 100 if gain==0: print ("KO") else: print (gain)<file_sep>#******* #* Read input from STDIN #* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line. #* Use: sys.stderr.write() to display debugging information to STDERR #* ***/ import sys import itertools anc_temple = input() lst_ville = set() links = {} ville = [] liens_ville = [] for i in range (0, 21): a = input() lst_ville.add (a.split(' ')[0]) lst_ville.add (a.split(' ')[1]) ville_A = a.split(' ')[0] ville_B = a.split(' ')[0] #if not ville_A in links : links[ville_A] = ville_B links[ville_B] = ville_A if not ville_A in ville: ville.append (ville_A) liens_ville.append (0) if not ville_B in ville: ville.append (ville_B) liens_ville.append (0) i = ville.index (ville_A) liens_ville[i]+=1 print ("a") <file_sep>#******* #* Read input from STDIN #* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line. #* Use: sys.stderr.write() to display debugging information to STDERR #* ***/ import sys largeur = int(input()) niv = input() s_prev = '*' max = 1 cur_jump=1 for s in niv: if s == '_': cur_jump+=1 if s == "-" and s_prev == '_': if cur_jump>max: max = cur_jump cur_jump=1 s_prev = s print (max) <file_sep>#******* #* Read input from STDIN #* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line. #* Use: sys.stderr.write() to display debugging information to STDERR #* ***/ # E > F # F > P # P > E import sys from collections import Counter from itertools import permutations m_team_size = int (input ()) m_team = input () count_t = Counter (m_team) e_team_size = int (input ()) e_team = input () t_comp = list() t_typ = 'EFP' def brute_team (ind, curr): global m_team_size global t_comp global t_typ global count_t for typ in t_typ: l_curr = curr if ind<m_team_size-1: brute_team (ind+1, l_curr + typ) else : count_c = Counter (l_curr + typ) if count_c['E']==count_t['E'] and count_c['F']==count_t['F'] and count_c['P']==count_t['P']: t_comp.append (l_curr + typ) def test_comp (comp1, comp2): def best_w (w1, w2): # E > F # F > P # P > E b = ["EE=","EF+","EP-","FE-","FF=","FP+","PE+","PF-","PP="] for poss in b: if poss[0:2] == (w1 + w2): return poss[2] fight_end = False t1_warrior_ind = 0 t2_warrior_ind = 0 while not fight_end: if t1_warrior_ind>=len(comp1) and t2_warrior_ind>=(len(comp2)): return "=" elif t1_warrior_ind>=len(comp1) and t2_warrior_ind<(len(comp2)): return "-" elif t1_warrior_ind<len(comp1) and t2_warrior_ind>=(len(comp2)): return "+" res_battle = best_w (comp1[t1_warrior_ind], comp2[t2_warrior_ind]) if res_battle == '=' : t1_warrior_ind += 1 t2_warrior_ind += 1 if res_battle == "+": t2_warrior_ind += 1 if res_battle == "-": t1_warrior_ind += 1 point = {'-':-1, '=':0,'+':1} best_res = '-' best_res_full = '-' t_comp = permutations (m_team, len (m_team)) #brute_team (0, '') for team in t_comp: res = test_comp (team, e_team) if point[res]>=point[best_res]: best_res=res best_res_full = res + ''.join (team) print(best_res_full) #sys.stderr.write(str(t_comp))<file_sep>#!/usr/bin/env python3 ################################ SETTINGS ex_to_launch = "M2017_BD_ex5" input_to_open = "input1.txt" output_to_compare = "output1.txt" ################################ import sys, os, glob, io import colored from contextlib import redirect_stdout from importlib import reload import importlib import subprocess root_dir = os.path.dirname(os.path.realpath(__file__)) reset = colored.attr('reset') green = reset + colored.fg('green') red = reset + colored.fg('red') yellow = reset + colored.fg ('yellow') blue = reset + colored.fg ('blue') white_on_blue = reset + colored.fg ('white') + colored.bg ('blue') red_on_blue = reset + colored.fg ('red') + colored.bg ('blue') white_on_green = reset + colored.fg ('white') + colored.bg ('green') white_on_yellow = reset + colored.fg ('white') + colored.bg ('yellow') white_on_red = reset + colored.fg ('white') + colored.bg ('red') white = reset + colored.fg ('white') are_tests_ok = True missing_file = False nb_input_file = 0 mod_loaded = False mod = "" ############################################### Functions def exec_exe (p_ex_to_launch, p_input_to_open, p_output_to_compare ): global are_tests_ok global mod_loaded global mod i_lines = [] #store Input lines c_lines = [] #store Correct Lines (output file) o_lines = [] #store my Output with open (root_dir + "/" + p_ex_to_launch + "/sample/" + p_input_to_open ,"r") as f: i_lines = f.readlines () with open (root_dir + "/" + p_ex_to_launch + "/sample/" + p_output_to_compare ,"r") as f: c_lines = f.readlines () sys.stderr.write(white +'INPUT DATA :\n' + ''.join(i_lines[:]) + "\n\n") sys.stderr.write(white +'CORRECT OUTPUT DATA :\n ' + ''.join(c_lines[:]) + "\n\n") ################################################## sys.stdin = io.StringIO(''.join(i_lines)) stream = io.StringIO() with redirect_stdout(stream): #if not mod_loaded: # mod = __import__ (p_ex_to_launch+'.'+p_ex_to_launch) # mod_loaded = True #else: # mod = reload (mod) name = p_ex_to_launch+'.'+p_ex_to_launch spec = importlib.util.find_spec(name) modul = importlib.util.module_from_spec(spec) sys.modules[name] = modul spec.loader.exec_module(modul) o_lines = stream.getvalue().split("\n")[0:-1] #scrpt = os.path.join (root_dir, p_ex_to_launch, p_ex_to_launch + ".py") #o_lines = subprocess.run(["python",scrpt], capture_output=True, text=True, input=''.join(i_lines) ).stdout #if o_lines[-1:]=="\n": # o_lines=o_lines[0:-1] #o_lines = o_lines.split('\n') ################################################## #print (o_lines) if len(c_lines)!=len(o_lines): print (red + f"KO nb of line differ from corrects lines ({len(c_lines)}) to my lines ({len(o_lines)})") are_tests_ok = False else : print (green + f"Nb of result lines are matching ({len(c_lines)})") for i,l in enumerate (c_lines): if i< len (o_lines): if l != o_lines [i]: print (red + f"KO on line {str (i)} :\n correct lines : {l}\n my lines : {o_lines[i]}") are_tests_ok = False else : print (green + f"OK on line {str (i)} :\n correct lines : {l}\n my lines : {o_lines[i]}") ############################################### Main Script all_sample = False try : if len (sys.argv[1])!=0 and sys.argv[1]!="wrapper" : print (blue + "Using ARG as exercice to launch : " + sys.argv[1]) ex_to_launch = sys.argv[1] if len (sys.argv[2])!=0 and sys.argv[2]=="--all-samples" : all_sample = True except: pass all_sample = False if not all_sample: exec_exe (ex_to_launch, input_to_open, output_to_compare ) nb_input_file +=1 else: for input_file in os.listdir( root_dir + "/" + ex_to_launch + "/sample"): if input_file.startswith("input") and input_file.endswith(".txt"): input_file_name, input_file_ext = os.path.splitext (os.path.basename (input_file)) output_file="output"+input_file_name[5:]+input_file_ext output_file_full_path = os.path.join (root_dir, ex_to_launch , "sample", output_file) if not os.path.exists(output_file_full_path) : sys.stderr.write (red_on_blue + f"ERROR, NOT FINDING THE OUTPUT FILE {output_file_full_path} CORRESPONDING TO INPUT FILE {input_file} \n\n" ) missing_file = True else : sys.stderr.write (white_on_blue + f'\n-------------------\nLAUNCHING WITH FILE {input_file_name} \n') exec_exe (ex_to_launch, input_file, output_file) nb_input_file +=1 sys.stderr.write ('\n\n') if are_tests_ok==True: if not missing_file: print (white_on_green + f"Hey, tests seem's ok for all input files ({nb_input_file})!") else: print (white_on_yellow + f"Seem's ok but missing files !") else: print (white_on_red + "Don't give up, try again :)") print (reset, end='')<file_sep>#******* #* Read input from STDIN #* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line. #* Use: sys.stderr.write() to display debugging information to STDERR #* ***/ import sys from operator import itemgetter a = input() nb_pierre = int(a.split(' ')[0]) nb_poudre = int(a.split(' ')[1]) cont = int(a.split(' ')[2]) pierres = [] for i in range (0, nb_pierre): a = input() pierres.append ([ 'pierre', int(a.split(' ')[0]), int(a.split(' ')[1]), int(a.split(' ')[0])/int(a.split(' ')[1] ) ] ) #pierres.sort (key=itemgetter(2), reverse=True) poudres = [] for i in range (0, nb_poudre): a = input() poudres.append ([ 'poudre', int(a.split(' ')[1]) * int(a.split(' ')[0]), int(a.split(' ')[1]), int(a.split(' ')[0]) ] ) #poudres.sort (key=itemgetter(2), reverse=True) all = [] all.extend (pierres) all.extend (poudres) all.sort (key=itemgetter(3), reverse=True) reste = cont again = True valeur = 0 #0 : type #1 : valeur tot #2 : poids dispo en g #3 : prix au g while again: if reste>=all[0][2]: reste -= all[0][2] valeur += all[0][1] all.pop(0) elif reste<all[0][2]: if all[0][0]=='pierre': all.pop(0) else: valeur += reste * all[0][3] reste = 0 if len (all)==0: again = False if reste ==0: again = False print (valeur) <file_sep>#******* #* Read input from STDIN #* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line. #* Use: to display debugging information to STDERR #* ***/ import sys from itertools import permutations nb = int(input()) mots = [] lettres = set () for i in range (0, nb): mots.append (input()) for l in mots[-1]: lettres.add (l) lettres.add (" ") for y in range (1,10): sys.stderr.write ("perm deep " + str (y) + '\n') for perm in permutations (lettres,y): sys.stderr.write ("Test perm" + str(perm) + '\n') resp = [] for i,mot in enumerate (mots): resp.append (mot) for p_letter in perm: if resp[i].find (p_letter): resp[i] = resp[i].replace (p_letter, '') ok = True for i in range (1, len (resp)): #sys.stderr.write (resp[i]) #sys.stderr.write (resp[i-1]) #sys.stderr.write (str (resp[i]!=resp[i-1])) if resp[i]!=resp[i-1]: ok = False if ok: print (resp[0]) quit() #sys.stderr.write(str(mots)) #sys.stderr.write(str(poss)) <file_sep>#******* #* Read input from STDIN #* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line. #* Use: sys.stderr.write() to display debugging information to STDERR #* ***/ import sys import copy class Dead_Past(Exception): """Raised when PAst in Dead""" pass class Win(Exception): """Raised when Win""" pass class No_More_Move(Exception): """Raised when Win""" pass world_h = int(input()) space = [] for line in sys.stdin: space.append(list(line.rstrip('\n'))) def find_past (space): for i_l, l in enumerate (space): for i_c, c in enumerate (space[i_l]): if c == "O": return [i_c, i_l] def next_space_time (prev): """ futur = list () for i_l, l in enumerate (prev): futur.append([]) for i_c, c in enumerate (prev[i_l]): futur[i_l].append(prev[i_l][i_c]) """ futur = copy.deepcopy(prev) move_done = False possible_move = [ [0,-1], [+1,0], [0,+1], [-1,0], ] for i_l, l in enumerate (prev): for i_c, c in enumerate (prev[i_l]): if c == "M": for x, y in possible_move: real_y = i_l+y if real_y >= len (futur): real_y = real_y - len (futur) real_x = i_c+x if real_x >= len (futur[real_y]): real_x = real_x - len (futur[real_y]) if futur[real_y][real_x ]=="." or futur[real_y][real_x ]=="C" : futur[real_y][real_x ]="M" move_done=True elif futur[real_y][real_x ]=="O": raise Dead_Past for i_l, l in enumerate (prev): for i_c, c in enumerate (prev[i_l]): if c == "C": for x, y in possible_move: real_y = i_l+y if real_y >= len (futur): real_y = real_y - len (futur) real_x = i_c+x if real_x >= len (futur[real_y]): real_x = real_x - len (futur[real_y]) if futur[real_y][real_x]=="." : futur[real_y][real_x]="C" move_done=True elif futur[real_y][real_x]=="O": raise Win if not move_done: raise No_More_Move return futur space_time = [] space_time.append (space) ### wher is the PAstille ? Past_X, Past_Y = find_past (space) ###Si pas de fantome on ne calcul rien casper = False for l in space: if "M" in l: casper = True break if casper: try : i = 0 while True: space_time.append (next_space_time (space_time[i])) i +=1 except Dead_Past: print ("0") except No_More_Move: print ("0") except Win: print (str(i+1)) else: pass pass <file_sep>#******* #* Read input from STDIN #* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line. #* Use: sys.stderr.write() to display debugging information to STDERR #* ***/ """ Format des données Entrée Ligne 1 : un entier N compris entre 1 et 1000, indiquant le nombre de pylônes le long de la vallée. Lignes 2 à N+1 : la hauteur d'un pylône, un entier compris entre 1 et 100. """ import sys lines = [] for line in sys.stdin: lines.append(line.rstrip('\n')) <file_sep>#******* #* Read input from STDIN #* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line. #* Use: sys.stderr.write() to display debugging information to STDERR #* ***/ import sys nb_games = int(input()) an = [] for i in range (nb_games): an.append (int(input())) print (str (max (an) - min (an)))<file_sep>#!/usr/bin/env python3 import sys, os, glob, io import urllib.request import subprocess import shutil root_dir = os.path.dirname(os.path.realpath(__file__)) if len (sys.argv)<3 : print ("Need two parameter : NAME_OF_EXO URL_OF_ZIP_SAMPLE") quit(1) NAME = sys.argv[1] URL = sys.argv[2] if os.path.exists(os.path.join(root_dir, NAME)): print (f"{NAME} already exist") quit(1) try : sample_dir = os.path.join(root_dir, NAME, 'sample') os.makedirs(sample_dir, exist_ok=False) f = open (os.path.join(root_dir, NAME, NAME+'.py'), 'w+') f.close() except : print (f"Error creating folders and file !!") quit(1) try: local_zip_file = os.path.join(root_dir, NAME, 'sample', '__tmpx.zip') urllib.request.urlretrieve(URL, local_zip_file ) except Exception as e : print (f"Error downloading file !!!" + str(e)) quit(1) try: subprocess.call (['unzip', local_zip_file ], cwd=sample_dir) LS = os.listdir (sample_dir) DIRS = [os.path.join(sample_dir,name) for name in LS if os.path.isdir(os.path.join(sample_dir,name))] if len (DIRS)>1: raise Exception ("MORE THAN ONE DIR IN SAMPLE DIR") files = os.listdir(DIRS[0]) files.sort() for f in files: src = os.path.join(DIRS[0],f) dst = os.path.join(sample_dir,f) shutil.move(src,dst) os.remove (local_zip_file) shutil.rmtree (DIRS[0]) except Exception as e : print (f"Error unpacking files !!!" + str(e)) quit(1)<file_sep>#******* #* Read input from STDIN #* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line. #* Use: sys.stderr.write() to display debugging information to STDERR #* ***/ """ Format des données Entrée Ligne 1 : un entier N compris entre 1 et 100000 indiquant le nombre de poteaux de l'entrée. Lignes 2 à N+1 : un entier compris entre 1 et 100000 représentant la hauteur d'un poteau. Sortie Un entier représentant la longueur totale de banderole que vous pourrez accrocher sur les poteaux en considérant que la distance entre deux poteaux consécutifs est de 1 mètre. """ import sys nb_pot = int(input()) pots = [] for line in sys.stdin: pots.append(int(line.rstrip('\n'))) banderole = 0 for i, pot in enumerate (pots): ok = True j = 1 while ok: if (i+j)>=nb_pot : ok=False else : if pots[i+j]<pot: banderole += 1 elif pots[i+j]==pot: banderole += 1 ok = False elif pots[i+j]>pot: ok = False j +=1 print (banderole)<file_sep>#******* #* Read input from STDIN #* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line. #* Use: sys.stderr.write() to display debugging information to STDERR #* ***/ import sys prenom = [] taille = [] nb = int(input()) for i in range (0,nb): inp = input() prenom.append (inp.split(' ')[0]) taille.append (int(inp.split(' ')[1])) xmin = min(taille) print (prenom[taille.index(xmin)]) <file_sep>#******* #* Read input from STDIN #* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line. #* Use: sys.stderr.write() to display debugging information to STDERR #* ***/ import sys pl=[] for i in range (0,4): pl.append (int(input())) lng = min (pl) j = 0 for p in pl: j += p-lng print (j)<file_sep>#******* #* Read input from STDIN #* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line. #* Use: sys.stderr.write() to display debugging information to STDERR #* *** import sys #################### #print ("YYYYYYYYYYYYYYYYYY") #quit() #################### N = int (input()) #NUM = [map (int, input().split())] NUM= [int(i) for i in input().split() ] AVERAGE = N/2 #sys.stderr.write(str(N) + "\n") #sys.stderr.write('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ' + str(N) + "seeking value :" + str(AVERAGE) + "\n") #sys.stderr.write(' '.join(map(str,NUM)) + "\n") RESULT = 0 P_VAL = NUM[0] for C_VAL in NUM [1:]: if P_VAL == C_VAL == AVERAGE : RESULT = -1 break if (P_VAL< AVERAGE <=C_VAL) or (P_VAL> AVERAGE >=C_VAL) : RESULT +=1 P_VAL = C_VAL if RESULT==-1: print ("INF") else: print (RESULT) <file_sep>#******* #* Read input from STDIN #* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line. #* Use: sys.stderr.write() to display debugging information to STDERR #* ***/ import sys lines = [] for line in sys.stdin: lines.append(line.rstrip('\n')) p1_lat, p1_lng, p2_lat, p2_lng = map (float, lines[0].split()) nb_ppl = int (lines[1]) nb_ppl_in = 0 for ppl in lines [2:nb_ppl+2]: ppl_lat, ppl_lng = map (float, ppl.split (" ")) if p1_lat <= ppl_lat <= p2_lat and p1_lng <= ppl_lng <= p2_lng: nb_ppl_in += 1 print (str(nb_ppl_in))<file_sep>if int(input())>=10: print ("JOB") else : print ("ECHEC")
f10a6ca624e6b6ed9643142c323c79d5e89cfdb2
[ "Markdown", "Python" ]
19
Python
mcandries/b-dev-test
057737166e36997ca3c063904902ef5ab371dd5b
2293e8461065f32b80f7e5b4639b66e7cbfbec0f
refs/heads/master
<repo_name>nesyoddoi/projectNumerical<file_sep>/src/index.js import React from 'react'; import ReactDOM from 'react-dom'; // import './index.css'; import App from './App'; import {Router,Route,Link,browserHistory} from 'react-router' import Bisection from './bisection'; import Falseposition from './false'; import Secant from './secant'; import Onepoint from './onepoint'; import Newton from './newton'; import Trapezoidal from './trape' import Comtrapezoidal from './comtrape' import Simpson from './simpson' import Comsimpson from './comsimpson' import Firstforward from './firstforward' import Backward from './backward' import Central from './central' import Firstforwardh2 from './firstforwardh2' import Backwardh2 from './backwardh2' import Centralh2 from './centralh2' import Cramer from './cramer' import 'antd/dist/antd.css'; // import Bisection1 from './test2'; ReactDOM.render( <Router history={browserHistory}> <Router path="/" component={App}/> <Router path="/bisection" component={Bisection}/> <Router path="/falseposition" component={Falseposition}/> <Router path="/onepoint" component={Onepoint}/> <Router path="/newton" component={Newton}/> <Router path="/secant" component={Secant}/> <Router path="/trapezoidal" component={Trapezoidal}/> <Router path="/comtrapezoidal" component={Comtrapezoidal}/> <Router path="/simpson" component={Simpson}/> <Router path="/comsimpson" component={Comsimpson}/> <Router path="/firstforward" component={Firstforward}/> <Router path="/backward" component={Backward}/> <Router path="/central" component={Central}/> <Router path="/firstforwardh2" component={Firstforwardh2}/> <Router path="/backwardh2" component={Backwardh2}/> <Router path="/centralh2" component={Centralh2}/> <Router path="/cramer" component={Cramer}/> </Router>, document.getElementById('root') ); <file_sep>/src/false.js import React, { Component } from 'react'; import { InputNumber,Button, Layout, Menu, Breadcrumb,Select,Table } from 'antd'; import './App.css'; import Sidebar from './Sidebar'; import { Cascader , Input } from 'antd'; import axios from 'axios'; import { parse } from 'mathjs'; // import Plot from 'react-plotly.js'; const { Header, Content, Footer, Sider } = Layout; const { Option } = Select; function onBlur() { console.log('blur'); } function onFocus() { console.log('focus'); } function onSearch(val) { console.log('search:', val); } class Falseposition extends Component { state = { collapsed: false, }; // handleSizeChange = e => { // this.setState({ size: e.target.value }); // }; onCollapse = collapsed => { console.log(collapsed); this.setState({ collapsed }); }; constructor(props) { super(props); this.state={ bisec:[], equation:"", xl:"", xr:"", Xm:null, datatable:[] }; } componentDidMount() { axios.get('http://localhost/numerical/php/falseposition.php') .then(res=>{ // console.log(res.data); let item =[]; res.data.map(dataMap=>{ item = item.concat(dataMap.equation); // console.log(item); }); this.setState({ bisec:item }); }); } Solve(Eq,xi) { const nEq = parse(Eq); const Equation = nEq.compile(); let scope = { x:xi } return Equation.eval(scope); } err(xmold, xmnew){ var er = ((Math.abs((xmnew - xmold) / xmnew)) * 100) / 100; return er; } falseposition=()=>{ // console.log(this.state); var eq = this.state.equation; var xl = parseFloat(this.state.xl); var xr = parseFloat(this.state.xr); var xm = (xl + xr) / 2; let tabledata = []; // console.log(eq+" "+xl+" "+xr+" "+xm); var xmold = xm; var fxl; var fxr; var fxm; var i = 0; var es = 0.00001; var er = 1; while (er >= es) { if (i != 0) { fxl = this.Solve(xl); fxr = this.Solve(xr); xm = ((xl*fxr)-(xr*fxl))/(fxr-fxl) } fxm = this.Solve(xm); if ((fxm * fxl) > 0) { xl = xm; } else { xr = xm; } if (i != 0) { er = this.err(xmold, xm); xmold = xm; // console.log("If Work"); } let table = {}; table.index = i; table.xl = xl; table.xr = xr; table.xm = xm; table.error = er; tabledata.push(table); i++; // console.log("XMVALUE = ", xm); } this.setState({Xm : xm,datatable:tabledata}) } handleChangeeq = (value) => { console.log('Selected',value); this.setState({ equation:value }) } handleChangexl = (value) => { console.log('xl',value); this.setState({ xl:value }) } handleChangexr = (value) => { console.log('xr',value); this.setState({ xr:value }) } showgraph = () =>{ const columns = [ { title: 'Iteration', dataIndex: 'index', key: 'index', }, { title: 'Xl', dataIndex: 'xl', key: 'xl', }, { title: 'Xr', dataIndex: 'xr', key: 'xr', }, { title: 'Xm', dataIndex: 'xm', key: 'xm', }, { title: 'Error', dataIndex: 'error', key: 'error' }, ]; if(this.state.Xm != null){ return <Table dataSource={this.state.datatable} columns={columns} />; } } render(){ return ( <Layout style={{ minHeight: '100vh' }}> <Sidebar/> <Layout className="site-layout"> {/* <Header className="site-layout-background" style={{ padding: 0 }}></Header> */} <Content style={{ margin: '0 16px' }}> <Breadcrumb style={{ margin: '16px 0' }}> <Breadcrumb.Item>Home</Breadcrumb.Item> <Breadcrumb.Item>False-position</Breadcrumb.Item> </Breadcrumb> <div className="site-layout-background" style={{ padding: 24, minHeight: 360 }}> FALSE-POSITION METHOD<br/><br/> <div> <Select showSearch style={{ width: 200 }} placeholder="Select your Function" onChange={this.handleChangeeq} onFocus={onFocus} onBlur={onBlur} onSearch={onSearch} > {this.state.bisec.map(e=>{ // console.log(e); return <Option value={e}>{e}</Option> })} </Select> </div> <br/> <div> <InputNumber placeholder="INITIAL NUMBER(xl)" style={{width:200}} value={this.state.xl} onChange={this.handleChangexl}/> </div> <br/> <div> <InputNumber placeholder="INITIAL NUMBER(xr)" style={{width:200}} value={this.state.xr} onChange={this.handleChangexr}/> </div> <br/> <div> <Button type="primary" onClick={this.falseposition}>Submit</Button> </div> <br /> {this.showgraph()} </div> </Content> <Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by Ant UED</Footer> </Layout> </Layout> ); } } export default Falseposition; <file_sep>/src/App.js import React, { Component } from 'react'; // import logo from './logo.svg'; // import './App.css'; // import {Link} from "react-router"; import { Layout, Menu, Breadcrumb } from 'antd'; import Sidebar from './Sidebar'; import {CaretRightOutlined } from '@ant-design/icons'; const { Header, Content, Footer, Sider } = Layout; const { SubMenu } = Menu; class App extends Component { state = { collapsed: false, }; onCollapse = collapsed => { console.log(collapsed); this.setState({ collapsed }); }; render(){ return ( <Layout style={{ minHeight: '100vh' }}> <Sidebar/> <Layout className="site-layout"> {/* <Header className="site-layout-background" style={{ padding: 0 }}></Header> */} <Content style={{ margin: '0 16px' }}> <Breadcrumb style={{ margin: '16px 0' }}> <Breadcrumb.Item>Home</Breadcrumb.Item> </Breadcrumb> <div className="site-layout-background" style={{ padding: 24, minHeight: 360 ,fontSize: "24px" ,color: "Black 85%",background: "#adc6ff"}}> <i>WELCOME TO NUMERICAL METHODS<br/><br/> &nbsp;&nbsp;&nbsp; <CaretRightOutlined />NIPAPORN DAOLOET (นิภาพร ดาวเลิศ) <br/> &nbsp;&nbsp;&nbsp; <CaretRightOutlined />5904062630292<br/> &nbsp;&nbsp;&nbsp; <CaretRightOutlined />SECTION : 1<br/> &nbsp;&nbsp;&nbsp; <CaretRightOutlined />PROFESSOR : ผู้ช่วยศาสตราจารย์ ดร. สุวัจชัย กมลสันติโรจน์ <br/><br/> COMPUTER SCIENCE<br/> FACULTY OF APPLIED SCIENCE<br/> KING MONGKUT'S UNIVERSITY OF TECHNOLOGY NORTH BANGKOK.</i> </div> </Content> <Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by <NAME></Footer> </Layout> </Layout> ); } } export default App; <file_sep>/src/comtrape.js import React, { Component } from 'react'; import { InputNumber,Button, Layout, Menu, Breadcrumb,Select,Table } from 'antd'; import './App.css'; import Sidebar from './Sidebar'; import { Cascader , Input } from 'antd'; import axios from 'axios'; import { parse} from 'mathjs'; // import Plot from 'react-plotly.js'; var Algebrite = require('algebrite') // import Algebrite from 'mathjs-simple-integral'; const { Header, Content, Footer, Sider } = Layout; const { Option } = Select; const InputStyle = { background: "#08979c", color: "white", fontWeight: "bold", fontSize: "24px" }; function onBlur() { console.log('blur'); } function onFocus() { console.log('focus'); } function onSearch(val) { console.log('search:', val); } class Comtrapezoidal extends Component { state = { collapsed: false, }; // handleSizeChange = e => { // this.setState({ size: e.target.value }); // }; onCollapse = collapsed => { console.log(collapsed); this.setState({ collapsed }); }; constructor(props) { super(props); this.state={ comtrape:[], equation:"", check:null, a:"", b:"", n:"", I:"", error:"", exact:"", showOutput:false }; } componentDidMount() { axios.get('http://localhost/numerical/php/trapezoidal.php') .then(res=>{ // console.log(res.data); let item =[]; res.data.map(dataMap=>{ item = item.concat(dataMap.equation); // console.log(item); }); this.setState({ comtrape:item }); }); } Solve(Eq,xi) { const nEq = parse(Eq); const Equation = nEq.compile(); let scope = { x:xi } return Equation.eval(scope); } err(cal, exact) { var er = ((Math.abs((exact - cal) / exact))*100)/100; return er; } exact(Eq,xi) { const node = parse(Eq); var expr = node.compile(Algebrite.integral(node)); let scope = { x:xi } return expr.eval(scope) ; } comtrapezoidal=()=>{ var eq = this.state.equation; var a = parseFloat(this.state.a); var b = parseFloat(this.state.b); var n = parseInt(this.state.n); var h=(b-a)/n; var x =[n]; var fx =[n]; x[0]=a; var sum=0; fx[0]=this.Solve(eq,x[0]); // fx[n-1]=this.Solve(eq,x[n-1]); for(var j=1;j<=n;j++) { x[j]=x[j-1]+h; fx[j]=this.Solve(eq,x[j]); } // console.log(x); // console.log(fx); // fx[n-1]=this.Solve(eq,x[n-1]); for(var j=1;j<=n-1;j++) { sum+=2*fx[j]; // console.log(j); // console.log(sum); } var cal=(h/2)*(fx[0]+sum+fx[n]); var exact = this.exact(eq,b)-this.exact(eq,a); var error = this.err(cal,exact); this.setState({I:cal,error:error,exact:exact,showOutput:true}) } handleChangeeq = (value) => { console.log('Selected',value); this.setState({ equation:value }); } handleChangea = (value) => { console.log('a',value); this.setState({ a:value }); } handleChangeb = (value) => { console.log('b',value); this.setState({ b:value }); } handleChangen = (value) => { console.log('n',value); this.setState({ n:value }); } render(){ return ( <Layout style={{ minHeight: '100vh' }}> <Sidebar/> <Layout className="site-layout"> {/* <Header className="site-layout-background" style={{ padding: 0 }}></Header> */} <Content style={{ margin: '0 16px' }}> <Breadcrumb style={{ margin: '16px 0' }}> <Breadcrumb.Item>Home</Breadcrumb.Item> <Breadcrumb.Item>Composite Trapezoidal's Rule</Breadcrumb.Item> </Breadcrumb> <div className="site-layout-background" style={{ padding: 24, minHeight: 360 }}> COMPOSITE TRAPEZOIDAL'S RULE<br/><br/> <div> <Select showSearch style={{ width: 200 }} placeholder="Select your Function" onChange={this.handleChangeeq} onFocus={onFocus} onBlur={onBlur} onSearch={onSearch} > {this.state.comtrape.map(e=>{ // console.log(e); return <Option value={e}>{e}</Option> })} </Select> </div> <br/> <div> <InputNumber placeholder="INITIAL NUMBER(a)" style={{width:200}} value={this.state.a} onChange={this.handleChangea}/> </div> <br/> <div> <InputNumber placeholder="INITIAL NUMBER(b)" style={{width:200}} value={this.state.b} onChange={this.handleChangeb}/> </div> <br/> <div> <InputNumber placeholder="INITIAL NUMBER(n)" style={{width:200}} value={this.state.n} onChange={this.handleChangen}/> </div> <br/> <div> <Button type="primary" onClick={this.comtrapezoidal}>Submit</Button> </div> <br /> {this.state.showOutput && <div style={InputStyle}> OUTPUT <br/> I : {this.state.I}<br/> EXACT : {this.state.exact}<br/> ERROR : {this.state.error} </div> } </div> </Content> <Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by <NAME></Footer> </Layout> </Layout> ); } } export default Comtrapezoidal; <file_sep>/src/cramer.js import React, { Component } from 'react'; import { InputNumber,Button, Layout, Menu, Breadcrumb,Select,Table,Card } from 'antd'; import './App.css'; import Sidebar from './Sidebar'; import { Cascader , Input } from 'antd'; import axios from 'axios'; import { parse,derivative,det } from 'mathjs'; // import Plot from 'react-plotly.js'; const { Header, Content, Footer, Sider } = Layout; var A = [], B = [], answer = [], matrixA = [], matrixB = [] class Cramer extends Component { constructor() { super(); this.state={ row:"", column:"", check:null, x0:"", showInput: true, showOutput: false, showMatrix: false, showButtonMatrix:false }; } createMatrix(row, column) { for (var i=1 ; i<=row ; i++) { for (var j=1 ; j<=column ; j++) { matrixA.push(<Input style={{ width: "10%", height: "50%", backgroundColor:"#Gray", marginInlineEnd: "5%", marginBlockEnd: "5%", color: "Black", fontSize: "14px", fontWeight: "bold" }} id={"a"+i+""+j} key={"a"+i+""+j} placeholder={"a"+i+""+j} />) } matrixA.push(<br/>) matrixB.push(<Input style={{ width: "10%", height: "50%", backgroundColor:"black", marginInlineEnd: "5%", marginBlockEnd: "5%", color: "white", fontSize: "14px", fontWeight: "bold" }} id={"b"+i} key={"b"+i} placeholder={"b"+i} />) } this.setState({ showInput: false, showMatrix: true, showButtonMatrix:true }) } handleChangerow = (value) => { console.log('Selected',value); this.setState({ row:value }); } handleChangecolum = (value) => { console.log('a',value); this.setState({ column:value }); } cramer() { this.initMatrix(); var counter=0; // eslint-disable-next-line eqeqeq while (counter != this.state.row) { var transformMatrix = JSON.parse(JSON.stringify(A));//Deep copy for (var i=0 ; i<this.state.row ; i++) { for (var j=0 ; j<this.state.column ; j++) { if (j === counter) { transformMatrix[i][j] = B[i] break; } } } counter++; answer.push(<h2>X<sub>{counter}</sub>=&nbsp;&nbsp;{Math.round(det(transformMatrix))/Math.round(det(A))}</h2>) } this.setState({ showOutput: true, showButtonMatrix:false }); } initMatrix() { for(var i=0 ; i<this.state.row ; i++) { A[i] = [] for(var j=0 ; j<this.state.column ; j++) { A[i][j] = (parseFloat(document.getElementById("a"+(i+1)+""+(j+1)).value)); } B.push(parseFloat(document.getElementById("b"+(i+1)).value)); } } render(){ return ( <Layout style={{ minHeight: '100vh' }}> <Sidebar/> <Layout className="site-layout"> {/* <Header className="site-layout-background" style={{ padding: 0 }}></Header> */} <Content style={{ margin: '0 16px' }}> <Breadcrumb style={{ margin: '16px 0' }}> <Breadcrumb.Item>Home</Breadcrumb.Item> <Breadcrumb.Item>Cramer's Rule</Breadcrumb.Item> </Breadcrumb> <div className="site-layout-background" style={{ padding: 24, minHeight: 360 }}> CRAMER'S RULE<br/><br/> {this.state.showInput && <div>Create your Matrix: <div> <InputNumber placeholder="INITIAL NUMBER(row)" style={{width:200}} value={this.state.row} onChange={this.handleChangerow} /> </div><br/> <div> <InputNumber placeholder="INITIAL NUMBER(column)" style={{width:200}} value={this.state.column} onChange={this.handleChangecolum}/> </div> <br/> <div> <Button type="primary" onClick= {()=>this.createMatrix(this.state.row, this.state.column)} >Submit</Button> </div> <br /> </div> } {this.state.showMatrix && <div><h2>Matrix [A]</h2>{matrixA}<br/><h2>Vector [B]<br/></h2>{matrixB}<br/><br/> </div> } {this.state.showButtonMatrix && <div> <Button type="primary" onClick= {()=>this.cramer()} >Submit</Button> </div> } <br/> {this.state.showOutput && <div ><b style={{ fontSize:"20px" ,color:"#f5222d"}}>OUTPUT </b><br/><p>{answer}</p></div>} </div> </Content> <Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by <NAME></Footer> </Layout> </Layout> ); } } export default Cramer; <file_sep>/src/newton.js import React, { Component } from 'react'; import { InputNumber,Button, Layout, Menu, Breadcrumb,Select,Table } from 'antd'; import './App.css'; import Sidebar from './Sidebar'; import { Cascader , Input } from 'antd'; import axios from 'axios'; import { parse,derivative } from 'mathjs'; // import Plot from 'react-plotly.js'; const { Header, Content, Footer, Sider } = Layout; const { Option } = Select; function onBlur() { console.log('blur'); } function onFocus() { console.log('focus'); } function onSearch(val) { console.log('search:', val); } class Newton extends Component { state = { collapsed: false, }; // handleSizeChange = e => { // this.setState({ size: e.target.value }); // }; onCollapse = collapsed => { console.log(collapsed); this.setState({ collapsed }); }; constructor(props) { super(props); this.state={ newton:[], equation:"", check:null, x0:"", datatable:[] }; } componentDidMount() { axios.get('http://localhost/numerical/php/newtonrap.php') .then(res=>{ // console.log(res.data); let item =[]; res.data.map(dataMap=>{ item = item.concat(dataMap.equation); // console.log(item); }); this.setState({ newton:item }); }); } Solve(Eq,xi) { const nEq = parse(Eq); const Equation = nEq.compile(); let scope = { x:xi } return Equation.eval(scope); } err(xold, xnew) { var er = ((Math.abs((xnew - xold) / xnew))*100)/100; return er; } onepoint=()=>{ // console.log(this.state); var eq = this.state.equation; var eq1 = derivative(this.state.equation,'x'); // console.log(eq1.toString()); var x0 = parseFloat(this.state.x0); let tabledata = []; var i=0; var xi; var fixerror = 0.00001; var error=1; while(error >= fixerror) { // x = this.Equet(eq,x0); // xd = this.Equet(eq1,x0); // console.log(xnew); xi=x0-(this.Solve(eq,x0)/this.Solve(eq1.toString(),x0)); error= this.err(x0,xi); let table = {}; table.index = i; table.xold = x0; table.xnew = xi; // table.xm = xm; table.error = error; tabledata.push(table); x0=xi; i++; } this.setState({check:xi,datatable:tabledata}) } handleChangeeq = (value) => { console.log('Selected',value); this.setState({ equation:value }); } handleChangex0 = (value) => { console.log('x',value); this.setState({ x0:value }); } showgraph = () =>{ const columns = [ { title: 'Iteration', dataIndex: 'index', key: 'index', }, { title: 'X(i)', dataIndex: 'xold', key: 'xold', }, { title: 'X(i+1)', dataIndex: 'xnew', key: 'xnew', }, { title: 'Error', dataIndex: 'error', key: 'error' }, ]; if(this.state.check != null){ return <Table dataSource={this.state.datatable} columns={columns} />; } } render(){ return ( <Layout style={{ minHeight: '100vh' }}> <Sidebar/> <Layout className="site-layout"> {/* <Header className="site-layout-background" style={{ padding: 0 }}></Header> */} <Content style={{ margin: '0 16px' }}> <Breadcrumb style={{ margin: '16px 0' }}> <Breadcrumb.Item>Home</Breadcrumb.Item> <Breadcrumb.Item>Newton-Raphson Method</Breadcrumb.Item> </Breadcrumb> <div className="site-layout-background" style={{ padding: 24, minHeight: 360 }}> NEWTON-RAPHSON METHOD<br/><br/> <div> <Select showSearch style={{ width: 200 }} placeholder="Select your Function" onChange={this.handleChangeeq} onFocus={onFocus} onBlur={onBlur} onSearch={onSearch} > {this.state.newton.map(e=>{ // console.log(e); return <Option value={e}>{e}</Option> })} </Select> </div> <br/> <div> <InputNumber placeholder="INITIAL NUMBER(X)" style={{width:200}} value={this.state.x0} onChange={this.handleChangex0}/> </div> <br/> <div> <Button type="primary" onClick={this.onepoint}>Submit</Button> </div> <br /> {this.showgraph()} </div> </Content> <Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by Ant UED</Footer> </Layout> </Layout> ); } } export default Newton; <file_sep>/php/connect.php <?php header("Access-Control-Allow-Origin: http://localhost:3000"); $hostname = "localhost"; $username = "root"; $password = ""; $dbname = "numer"; $connect = mysqli_connect($hostname,$username,$password,$dbname); if($connect->connect_error) { die("Connect Failed : " .$connect->connect_error); } // echo "Connect Successfully !!"; // $con= mysqli_connect("localhost","root","","numer") or die("Error: " . mysqli_error($con)); // mysqli_query($con, "SET NAMES 'utf8' "); ?><file_sep>/numer.sql -- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Mar 25, 2020 at 01:55 PM -- Server version: 10.1.38-MariaDB -- PHP Version: 7.3.3 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 */; -- -- Database: `numer` -- -- -------------------------------------------------------- -- -- Table structure for table `backward` -- CREATE TABLE `backward` ( `id` int(11) NOT NULL, `equation` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `backward` -- INSERT INTO `backward` (`id`, `equation`) VALUES (1, 'x^3'); -- -------------------------------------------------------- -- -- Table structure for table `bisection` -- CREATE TABLE `bisection` ( `id` int(11) NOT NULL, `equation` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `bisection` -- INSERT INTO `bisection` (`id`, `equation`) VALUES (1, 'x^4-13'), (2, 'x^10-1'), (3, 'x^2+3'); -- -------------------------------------------------------- -- -- Table structure for table `central` -- CREATE TABLE `central` ( `id` int(11) NOT NULL, `equation` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `central` -- INSERT INTO `central` (`id`, `equation`) VALUES (1, 'x^3'); -- -------------------------------------------------------- -- -- Table structure for table `falseposition` -- CREATE TABLE `falseposition` ( `id` int(11) NOT NULL, `equation` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `falseposition` -- INSERT INTO `falseposition` (`id`, `equation`) VALUES (1, '43*x-1'), (2, '14*x-1'); -- -------------------------------------------------------- -- -- Table structure for table `firstforward` -- CREATE TABLE `firstforward` ( `id` int(11) NOT NULL, `equation` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `firstforward` -- INSERT INTO `firstforward` (`id`, `equation`) VALUES (1, 'x^3'); -- -------------------------------------------------------- -- -- Table structure for table `newton` -- CREATE TABLE `newton` ( `id` int(11) NOT NULL, `equation` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `newton` -- INSERT INTO `newton` (`id`, `equation`) VALUES (1, 'x^2-7'), (2, 'cos(x)-2x'), (3, 'sin(x)-x^2'); -- -------------------------------------------------------- -- -- Table structure for table `onepoint` -- CREATE TABLE `onepoint` ( `id` int(11) NOT NULL, `equation` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `onepoint` -- INSERT INTO `onepoint` (`id`, `equation`) VALUES (1, 'e^-x'), (2, '1/4+x/2'), (3, '4*e^-x'); -- -------------------------------------------------------- -- -- Table structure for table `secant` -- CREATE TABLE `secant` ( `id` int(11) NOT NULL, `equation` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `secant` -- INSERT INTO `secant` (`id`, `equation`) VALUES (1, 'x^2-7'), (2, '2e^x+x-4'); -- -------------------------------------------------------- -- -- Table structure for table `simpson` -- CREATE TABLE `simpson` ( `id` int(11) NOT NULL, `equation` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `simpson` -- INSERT INTO `simpson` (`id`, `equation`) VALUES (1, 'x^7+2*x^3-1'), (2, '2*x^3-5*x^2+3*x+1'); -- -------------------------------------------------------- -- -- Table structure for table `trapezoidal` -- CREATE TABLE `trapezoidal` ( `id` int(11) NOT NULL, `equation` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `trapezoidal` -- INSERT INTO `trapezoidal` (`id`, `equation`) VALUES (1, '2*x^3-5*x^2+3*x+1'), (2, '4*x^5-3*x^4+x^3-6*x+2'), (3, '2x^3-5x^2+3x+1'), (4, 'x^2'); -- -- Indexes for dumped tables -- -- -- Indexes for table `backward` -- ALTER TABLE `backward` ADD PRIMARY KEY (`id`); -- -- Indexes for table `bisection` -- ALTER TABLE `bisection` ADD PRIMARY KEY (`id`); -- -- Indexes for table `central` -- ALTER TABLE `central` ADD PRIMARY KEY (`id`); -- -- Indexes for table `falseposition` -- ALTER TABLE `falseposition` ADD PRIMARY KEY (`id`); -- -- Indexes for table `firstforward` -- ALTER TABLE `firstforward` ADD PRIMARY KEY (`id`); -- -- Indexes for table `newton` -- ALTER TABLE `newton` ADD PRIMARY KEY (`id`); -- -- Indexes for table `onepoint` -- ALTER TABLE `onepoint` ADD PRIMARY KEY (`id`); -- -- Indexes for table `secant` -- ALTER TABLE `secant` ADD PRIMARY KEY (`id`); -- -- Indexes for table `simpson` -- ALTER TABLE `simpson` ADD PRIMARY KEY (`id`); -- -- Indexes for table `trapezoidal` -- ALTER TABLE `trapezoidal` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `backward` -- ALTER TABLE `backward` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `bisection` -- ALTER TABLE `bisection` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `central` -- ALTER TABLE `central` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `falseposition` -- ALTER TABLE `falseposition` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `firstforward` -- ALTER TABLE `firstforward` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `newton` -- ALTER TABLE `newton` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `onepoint` -- ALTER TABLE `onepoint` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `secant` -- ALTER TABLE `secant` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `simpson` -- ALTER TABLE `simpson` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `trapezoidal` -- ALTER TABLE `trapezoidal` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; 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 */;
6128d69db17a12be37dabcbb52d47435d175715e
[ "JavaScript", "SQL", "PHP" ]
8
JavaScript
nesyoddoi/projectNumerical
006dd3a4792141ed441b971300b3bd436030e505
627344ce3329795b59f10a0929b9f5a42cd0472b
refs/heads/master
<file_sep>const content = document.querySelector('#content'); const submit = document.querySelector('#submit'); const update = document.querySelector('#updateBtn'); window.addEventListener('load', () => { getStudent(); }); submit.addEventListener('click', ()=> { let fullname = document.querySelector('#fullname').value; let age = document.querySelector('#age').value; let address = document.querySelector('#address').value; let formData = { fullname, age, address}; fetch('http://localhost:5000/student', { method: 'POST', body: JSON.stringify(formData), headers: { 'Content-Type' : 'application/json' } }); }); function getStudent(){ let html = ""; fetch('http://localhost:5000/student') .then(response => { console.log(response); return response.json(); }).then(data => { console.log(data); data.forEach(element => { html += `<table class="table table-bordered"> <tr> <td>${element.fullname}</td> <td>${element.age}</td> <td>${element.address}</td> <td><a href="javascript:void(0)" onClick="deleteStudent(${element.id})">Delete</a></td> <td><a href="javascript:void(0)" onClick="editStudent(${element.id})">Edit</a></td> </tr> </table>`; }); content.innerHTML = html; }).catch(error => { console.log(error); }); } function deleteStudent(id){ let formData = {id}; fetch('http://localhost:5000/student', { method: 'DELETE', body: JSON.stringify(formData), headers: { 'Content-Type' : 'application/json' } }).then(response => response.text()) .then(response => console.log(response)) .catch(error => console.log(error)); } function editStudent(id){ fetch(`http://localhost:5000/student/${id}`) .then(res => res.json()) .then( (data) => { document.querySelector('#fullname').value = data[0].fullname; document.querySelector('#age').value = data[0].age; document.querySelector('#address').value = data[0].address; document.querySelector('#ID').value = data[0].id; }); } update.addEventListener('click', ()=> { let fullname = document.querySelector('#fullname').value; let age = document.querySelector('#age').value; let address = document.querySelector('#address').value; let id = document.querySelector('#ID').value; let formData = { fullname, age, address, id }; fetch('http://localhost:5000/student', { method: 'PUT', body: JSON.stringify(formData), headers: { 'Content-Type' : 'application/json' } }); });
1ecb291ec3fbc4653c320d1d1a3a435ace95b7e6
[ "JavaScript" ]
1
JavaScript
loyladejito/mongodb-connect-to-web
26439b41db42d5dde8c2b0f2b72d7096c3052f26
989194cdcffcec8f950887edd47205369bfd1ada
refs/heads/main
<file_sep>print('ello worl')
a8ca9d29160bfd43bdf6e92bdae94b9bc8466308
[ "Python" ]
1
Python
nageswarrao321/bannu
7549180a0e1854142ad75d9e3a2616fd0a2c44c7
cb84a0c4717b5131d05f9efc72db656962de3bd8
refs/heads/master
<repo_name>jdadone/canvas<file_sep>/prototype 1/update.js function update(){ tick++; } function setPlayerInput(){ document.addEventListener("keydown", movePlayer); } function movePlayer(evt){ if(evt.keyCode == UP_ARROW){ updatePlayerLocationIfKeyPressed(0, -1); drawAll(); } if(evt.keyCode == LEFT_ARROW){ updatePlayerLocationIfKeyPressed(-1, 0); drawAll(); } if(evt.keyCode == DOWN_ARROW){ updatePlayerLocationIfKeyPressed(0, 1); drawAll(); } if(evt.keyCode == RIGHT_ARROW){ updatePlayerLocationIfKeyPressed(1, 0); drawAll(); } } function updatePlayerLocationIfKeyPressed(deltaX, deltaY){ if(isMovePosValid(player.x + deltaX, player.y + deltaY)){ if(map[player.x + deltaX][player.y + deltaY] == getItemValInArrayByName(tiles, "enemy_red")){ player.health -= 5; } if(map[player.x + deltaX][player.y + deltaY] == getItemValInArrayByName(tiles, "enemy_blue")){ player.mana -= 5; } else if (map[player.x + deltaX][player.y + deltaY] == getItemValInArrayByName(tiles, "door")){ if(numKeys == 0){ console.log("no keys"); return; } else{ var index = getIndexOfItemInArray(inventory, "key"); if(index == inventory.length - 1){ inventory.pop(); } else{ inventory.splice(index, index + 1); } numKeys--; } } else if(map[player.x + deltaX][player.y + deltaY] == getItemValInArrayByName(tiles, "key")){ inventory.push(tiles[getItemValInArrayByName(tiles, "key")]); numKeys++; } clearMapPos(player.x, player.y, getItemValInArrayByName(tiles, "ground")); player.x += deltaX; player.y += deltaY; map[player.x][player.y] = getItemValInArrayByName(tiles, "player"); /*console.clear(); console.log("PlayerX: " + player.x); console.log("PlayerY: " + player.y); */ } }<file_sep>/prototype 1/draw.js function drawAll(){ drawTiles(); player.draw(); drawUI(); drawInventory(); console.log("drawAll called"); } function drawUI(){ drawPlayerStatBar(player.y * TILE_HEIGHT - 4, "#00ff00","#ff0000", player.health); drawPlayerStatBar(player.y * TILE_HEIGHT - 2, "#0000ff","#ff0000", player.mana); } function drawPlayerStatBar(y, colorFilled, colorDepleted, type){ ctx.fillStyle = colorFilled;//"#00ff00"; ctx.fillRect(player.x * TILE_WIDTH, y, 40, 2); ctx.fillStyle = colorDepleted;//"#ff0000"; ctx.fillRect(player.x * TILE_WIDTH + type, y, TILE_WIDTH - type, 2); } function drawInventory(){ ctx.fillStyle = "#a11a2c"; ctx.fillRect(0, (NUM_ROWS - 1) * TILE_WIDTH, canvas.width, TILE_HEIGHT); ctx.drawImage(images[getItemValInArrayByName(tiles, "bag")], 0, (NUM_ROWS - 1) * 40); drawSeparatorLineInInventory(41); for(var x = 0; x < inventory.length; x++){ ctx.drawImage(images[inventory[x].val], (x + 1) * 40, (NUM_ROWS - 1) * 40); drawSeparatorLineInInventory((x + 2) * 40); } } function drawSeparatorLineInInventory(x){ ctx.strokeStyle = "black"; ctx.beginPath(); ctx.moveTo(x, (NUM_ROWS - 1) * 40); ctx.lineTo(x, (NUM_ROWS) * 40); ctx.stroke(); } function drawTiles(){ for(var x = 0; x < NUM_COLS; x++){ for(var y = 0; y < NUM_ROWS - 1; y++){ //ground if(map[x][y] != getItemValInArrayByName(tiles, "wall") && map[x][y] != getItemValInArrayByName(tiles, "door")){ ctx.drawImage(images[getItemValInArrayByName(tiles, "ground")], x * 40, y * 40); } //player if(map[x][y] == getItemValInArrayByName(tiles, "player")){ player.x = x; player.y = y; } ctx.drawImage(images[map[x][y]], x * 40, y * 40); } } }<file_sep>/prototype 1/classes.js function TileClass(val, name, imgName){ this.val = val; this.name = name; this.imgLoc = IMG_PATH + imgName; } function ImageClass(path){ this.image = new Image(); this.isLoaded = false; this.image.onload = function () { checkImagesLoaded(this.image); }.bind(this); this.image.src = path; } function PlayerClass(x, y, health, attack, numKeys, img, sprite, animSpeed){ this.x = x; this.y = y; this.health = health; this.mana = health; this.attack = attack; this.numKeys = numKeys; this.img = img; this.spriteIndex = sprite; this.animationSpeed = animSpeed; this.numSprites = img.width / TILE_WIDTH; //this.inventory = inventory; this.move = function(newX, newY){ this.x = newX * TILE_WIDTH; this.x = newY * TILE_HEIGHT; } this.draw = function(){ ctx.drawImage(img, this.spriteIndex * TILE_WIDTH, 0, TILE_WIDTH, TILE_HEIGHT, this.x * 40, this.y * 40, TILE_WIDTH, TILE_HEIGHT); } this.updateSprite = function(){ if(tick % animSpeed == 0){ if(spriteIndex == numSprites){ spriteIndex = 0; } else{ spriteIndex++; } } } }
4f8e66924d91b87074e7710e695959dd8720f021
[ "JavaScript" ]
3
JavaScript
jdadone/canvas
7f6f87a0143f26037d5e06ccb3502c6c93a7bdbf
8cf780eafd97af8d0e8485cdacbc01b209c7d0f9
refs/heads/master
<file_sep>import json import re import operator import configparser import math from collections import Counter from collections import defaultdict import nltk #nltk.download('punkt') nltk.download('stopwords') from nltk.corpus import stopwords from nltk import bigrams import string #from nltk.tokenize import word_tokenize config = configparser.ConfigParser() config.read('TwitterSentimentDetector.ini') emoticons_str = r""" (?: [:=;] # Eyes [oO\-]? # Nose (optional) [D\)\]\(\]/\\OpP] # Mouth )""" regex_str = [ emoticons_str, r'<[^>]+>', # HTML tags r'(?:@[\w_]+)', # @-mentions r"(?:\#+[\w_]+[\w\'_\-]*[\w_]+)", # hash-tags r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+', # URLs r'(?:(?:\d+,?)+(?:\.?\d+)?)', # numbers r"(?:[a-z][a-z'\-_]+[a-z])", # words with - and ' r'(?:[\w_]+)', # other words r'(?:\S)' # anything else ] tokens_re = re.compile(r'('+'|'.join(regex_str)+')', re.VERBOSE | re.IGNORECASE) emoticon_re = re.compile(r'^'+emoticons_str+'$', re.VERBOSE | re.IGNORECASE) punctuation = list(string.punctuation) numbers = list(string.digits) articles = list(["a", "A", "The", "the"]) stop = stopwords.words('english') + punctuation + articles + numbers + ['2017', '2018'] + ['rt','RT', "we're", 'via'] def tokenize(s): return tokens_re.findall(s) def preprocess(s, lowercase=False): tokens = tokenize(s) if lowercase: tokens = [token if emoticon_re.search(token) else token.lower() for token in tokens] return tokens fname = config['DEFAULT']['tweet_file'] # co-occurence matrix com = defaultdict(lambda : defaultdict(int)) # document frequency of terms not including stop words count_stop_single = Counter() # document frequency of terms including stop words count_single = Counter() tweetCount = 0.0 with open(fname, 'r') as f: for line in f: tweetCount = tweetCount + 1 tweet = json.loads(line) # load it as Python dict # Create a list with all the terms terms_all = [term for term in preprocess(tweet['text'])] # Count terms only once, equivalent to Document Frequency count_single = set(terms_all) # Count hashtags only #terms_hash = [term for term in preprocess(tweet['text']) # if term.startswith('#')] # Count terms only (no hashtags, no mentions) terms_only = [term for term in preprocess(tweet['text']) if term not in stop and not term.startswith(('#', '@'))] # mind the ((double brackets)) # startswith() takes a tuple (not a list) if # we pass a list of inputs terms_stop = [term for term in preprocess(tweet['text']) if term not in stop] # Update the Counter count_stop_single.update(terms_stop) # The bigrams() function from NLTK will take a list of tokens # and produce a list of tuples using adjacent tokens #terms_bigram = bigrams(terms_stop) # have to cast bigram as a list #print(list(terms_bigram)) # Build co-occurrence matrix for i in range(len(terms_only)-1): for j in range(i+1, len(terms_only)): w1, w2 = sorted([terms_only[i], terms_only[j]]) if w1 != w2: com[w1][w2] += 1 #print(count_stop_single.most_common(5)) file.close(f) # p_t is the probability of the term occurring in a document p_t = {} # p_t_com is the probability of two terms occurring together in a document p_t_com = defaultdict(lambda : defaultdict(int)) # for term, n in count_stop_single.items(): p_t[term] = n / tweetCount for t2 in com[term]: p_t_com[term][t2] = com[term][t2] / tweetCount fname = config['DEFAULT']['positive_words'] positive_vocab = [] with open(fname, 'r') as f: positive_vocab = f.read().splitlines() file.close(f) fname = config['DEFAULT']['negative_words'] negative_vocab = [] with open(fname, 'r') as f: negative_vocab = f.read().splitlines() # pmi is the Pointwise Mutual Information # or the closeness of a word to terms like good or bad pmi = defaultdict(lambda : defaultdict(int)) for t1 in p_t: for t2 in com[t1]: denom = p_t[t1] * p_t[t2] pmi[t1][t2] = math.log((p_t_com[t1][t2] / denom), 2) semantic_orientation = {} for term, n in p_t.items(): positive_assoc = sum(pmi[term][tx] for tx in positive_vocab) negative_assoc = sum(pmi[term][tx] for tx in negative_vocab) semantic_orientation[term] = positive_assoc - negative_assoc semantic_sorted = sorted(semantic_orientation.items(), key=operator.itemgetter(1), reverse=True) top_pos = semantic_sorted[:10] top_neg = semantic_sorted[-10:] print(top_pos) print(top_neg) # Trump Tweets #print("Jerusalem: ", semantic_orientation["Jerusalem"]) #print("Trump: ", semantic_orientation["Trump"]) #print("US: ", semantic_orientation["US"]) # Happy Tweets <file_sep># TwitterSentimentDetector ## Artificial Intelligence Project ###### Introduction This project aims to allow a computer program to predict the sentiment – positive or negative – of Twitter using Machine Learning techniques. Sentiment is defined as an attitude, emotion, or feeling. As Twitter is filled with “tweets” authored by numerous individuals “tweeting” about a variety of events, the program’s job is to give a probability of how those individuals feel about certain things. By analyzing these results, we can generally determine how Twitter users feel about a recent event, a particular person, and more. ###### Process Using Twitter’s API, we are able to access the most recent tweets from Twitter with our program. In our first run-through, our input was the last 25 to 100 tweets on our home page. These tweets were from the users we follow, and the topics of them are extremely diverse. By tokenizing these tweets, finding the most used terms, and eliminating other words from the file, we are left with words and phrases that are often associated with opinions. By associating these opinionated words and phrases with an opinion lexicon file, we may gather Twitter users’ emotions about certain topics and entities. In our second run-through, we decided to make our input to be filtered by certain hashtags. This means that we can find the sentiment on a certain hashtag through the same process. Our output gives probabilities of semantic orientation which shows what good and bad terms are popping up in our timeline and in what context. This type of sentiment detector would be highly valuable to many businesses attempting to garner the reaction to a product they have just released or even to a campaign manager attempting to gather information on how voters feel about their candidate. Our Twitter Sentiment Detector project is composed of two files: TwitterDataMining.py and TwitterPreProcessing.py. In TwitterDataMining.py, we use Twitter’s API to access the tweets, and then we write the most recent tweets to a json file. TweetPreProcessing.py sets up which words or characters to ignore in the file – called stop words – and compiles them into a list. We then use a co-occurrence matrix which counts the number of times certain terms occur together throughout the json file. This is important because certain opinions and emotions are expressed through multiple words instead of just one. Finally, our program then calculates the Pointwise Mutual Information (PMI) of each word or co-occurring words to test if they are “good” or “bad.” This is a mathematical equation which calculates the closeness of a word to good and bad terms by using the number of times it has occurred in the file and in what context. This essentially compares the words in the tweets to the opinion lexicon in our project file. The semantic orientation is then calculated to see the probability of some words appearing more often with the positive or negative words from the lexicon. If a word appears more frequently with positive words, the output will be a positive probability; else, it will be negative. ###### For a clearer example, a tweet is given below: “Firefighters are fighting to save homes and lives in California. Sending love and support to them and those affected.” – <NAME>, 9:45 AM – 5 Dec 2017 From this example tweet, our program would parse through each word and find words such as “fighting,” “save,” “love,” and “support.” Our program would see these words and assign a positive or negative probability to them. In this case, “fighting” would get a negative probability while “save,” “love,” and “support” would get a positive one. To make this project more applicable, we filtered our input through one hashtag. For example, if this example tweet had “#california”, then our sentiment detector would pick up that there are good and bad associations with this hashtag because of the wildfires. This is helpful in finding Twitter users’ attitude towards one specific topic. ###### Error Analysis Our project has had several setbacks including finding the correct formatting and the struggle to filter out irrelevant data. Since we are using a json file, we had to learn how to format this file in order for it to be readable into our code. We also had issues with making our list of stop words as we were unsure of which available dictionaries of words there were. As a result, we individually went through and chose words we did not want to be picked up in our file. There is certainly a more accurate way to solve this problem, and this would be something we would work on in the future. Furthermore, we used unsupervised learning in our approach, and it could be argued that a supervised environment might be more effective. For example, we could have trained our data on which words were positive and negative, and perhaps the results would come to be more accurate. Also, since we have not officially learned unsupervised learning in class, we spent a considerable amount of time just trying to understand what that meant. The results of our project show that our calculation of sentiment is generally correct. By filtering through Twitter for a specific hashtag, we were able to obtain results that showed how Twitter users generally felt about the hashtag. For example, we queried for the hashtag “#Trump,” and the program outputted a -9.70 rating that shows that tweets about Trump are generally negative. It also outputs the evidence of this by showing the positive and negative words associated with this hashtag. For example, the some positive words associated with this hashtag are “Lead” with a rating of 6.6 and “decisions” with a 13.3 rating. Some negative words found to associate with “#Trump” include “Dems” (-13.3) and “capital” (-21.6). While our results seem to come out as generally accurate, we still have trouble with some unnecessary words coming into our results. For example, for “#Trump,” the word “I’m” came out as positive with a 6.6 rating. This word should have been eliminated with our stop words since it is a pronoun, but it still slipped through. We also have not yet found a way to eliminate URL’s to images and videos from our results. These commonly pop up with happy hashtags, but they do not show how a user feels from a sentiment perspective. In the future, we hope to improve upon these issues. <file_sep>import tweepy # pip install tweepy==3.5.0 import django # pip install Django import json import configparser from django.utils.encoding import smart_str, smart_unicode from tweepy import OAuthHandler config = configparser.ConfigParser() config.read('TwitterSentimentDetector.ini') fname = config['DEFAULT']['tweet_file'] file = open(fname, "w") # call file what ever you need to # this method writes a tweet to a file def process_or_store(tweet): file.write(json.dumps(tweet) + "\n") consumer_key = config['twitter.com']['consumer_key'] consumer_secret = config['twitter.com']['consumer_secret'] access_token = config['twitter.com']['access_token'] access_secret = config['twitter.com']['access_secret'] auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) # api is what you use to access anything from twitter api = tweepy.API(auth) tweets = tweepy.Cursor(api.search, q='#Christmas').items(100) # change the number of tweets it grabs by changing the number '25' #for tweet in tweepy.Cursor(api.home_timeline).items(25): for tweet in tweets: # Process a single status # if you're going to print any text use smart_str from django # print smart_str(status._json) #print smart_str(tweet._json) process_or_store(tweet._json) file.close()
9f23ff0a8f28c747266f3f3c9dae490e25b04563
[ "Markdown", "Python" ]
3
Python
awetstone56/TwitterSentimentDetector
1f9ce85783fd6fca14e3996aca8f5bd16b256348
71d1342784ca5a15d904ec4bc14a27e2cb8150b1
refs/heads/master
<repo_name>organizations-loop/Compiler-7<file_sep>/TestByMyself/Tese/main.c const int k = 10; const int t = 22,y = 403,i=10; const char cca = 'a'; const char ccb = 'b',ccc = 'c'; int j,n; int a[30]; void dowhile() { const int NUMBER=14061176; const char C = 'A'; int i,j; char c,s; int a[30]; printf(" do-while begin: "); scanf("%d",&n); scanf("%d",&i); j = 0; do{ a[j] = j; j = j+1; }while(j<30); printf(" result is: "); do{ j = 0; do{ a[j] = a[j]+i; printf("%d",a[j]); printf(" "); j = j+1; }while(j<30); i = i+1; }while(i<n); } void forfun() { int i,j; int n; int a[30]; printf(" for loop begin: "); scanf("%d",&n); for(i=0;i<30;i=i+1) a[i] = i; for(i=0;i<n;i=i+1) { for(j=0;j<30;j=j+1) { a[j] = a[j]+i; } } for(i=0;i<30;i=i+1) { printf("%d",a[i]); printf(" "); } } int fun(int a) { int n; n = i; return (a+n); } void loop() { int n,i,j; printf(" mixtra loop begin: "); for(i=0;i<30;i=i+1) { a[i] = i; j = 0; do{ a[i] = fun(a[i])+j; j = j+1; }while(j<30); } printf(" before: "); for(i=0;i<30;i=i+1) { printf("%d",a[i]); printf(" "); } for(i=0;i<30;i=i+1) { for(j=i;j<30;j=j+1) { n=0; do{ a[n] = a[n]+j+fun(n); n = n+1; }while(n<30); } } printf(" after: "); i=0; do{ printf("%d",a[i]); printf(" "); i = i+1; }while(i<30); } void main() { dowhile(); forfun(); loop(); } <file_sep>/SourceCodes/getsym/main.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <malloc.h> //symbol 类型定义 #define CONSTSYM 1 #define INTSYM 2 #define CHARSYM 3 #define VOIDSYM 4 #define MAINSYM 5 #define IFSYM 6 #define ELSESYM 7 #define DOSYM 8 #define WHILESYM 9 #define FORSYM 10 #define SCANFSYM 11 #define PRINTFSYM 12 #define RETURNSYM 13 #define PLUS 14 #define MINUS 15 #define TIMES 16 #define DIVI 17 #define LSS 18 #define LEQ 19 #define GRT 20 #define GEQ 21 #define NEQ 22 #define EQL 23 #define ASSIGN 24 #define LPAREN 25 #define RPAREN 26 #define LBRACE 27 #define RBRACE 28 #define LBKET 29 #define RBKET 30 #define COMMA 31 #define SEMICOLON 32 #define LSINQ 33 #define RSINQ 34 #define LDOUQ 35 #define RDOUQ 36 #define IDEN 37 #define NUMBER 38 #define CHARCST 39 #define STRING 40 #define ERRORSYM 111 #define FALSE -1 #define TRUE 0 #define MAXPATH 60 //the string of file path's max size 输入文件的路径字符串的最大值 #define MAXLS 1000 //max one line size of input file 输入文件中一行的字符数的最大值 #define MAXIDS 20 //max size of identifier 一个标识符长度的最大值 #define MAXSTR 100 //max size of output string 输出字符串的最大长度 #define MAXTAB 10000 //max size of table 符号表的最大长度 #define MAXSTRLENG 2000 //max length of string's size 字符串的最大数量 #define MAXMEDI 8000 //max medial size 中间表达式的最大数量 #define MAXTEMP 4000 //中间临时变量的数量 #define MAXMSTACK 10000 // #define MAXLABELS 300 //最大标签数 //四元式操作符定义 #define ADD 0 #define SUB 1 #define MUL 2 #define DIV 3 #define BIG 4 #define SMA 5 #define EQU 6 #define BEQU 7 #define SEQU 8 #define NOT 9 #define NEQU 10 #define ASN 11 #define BEQ 12 #define GOTO 13 #define LAB 14 #define GLOBEG 15 #define BEGIN 16 #define END 17 #define SW 18 #define LW 19 #define CALL 20 #define FORM 21 #define RETURN 22 #define PARA 23 #define ADDI 24 #define SUBI 25 #define RD 26 #define WRT 27 #define JR 28 char* file; //= (char*)malloc(sizeof(char)*MAXPATH);//file of input char* file1; char linebuf[MAXLS]; //line buffer to storage one line of the input file 保存读入文件的一行,行缓冲区 int lineIndex=MAXLS-1; //index of the linebuffer 行缓冲区指针 //char ch; //last charactor read 最近一次读入的字符 int symbol=0; //last symbol read 最近一次识别出来的单词类型 char id[MAXIDS]; //last identifier read 最近一次识别出来的标识符名称 int num=0; //last const number read 最近一次读入的整常数的值 char chconst; //last const character read 最近一次读入的字符常量的值 char str[MAXSTR]; //last output string read 最近一次读入的字符串 int isFileEnd; int linenum=0; //current line of read file 当前读到的行,用于出错处理的定位 int infunc; int curscope=0;//当前的作用域 //symbol栈,int或char int tmpstack[50]={-1}; int stackindex=1; //分配寄存器编号,轮盘制 int regid=0; int curcompifunid=0;//当前编译的函数的medsindex //int haveretuval=FALSE; //return 栈,return的返回值所在的medstack索引 struct{ int id; int scope; }returnstack; //全局变量的偏移量 int offset=0; //局部变量的偏移量 int tmpoffset = 0; int calmyparasum = 0; //table 符号表 struct{ char name[MAXIDS];//名字 int obj; //constant variable function int type; //int char arrays int valuei; //value of const integer char valuec; //value of const char int offset; //var or array or function 's offset int scope; int length; // int locate; // int index; //在中间栈中的索引id int tmpbasic; int myparasum;//the sum of function parameter }table[MAXTAB]; //四元式 struct{ int op; //option int rs; int rt; int rd; }medial[MAXMEDI]; int medialindex=0; //临时变量表 struct{ int type;//1:int,2:char int valuei; char valuec; }tempv[MAXTEMP]; int tempvindex=0; //总表 struct{ int id; int tbindex; int tpindex; int lableindex; }medstack[MAXMSTACK]; int medsindex=0; //临时寄存器 struct{ int distribute;//是否已分配 int index; }registers[21]; //标签,主要用于if-else,for等,函数不需要 struct{ char name[10]; int index; }labels[MAXLABELS]; int labelindex=0; //标签栈,保存已经生成但未使用的标签,生成时进栈,使用后退栈 int labelstack[MAXLABELS]; int labstaindex = 0; int tableindex=0;//index of table char strings[MAXSTRLENG][MAXSTR]; int strindex=0; int isjmain = TRUE; //function declare int findtable(char name[MAXIDS],int obj); int ftableindex(char name[MAXIDS]); void genlabel(); void malloctb(int index); void mallocint(); void mallocchar(); void malloclab(int index); void genmedi(int o,int rs,int rt,int rd); void error(int i); char getch(); void goback(); void getsym(); int openfile(); void printgetsym(); void constopro(); void constdec(); void tovardec(); void vardec(); void mixsta(); void statements(); void statemt(); int condition(); void ifsta(); void loopsta(); void callsta(int idenid); void assignsta(int idenid); void readsta(); void writesta(); void returnsta(); int expression(); int term(); int factor(); int isint(); void inttoconst(); void vartopro(); void parameter(); void fictopro(); void fvotopro(); void ismain(); void program(); //主要用于查重复定义,全局变量和局部变量可以重名 //若是局部变量只需要查函数内部是否重复定义,不需要查函数外部的全局变量 int findtable(char name[MAXIDS],int obj) { int i; if(tableindex<2) return -1; switch(obj) { case 1: for(i=tableindex-1;i>=0&&table[i].scope==curscope;i--) { if(strcmp(name,table[i].name)==0) return i; } return -1; break; case 2: for(i=tableindex-1;i>=0&&table[i].scope==curscope;i--) { if(strcmp(name,table[i].name)==0) return i; } return -1; break; case 3: for(i = tableindex-1;i>=0;i--) { if(table[i].obj==3) { if(strcmp(name,table[i].name)==0) return i; } } return -1; break; case 4: for(i=tableindex-1;i>=0&&table[i].scope==curscope;i--) { if(strcmp(name,table[i].name)==0) return i; } return -1; break; } return -1; } //主要用于运算的时候查表,查最靠近栈顶的位置, //若是出现在函数内,不仅要查局部变量还要查全局变量。 int ftableindex(char name[MAXIDS]) { int i; if(tableindex==0) return -1; for(i=tableindex-1;i>=0&&table[i].scope==curscope;i--) { if(strcmp(name,table[i].name)==0) return i; } for(i=0;i<=MAXTAB&&table[i].scope==0;i++) { if(strcmp(name,table[i].name)==0) { return i; } } for(i=0;i<=MAXTAB&&i<=tableindex;i++) { if(table[i].obj==3) { if(strcmp(name,table[i].name)==0) { return i; } } } return -1; } //生成label,label+数字,数字每次加1 void genlabel() { int i; char j[5]; char tmp[10]={"$labe"}; // strcpy(labels[++labelindex].name,tmp); itoa(labelindex,j,10); for(i=5;i<10&&j[i-5]<='9'&&j[i-5]>='0';i++) labels[labelindex].name[i] = j[i-5]; labels[labelindex].name[i] = '\0'; //生成的标签未使用,进入标签栈中等待使用 //labelstack[labstaindex++] = labelindex; } void malloctb(int index) { medstack[medsindex].id = medsindex; medstack[medsindex].tbindex = index; medstack[medsindex].tpindex = -1; medstack[medsindex].lableindex = -1; table[index].index = medsindex; medsindex++; } void mallocint() { tempv[tempvindex].type = 1; medstack[medsindex].id = medsindex; medstack[medsindex].tbindex = -1; medstack[medsindex].tpindex = tempvindex; medstack[medsindex].lableindex = -1; tempvindex++; medsindex++; } void mallocchar() { tempv[tempvindex].type = 2; medstack[medsindex].id = medsindex; medstack[medsindex].tbindex = -1; medstack[medsindex].tpindex = tempvindex; medstack[medsindex].lableindex = -1; tempvindex++; medsindex++; } void malloclab(int index) { medstack[medsindex].id = medsindex; medstack[medsindex].tbindex = -1; medstack[medsindex].tpindex = -1; medstack[medsindex].lableindex = index; labels[index].index = medsindex; medsindex++; } void genmedi(int o,int rs,int rt,int rd) { medial[medialindex].op = o; medial[medialindex].rs = rs; medial[medialindex].rt = rt; medial[medialindex].rd = rd; medialindex++; } void error(int i) { switch(i) { case 0: printf("ERROR!!!!!Can't open the file!\n"); exit(0); break; case 1: printf("ERROR!!!!!类型标识符后面没有接标识符\n"); break; case 2: printf("ERROR!!!!!常量或变量说明中逗号后面没有接标识符\n"); getsym(); break; case 3: printf("ERROR!!!!!数组声明中[]内应该是无符号整数\n"); getsym(); break; case 4: printf("ERROR!!!!!数组声明时长度不能为0\n"); break; case 5: printf("ERROR!!!!!数组少了右边的方括号\n"); break; case 6: printf("ERROR!!!!!变量说明标识符后面没有跟逗号方括号或分号\n"); getsym(); break; case 7: printf("ERROR!!!!!函数定义中没有左括号\(\n"); break; case 8: printf("ERROR!!!!!参数表逗号后面没有接int或char\n"); getsym(); break; case 9: printf("ERROR!!!!!函数定义中没有右括号)\n"); break; case 10: printf("ERROR!!!!!函数定义中没有左大括号{\n"); break; case 11: printf("ERROR!!!!!函数定义中没有右大括号}\n"); break; case 12: printf("ERROR!!!!!函数定义中缺乏返回类型(void int char)\n"); break; case 13: printf("ERROR!!!!!无返回值函数定义中缺乏函数名\n"); break; case 14: printf("ERROR!!!!!缺乏主函数\n"); break; case 15: printf("ERROR!!!!!整数的第一个字符非法\n"); break; case 16: printf("ERROR!!!!!整数的正负号后面紧跟着不是数字\n"); break; case 17: printf("ERROR!!!!!常量定义中没有int或char\n"); break; case 18: printf("ERROR!!!!!常量定义中标识符后面没有等号=\n"); break; case 19: printf("ERROR!!!!!常量定义中分隔符非法,不是逗号或分号\n"); getsym(); break; case 20: printf("ERROR!!!!!字符常量定义中缺少字符值\n"); break; case 21: printf("ERROR!!!!!标识符超出最大长度,自动截取前20个字符\n"); break; case 22: printf("ERROR!!!!!无符号整数不存在前导零\n"); break; case 23: printf("ERROR!!!!!标识符出现非法字符\n"); break; case 24: printf("ERROR!!!!!字符常量或字符串常量缺少右单引号\n"); break; case 25: printf("ERROR!!!!!出现非法字符\n"); break; case 26: printf("ERROR!!!!!语句推出语句列时没有右边的大括号}\n"); break; case 27: printf("ERROR!!!!!因子推出表达式时缺少右括号\)\n"); break; case 28: printf("ERROR!!!!!if后面少了左括号\(\n"); break; case 29: printf("ERROR!!!!!if后面少了右括号\)\n"); break; case 30: printf("ERROR!!!!!do后面没有while\n"); break; case 31: printf("ERROR!!!!!while后面少了左括号\n"); break; case 32: printf("ERROR!!!!!while后面少了右括号\n"); break; case 33: printf("ERROR!!!!!for后面少了左括号\n"); break; case 34: printf("ERROR!!!!!for的左括号后面没有标识符\n"); break; case 35: printf("ERROR!!!!!for后面少了右括号\n"); break; case 36: printf("ERROR!!!!!for的标识符后面没有等号\n"); getsym(); break; case 37: printf("ERROR!!!!!for赋初值后没有加分号\n"); getsym(); break; case 38: printf("ERROR!!!!!for条件之后没有加分号\n"); getsym(); break; case 39: printf("ERROR!!!!!for的增长值中没有标识符\n"); break; case 40: printf("ERROR!!!!!for的增长值中没有加减号\n"); break; case 41: printf("ERROR!!!!!for的步长中不是无符号整数\n"); break; case 42: printf("ERROR!!!!!步长不能为0\n"); break; case 43: printf("ERROR!!!!!函数调用少了右括号\n"); break; case 44: printf("ERROR!!!!!读写语句缺少左括号\n"); break; case 45: printf("ERROR!!!!!读写语句缺少右括号\n"); break; case 46: printf("ERROR!!!!!scanf缺少标识符\n"); break; case 47: printf("ERROR!!!!!return缺少右括号\n"); break; case 48: printf("ERROR!!!!!语句没有以分号结尾\n"); break; case 49: printf("ERROR!!!!!重复定义\n"); break; case 50: printf("ERROR!!!!!函数有返回值但是没有return语句\n"); break; case 51: printf("ERROR!!!!!使用前未声明\n"); break; case 52: printf("ERROR!!!!!不能给常量赋值\n"); break; case 53: printf("ERROR!!!!!不能给函数赋值\n"); break; case 54: //printf("ERROR!!!!!读语句不能对参数赋值\n"); break; case 55: printf("ERROR!!!!!数组的标识符不对,而且其他常量或函数名\n"); break; case 56: printf("ERROR!!!!!函数调用中函数名不是函数名,而是其他常量或变量或参数名\n"); break; case 57: printf("ERROR!!!!!因子中的函数调用没有返回值\n"); break; case 58: printf("ERROR!!!!!void的函数定义中return后面有返回值\n"); break; case 59: printf("ERROR!!!!!函数调用与定义的参数个数不符\n"); break; } printf("code is %d error is in the line of %d !!!!\n",i,linenum); } //read one character 读入一个字符,不直接用getchar因为不能回退 char getch() { if((lineIndex>=MAXLS-1)||linebuf[lineIndex]=='\n'||linebuf[lineIndex]=='\0') { linenum++; if((gets(linebuf))==NULL) { isFileEnd = TRUE; return EOF;//////////// } else { if(linebuf[0]=='\0') { linebuf[0]='\n'; linebuf[1]='\0'; } lineIndex=0; return linebuf[lineIndex++]; } } else { return linebuf[lineIndex++]; } } //go back to read previous character 回退读入的字符 void goback() { if(lineIndex>0) lineIndex--; } //read one token and identify the symbol 词法分析过程 void getsym() { int i=0,j=0; char c; c=getch(); if(isFileEnd==TRUE) return; while(c==' '||c=='\n'||c=='\t') { c=getch(); if(isFileEnd==TRUE) { printf("read the end of file\n"); return; } } if((c>='a'&&c<='z')||(c>='A'&&c<='Z')) { i = 0; while((c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c=='_')||(c>='0'&&c<='9')) { //out of range if(i>=MAXIDS-1) { error(21); break; } id[i++]=c; c=getch(); if(isFileEnd==TRUE) return; } id[i]='\0'; goback(); if(id[0]=='c'&&id[1]=='o'&&id[2]=='n'&&id[3]=='s'&&id[4]=='t'&&id[5]=='\0') { symbol = CONSTSYM; } else if(id[0]=='i'&&id[1]=='n'&&id[2]=='t'&&id[3]=='\0') { symbol = INTSYM; } else if(id[0]=='c'&&id[1]=='h'&&id[2]=='a'&&id[3]=='r'&&id[4]=='\0') { symbol = CHARSYM; } else if(id[0]=='v'&&id[1]=='o'&&id[2]=='i'&&id[3]=='d'&&id[4]=='\0') { symbol = VOIDSYM; } else if(id[0]=='m'&&id[1]=='a'&&id[2]=='i'&&id[3]=='n'&&id[4]=='\0') { symbol = MAINSYM; } else if(id[0]=='i'&&id[1]=='f'&&id[2]=='\0') { symbol = IFSYM; } else if(id[0]=='e'&&id[1]=='l'&&id[2]=='s'&&id[3]=='e'&&id[4]=='\0') { symbol = ELSESYM; } else if(id[0]=='d'&&id[1]=='o'&&id[2]=='\0') { symbol = DOSYM; } else if(id[0]=='w'&&id[1]=='h'&&id[2]=='i'&&id[3]=='l'&&id[4]=='e'&&id[5]=='\0') { symbol = WHILESYM; } else if(id[0]=='f'&&id[1]=='o'&&id[2]=='r'&&id[3]=='\0') { symbol = FORSYM; } else if(id[0]=='s'&&id[1]=='c'&&id[2]=='a'&&id[3]=='n'&&id[4]=='f'&&id[5]=='\0') { symbol = SCANFSYM; } else if(id[0]=='p'&&id[1]=='r'&&id[2]=='i'&&id[3]=='n'&&id[4]=='t'&&id[5]=='f'&&id[6]=='\0') { symbol = PRINTFSYM; } else if(id[0]=='r'&&id[1]=='e'&&id[2]=='t'&&id[3]=='u'&&id[4]=='r'&&id[5]=='n'&&id[6]=='\0') { symbol = RETURNSYM; } else { symbol = IDEN; } } else if(c>='0'&&c<='9') { num = 0; if(c=='0') { c = getch(); if(isFileEnd==TRUE) return; if(c>='0'&&c<='9') { error(22); } while(c>='0'&&c<='9') { num = num*10+(c-'0'); c = getch(); if(isFileEnd==TRUE) return; } } else { while(c>='0'&&c<='9') { num = num*10+(c-'0'); c = getch(); if(isFileEnd==TRUE) return; } } goback(); symbol = NUMBER; } else { switch(c) { case '+': symbol = PLUS; break; case '-': symbol = MINUS; break; case '*': symbol = TIMES; break; case '/': symbol = DIVI; break; case '<': c = getch(); if(isFileEnd==TRUE) return; if(c=='=') symbol = LEQ; else { symbol = LSS; goback(); } break; case '>': c = getch(); if(isFileEnd==TRUE) return; if(c=='=') symbol = GEQ; else { symbol = GRT; goback(); } break; case '!': c = getch(); if(isFileEnd==TRUE) return; if(c=='=') symbol = NEQ; else { symbol = ERRORSYM; goback(); } break; case '=': c = getch(); if(isFileEnd==TRUE) return; if(c=='=') symbol = EQL; else { symbol = ASSIGN; goback(); } break; case '(': symbol = LPAREN; break; case ')': symbol = RPAREN; break; case '{': symbol = LBRACE; break; case '}': symbol = RBRACE; break; case '[': symbol = LBKET; break; case ']': symbol = RBKET; break; case ',': symbol = COMMA; break; case ';': symbol = SEMICOLON; break; case '_': i = 0; while((c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c=='_')||(c>='0'&&c<='9')) { //out of range if(i>=MAXIDS-1) { error(21); break; } id[i++]=c; c=getch(); if(isFileEnd==TRUE) return; } id[i]='\0'; goback(); symbol = IDEN; break; case '\'': chconst = getch(); if(isFileEnd==TRUE) return; c = getch(); if(isFileEnd==TRUE) return; if(c=='\'') { if(chconst=='+'||chconst=='-'||chconst=='*'||chconst=='/'|| (chconst>='a'&&chconst<='z')||(chconst>='A'&&chconst<='Z')|| (chconst>='0'&&chconst<='9')) { symbol = CHARCST; } else { error(23); symbol = ERRORSYM; } } else { goback(); symbol = ERRORSYM; error(24); } break; case '\"': j = 0; c = getch(); if(isFileEnd==TRUE) return; while(c!='\"'&&j<MAXSTR-1) { str[j++] = c; c = getch(); if(isFileEnd==TRUE) return; } str[j]='\0'; if(c=='\"') { symbol = STRING; } else { symbol = ERRORSYM; goback(); error(24); } break; default: symbol = ERRORSYM; error(25); break; } } } int openfile() { file = (char*)malloc((sizeof(char))*MAXPATH); printf("please input the test file path\n"); gets(file); if(freopen(file,"r",stdin)==NULL) { printf("file to open the test file\n"); return 0; } else { isFileEnd = FALSE; printf("success to open the test file\n"); return 1; } } void printgetsym() { printf("类别码\t\t单词值\n"); getsym(); while(isFileEnd==FALSE) { switch(symbol) { case CONSTSYM: printf("CONSTSYM\tconst\n"); break; case INTSYM: printf("INTSYM\tint\n"); break; case CHARSYM: printf("CHARSYM\tchar\n"); break; case VOIDSYM: printf("VOIDSYM\tvoid\n"); break; case MAINSYM: printf("MAINSYM\tmain\n"); break; case IFSYM: printf("IFSYM\tif\n"); break; case ELSESYM: printf("ELSESYM\telse\n"); break; case DOSYM: printf("DOSYM\tdo\n"); break; case WHILESYM: printf("WHILESYM\twhile\n"); break; case FORSYM: printf("FORSYM\tfor\n"); break; case SCANFSYM: printf("SCANFSYM\tscanf\n"); break; case PRINTFSYM: printf("PRINTFSYM\tprintf\n"); break; case RETURNSYM: printf("RETURNSYM\treturn\n"); break; case PLUS: printf("PLUS\t+\n"); break; case MINUS: printf("MINUS\t-\n"); break; case TIMES: printf("TIMES\t*\n"); break; case DIVI: printf("DIVI\t/\n"); break; case LSS: printf("LSS\t<\n"); break; case LEQ: printf("LEQ\t<=\n"); break; case GRT: printf("GRT\t>\n"); break; case GEQ: printf("GEQ\t>=\n"); break; case NEQ: printf("NEQ\t!=\n"); break; case EQL: printf("EQL\t==\n"); break; case ASSIGN: printf("ASSIGN\t=\n"); break; case LPAREN: printf("LPAREN\t(\n"); break; case RPAREN: printf("RPAREN\t)\n"); break; case LBRACE: printf("LBRACE\t{\n"); break; case RBRACE: printf("RBRACE\t}\n"); break; case LBKET: printf("LBKET\t[\n"); break; case RBKET: printf("RBKET\t]\n"); break; case COMMA: printf("COMMA\t,\n"); break; case SEMICOLON: printf("SEMICOLON\t;\n"); break; case IDEN: printf("IDEN\t%s\n",id); break; case NUMBER: printf("NUMBER\t%d\n",num); break; case CHARCST: printf("CHARCST\t%c\n",chconst); break; case STRING: printf("STRING\t%s\n",str); break; case ERRORSYM: printf("ERRORSYM\terror\n"); break; } getsym(); } } void constopro() { if(symbol==CONSTSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=INTSYM&&symbol!=CHARSYM) { error(17); while(symbol!=INTSYM&&symbol!=CHARSYM&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(symbol==INTSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,1)>=0) error(49); strcpy(table[tableindex].name,id); getsym(); if(isFileEnd==TRUE) return; if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; } else { error(18); } inttoconst(); table[tableindex].obj = 1; table[tableindex].type = 1; table[tableindex].valuei = num; table[tableindex].scope = curscope; malloctb(tableindex); tableindex++; if(symbol==COMMA) { while(symbol==COMMA) { getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(findtable(id,1)>=0) error(49); strcpy(table[tableindex].name,id); getsym(); if(isFileEnd==TRUE) return; if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; inttoconst(); } else { error(18); inttoconst(); } table[tableindex].obj = 1; table[tableindex].type = 1; table[tableindex].valuei = num; table[tableindex].scope = curscope; malloctb(tableindex); tableindex++; } else { error(2); } } if(symbol!=SEMICOLON) { error(19); } } if(symbol==SEMICOLON) { getsym(); if(isFileEnd==TRUE) return; if(symbol==CONSTSYM) { constopro(); } } else { error(19); } } else if(symbol==CHARSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,1)>=0) error(49); strcpy(table[tableindex].name,id); getsym(); if(isFileEnd==TRUE) return; if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; } else { error(18); } if(symbol!=CHARCST) { error(20); while(symbol!=CHARCST&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } table[tableindex].obj = 1; table[tableindex].type = 2; table[tableindex].valuec = chconst; table[tableindex].scope = curscope; malloctb(tableindex); tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==COMMA) { while(symbol==COMMA) { getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(findtable(id,1)>=0) error(49); strcpy(table[tableindex].name,id); getsym(); if(isFileEnd==TRUE) return; if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; } else { error(18); } if(symbol!=CHARCST) { error(20); while(symbol!=CHARCST&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } table[tableindex].obj = 1; table[tableindex].type = 2; table[tableindex].valuec = chconst; table[tableindex].scope = curscope; malloctb(tableindex); tableindex++; getsym(); if(isFileEnd==TRUE) return; } else { error(2); } } if(symbol!=SEMICOLON) { error(19); } } if(symbol==SEMICOLON) { getsym(); if(isFileEnd==TRUE) return; if(symbol==CONSTSYM) { constopro(); } } else { error(19); } } // printf("This is const declaration.\n"); } } void constdec() { if(symbol==CONSTSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=INTSYM&&symbol!=CHARSYM) { error(17); while(symbol!=INTSYM&&symbol!=CHARSYM&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(symbol==INTSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,1)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].obj = 1; table[tableindex].type = 1; getsym(); if(isFileEnd==TRUE) return; if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; } else { error(18); } inttoconst(); table[tableindex].valuei = num; table[tableindex].scope = curscope; malloctb(tableindex); tableindex++; if(symbol==COMMA) { while(symbol==COMMA) { getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(findtable(id,1)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].obj = 1; table[tableindex].type = 1; getsym(); if(isFileEnd==TRUE) return; if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; inttoconst(); } else { error(18); inttoconst(); } table[tableindex].valuei = num; table[tableindex].scope = curscope; malloctb(tableindex); tableindex++; } else { error(2); } } if(symbol!=SEMICOLON) { error(19); } } if(symbol==SEMICOLON) { getsym(); if(isFileEnd==TRUE) return; if(symbol==CONSTSYM) { constdec(); } } else { error(19); } } else if(symbol==CHARSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,1)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].obj = 1; table[tableindex].type = 2; getsym(); if(isFileEnd==TRUE) return; if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; } else { error(18); } if(symbol!=CHARCST) { error(20); while(symbol!=CHARCST&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } table[tableindex].valuec = chconst; table[tableindex].scope = curscope; malloctb(tableindex); tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==COMMA) { while(symbol==COMMA) { getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(findtable(id,1)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].obj = 1; table[tableindex].type = 2; getsym(); if(isFileEnd==TRUE) return; if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; } else { error(18); } if(symbol!=CHARCST) { error(20); while(symbol!=CHARCST&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } table[tableindex].valuec = chconst; table[tableindex].scope = curscope; malloctb(tableindex); tableindex++; getsym(); if(isFileEnd==TRUE) return; } else { error(2); } } if(symbol!=SEMICOLON) { error(19); } } if(symbol==SEMICOLON) { getsym(); if(isFileEnd==TRUE) return; if(symbol==CONSTSYM) { constdec(); } } else { error(19); } } // printf("This is const declaration.\n"); } } void tovardec() { if(symbol==COMMA) { if(table[tableindex].type==0) { if(tmpstack[stackindex]==INTSYM) { table[tableindex].type = 1; } else if(tmpstack[stackindex]==CHARSYM) { table[tableindex].type = 2; } malloctb(tableindex); //genmedi(SW,medsindex-1,0,0); } tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(findtable(id,2)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].obj = 2; if(tmpstack[stackindex]==INTSYM) table[tableindex].type = 1; else if(tmpstack[stackindex]==CHARSYM) table[tableindex].type = 2; malloctb(tableindex); //genmedi(SW,medsindex-1,0,0); table[tableindex].offset = tmpoffset++; table[tableindex].scope = curscope; // tableindex++; getsym(); if(isFileEnd==TRUE) return; tovardec(); } else { error(2); } } if(symbol==LBKET) { if(tmpstack[stackindex]==INTSYM) table[tableindex].type = 3; else if(tmpstack[stackindex]==CHARSYM) table[tableindex].type = 4; tmpoffset--; getsym(); if(isFileEnd==TRUE) return; if(symbol==NUMBER) { if(num==0) { error(4); num = 10; } getsym(); if(isFileEnd==TRUE) return; } else { error(3); num = 10; } table[tableindex].length = num; if(symbol!=RBKET) { error(5); } else { getsym(); if(isFileEnd==TRUE) return; } malloctb(tableindex); //genmedi(SW,medsindex-1,0,0); //tableindex++; tmpoffset += num; if(symbol==COMMA) { tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(findtable(id,2)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].obj = 2; table[tableindex].offset = tmpoffset++; table[tableindex].scope = curscope; table[tableindex].type = 0; getsym(); if(isFileEnd==TRUE) return; tovardec(); } else { error(2); } } } if(symbol==SEMICOLON) { if(table[tableindex].type==0) { if(tmpstack[stackindex]==INTSYM) { table[tableindex].type = 1; } else if(tmpstack[stackindex]==CHARSYM) { table[tableindex].type = 2; } malloctb(tableindex); } stackindex--; tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==INTSYM||symbol==CHARSYM) { vardec(); } } } void vardec() { if(symbol==INTSYM||symbol==CHARSYM) { tmpstack[++stackindex] = symbol; table[tableindex].obj = 2; table[tableindex].type = 0; table[tableindex].offset = tmpoffset++; table[tableindex].scope = curscope; getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,2)>=0) error(49); strcpy(table[tableindex].name,id); getsym(); if(isFileEnd==TRUE) return; tovardec(); // printf("This is variation declaration.\n"); } } void mixsta() { if(symbol==CONSTSYM) { constdec(); } if(symbol==INTSYM||symbol==CHARSYM) { vardec(); } statements(); // printf("This is mixture statements.\n"); } void statements() { if(symbol==IFSYM||symbol==DOSYM||symbol==FORSYM||symbol==LBRACE||symbol==IDEN|| symbol==SCANFSYM||symbol==PRINTFSYM||symbol==SEMICOLON||symbol==RETURNSYM) { while((symbol==IFSYM||symbol==DOSYM||symbol==FORSYM||symbol==LBRACE||symbol==IDEN|| symbol==SCANFSYM||symbol==PRINTFSYM||symbol==SEMICOLON||symbol==RETURNSYM) &&isFileEnd==FALSE) { statemt(); } //printf("This is statements.\n"); } } void statemt() { int idenid; if(symbol==IFSYM) { ifsta(); } else if(symbol==DOSYM||symbol==FORSYM) { loopsta(); } else if(symbol==LBRACE) { getsym(); if(isFileEnd==TRUE) return; statements(); if(symbol!=RBRACE) { error(26); while(symbol!=RBRACE&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; /////////////// } else if(symbol==IDEN) { idenid = ftableindex(id); getsym(); if(isFileEnd==TRUE) return; if(symbol==LPAREN) { if(idenid<0) { error(51); } else { if(table[idenid].obj!=3) { error(56); } idenid = table[idenid].index; } callsta(idenid); if(symbol!=SEMICOLON) { error(48); } getsym(); if(isFileEnd==TRUE) return; } else if(symbol==LBKET||symbol==ASSIGN) { if(idenid<0) { error(51); } else { if(table[idenid].obj==1) { error(52); } else if(table[idenid].obj==3) { error(53); } idenid = table[idenid].index; } assignsta(idenid); if(symbol!=SEMICOLON) { error(48); } getsym(); if(isFileEnd==TRUE) return; } } else if(symbol==SCANFSYM) { readsta(); if(symbol!=SEMICOLON) { error(48); } getsym(); if(isFileEnd==TRUE) return; } else if(symbol==PRINTFSYM) { writesta(); if(symbol!=SEMICOLON) { error(48); } getsym(); if(isFileEnd==TRUE) return; } else if(symbol==SEMICOLON) { getsym(); if(isFileEnd==TRUE) return; } else if(symbol==RETURNSYM) { returnsta(); if(symbol!=SEMICOLON) { error(48); } getsym(); if(isFileEnd==TRUE) return; } } int condition() { int tmp1,tmp2,tmp3,flag; tmp1 = expression(); if(symbol==LSS||symbol==LEQ||symbol==GRT||symbol==GEQ||symbol==NEQ||symbol==EQL) { switch(symbol) { case LSS: flag = 1;//< break; case LEQ: flag = 2;//<= break; case GRT: flag = 3;//> break; case GEQ: flag = 4;//>= break; case NEQ: flag = 5; //!= break; case EQL: flag = 6;//== break; } getsym(); if(isFileEnd==TRUE) return 0; tmp2 = expression(); mallocint(); tmp3 = medsindex-1; switch(flag) { //< case 1: genmedi(SMA,tmp1,tmp2,tmp3); break; //<= case 2: genmedi(SEQU,tmp1,tmp2,tmp3); break; //> case 3: genmedi(BIG,tmp1,tmp2,tmp3); break; //>= case 4: genmedi(BEQU,tmp1,tmp2,tmp3); break; //!= case 5: genmedi(NEQU,tmp1,tmp2,tmp3); break; //== case 6: genmedi(EQU,tmp1,tmp2,tmp3); break; } return tmp3; } return tmp1; } void ifsta() { int beqs1,iflabel,endlabel12; if(symbol==IFSYM) { genlabel(); malloclab(labelindex); iflabel = medsindex-1; getsym(); if(isFileEnd==TRUE) return; if(symbol!=LPAREN) { error(28); } else { getsym(); if(isFileEnd==TRUE) return; } beqs1 = condition();//beqs1 is id genmedi(BEQ,beqs1,0,iflabel); if(symbol!=RPAREN) { error(29); } else { getsym(); if(isFileEnd==TRUE) return; } statemt(); if(symbol==ELSESYM) { genlabel(); malloclab(labelindex); endlabel12 = medsindex-1; genmedi(GOTO,0,0,endlabel12); genmedi(LAB,iflabel,0,0); getsym(); if(isFileEnd==TRUE) return; statemt(); genmedi(LAB,endlabel12,0,0); // genmedi(LAB,endlabel12,0,0); } else { genmedi(LAB,iflabel,0,0); } // printf("This is if statement.\n"); } } void loopsta() { int dolabel,beqs,forlabel1,forlabel2; int tmp1,tmp2,idenid,tmpnum; int addorsub=0; if(symbol==DOSYM) { genlabel(); malloclab(labelindex); dolabel = medsindex - 1; genmedi(LAB,dolabel,0,0); getsym(); if(isFileEnd==TRUE) return; statemt(); if(symbol!=WHILESYM) { error(30); while(symbol!=WHILESYM&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; if(symbol!=LPAREN) { error(31); } else { getsym(); if(isFileEnd==TRUE) return; } beqs = condition(); genmedi(BEQ,beqs,0,dolabel); if(symbol!=RPAREN) { error(32); } getsym(); if(isFileEnd==TRUE) return; //printf("This is do-while statement.\n"); } else if(symbol==FORSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=LPAREN) { error(33); } else { getsym(); if(isFileEnd==TRUE) return; } if(symbol!=IDEN) { error(34); while(symbol!=IDEN) { getsym(); if(isFileEnd==TRUE) return; } } idenid = ftableindex(id); if(idenid<0) { error(51); } else { if(table[idenid].obj==1) { error(52); } else if(table[idenid].obj==3) { error(53); } idenid = table[idenid].index; } getsym(); if(isFileEnd==TRUE) return; if(symbol!=ASSIGN) { error(36); } else { getsym(); if(isFileEnd==TRUE) return; } tmp1 = expression(); genmedi(ASN,tmp1,0,idenid); genlabel(); malloclab(labelindex); forlabel1 = medsindex -1; genlabel(); malloclab(labelindex); forlabel2 = medsindex -1; genmedi(LAB,forlabel1,0,0); if(symbol!=SEMICOLON) { error(37); } else { getsym(); if(isFileEnd==TRUE) return; beqs = condition(); genmedi(BEQ,beqs,0,forlabel2); if(symbol!=SEMICOLON) { error(38); } else { getsym(); if(isFileEnd==TRUE) return; } if(symbol!=IDEN) { error(39); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } idenid = ftableindex(id); if(idenid<0) { error(51); } else { if(table[idenid].obj==1) { error(52); } else if(table[idenid].obj==3) { error(53); } idenid = table[idenid].index; } getsym(); if(isFileEnd==TRUE) return; if(symbol!=ASSIGN) { error(36); } else { getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(39); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } tmp2 = ftableindex(id); if(tmp2<0) { error(51); } else { if(table[idenid].obj==3) { error(53); } tmp2 = table[tmp2].index; } getsym(); if(isFileEnd==TRUE) return; if(!(symbol==PLUS||symbol==MINUS)) { error(40); while(symbol!=PLUS&&symbol!=MINUS&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(symbol==PLUS) addorsub = 1; else addorsub = 2; getsym(); if(isFileEnd==TRUE) return; if(symbol!=NUMBER) { error(41); while(symbol!=NUMBER&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(num==0) { error(42); num = 1; } tmpnum = num; getsym(); if(isFileEnd==TRUE) return; if(symbol!=RPAREN) { error(35); } else { getsym(); if(isFileEnd==TRUE) return; } statemt(); //add if(addorsub==1) { genmedi(ADDI,tmp2,tmpnum,idenid); } //sub else if(addorsub==2) { genmedi(SUBI,tmp2,tmpnum,idenid); } genmedi(GOTO,0,0,forlabel1); } } genmedi(LAB,forlabel2,0,0); // printf("This is for statement.\n"); } } void callsta(int idenid) { int tmp1,i =0,callftableid; if(symbol==LPAREN) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=RPAREN) { tmp1 = expression(); genmedi(FORM,tmp1,i++,0); while(symbol==COMMA&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; tmp1 = expression(); genmedi(FORM,tmp1,i++,0); } callftableid = medstack[idenid].tbindex; if(table[callftableid].myparasum!=(i)) { error(59); } } if(symbol!=RPAREN) { error(43); while(symbol!=RPAREN) { getsym(); if(isFileEnd==TRUE) return; } } genmedi(CALL,idenid,0,0); getsym(); if(isFileEnd==TRUE) return; // printf("This is call statement.\n"); } } void assignsta(int idenid) { int tmp1,tmp2; if(symbol==LBKET) { getsym(); if(isFileEnd==TRUE) return; tmp1 = expression(); if(symbol!=RBKET) { error(5); } else { getsym(); if(isFileEnd==TRUE) return; } if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; tmp2 = expression(); genmedi(SW,idenid,tmp1,tmp2); } } else if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; tmp2 = expression(); genmedi(ASN,tmp2,0,idenid); } // printf("This is assign statement.\n"); } void readsta() { int tmp1; if(symbol==SCANFSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=LPAREN) { error(44); while(symbol!=LPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(46); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } tmp1 = ftableindex(id); if(tmp1<0) { error(51); } else { if(table[tmp1].obj==1) { error(52); } else if(table[tmp1].obj==3) { error(53); } tmp1 = table[tmp1].index; } genmedi(RD,tmp1,0,0); getsym(); if(isFileEnd==TRUE) return; if(symbol==COMMA) { while(symbol==COMMA&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(46); break; } tmp1 = ftableindex(id); if(tmp1<0) { error(51); } else { if(table[tmp1].obj==1) { error(52); } else if(table[tmp1].obj==3) { error(53); } else if(table[tmp1].obj==4) { error(54); } tmp1 = table[tmp1].index; } genmedi(RD,tmp1,0,0); getsym(); if(isFileEnd==TRUE) return; } } if(symbol!=RPAREN) { error(45); while(symbol!=RPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; //printf("This is read statement.\n"); } } void writesta() { int tmp1; if(symbol==PRINTFSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=LPAREN) { error(44); while(symbol!=LPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; if(symbol==STRING) { strcpy(strings[strindex],str); table[tableindex].obj = 5; table[tableindex].scope = curscope; table[tableindex].locate = strindex; malloctb(tableindex); genmedi(WRT,medsindex-1,0,0); tableindex++; strindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==COMMA) { getsym(); if(isFileEnd==TRUE) return; tmp1 = expression(); genmedi(WRT,tmp1,0,0); } } else { tmp1 = expression(); genmedi(WRT,tmp1,0,0); } if(symbol!=RPAREN) { error(45); while(symbol!=RPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; // printf("This is write statement.\n"); } } void returnsta() { int tmp1,tmpfuntableid; if(symbol==RETURNSYM) { returnstack.id = curcompifunid; returnstack.scope = curscope; getsym(); if(isFileEnd==TRUE) return; if(symbol==LPAREN) { getsym(); if(isFileEnd==TRUE) return; //returnstack.id = expression(); //returnstack.scope = curscope; tmp1 = expression(); if(symbol!=RPAREN) { error(47); while(symbol!=RPAREN) { getsym(); if(isFileEnd==TRUE) return; } } //void but have return values tmpfuntableid = medstack[curcompifunid].tbindex; if(table[tmpfuntableid].type==3) { error(58); } genmedi(RETURN,tmp1,0,0); genmedi(END,curcompifunid,0,0); getsym(); if(isFileEnd==TRUE) return; } else { //have return value but return; tmpfuntableid = medstack[curcompifunid].tbindex; if(table[tmpfuntableid].type!=3) { error(50); genmedi(RETURN,0,0,0); } genmedi(END,curcompifunid,0,0); } genmedi(JR,0,0,0); // printf("This is return statement.\n"); } } int expression() { int tmp1,tmp2,tmp3,flag; if(symbol==PLUS||symbol==MINUS) { if(symbol==PLUS) flag = 1; else flag = 2; getsym(); if(isFileEnd==TRUE) return 0; } tmp1 = term(); if(flag==2) { mallocint(); tmp2 = medsindex-1; genmedi(NOT,tmp1,0,tmp2); } else { tmp2 = tmp1; } if(symbol==PLUS||symbol==MINUS) { while((symbol==PLUS||symbol==MINUS)&&isFileEnd==FALSE) { if(symbol==PLUS) flag = 1; else flag = 2; getsym(); if(isFileEnd==TRUE) return 0; tmp1 = term(); if(flag==2) { mallocint(); tmp3 = medsindex-1; genmedi(SUB,tmp2,tmp1,tmp3); } else { mallocint(); tmp3 = medsindex-1; genmedi(ADD,tmp2,tmp1,tmp3); } tmp2 = tmp3; } } return tmp2; } int term() { int tmp1,tmp2,tmp3,flag; tmp1 = factor(); if(symbol==TIMES||symbol==DIVI) { while((symbol==TIMES||symbol==DIVI)&&isFileEnd==FALSE) { if(symbol==TIMES) flag = 1; else flag = 2; getsym(); if(isFileEnd==TRUE) return 0; tmp2 = factor(); mallocint(); tmp3 = medsindex-1; if(flag==1) { genmedi(MUL,tmp1,tmp2,tmp3); } else { genmedi(DIV,tmp1,tmp2,tmp3); } tmp1 = tmp3; } } return tmp1; } int factor() { int tmp1,tmp2,tmp3; if(symbol==IDEN) { tmp1 = ftableindex(id); getsym(); if(isFileEnd==TRUE) return 0; if(symbol==LPAREN) { if(tmp1<0) { error(51); } else { if(table[tmp1].obj!=3) { error(56); } else if(table[tmp1].obj==3&&table[tmp1].type==3) { error(57); } tmp1 = table[tmp1].index; } callsta(tmp1); mallocint(); genmedi(ASN,1,0,medsindex-1); return (medsindex-1); } else if(symbol==LBKET) { if(tmp1<0) { error(51); } else { if(table[tmp1].obj!=2) { error(55); } tmp1 = table[tmp1].index; } getsym(); if(isFileEnd==TRUE) return 0; tmp2 = expression(); mallocint(); tmp3 = medsindex-1; genmedi(LW,tmp1,tmp2,tmp3); if(symbol!=RBKET) { error(5); } else { getsym(); if(isFileEnd==TRUE) return 0; } return tmp3; } else { if(tmp1<0) { error(51); tmp1=0; } else { if(table[tmp1].obj==3) { error(53); } tmp1 = table[tmp1].index; } return tmp1; } } else if(symbol==PLUS||symbol==MINUS||symbol==NUMBER) { tmp1 = isint(); return tmp1; } else if(symbol==CHARCST) { table[tableindex].name[0] = '\0'; table[tableindex].obj = 1; table[tableindex].type = 2; table[tableindex].valuec = chconst; table[tableindex].scope = curscope; malloctb(tableindex); tmp1 = medsindex-1; tableindex++; getsym(); if(isFileEnd==TRUE) return 0; return tmp1; } else if(symbol==LPAREN) { getsym(); if(isFileEnd==TRUE) return 0; tmp1=expression(); if(symbol!=RPAREN) { error(27); while(symbol!=RPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return 0; } } getsym(); if(isFileEnd==TRUE) return 0; return tmp1; } else return 0; } int isint() { int tmp1; if(symbol!=PLUS&&symbol!=MINUS&&symbol!=NUMBER) { error(15); while(symbol!=PLUS&&symbol!=MINUS&&symbol!=NUMBER&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return 0; } } if(symbol==PLUS) { getsym(); if(isFileEnd==TRUE) return 0; if(symbol!=NUMBER) { error(16); while(symbol!=NUMBER&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return 0; } } table[tableindex].name[0] = '\0'; table[tableindex].obj = 1; table[tableindex].type = 1; table[tableindex].valuei = num; table[tableindex].scope = curscope; malloctb(tableindex); tmp1 = medsindex-1; tableindex++; //tmpoffset++; getsym(); if(isFileEnd==TRUE) return 0; return tmp1; } else if(symbol==MINUS) { getsym(); if(isFileEnd==TRUE) return 0; if(symbol!=NUMBER) { error(16); while(symbol!=NUMBER&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return 0; } } num = 0-num; table[tableindex].name[0] = '\0'; table[tableindex].obj = 1; table[tableindex].type = 1; table[tableindex].valuei = num; table[tableindex].scope = curscope; malloctb(tableindex); tmp1 = medsindex-1; tableindex++; getsym(); if(isFileEnd==TRUE) return 0; return tmp1; } else if(symbol==NUMBER) { table[tableindex].name[0] = '\0'; table[tableindex].obj = 1; table[tableindex].type = 1; table[tableindex].valuei = num; table[tableindex].scope = curscope; malloctb(tableindex); tmp1 = medsindex-1; tableindex++; getsym(); if(isFileEnd==TRUE) return 0; return tmp1; } else return 0; } void inttoconst() { if(symbol!=PLUS&&symbol!=MINUS&&symbol!=NUMBER) { error(15); while(symbol!=PLUS&&symbol!=MINUS&&symbol!=NUMBER&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(symbol==PLUS) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=NUMBER) { error(16); while(symbol!=NUMBER&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; } else if(symbol==MINUS) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=NUMBER) { error(16); while(symbol!=NUMBER&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } num = 0-num; getsym(); if(isFileEnd==TRUE) return; } else if(symbol==NUMBER) { getsym(); if(isFileEnd==TRUE) return; } } void vartopro() { if(symbol==COMMA) { if(table[tableindex].obj==0) { table[tableindex].obj = 2; if(tmpstack[stackindex]==INTSYM) table[tableindex].type = 1; else if(tmpstack[stackindex]==CHARSYM) table[tableindex].type = 2; malloctb(tableindex); genmedi(GLOBEG,medsindex-1,0,0); //table[tableindex].offset = offset++; table[tableindex].scope = curscope; } tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(findtable(id,2)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].offset = offset++; getsym(); if(isFileEnd==TRUE) return; vartopro(); } else { error(2); } } if(symbol==LBKET) { table[tableindex].obj = 2; if(tmpstack[stackindex]==INTSYM) table[tableindex].type = 3; else if(tmpstack[stackindex]==CHARSYM) table[tableindex].type = 4; offset--; table[tableindex].scope = curscope; getsym(); if(isFileEnd==TRUE) return; if(symbol==NUMBER) { if(num==0) { error(4); num = 10; } getsym(); if(isFileEnd==TRUE) return; } else { error(3); num = 10; } malloctb(tableindex); genmedi(GLOBEG,medsindex-1,0,0); table[tableindex].length = num; offset += num; if(symbol!=RBKET) { error(5); } else { getsym(); if(isFileEnd==TRUE) return; } if(symbol==COMMA) { tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(findtable(id,2)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].offset = offset++; //flag table[tableindex].obj = 0; table[tableindex].type = 0; getsym(); if(isFileEnd==TRUE) return; vartopro(); } else { error(2); } } } if(symbol==SEMICOLON) { //[]; if(table[tableindex].obj!=0&&table[tableindex].type!=0) { tableindex++; } //标; else { table[tableindex].obj = 2; if(tmpstack[stackindex]==INTSYM) table[tableindex].type = 1; else if(tmpstack[stackindex]==CHARSYM) table[tableindex].type = 2; malloctb(tableindex); genmedi(GLOBEG,medsindex-1,0,0); //table[tableindex].offset = offset++; table[tableindex].scope = curscope; tableindex++; } stackindex--; // printf("This is varaible declaration for program.\n"); getsym(); if(isFileEnd==TRUE) return; if(symbol==INTSYM||symbol==CHARSYM) { tmpstack[++stackindex] = symbol; getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } strcpy(table[tableindex].name,id); table[tableindex].offset = offset++; //flag table[tableindex].obj = 0; table[tableindex].type = 0; getsym(); if(isFileEnd==TRUE) return; if(symbol==COMMA||symbol==SEMICOLON||symbol==LBKET) { if(findtable(table[tableindex].name,2)>=0) error(49); vartopro(); } if(symbol==LPAREN) { /////////////////////////////////// if(isjmain==FALSE) { genmedi(GOTO,0,0,2); isjmain = TRUE; } tmpoffset = 0; curscope++; if(findtable(table[tableindex].name,3)>=0) error(49); fictopro(); } } } } void parameter() { int paraid; if(symbol==INTSYM||symbol==CHARSYM) { table[tableindex].obj = 4; if(symbol==INTSYM) { table[tableindex].type = 1; } else if(symbol==CHARSYM) { table[tableindex].type = 2; } getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,4)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].scope = curscope; table[tableindex].offset = tmpoffset++; malloctb(tableindex); paraid = medsindex-1; calmyparasum++; genmedi(PARA,paraid,0,0); tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==COMMA) { getsym(); if(isFileEnd==TRUE) return; parameter(); } } else { error(8); } } void fictopro() { int tableid,funid; int tmpbegin,tmpend; if(symbol!=LPAREN) { error(7); while(symbol!=LPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } malloctb(tableindex); funid = medsindex-1; curcompifunid = funid; genmedi(LAB,funid,0,0); genmedi(BEGIN,funid,0,0); tmpoffset = 0; table[tableindex].obj = 3; if(tmpstack[stackindex]==INTSYM) table[tableindex].type = 1; else if(tmpstack[stackindex]==CHARSYM) table[tableindex].type = 2; table[tableindex].scope = curscope; tableid = tableindex; calmyparasum=0; tmpbegin = tempvindex; table[tableindex].tmpbasic = tmpbegin; tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==INTSYM||symbol==CHARSYM) { parameter(); } if(symbol!=RPAREN) { error(9); while(symbol!=RPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } table[tableid].myparasum = calmyparasum; calmyparasum = 0; getsym(); if(isFileEnd==TRUE) return; if(symbol!=LBRACE) { error(10); while(symbol!=LBRACE&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; mixsta(); if(symbol!=RBRACE) { error(11); while(symbol!=RBRACE&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } //have return values if(table[tableid].type!=3) { //no return statement if(returnstack.scope!=curscope||returnstack.id!=funid) { error(50); genmedi(RETURN,0,0,0); genmedi(END,funid,0,0); genmedi(JR,0,0,0); } } else { //void no return statement if(returnstack.scope!=curscope||returnstack.id!=funid) { genmedi(END,funid,0,0); genmedi(JR,0,0,0); } } table[tableid].offset = tmpoffset; tmpend = tempvindex; table[tableid].length = tmpoffset+tmpend-tmpbegin; // printf("This is valued function's declaration for program.\n"); getsym(); if(isFileEnd==TRUE) return; if(symbol!=INTSYM&&symbol!=CHARSYM&&symbol!=VOIDSYM) { error(12); while(symbol!=INTSYM&&symbol!=CHARSYM&&symbol!=VOIDSYM&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(symbol==INTSYM||symbol==CHARSYM) { tmpstack[++stackindex] = symbol; getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,3)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].offset = offset++; table[tableindex].obj = 3; getsym(); if(isFileEnd==TRUE) return; curscope++; fictopro(); } else if(symbol==VOIDSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(isjmain==FALSE) { genmedi(GOTO,0,0,2); isjmain = TRUE; } curscope++; fvotopro(); } } } void fvotopro() { int tableid,funid; int tmpbegin,tmpend; if(symbol!=IDEN) { error(13); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,3)>=0) error(49); strcpy(table[tableindex].name,id); malloctb(tableindex); funid = medsindex-1; curcompifunid = funid; genmedi(LAB,funid,0,0); genmedi(BEGIN,funid,0,0); tmpoffset=0; table[tableindex].obj = 3; table[tableindex].type = 3; table[tableindex].scope = curscope; tableid = tableindex; tmpbegin = tempvindex; table[tableindex].tmpbasic = tmpbegin; calmyparasum=0; tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol!=LPAREN) { error(7); while(symbol!=LPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; if(symbol==INTSYM||symbol==CHARSYM) { parameter(); } if(symbol!=RPAREN) { error(9); while(symbol!=RPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } table[tableid].myparasum = calmyparasum; calmyparasum = 0; getsym(); if(isFileEnd==TRUE) return; if(symbol!=LBRACE) { error(10); while(symbol!=LBRACE&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; mixsta(); if(symbol!=RBRACE) { error(11); while(symbol!=RBRACE&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } //have return values if(table[tableid].type!=3) { //no return statement if(returnstack.scope!=curscope||returnstack.id!=funid) { error(50); genmedi(RETURN,0,0,0); genmedi(END,funid,0,0); genmedi(JR,0,0,0); } } else { //void no return statement if(returnstack.scope!=curscope||returnstack.id!=funid) { genmedi(END,funid,0,0); genmedi(JR,0,0,0); } } table[tableid].offset = tmpoffset; tmpend = tempvindex; table[tableid].length = tmpoffset+tmpend-tmpbegin; //printf("This is void function's declaration for program.\n"); getsym(); if(isFileEnd==TRUE) return; if(symbol!=INTSYM&&symbol!=CHARSYM&&symbol!=VOIDSYM) { error(12); while(symbol!=INTSYM&&symbol!=CHARSYM&&symbol!=VOIDSYM&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(symbol==INTSYM||symbol==CHARSYM) { tmpstack[++stackindex] = symbol; getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,3)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].offset = offset++; table[tableindex].obj = 3; getsym(); if(isFileEnd==TRUE) return; curscope++; if(isjmain==FALSE) { genmedi(GOTO,0,0,2); isjmain = TRUE; } fictopro(); } else if(symbol==VOIDSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(isjmain==FALSE) { genmedi(GOTO,0,0,2); isjmain = TRUE; } curscope++; fvotopro(); } } } void ismain() { int tableid,funid,tmpbegin,tmpend; char name[10] = {"main"}; name[5] = '\0'; curscope++; if(symbol!=MAINSYM) { error(14); while(symbol!=MAINSYM&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(name,3)>=0) error(49); strcpy(table[tableindex].name,name); malloctb(tableindex); funid = medsindex-1; curcompifunid = funid; genmedi(LAB,funid,0,0); genmedi(BEGIN,funid,0,0); tmpoffset=0; table[tableindex].obj = 3; table[tableindex].type = 3; table[tableindex].scope = curscope; tableid = tableindex; tmpbegin = tempvindex; table[tableindex].tmpbasic = tmpbegin; tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol!=LPAREN) { error(7); while(symbol!=LPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; if(symbol!=RPAREN) { error(9); while(symbol!=RPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; if(symbol!=LBRACE) { error(10); while(symbol!=LBRACE&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; mixsta(); if(symbol!=RBRACE) { error(11); while(symbol!=RBRACE&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } //void no return statement if(returnstack.scope!=curscope||returnstack.id!=funid) { genmedi(END,funid,0,0); genmedi(JR,0,0,0); } table[tableid].offset = tmpoffset; tmpend = tempvindex; table[tableid].length = tmpoffset+tmpend-tmpbegin; //table[tableid].length = medsindex - funid; // printf("This is main function.\n"); return; } //注意声明的顺序 void program() { getsym(); if(isFileEnd==TRUE) { error(14); return; } labels[labelindex].name[0] = '$'; labels[labelindex].name[1]='e'; labels[labelindex].name[2]='n'; labels[labelindex].name[3]='d'; labels[labelindex].name[4]='\0'; table[tableindex].name[0] = '\0'; table[tableindex].obj = 1; table[tableindex].type = 1; table[tableindex].valuei = 0; table[tableindex].scope = curscope; malloctb(tableindex); tableindex++; /* tempv[tempvindex].type = 1; tempv[tempvindex].valuei = 0; medstack[medsindex].id = medsindex; medstack[medsindex].tbindex = -1; medstack[medsindex].tpindex = tempvindex; tempvindex=1; medsindex=1; */ table[tableindex].name[0] = '\0'; table[tableindex].obj = 6; table[tableindex].scope = curscope; malloctb(tableindex); tableindex++; medsindex = 2; malloclab(labelindex); labelindex=1; medsindex = 3; if(symbol==CONSTSYM) { constopro(); } if(symbol==INTSYM||symbol==CHARSYM) { tmpstack[stackindex] = symbol; getsym(); if(isFileEnd==TRUE) { error(14); return; } if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) { error(14); return; } } } if(findtable(id,2)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].offset = offset++; //flag table[tableindex].obj = 0; table[tableindex].type = 0; getsym(); if(isFileEnd==TRUE) { error(14); return; } if(symbol==COMMA||symbol==SEMICOLON||symbol==LBKET) { if(findtable(table[tableindex].name,2)>=0) error(49); vartopro(); } if(symbol==LPAREN) { if(isjmain==FALSE) { genmedi(GOTO,0,0,2); isjmain = TRUE; } tmpoffset = 0; curscope++; if(findtable(table[tableindex].name,3)>=0) error(49); fictopro(); } } if(symbol==VOIDSYM) { getsym(); if(isFileEnd==TRUE) { error(14); return; } if(symbol==IDEN) { if(isjmain==FALSE) { genmedi(GOTO,0,0,2); isjmain = TRUE; } tmpoffset = 0; curscope++; fvotopro(); } } if(symbol==MAINSYM) { tmpoffset = 0; curscope++; ismain(); } } int openoutput() { file1 = (char*)malloc((sizeof(char))*MAXPATH); printf("please input the test file path\n"); gets(file1); if(freopen(file1,"w",stdout)==NULL) { printf("file to open the output file\n"); return 0; } else { printf("success to open the output file\n"); return 1; } } void initreg() { int i; for(i=0;i<21;i++) { registers[i].distribute=FALSE; } } //分配寄存器 int allocreg(int index,int funid) { int i,tablefuncid,basic,addr,prev; int pretableid,curtableid,tmp,pretmpindex,curtmpindex; for(i=0;i<21;i++) if(registers[i].distribute==FALSE) break; if(i==21) { if(medstack[index].tbindex!=-1) { tmp = medstack[index].tbindex; if(table[tmp].obj==6) return 2; } regid++; regid %= 21; if(registers[regid].index==-1) { i = regid; } else { prev = registers[regid].index; //8号寄存器原来存的是局部变量或是全局变量 if(medstack[prev].tbindex!=-1) { pretableid = medstack[prev].tbindex; //参数或是变量需要写回内存 if(table[pretableid].obj==4) { addr = table[pretableid].offset; addr *= 4; addr = -addr; printf("sw $%d %d($fp)\n",(regid+5),addr); } else if(table[pretableid].obj==2) { //局部变量 if(table[pretableid].scope!=0) { addr = table[pretableid].offset; addr *= 4; addr = -addr; printf("sw $%d %d($fp)\n",(regid+5),addr); } //全局变量 else { printf("sw $%d %s($0)\n",(regid+5),table[pretableid].name); } } } //8号寄存器原来存的是临时变量 else if(medstack[prev].tpindex!=-1) { tablefuncid = medstack[funid].tbindex; basic = table[tablefuncid].tmpbasic; pretmpindex = medstack[prev].tpindex; addr = pretmpindex-basic+table[tablefuncid].offset; addr *= 4; addr = -addr; printf("sw $%d %d($fp)\n",(regid+5),addr); } i = regid; } } //是符号表中的东西 if(medstack[index].tbindex!=-1) { curtableid = medstack[index].tbindex; if(table[curtableid].obj==4) { addr = table[curtableid].offset; addr *= 4; addr = -addr; printf("lw $%d %d($fp)\n",(i+5),addr); } else if(table[curtableid].obj==2) { //局部变量 if(table[curtableid].scope!=0) { addr = table[curtableid].offset; addr *= 4; addr = -addr; printf("lw $%d %d($fp)\n",(i+5),addr); } //全局变量 else { printf("lw $%d %s($0)\n",(i+5),table[curtableid].name); } } } //即将要分配的变量是临时变量 else if(medstack[index].tpindex!=-1) { tablefuncid = medstack[funid].tbindex; basic = table[tablefuncid].tmpbasic; curtmpindex = medstack[index].tpindex; addr = curtmpindex-basic+table[tablefuncid].offset; addr *= 4; addr = -addr; printf("lw $%d %d($fp)\n",(i+5),addr); } registers[i].distribute = TRUE; registers[i].index = index; return (i+5); } int allocregforint(int value,int funid) { int i,tablefuncid,basic,addr,prev; int pretableid,curtableid,pretmpindex; for(i=0;i<21;i++) if(registers[i].distribute==FALSE) break; if(i==21) { regid++; regid %= 21; prev = registers[regid].index; //8号寄存器原来存的是局部变量或是全局变量 if(medstack[prev].tbindex!=-1) { pretableid = medstack[prev].tbindex; //参数或是变量需要写回内存 if(table[pretableid].obj==4) { addr = table[pretableid].offset; addr *= 4; addr = -addr; printf("sw $%d %d($fp)\n",(regid+5),addr); } else if(table[pretableid].obj==2) { //局部变量 if(table[pretableid].scope!=0) { addr = table[pretableid].offset; addr *= 4; addr = -addr; printf("sw $%d %d($fp)\n",(regid+5),addr); } //全局变量 else { printf("sw $%d %s($0)\n",(regid+5),table[pretableid].name); } } } //8号寄存器原来存的是临时变量 else if(medstack[prev].tpindex!=-1) { tablefuncid = medstack[funid].tbindex; basic = table[tablefuncid].tmpbasic; pretmpindex = medstack[prev].tpindex; addr = pretmpindex-basic+table[tablefuncid].offset; addr *= 4; addr = -addr; printf("sw $%d %d($fp)\n",(regid+5),addr); } i = regid; } registers[i].distribute = TRUE; registers[i].index = -1; printf("addi $%d $0 %d\n",(i+5),value); return (i+5); } int isalloc(int index) { int i; for(i=0;i<21;i++) if(registers[i].index==index) return (i+5); if(medstack[index].tbindex!=-1) { i = medstack[index].tbindex; if(table[i].obj==6) return 2; } return -1; } void printsw() { int i = 5,j = 152,k=0; printf("sw $ra 160($sp)\n"); printf("sw $fp 156($sp)\n"); for(k=0;k<21;k++,i++,j=j-4) { printf("sw $%d %d($sp)\n",i,j); } } void writebackmem(int funid) { int i,tablefuncid,basic,addr,prev; int pretableid,curtableid,pretmpindex; for(i=0;i<21;i++) { if(registers[i].distribute==TRUE&&registers[i].index!=-1) { prev = registers[i].index; //8号寄存器原来存的是临时变量 if(medstack[prev].tpindex!=-1) { tablefuncid = medstack[funid].id; basic = table[tablefuncid].tmpbasic; pretmpindex = medstack[prev].tpindex; addr = pretmpindex-basic+table[tablefuncid].offset; addr *= 4; addr = -addr; printf("sw $%d %d($fp)\n",(i+5),addr); } //8号寄存器原来存的是局部变量或是全局变量 else if(medstack[prev].tbindex!=-1) { pretableid = medstack[prev].tbindex; //参数或是变量需要写回内存 if(table[pretableid].obj==4) { addr = table[pretableid].offset; addr *= 4; addr = -addr; printf("sw $%d %d($fp)\n",(i+5),addr); } else if(table[pretableid].obj==2) { //局部变量 if(table[pretableid].scope!=0) { addr = table[pretableid].offset; addr *= 4; addr = -addr; printf("sw $%d %d($fp)\n",(i+5),addr); } //全局变量 else { printf("sw $%d %s($0)\n",(i+5),table[pretableid].name); } } } } } } void printlw() { int i = 5,j = 152,k=0; printf("lw $ra 160($sp)\n"); printf("lw $fp 156($sp)\n"); for(k=0;k<21;k++,i++,j=j-4) { printf("lw $%d %d($sp)\n",i,j); } } void genemips() { int i,rs,rt,rd; //int rsmedid,rtmedid,rdmedid; int rstabid,rttabid,rdtabid; int rsreg,rtreg,rdreg,tmpreg; int rsv,rtv,rdv; int rsint,rtint,rdint;//是否为常量 //int fend;//function end index int funid;//函数基地址index int funtabid; int j,k,t,m,n; int reserve = 40;//保留区的长度 char tmp[10]={"str"}; char no[5]; //i = openoutput(); //if(i==0) // return; printf(".data\n"); i = 0; while(i<medialindex&&medial[i].op==GLOBEG) { rs = medial[i].rs; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //全局变量 if(table[rstabid].type==1||table[rstabid].type==2) { printf("%s: .word 0 \n",table[rstabid].name); } //数组 else { printf("%s: .word 0:%d \n",table[rstabid].name,table[rstabid].length); } } i++; } for(j=0;j<strindex;j++) { printf("str%d: .asciiz \"%s\"\n",j,strings[j]); } printf(".text\n"); printf("j $end\n"); for(;i<medialindex;i++) { rs = medial[i].rs; rt = medial[i].rt; rd = medial[i].rd; switch(medial[i].op) { case ADD: rsint = FALSE; rtint = FALSE; rdint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); j = rsv+rtv; printf("addi $%d $0 %d\n",rdreg,j); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); printf("addi $%d $%d %d\n",rdreg,rtreg,rsv); } } else { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("addi $%d $%d %d\n",rdreg,rsreg,rtv); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("add $%d $%d $%d\n",rdreg,rsreg,rtreg); } } break; case SUB: rsint = FALSE; rtint = FALSE; rdint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); j = rsv-rtv; printf("addi $%d $0 %d\n",rdreg,j); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); printf("subi $%d $%d %d\n",rdreg,rtreg,rsv); printf("sub $%d $0 $%d\n",rdreg,rdreg); } } else { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("subi $%d $%d %d\n",rdreg,rsreg,rtv); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("sub $%d $%d $%d\n",rdreg,rsreg,rtreg); } } break; case MUL: rsint = FALSE; rtint = FALSE; rdint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); j = rsv*rtv; printf("addi $%d $0 %d\n",rdreg,j); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); printf("mul $%d $%d %d\n",rdreg,rtreg,rsv); } } else { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("mul $%d $%d %d\n",rdreg,rsreg,rtv); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("mul $%d $%d $%d\n",rdreg,rsreg,rtreg); } } break; case DIV: rsint = FALSE; rtint = FALSE; rdint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); j = rsv/rtv; printf("addi $%d $0 %d\n",rdreg,j); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rsreg = allocregforint(rsv,funid); printf("div $%d $%d $%d\n",rdreg,rsreg,rtreg); } } else { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("div $%d $%d %d\n",rdreg,rsreg,rtv); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("div $%d $%d $%d\n",rdreg,rsreg,rtreg); } } break; case BIG: rsint = FALSE; rtint = FALSE; rdint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); j = ((rsv>rtv)?1:0); printf("addi $%d $0 %d\n",rdreg,j); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rsreg = allocregforint(rsv,funid); printf("sgt $%d $%d $%d\n",rdreg,rsreg,rtreg); } } else { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("sgt $%d $%d %d\n",rdreg,rsreg,rtv); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("sgt $%d $%d $%d\n",rdreg,rsreg,rtreg); } } break; case SMA: rsint = FALSE; rtint = FALSE; rdint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); j = ((rsv<rtv)?1:0); printf("addi $%d $0 %d\n",rdreg,j); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rsreg = allocregforint(rsv,funid); printf("slt $%d $%d $%d\n",rdreg,rsreg,rtreg); } } else { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("slti $%d $%d %d\n",rdreg,rsreg,rtv); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("slt $%d $%d $%d\n",rdreg,rsreg,rtreg); } } break; case EQU: rsint = FALSE; rtint = FALSE; rdint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); j = ((rsv==rtv)?1:0); printf("addi $%d $0 %d\n",rdreg,j); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rsreg = allocregforint(rsv,funid); printf("seq $%d $%d $%d\n",rdreg,rsreg,rtreg); } } else { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("seq $%d $%d %d\n",rdreg,rsreg,rtv); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("seq $%d $%d $%d\n",rdreg,rsreg,rtreg); } } break; case BEQU: rsint = FALSE; rtint = FALSE; rdint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); j = ((rsv>=rtv)?1:0); printf("addi $%d $0 %d\n",rdreg,j); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rsreg = allocregforint(rsv,funid); printf("sge $%d $%d $%d\n",rdreg,rsreg,rtreg); } } else { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("sge $%d $%d %d\n",rdreg,rsreg,rtv); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("sge $%d $%d $%d\n",rdreg,rsreg,rtreg); } } break; case SEQU: rsint = FALSE; rtint = FALSE; rdint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); j = ((rsv<=rtv)?1:0); printf("addi $%d $0 %d\n",rdreg,j); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rsreg = allocregforint(rsv,funid); printf("sle $%d $%d $%d\n",rdreg,rsreg,rtreg); } } else { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("sle $%d $%d %d\n",rdreg,rsreg,rtv); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("sle $%d $%d $%d\n",rdreg,rsreg,rtreg); } } break; case NOT: rsint = FALSE; rtint = FALSE; rdint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(rsint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); printf("subi $%d $0 %d\n",rdreg,rsv); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("sub $%d $0 $%d\n",rdreg,rsreg); } break; case NEQU: rsint = FALSE; rtint = FALSE; rdint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); if(rsv==rtv) printf("ori $%d $0 0\n",rdreg); else printf("ori $%d $0 1\n",rdreg); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); printf("sne $%d $%d %d\n",rdreg,rtreg,rsv); } } else { if(rtint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("sne $%d $%d %d\n",rdreg,rsreg,rtv); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("sne $%d $%d $%d\n",rdreg,rsreg,rtreg); } } break; case ASN: k = isalloc(rd); if(k==-1) { k = allocreg(rd,funid); } if(medstack[rs].tbindex!=-1) { j = medstack[rs].tbindex; if(table[j].obj==1) { if(table[j].type==1) printf("addi $%d $0 %d\n",k,table[j].valuei); else printf("addi $%d $0 %d\n",k,table[j].valuec); } else { t = isalloc(rs); if(t==-1) t = allocreg(rs,funid); printf("move $%d $%d\n",k,t); } } else { t = isalloc(rs); if(t==-1) t = allocreg(rs,funid); printf("move $%d $%d\n",k,t); } break; case BEQ: k = isalloc(rs); if(k==-1) { k = allocreg(rs,funid); } //跳转到函数 if(medstack[rd].tbindex!=-1) { funtabid = medstack[rd].tbindex; printf("beq $%d $0 %s\n",k,table[funtabid].name); } //跳转到条件标签 else { t = medstack[rd].lableindex; printf("beq $%d $0 %s\n",k,labels[t].name); } break; case GOTO: //跳转到函数 if(medstack[rd].tbindex!=-1) { funtabid = medstack[rd].tbindex; printf("j %s\n",table[funtabid].name); } //跳转到条件标签 else { k = medstack[rd].lableindex; printf("j %s\n",labels[k].name); //writebackmem(funid); //initreg(); } break; case LAB: //设置函数标签 if(medstack[rs].tbindex!=-1) { funtabid = medstack[rs].tbindex; printf("%s:\n",table[funtabid].name); } //设置条件跳转标签 else { k = medstack[rs].lableindex; printf("%s:\n",labels[k].name); } break; case BEGIN: funid = rs; funtabid = medstack[funid].tbindex; j = table[funtabid].length+reserve; j*=4; printf("move $fp $sp\n"); printf("subi $sp $sp %d\n",j); printsw(); initreg(); break; case END: funid = rs; funtabid = medstack[funid].tbindex; j = table[funtabid].length+reserve; j*=4; //write将寄存器里的值写回内存 writebackmem(funid); printlw(); printf("addi $sp $sp %d\n",j); break; case SW: rstabid = medstack[rs].tbindex; //全局变量数组 if(table[rstabid].scope==0) { rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); tmpreg = allocregforint(0,funid); printf("sll $%d $%d 2\n",tmpreg,rtreg); printf("sw $%d %s($%d)\n",rdreg,table[rstabid].name,tmpreg); } //局部变量数组 else { rsv = (table[rstabid].offset)*4; //rsreg = allocregforint(rsv,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); tmpreg = allocregforint(0,funid); printf("sll $%d $%d 2\n",tmpreg,rtreg); printf("add $%d $%d $fp\n",tmpreg,tmpreg); printf("sw $%d %d($%d)\n",rdreg,rsv,tmpreg); } break; case LW: rstabid = medstack[rs].tbindex; //全局变量数组 if(table[rstabid].scope==0) { rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); tmpreg = allocregforint(0,funid); printf("sll $%d $%d 2\n",tmpreg,rtreg); printf("lw $%d %s($%d)\n",rdreg,table[rstabid].name,tmpreg); } //局部变量数组 else { rsv = (table[rstabid].offset)*4; //rsreg = allocregforint(rsv,funid); rtreg = isalloc(rt); if(rtreg==-1) rtreg = allocreg(rt,funid); rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); tmpreg = allocregforint(0,funid); printf("sll $%d $%d 2\n",tmpreg,rtreg); printf("add $%d $%d $fp\n",tmpreg,tmpreg); printf("lw $%d %d($%d)\n",rdreg,rsv,tmpreg); } break; case CALL: rstabid = medstack[rs].tbindex; printf("jal %s\n",table[rstabid].name); break; case FORM: while(i<medialindex&&medial[i].op==FORM) { rsint = FALSE; rs = medial[i].rs; rt = medial[i].rt; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(rsint==TRUE) { rsreg = allocregforint(rsv,funid); } else { rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); } m = -(rt*4); printf("sw $%d %d($sp)\n",rsreg,m); i++; } i--; /* j = i; while(j<medialindex&&medial[j].op==FORM) j++; t = j-i; if(t<4) { for(k=0;i<j;i++,k++) { rs = medial[i].rs; rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("move $a%d $%d\n",k,rsreg); } } else { for(k=0;k<4;i++,k++) { rs = medial[i].rs; rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("move $a%d $%d\n",k,rsreg); } t-=4; for(k=1;k<=t&&medial[i].op==FORM;k++,i++) { rs = medial[i].rs; rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); m = k*4; printf("sw $%d %d($sp)\n",rsreg,m); } } i = j-1; */ break; case RETURN: if(rs==0) printf("move $v0 $0\n"); else { if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) printf("addi $v0 $0 %d\n",table[rstabid].valuei); else printf("addi $v0 $0 %d\n",table[rstabid].valuec); } else { rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("move $v0 $%d\n",rsreg); } } else { rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("move $v0 $%d\n",rsreg); } } break; case PARA: break; case ADDI: rsint = FALSE; rtint = FALSE; rdint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(rsint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); j = rsv+rt; printf("addi $%d $0 %d\n",rdreg,j); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("addi $%d $%d %d\n",rdreg,rsreg,rt); } break; case SUBI: rsint = FALSE; rtint = FALSE; rdint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(rsint==TRUE) { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); j = rsv-rt; printf("addi $%d $0 %d\n",rdreg,j); } else { rdreg = isalloc(rd); if(rdreg==-1) rdreg = allocreg(rd,funid); rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("addi $%d $%d %d\n",rdreg,rsreg,rt); } break; case RD: rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); //read printf("li $v0 5\n"); printf("syscall\n"); printf("move $%d $v0\n",rsreg); break; case WRT: //write string if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; if(table[rstabid].obj!=5) { rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("li $v0 1\n"); printf("move $a0 $%d\n",rsreg); printf("syscall\n"); } else { j = table[rstabid].locate; printf("li $v0 4\n"); printf("la $a0 str%d\n",j); printf("syscall\n"); } } else { rsreg = isalloc(rs); if(rsreg==-1) rsreg = allocreg(rs,funid); printf("li $v0 1\n"); printf("move $a0 $%d\n",rsreg); printf("syscall\n"); } break; case JR: printf("jr $ra\n"); break; } } printf("$end: jal main\n"); } int main() { int i; i = openfile(); if(i==0) return 0; program(); genemips(); //printgetsym(); /* if(freopen("output.txt","w",stdout)==NULL) { printf("file to open the output file\n"); return 1; } */ //printf("hello world\n"); free(file); //free(file1); return 0; } <file_sep>/README.md # Compiler the compiler like c <file_sep>/SourceCodes/compiler1176/main.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <malloc.h> //symbol 类型定义 #define CONSTSYM 1 #define INTSYM 2 #define CHARSYM 3 #define VOIDSYM 4 #define MAINSYM 5 #define IFSYM 6 #define ELSESYM 7 #define DOSYM 8 #define WHILESYM 9 #define FORSYM 10 #define SCANFSYM 11 #define PRINTFSYM 12 #define RETURNSYM 13 #define PLUS 14 #define MINUS 15 #define TIMES 16 #define DIVI 17 #define LSS 18 #define LEQ 19 #define GRT 20 #define GEQ 21 #define NEQ 22 #define EQL 23 #define ASSIGN 24 #define LPAREN 25 #define RPAREN 26 #define LBRACE 27 #define RBRACE 28 #define LBKET 29 #define RBKET 30 #define COMMA 31 #define SEMICOLON 32 #define LSINQ 33 #define RSINQ 34 #define LDOUQ 35 #define RDOUQ 36 #define IDEN 37 #define NUMBER 38 #define CHARCST 39 #define STRING 40 #define ERRORSYM 111 #define FALSE -1 #define TRUE 0 #define REGGSUM 12 #define REGGBASIC 14 #define REGLWSUM 6 #define REGLWBASIC 8 #define REGARRAYSUM 3 #define REGARRAYBASIC 5 #define RESERVE 16 #define MAXPATH 60 //the string of file path's max size 输入文件的路径字符串的最大值 #define MAXLS 1000 //max one line size of input file 输入文件中一行的字符数的最大值 #define MAXIDS 20 //max size of identifier 一个标识符长度的最大值 #define MAXSTR 100 //max size of output string 输出字符串的最大长度 #define MAXTAB 10000 //max size of table 符号表的最大长度 #define MAXSTRLENG 2000 //max length of string's size 字符串的最大数量 #define MAXMEDI 8000 //max medial size 中间表达式的最大数量 #define MAXTEMP 4000 //中间临时变量的数量 #define MAXMSTACK 10000 // #define MAXLABELS 300 //最大标签数 #define MAXBLOCKS 3000 //最大块数 #define MAXDAGNODES 1000 //dag图节点数最大值 //四元式操作符定义 #define ADD 0 #define SUB 1 #define MUL 2 #define DIV 3 #define BIG 4 #define SMA 5 #define EQU 6 #define BEQU 7 #define SEQU 8 #define NOT 9 #define NEQU 10 #define ASN 11 #define BEQ 12 #define GOTO 13 #define LAB 14 #define GLOBEG 15 #define BEGIN 16 #define END 17 #define SW 18 #define LW 19 #define CALL 20 #define FORM 21 #define RETURN 22 #define DEL 23 #define ADDI 24 #define SUBI 25 #define RD 26 #define WRT 27 #define JR 28 #define LOOPBEGIN 29 #define LOOPEND 30 char* file; //= (char*)malloc(sizeof(char)*MAXPATH);//file of input char* file1; char linebuf[MAXLS]; //line buffer to storage one line of the input file 保存读入文件的一行,行缓冲区 int lineIndex=MAXLS-1; //index of the linebuffer 行缓冲区指针 //char ch; //last charactor read 最近一次读入的字符 int symbol=0; //last symbol read 最近一次识别出来的单词类型 char id[MAXIDS]; //last identifier read 最近一次识别出来的标识符名称 int num=0; //last const number read 最近一次读入的整常数的值 char chconst; //last const character read 最近一次读入的字符常量的值 char str[MAXSTR]; //last output string read 最近一次读入的字符串 int isFileEnd; int linenum=0; //current line of read file 当前读到的行,用于出错处理的定位 int infunc; int curscope=0;//当前的作用域 //symbol栈,int或char int tmpstack[50]={-1}; int stackindex=1; //分配寄存器编号,轮盘制 //int regid=0; int curcompifunid=0;//当前编译的函数的medsindex //int haveretuval=FALSE; //return 栈,return的返回值所在的medstack索引 struct{ int id; int scope; }returnstack; //全局变量的偏移量 int offset=0; //局部变量的偏移量 int tmpoffset = 0; int calmyparasum = 0;//本函数定义时的参数个数 //table 符号表 struct{ char name[MAXIDS];//名字 int obj; //constant variable function int type; //int char arrays int valuei; //value of const integer char valuec; //value of const char int offset; //var or array or function 's offset int scope; int length; // int locate; // int index; //在中间栈中的索引id int distru; int myparasum;//the sum of function parameter int callparasum; int paraid; int num; int beginid; int endid; }table[MAXTAB]; struct{ int id; int op; int left; int right; }dagnodes[MAXDAGNODES]; int dagnodindex = 0; struct{ int medsid; int nodeid; }dagtable[MAXDAGNODES]; int dagtabindex = 0; //四元式 struct{ int op; //option int rs; int rt; int rd; int dagnodeid; }medial[MAXMEDI]; int medialindex=0; //临时变量表 struct{ int type;//1:int,2:char int num; int regid; int addr; int scope; }tempv[MAXTEMP]; int tempvindex=0; //总表 struct{ int id; int tbindex; int tpindex; int lableindex; int num;//被引用次数 }medstack[MAXMSTACK]; int medsindex=0; struct{ int id; int num; }statis[MAXMSTACK]; //全局寄存器 struct{ int distribute;//是否已分配 int index; }globalregs[REGGSUM]; //用于访问内存寻址 struct{ int distribute; int index; }lwregs[REGLWSUM]; //用于数组的操作 struct{ int distribute; int index; }arrayregs[REGARRAYSUM]; //标签,主要用于if-else,for等,函数不需要 struct{ char name[10]; int index; }labels[MAXLABELS]; int labelindex=0; struct{ int beginid;//指向四元式 int endid;//指向四元式 int scope;//当前作用的函数 }blocks[MAXBLOCKS]; int blocksindex = 0; //标签栈,保存已经生成但未使用的标签,生成时进栈,使用后退栈 //int labelstack[MAXLABELS]; //int labstaindex = 0; int tableindex=0;//index of table char strings[MAXSTRLENG][MAXSTR]; int strindex=0; //int isjmain = TRUE; //function declare int findtable(char name[MAXIDS],int obj); int ftableindex(char name[MAXIDS],int type); void genlabel(); void malloctb(int index); void mallocint(); void mallocchar(); void malloclab(int index); void genmedi(int o,int rs,int rt,int rd); void error(int i); char getch(); void goback(); void getsym(); int openfile(); void printgetsym(); void constopro(); void constdec(); void tovardec(); void vardec(); void mixsta(); void statements(); void statemt(); int condition(); void ifsta(); void loopsta(); void callsta(int idenid); void assignsta(int idenid); void readsta(); void writesta(); void returnsta(); int expression(); int term(); int factor(); int isint(); void inttoconst(); void vartopro(); void parameter(); void fictopro(); void fvotopro(); void ismain(); void program(); //优化相关 void genblocks(); int finddagtable(int index); void finddagnode1(int op,int left,int right,int result,int medindex); void finddagnode2(int op,int left,int right,int result,int medindex); void finddagnode3(int op,int left,int result,int medindex); void dag(); void alloc(); int openoutput(); void printsw(); void printlw(); void checkpara(int funtabid); int calreg(int num,int medid); void swreg(int medid,int regid); void genemips(); //主要用于查重复定义,全局变量和局部变量可以重名 //若是局部变量只需要查函数内部是否重复定义,不需要查函数外部的全局变量 int findtable(char name[MAXIDS],int obj) { int i; if(tableindex<2) return -1; switch(obj) { case 1: for(i=tableindex-1;i>=0&&table[i].scope==curscope;i--) { if(strcmp(name,table[i].name)==0) return i; } return -1; break; case 2: for(i=tableindex-1;i>=0&&table[i].scope==curscope;i--) { if(strcmp(name,table[i].name)==0) return i; } return -1; break; case 3: for(i = tableindex-1;i>=0;i--) { if(table[i].obj==3) { if(strcmp(name,table[i].name)==0) return i; } } return -1; break; case 4: for(i=tableindex-1;i>=0&&table[i].scope==curscope;i--) { if(strcmp(name,table[i].name)==0) return i; } return -1; break; case 7: for(i=tableindex-1;i>=0&&table[i].scope==curscope;i--) { if(strcmp(name,table[i].name)==0) return i; } return -1; break; } return -1; } //主要用于运算的时候查表,查最靠近栈顶的位置, //若是出现在函数内,不仅要查局部变量还要查全局变量。 //type为3,函数;1:变量或常量或参数(全局局部);2:数组 int ftableindex(char name[MAXIDS],int type) { int i; if(tableindex==0) return -1; switch(type) { case 1: for(i=tableindex-1;i>=0&&table[i].scope==curscope;i--) { if(table[i].obj==1||table[i].obj==2||table[i].obj==4) { if(strcmp(name,table[i].name)==0) return i; } } for(i=0;i<=MAXTAB&&table[i].scope==0;i++) { if(table[i].obj==1||table[i].obj==2) { if(strcmp(name,table[i].name)==0) return i; } } break; case 2: for(i=tableindex-1;i>=0&&table[i].scope==curscope;i--) { if(table[i].obj==7) { if(strcmp(name,table[i].name)==0) return i; } } for(i=0;i<=MAXTAB&&table[i].scope==0;i++) { if(table[i].obj==7) { if(strcmp(name,table[i].name)==0) return i; } } break; case 3: for(i=0;i<=MAXTAB&&i<=tableindex;i++) { if(table[i].obj==3) { if(strcmp(name,table[i].name)==0) { return i; } } } break; } return -1; } //生成label,label+数字,数字每次加1 void genlabel() { int i; char j[5]; char tmp[10]={"$labe"}; // strcpy(labels[++labelindex].name,tmp); itoa(labelindex,j,10); for(i=5;i<10&&j[i-5]<='9'&&j[i-5]>='0';i++) labels[labelindex].name[i] = j[i-5]; labels[labelindex].name[i] = '\0'; //生成的标签未使用,进入标签栈中等待使用 //labelstack[labstaindex++] = labelindex; } void malloctb(int index) { medstack[medsindex].id = medsindex; medstack[medsindex].tbindex = index; medstack[medsindex].tpindex = -1; medstack[medsindex].lableindex = -1; medstack[medsindex].num = 0; table[index].index = medsindex; medsindex++; } void mallocint() { tempv[tempvindex].type = 1; tempv[tempvindex].num = 0; tempv[tempvindex].regid = -1; tempv[tempvindex].addr = -1; tempv[tempvindex].scope = curscope; medstack[medsindex].id = medsindex; medstack[medsindex].tbindex = -1; medstack[medsindex].tpindex = tempvindex; medstack[medsindex].lableindex = -1; medstack[medsindex].num = 0; tempvindex++; medsindex++; } void mallocchar() { tempv[tempvindex].type = 2; tempv[tempvindex].num = 0; tempv[tempvindex].regid = -1; tempv[tempvindex].addr = -1; tempv[tempvindex].scope = curscope; medstack[medsindex].id = medsindex; medstack[medsindex].tbindex = -1; medstack[medsindex].tpindex = tempvindex; medstack[medsindex].lableindex = -1; medstack[medsindex].num = 0; tempvindex++; medsindex++; } void malloclab(int index) { medstack[medsindex].id = medsindex; medstack[medsindex].tbindex = -1; medstack[medsindex].tpindex = -1; medstack[medsindex].lableindex = index; medstack[medsindex].num = 0; labels[index].index = medsindex; medsindex++; } void genmedi(int o,int rs,int rt,int rd) { medial[medialindex].op = o; medial[medialindex].rs = rs; medial[medialindex].rt = rt; medial[medialindex].rd = rd; medial[medialindex].dagnodeid = -1; medialindex++; } void error(int i) { switch(i) { case 0: printf("ERROR!!!!!Can't open the file!\n"); exit(0); break; case 1: printf("ERROR!!!!!类型标识符后面没有接标识符\n"); break; case 2: printf("ERROR!!!!!常量或变量说明中逗号后面没有接标识符\n"); getsym(); break; case 3: printf("ERROR!!!!!数组声明中[]内应该是无符号整数\n"); getsym(); break; case 4: printf("ERROR!!!!!数组声明时长度不能为0\n"); break; case 5: printf("ERROR!!!!!数组少了右边的方括号\n"); break; case 6: printf("ERROR!!!!!变量说明标识符后面没有跟逗号方括号或分号\n"); getsym(); break; case 7: printf("ERROR!!!!!函数定义中没有左括号\(\n"); break; case 8: printf("ERROR!!!!!参数表逗号后面没有接int或char\n"); getsym(); break; case 9: printf("ERROR!!!!!函数定义中没有右括号)\n"); break; case 10: printf("ERROR!!!!!函数定义中没有左大括号{\n"); break; case 11: printf("ERROR!!!!!函数定义中没有右大括号}\n"); break; case 12: printf("ERROR!!!!!函数定义中缺乏返回类型(void int char)\n"); break; case 13: printf("ERROR!!!!!无返回值函数定义中缺乏函数名\n"); break; case 14: printf("ERROR!!!!!缺乏主函数\n"); break; case 15: printf("ERROR!!!!!整数的第一个字符非法\n"); break; case 16: printf("ERROR!!!!!整数的正负号后面紧跟着不是数字\n"); break; case 17: printf("ERROR!!!!!常量定义中没有int或char\n"); break; case 18: printf("ERROR!!!!!常量定义中标识符后面没有等号=\n"); break; case 19: printf("ERROR!!!!!常量定义中分隔符非法,不是逗号或分号\n"); getsym(); break; case 20: printf("ERROR!!!!!字符常量定义中缺少字符值\n"); break; case 21: printf("ERROR!!!!!标识符超出最大长度,自动截取前20个字符\n"); break; case 22: printf("ERROR!!!!!无符号整数不存在前导零\n"); break; case 23: printf("ERROR!!!!!标识符出现非法字符\n"); break; case 24: printf("ERROR!!!!!字符常量或字符串常量缺少右单引号\n"); break; case 25: printf("ERROR!!!!!出现非法字符\n"); break; case 26: printf("ERROR!!!!!语句推出语句列时没有右边的大括号}\n"); break; case 27: printf("ERROR!!!!!因子推出表达式时缺少右括号)\n"); break; case 28: printf("ERROR!!!!!if后面少了左括号(\n"); break; case 29: printf("ERROR!!!!!if后面少了右括号)\n"); break; case 30: printf("ERROR!!!!!do后面没有while\n"); break; case 31: printf("ERROR!!!!!while后面少了左括号\n"); break; case 32: printf("ERROR!!!!!while后面少了右括号\n"); break; case 33: printf("ERROR!!!!!for后面少了左括号\n"); break; case 34: printf("ERROR!!!!!for的左括号后面没有标识符\n"); break; case 35: printf("ERROR!!!!!for后面少了右括号\n"); break; case 36: printf("ERROR!!!!!for的标识符后面没有等号\n"); getsym(); break; case 37: printf("ERROR!!!!!for赋初值后没有加分号\n"); getsym(); break; case 38: printf("ERROR!!!!!for条件之后没有加分号\n"); getsym(); break; case 39: printf("ERROR!!!!!for的增长值中没有标识符\n"); break; case 40: printf("ERROR!!!!!for的增长值中没有加减号\n"); break; case 41: printf("ERROR!!!!!for的步长中不是无符号整数\n"); break; case 42: printf("ERROR!!!!!步长不能为0\n"); break; case 43: printf("ERROR!!!!!函数调用少了右括号\n"); break; case 44: printf("ERROR!!!!!读写语句缺少左括号\n"); break; case 45: printf("ERROR!!!!!读写语句缺少右括号\n"); break; case 46: printf("ERROR!!!!!scanf缺少标识符\n"); break; case 47: printf("ERROR!!!!!return缺少右括号\n"); break; case 48: printf("ERROR!!!!!语句没有以分号结尾\n"); break; case 49: printf("ERROR!!!!!重复定义\n"); break; case 50: printf("ERROR!!!!!函数有返回值但是没有return语句\n"); break; case 51: printf("ERROR!!!!!使用前未声明\n"); break; case 52: printf("ERROR!!!!!不能给常量赋值\n"); break; case 53: printf("ERROR!!!!!不能给函数赋值\n"); break; //case 54: // printf("ERROR!!!!!读语句不能对参数赋值\n"); // break; case 55: printf("ERROR!!!!!数组的标识符不对,不能为其他常量或函数名\n"); break; case 56: printf("ERROR!!!!!函数调用中函数名不是函数名,而是其他常量或变量或参数名\n"); break; case 57: printf("ERROR!!!!!因子中的函数调用没有返回值\n"); break; case 58: printf("ERROR!!!!!void的函数定义中return后面有返回值\n"); break; case 59: printf("ERROR!!!!!函数调用与定义的参数个数不符\n"); break; case 60: printf("ERROR!!!!!函数调用时参数声明类型与调用时不符\n"); break; case 61: printf("ERROR!!!!!赋值语句标识符声明的类型和赋值的类型不符\n"); break; case 62: printf("ERROR!!!!!数组下标不能为字符,应该是数字\n"); break; case 63: printf("ERROR!!!!!函数返回值定义的类型与实际返回的不一致\n"); break; } printf("code is %d error is in the line of %d !!!!\n",i,linenum); } //read one character 读入一个字符,不直接用getchar因为不能回退 char getch() { if((lineIndex>=MAXLS-1)||linebuf[lineIndex]=='\n'||linebuf[lineIndex]=='\0') { linenum++; if((gets(linebuf))==NULL) { isFileEnd = TRUE; return EOF;//////////// } else { if(linebuf[0]=='\0') { linebuf[0]='\n'; linebuf[1]='\0'; } lineIndex=0; return linebuf[lineIndex++]; } } else { return linebuf[lineIndex++]; } } //go back to read previous character 回退读入的字符 void goback() { if(lineIndex>0) lineIndex--; } //read one token and identify the symbol 词法分析过程 void getsym() { int i=0,j=0; char c; c=getch(); if(isFileEnd==TRUE) return; while(c==' '||c=='\n'||c=='\t') { c=getch(); if(isFileEnd==TRUE) { printf("read the end of file\n"); return; } } if((c>='a'&&c<='z')||(c>='A'&&c<='Z')) { i = 0; while((c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c=='_')||(c>='0'&&c<='9')) { //out of range if(i>=MAXIDS-1) { error(21); break; } id[i++]=c; c=getch(); if(isFileEnd==TRUE) return; } id[i]='\0'; goback(); if(id[0]=='c'&&id[1]=='o'&&id[2]=='n'&&id[3]=='s'&&id[4]=='t'&&id[5]=='\0') { symbol = CONSTSYM; } else if(id[0]=='i'&&id[1]=='n'&&id[2]=='t'&&id[3]=='\0') { symbol = INTSYM; } else if(id[0]=='c'&&id[1]=='h'&&id[2]=='a'&&id[3]=='r'&&id[4]=='\0') { symbol = CHARSYM; } else if(id[0]=='v'&&id[1]=='o'&&id[2]=='i'&&id[3]=='d'&&id[4]=='\0') { symbol = VOIDSYM; } else if(id[0]=='m'&&id[1]=='a'&&id[2]=='i'&&id[3]=='n'&&id[4]=='\0') { symbol = MAINSYM; } else if(id[0]=='i'&&id[1]=='f'&&id[2]=='\0') { symbol = IFSYM; } else if(id[0]=='e'&&id[1]=='l'&&id[2]=='s'&&id[3]=='e'&&id[4]=='\0') { symbol = ELSESYM; } else if(id[0]=='d'&&id[1]=='o'&&id[2]=='\0') { symbol = DOSYM; } else if(id[0]=='w'&&id[1]=='h'&&id[2]=='i'&&id[3]=='l'&&id[4]=='e'&&id[5]=='\0') { symbol = WHILESYM; } else if(id[0]=='f'&&id[1]=='o'&&id[2]=='r'&&id[3]=='\0') { symbol = FORSYM; } else if(id[0]=='s'&&id[1]=='c'&&id[2]=='a'&&id[3]=='n'&&id[4]=='f'&&id[5]=='\0') { symbol = SCANFSYM; } else if(id[0]=='p'&&id[1]=='r'&&id[2]=='i'&&id[3]=='n'&&id[4]=='t'&&id[5]=='f'&&id[6]=='\0') { symbol = PRINTFSYM; } else if(id[0]=='r'&&id[1]=='e'&&id[2]=='t'&&id[3]=='u'&&id[4]=='r'&&id[5]=='n'&&id[6]=='\0') { symbol = RETURNSYM; } else { symbol = IDEN; } } else if(c>='0'&&c<='9') { num = 0; if(c=='0') { c = getch(); if(isFileEnd==TRUE) return; if(c>='0'&&c<='9') { error(22); } while(c>='0'&&c<='9') { num = num*10+(c-'0'); c = getch(); if(isFileEnd==TRUE) return; } } else { while(c>='0'&&c<='9') { num = num*10+(c-'0'); c = getch(); if(isFileEnd==TRUE) return; } } goback(); symbol = NUMBER; } else { switch(c) { case '+': symbol = PLUS; break; case '-': symbol = MINUS; break; case '*': symbol = TIMES; break; case '/': symbol = DIVI; break; case '<': c = getch(); if(isFileEnd==TRUE) return; if(c=='=') symbol = LEQ; else { symbol = LSS; goback(); } break; case '>': c = getch(); if(isFileEnd==TRUE) return; if(c=='=') symbol = GEQ; else { symbol = GRT; goback(); } break; case '!': c = getch(); if(isFileEnd==TRUE) return; if(c=='=') symbol = NEQ; else { symbol = ERRORSYM; goback(); } break; case '=': c = getch(); if(isFileEnd==TRUE) return; if(c=='=') symbol = EQL; else { symbol = ASSIGN; goback(); } break; case '(': symbol = LPAREN; break; case ')': symbol = RPAREN; break; case '{': symbol = LBRACE; break; case '}': symbol = RBRACE; break; case '[': symbol = LBKET; break; case ']': symbol = RBKET; break; case ',': symbol = COMMA; break; case ';': symbol = SEMICOLON; break; case '_': i = 0; while((c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c=='_')||(c>='0'&&c<='9')) { //out of range if(i>=MAXIDS-1) { error(21); break; } id[i++]=c; c=getch(); if(isFileEnd==TRUE) return; } id[i]='\0'; goback(); symbol = IDEN; break; case '\'': chconst = getch(); if(isFileEnd==TRUE) return; c = getch(); if(isFileEnd==TRUE) return; if(c=='\'') { if(chconst=='+'||chconst=='-'||chconst=='*'||chconst=='/'|| (chconst>='a'&&chconst<='z')||(chconst>='A'&&chconst<='Z')|| (chconst>='0'&&chconst<='9')) { symbol = CHARCST; } else { error(23); symbol = ERRORSYM; } } else { goback(); symbol = ERRORSYM; error(24); } break; case '\"': j = 0; c = getch(); if(isFileEnd==TRUE) return; while(c!='\"'&&j<MAXSTR-1) { str[j++] = c; c = getch(); if(isFileEnd==TRUE) return; } str[j]='\0'; if(c=='\"') { symbol = STRING; } else { symbol = ERRORSYM; goback(); error(24); } break; default: symbol = ERRORSYM; error(25); break; } } } int openfile() { freopen("C:\\Users\\forever\\Documents\\GitHub\\Compiler\\SourceCodes\\test.txt","r",stdin); isFileEnd = FALSE; return 1; /* file = (char*)malloc((sizeof(char))*MAXPATH); printf("please input the test file path\n"); gets(file); if(freopen(file,"r",stdin)==NULL) { printf("file to open the test file\n"); return 0; } else { isFileEnd = FALSE; printf("success to open the test file\n"); return 1; } */ } void printgetsym() { printf("类别码\t\t单词值\n"); getsym(); while(isFileEnd==FALSE) { switch(symbol) { case CONSTSYM: printf("CONSTSYM\tconst\n"); break; case INTSYM: printf("INTSYM\tint\n"); break; case CHARSYM: printf("CHARSYM\tchar\n"); break; case VOIDSYM: printf("VOIDSYM\tvoid\n"); break; case MAINSYM: printf("MAINSYM\tmain\n"); break; case IFSYM: printf("IFSYM\tif\n"); break; case ELSESYM: printf("ELSESYM\telse\n"); break; case DOSYM: printf("DOSYM\tdo\n"); break; case WHILESYM: printf("WHILESYM\twhile\n"); break; case FORSYM: printf("FORSYM\tfor\n"); break; case SCANFSYM: printf("SCANFSYM\tscanf\n"); break; case PRINTFSYM: printf("PRINTFSYM\tprintf\n"); break; case RETURNSYM: printf("RETURNSYM\treturn\n"); break; case PLUS: printf("PLUS\t+\n"); break; case MINUS: printf("MINUS\t-\n"); break; case TIMES: printf("TIMES\t*\n"); break; case DIVI: printf("DIVI\t/\n"); break; case LSS: printf("LSS\t<\n"); break; case LEQ: printf("LEQ\t<=\n"); break; case GRT: printf("GRT\t>\n"); break; case GEQ: printf("GEQ\t>=\n"); break; case NEQ: printf("NEQ\t!=\n"); break; case EQL: printf("EQL\t==\n"); break; case ASSIGN: printf("ASSIGN\t=\n"); break; case LPAREN: printf("LPAREN\t(\n"); break; case RPAREN: printf("RPAREN\t)\n"); break; case LBRACE: printf("LBRACE\t{\n"); break; case RBRACE: printf("RBRACE\t}\n"); break; case LBKET: printf("LBKET\t[\n"); break; case RBKET: printf("RBKET\t]\n"); break; case COMMA: printf("COMMA\t,\n"); break; case SEMICOLON: printf("SEMICOLON\t;\n"); break; case IDEN: printf("IDEN\t%s\n",id); break; case NUMBER: printf("NUMBER\t%d\n",num); break; case CHARCST: printf("CHARCST\t%c\n",chconst); break; case STRING: printf("STRING\t%s\n",str); break; case ERRORSYM: printf("ERRORSYM\terror\n"); break; } getsym(); } } void constopro() { if(symbol==CONSTSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=INTSYM&&symbol!=CHARSYM) { error(17); while(symbol!=INTSYM&&symbol!=CHARSYM&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(symbol==INTSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,1)>=0) error(49); strcpy(table[tableindex].name,id); getsym(); if(isFileEnd==TRUE) return; if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; } else { error(18); } inttoconst(); table[tableindex].obj = 1; table[tableindex].type = 1; table[tableindex].valuei = num; table[tableindex].scope = curscope; table[tableindex].length = 0; table[tableindex].distru = -1; table[tableindex].num = 0; malloctb(tableindex); tableindex++; if(symbol==COMMA) { while(symbol==COMMA) { getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(findtable(id,1)>=0) error(49); strcpy(table[tableindex].name,id); getsym(); if(isFileEnd==TRUE) return; if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; inttoconst(); } else { error(18); inttoconst(); } table[tableindex].obj = 1; table[tableindex].type = 1; table[tableindex].valuei = num; table[tableindex].scope = curscope; table[tableindex].length = 0; table[tableindex].distru = -1; table[tableindex].num = 0; malloctb(tableindex); tableindex++; } else { error(2); } } if(symbol!=SEMICOLON) { error(19); } } if(symbol==SEMICOLON) { getsym(); if(isFileEnd==TRUE) return; if(symbol==CONSTSYM) { constopro(); } } else { error(19); } } else if(symbol==CHARSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,1)>=0) error(49); strcpy(table[tableindex].name,id); getsym(); if(isFileEnd==TRUE) return; if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; } else { error(18); } if(symbol!=CHARCST) { error(20); while(symbol!=CHARCST&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } table[tableindex].obj = 1; table[tableindex].type = 2; table[tableindex].valuec = chconst; table[tableindex].scope = curscope; table[tableindex].length = 0; table[tableindex].distru = -1; table[tableindex].num = 0; malloctb(tableindex); tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==COMMA) { while(symbol==COMMA) { getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(findtable(id,1)>=0) error(49); strcpy(table[tableindex].name,id); getsym(); if(isFileEnd==TRUE) return; if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; } else { error(18); } if(symbol!=CHARCST) { error(20); while(symbol!=CHARCST&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } table[tableindex].obj = 1; table[tableindex].type = 2; table[tableindex].valuec = chconst; table[tableindex].scope = curscope; table[tableindex].length = 0; table[tableindex].distru = -1; table[tableindex].num = 0; malloctb(tableindex); tableindex++; getsym(); if(isFileEnd==TRUE) return; } else { error(2); } } if(symbol!=SEMICOLON) { error(19); } } if(symbol==SEMICOLON) { getsym(); if(isFileEnd==TRUE) return; if(symbol==CONSTSYM) { constopro(); } } else { error(19); } } // printf("This is const declaration.\n"); } } void constdec() { if(symbol==CONSTSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=INTSYM&&symbol!=CHARSYM) { error(17); while(symbol!=INTSYM&&symbol!=CHARSYM&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(symbol==INTSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,1)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].obj = 1; table[tableindex].type = 1; getsym(); if(isFileEnd==TRUE) return; if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; } else { error(18); } inttoconst(); table[tableindex].valuei = num; table[tableindex].scope = curscope; table[tableindex].length = 0; table[tableindex].distru = -1; table[tableindex].num = 0; malloctb(tableindex); tableindex++; if(symbol==COMMA) { while(symbol==COMMA) { getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(findtable(id,1)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].obj = 1; table[tableindex].type = 1; getsym(); if(isFileEnd==TRUE) return; if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; inttoconst(); } else { error(18); inttoconst(); } table[tableindex].valuei = num; table[tableindex].scope = curscope; table[tableindex].length = 0; table[tableindex].distru = -1; table[tableindex].num = 0; malloctb(tableindex); tableindex++; } else { error(2); } } if(symbol!=SEMICOLON) { error(19); } } if(symbol==SEMICOLON) { getsym(); if(isFileEnd==TRUE) return; if(symbol==CONSTSYM) { constdec(); } } else { error(19); } } else if(symbol==CHARSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,1)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].obj = 1; table[tableindex].type = 2; getsym(); if(isFileEnd==TRUE) return; if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; } else { error(18); } if(symbol!=CHARCST) { error(20); while(symbol!=CHARCST&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } table[tableindex].valuec = chconst; table[tableindex].scope = curscope; table[tableindex].length = 0; table[tableindex].distru = -1; table[tableindex].num = 0; malloctb(tableindex); tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==COMMA) { while(symbol==COMMA) { getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(findtable(id,1)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].obj = 1; table[tableindex].type = 2; getsym(); if(isFileEnd==TRUE) return; if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; } else { error(18); } if(symbol!=CHARCST) { error(20); while(symbol!=CHARCST&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } table[tableindex].valuec = chconst; table[tableindex].scope = curscope; table[tableindex].length = 0; table[tableindex].distru = -1; table[tableindex].num = 0; malloctb(tableindex); tableindex++; getsym(); if(isFileEnd==TRUE) return; } else { error(2); } } if(symbol!=SEMICOLON) { error(19); } } if(symbol==SEMICOLON) { getsym(); if(isFileEnd==TRUE) return; if(symbol==CONSTSYM) { constdec(); } } else { error(19); } } // printf("This is const declaration.\n"); } } void tovardec() { if(symbol==COMMA) { malloctb(tableindex); //genmedi(SW,medsindex-1,0,0); tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(findtable(id,2)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].obj = 2; if(tmpstack[stackindex]==INTSYM) table[tableindex].type = 1; else if(tmpstack[stackindex]==CHARSYM) table[tableindex].type = 2; //malloctb(tableindex); //genmedi(SW,medsindex-1,0,0); table[tableindex].offset = tmpoffset++; table[tableindex].scope = curscope; table[tableindex].length = 0; table[tableindex].distru = -1; table[tableindex].num = 0; // tableindex++; getsym(); if(isFileEnd==TRUE) return; tovardec(); } else { error(2); } } if(symbol==LBKET) { table[tableindex].obj = 7; tmpoffset--; getsym(); if(isFileEnd==TRUE) return; if(symbol==NUMBER) { if(num==0) { error(4); num = 10; } getsym(); if(isFileEnd==TRUE) return; } else { error(3); num = 10; } table[tableindex].length = num; if(symbol!=RBKET) { error(5); } else { getsym(); if(isFileEnd==TRUE) return; } //malloctb(tableindex); //genmedi(SW,medsindex-1,0,0); //tableindex++; tmpoffset += num; if(symbol==COMMA) { malloctb(tableindex); tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(findtable(id,2)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].obj = 2; if(tmpstack[stackindex]==INTSYM) table[tableindex].type = 1; else if(tmpstack[stackindex]==CHARSYM) table[tableindex].type = 2; table[tableindex].offset = tmpoffset++; table[tableindex].scope = curscope; table[tableindex].length = 0; table[tableindex].distru = -1; table[tableindex].num = 0; getsym(); if(isFileEnd==TRUE) return; tovardec(); } else { error(2); } } } if(symbol==SEMICOLON) { malloctb(tableindex); stackindex--; tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==INTSYM||symbol==CHARSYM) { vardec(); } } } void vardec() { if(symbol==INTSYM||symbol==CHARSYM) { tmpstack[++stackindex] = symbol; if(symbol==INTSYM) table[tableindex].type = 1; else if(symbol==CHARSYM) table[tableindex].type = 2; table[tableindex].obj = 2; table[tableindex].offset = tmpoffset++; table[tableindex].scope = curscope; table[tableindex].length = 0; table[tableindex].distru = -1; table[tableindex].num = 0; getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,2)>=0) error(49); strcpy(table[tableindex].name,id); getsym(); if(isFileEnd==TRUE) return; tovardec(); // printf("This is variation declaration.\n"); } } void mixsta() { if(symbol==CONSTSYM) { constdec(); } if(symbol==INTSYM||symbol==CHARSYM) { vardec(); } statements(); // printf("This is mixture statements.\n"); } void statements() { if(symbol==IFSYM||symbol==DOSYM||symbol==FORSYM||symbol==LBRACE||symbol==IDEN|| symbol==SCANFSYM||symbol==PRINTFSYM||symbol==SEMICOLON||symbol==RETURNSYM) { while((symbol==IFSYM||symbol==DOSYM||symbol==FORSYM||symbol==LBRACE||symbol==IDEN|| symbol==SCANFSYM||symbol==PRINTFSYM||symbol==SEMICOLON||symbol==RETURNSYM) &&isFileEnd==FALSE) { statemt(); } //printf("This is statements.\n"); } } void statemt() { int idenid; char tmpid[MAXIDS]; if(symbol==IFSYM) { ifsta(); } else if(symbol==DOSYM||symbol==FORSYM) { loopsta(); } else if(symbol==LBRACE) { getsym(); if(isFileEnd==TRUE) return; statements(); if(symbol!=RBRACE) { error(26); while(symbol!=RBRACE&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; /////////////// } else if(symbol==IDEN) { strcpy(tmpid,id); getsym(); if(isFileEnd==TRUE) return; if(symbol==LPAREN) { idenid = ftableindex(tmpid,3); if(idenid<0) { error(51); idenid = 0; } else { if(table[idenid].obj!=3) { error(56); } idenid = table[idenid].index; } callsta(idenid); if(symbol!=SEMICOLON) { error(48); } getsym(); if(isFileEnd==TRUE) return; } else if(symbol==LBKET||symbol==ASSIGN) { if(symbol==LBKET) idenid = ftableindex(tmpid,2); else idenid = ftableindex(tmpid,1); if(idenid<0) { error(51); idenid = 0; } else { if(table[idenid].obj==1) { error(52); } else if(table[idenid].obj==3) { error(53); } idenid = table[idenid].index; } assignsta(idenid); if(symbol!=SEMICOLON) { error(48); } getsym(); if(isFileEnd==TRUE) return; } } else if(symbol==SCANFSYM) { readsta(); if(symbol!=SEMICOLON) { error(48); } getsym(); if(isFileEnd==TRUE) return; } else if(symbol==PRINTFSYM) { writesta(); if(symbol!=SEMICOLON) { error(48); } getsym(); if(isFileEnd==TRUE) return; } else if(symbol==SEMICOLON) { getsym(); if(isFileEnd==TRUE) return; } else if(symbol==RETURNSYM) { returnsta(); if(symbol!=SEMICOLON) { error(48); } getsym(); if(isFileEnd==TRUE) return; } } int condition() { int tmp1,tmp2,tmp3,flag; tmp1 = expression(); if(symbol==LSS||symbol==LEQ||symbol==GRT||symbol==GEQ||symbol==NEQ||symbol==EQL) { switch(symbol) { case LSS: flag = 1;//< break; case LEQ: flag = 2;//<= break; case GRT: flag = 3;//> break; case GEQ: flag = 4;//>= break; case NEQ: flag = 5; //!= break; case EQL: flag = 6;//== break; } getsym(); if(isFileEnd==TRUE) return 0; tmp2 = expression(); mallocint(); tmp3 = medsindex-1; switch(flag) { //< case 1: genmedi(SMA,tmp1,tmp2,tmp3); break; //<= case 2: genmedi(SEQU,tmp1,tmp2,tmp3); break; //> case 3: genmedi(BIG,tmp1,tmp2,tmp3); break; //>= case 4: genmedi(BEQU,tmp1,tmp2,tmp3); break; //!= case 5: genmedi(NEQU,tmp1,tmp2,tmp3); break; //== case 6: genmedi(EQU,tmp1,tmp2,tmp3); break; } return tmp3; } return tmp1; } void ifsta() { int beqs1,iflabel,endlabel12; if(symbol==IFSYM) { genlabel(); malloclab(labelindex); iflabel = medsindex-1; getsym(); if(isFileEnd==TRUE) return; if(symbol!=LPAREN) { error(28); } else { getsym(); if(isFileEnd==TRUE) return; } beqs1 = condition();//beqs1 is id genmedi(BEQ,beqs1,0,iflabel); if(symbol!=RPAREN) { error(29); } else { getsym(); if(isFileEnd==TRUE) return; } statemt(); if(symbol==ELSESYM) { genlabel(); malloclab(labelindex); endlabel12 = medsindex-1; genmedi(GOTO,0,0,endlabel12); genmedi(LAB,iflabel,0,0); getsym(); if(isFileEnd==TRUE) return; statemt(); genmedi(LAB,endlabel12,0,0); // genmedi(LAB,endlabel12,0,0); } else { genmedi(LAB,iflabel,0,0); } // printf("This is if statement.\n"); } } void loopsta() { int dolabel,beqs,forlabel1,forlabel2; int tmp1,tmp2,idenid,tmpnum; int idenidtype;//idenidtablid,idenidtmpid, int tmp1tableid,tmp1tmpid,tmp1type; int tmp2type;//tmp2tableid,tmp2tmpid, int addorsub=0; if(symbol==DOSYM) { genlabel(); malloclab(labelindex); dolabel = medsindex - 1; genmedi(LAB,dolabel,0,0); genmedi(LOOPBEGIN,0,0,0); getsym(); if(isFileEnd==TRUE) return; statemt(); if(symbol!=WHILESYM) { error(30); while(symbol!=WHILESYM&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; if(symbol!=LPAREN) { error(31); } else { getsym(); if(isFileEnd==TRUE) return; } beqs = condition(); genmedi(BEQ,beqs,1,dolabel); genmedi(LOOPEND,0,0,0); if(symbol!=RPAREN) { error(32); } getsym(); if(isFileEnd==TRUE) return; //printf("This is do-while statement.\n"); } else if(symbol==FORSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=LPAREN) { error(33); } else { getsym(); if(isFileEnd==TRUE) return; } if(symbol!=IDEN) { error(34); while(symbol!=IDEN) { getsym(); if(isFileEnd==TRUE) return; } } idenid = ftableindex(id,1); if(idenid<0) { error(51); idenid = 0; idenidtype = table[idenid].type; } else { if(table[idenid].obj==1) { error(52); } else if(table[idenid].obj==3) { error(53); } idenidtype = table[idenid].type; idenid = table[idenid].index; } getsym(); if(isFileEnd==TRUE) return; if(symbol!=ASSIGN) { error(36); } else { getsym(); if(isFileEnd==TRUE) return; } tmp1 = expression(); if(medstack[tmp1].tbindex!=-1) { tmp1tableid = medstack[tmp1].tbindex; tmp1type = table[tmp1tableid].type; } else if(medstack[tmp1].tpindex!=-1) { tmp1tmpid = medstack[tmp1].tpindex; tmp1type = tempv[tmp1tmpid].type; } if(idenidtype!=tmp1type) { error(61); } genmedi(ASN,tmp1,0,idenid); genlabel(); malloclab(labelindex); forlabel1 = medsindex -1; genlabel(); malloclab(labelindex); forlabel2 = medsindex -1; genmedi(LAB,forlabel1,0,0); genmedi(LOOPBEGIN,0,0,0); if(symbol!=SEMICOLON) { error(37); } else { getsym(); if(isFileEnd==TRUE) return; beqs = condition(); genmedi(BEQ,beqs,0,forlabel2); if(symbol!=SEMICOLON) { error(38); } else { getsym(); if(isFileEnd==TRUE) return; } if(symbol!=IDEN) { error(39); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } idenid = ftableindex(id,1); if(idenid<0) { error(51); idenid = 0; idenidtype = table[idenid].type; } else { if(table[idenid].obj==1) { error(52); } else if(table[idenid].obj==3) { error(53); } idenidtype = table[idenid].type; idenid = table[idenid].index; } getsym(); if(isFileEnd==TRUE) return; if(symbol!=ASSIGN) { error(36); } else { getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(39); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } tmp2 = ftableindex(id,1); if(tmp2<0) { error(51); tmp2 = 0; tmp2type = table[tmp2].type; } else { if(table[idenid].obj==3) { error(53); } tmp2type = table[tmp2].type; tmp2 = table[tmp2].index; } if(tmp2type!=idenidtype) { error(61); } getsym(); if(isFileEnd==TRUE) return; if(!(symbol==PLUS||symbol==MINUS)) { error(40); while(symbol!=PLUS&&symbol!=MINUS&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(symbol==PLUS) addorsub = 1; else addorsub = 2; getsym(); if(isFileEnd==TRUE) return; if(symbol!=NUMBER) { error(41); while(symbol!=NUMBER&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(num==0) { error(42); num = 1; } tmpnum = num; getsym(); if(isFileEnd==TRUE) return; if(symbol!=RPAREN) { error(35); } else { getsym(); if(isFileEnd==TRUE) return; } statemt(); //add if(addorsub==1) { genmedi(ADDI,tmp2,tmpnum,idenid); } //sub else if(addorsub==2) { genmedi(SUBI,tmp2,tmpnum,idenid); } genmedi(GOTO,0,0,forlabel1); genmedi(LOOPEND,0,0,0); } } genmedi(LAB,forlabel2,0,0); // printf("This is for statement.\n"); } } void callsta(int idenid) { int tmp1,i =0,callftableid,tmp1tableid,tmp1tmpid,tmp1type; if(symbol==LPAREN) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=RPAREN) { tmp1 = expression(); callftableid = medstack[idenid].tbindex; if(medstack[tmp1].tbindex!=-1) { tmp1tableid = medstack[tmp1].tbindex; tmp1type = table[tmp1tableid].type;//1:int 2:char } else if(medstack[tmp1].tpindex!=-1) { tmp1tmpid = medstack[tmp1].tpindex; tmp1type = tempv[tmp1tmpid].type; } if(table[callftableid].myparasum==0) { error(59); } if(table[callftableid+1].obj==4&&table[callftableid+1].paraid==0&&tmp1type!=table[callftableid+1].type) { error(60); if(medstack[tmp1].tbindex!=-1) { table[tmp1tableid].type = table[callftableid+1].type;//1:int 2:char } else if(medstack[tmp1].tpindex!=-1) { tempv[tmp1tmpid].type = table[callftableid+1].type; } } genmedi(FORM,tmp1,i++,0); while(symbol==COMMA&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; tmp1 = expression(); if(medstack[tmp1].tbindex!=-1) { tmp1tableid = medstack[tmp1].tbindex; tmp1type = table[tmp1tableid].type;//1:int 2:char } else if(medstack[tmp1].tpindex!=-1) { tmp1tmpid = medstack[tmp1].tpindex; tmp1type = tempv[tmp1tmpid].type; } //强制转换 if(table[callftableid+1+i].obj==4&&table[callftableid+1+i].paraid==i&&tmp1type!=table[callftableid+1+i].type) { error(60); if(medstack[tmp1].tbindex!=-1) { table[tmp1tableid].type = table[callftableid+1+i].type;//1:int 2:char } else if(medstack[tmp1].tpindex!=-1) { tempv[tmp1tmpid].type = table[callftableid+1+i].type; } } genmedi(FORM,tmp1,i++,0); } if(table[callftableid].myparasum!=(i)) { error(59); } } if(symbol!=RPAREN) { error(43); while(symbol!=RPAREN) { getsym(); if(isFileEnd==TRUE) return; } } genmedi(CALL,idenid,0,0); getsym(); if(isFileEnd==TRUE) return; // printf("This is call statement.\n"); } } void assignsta(int idenid) { int tmp1,tmp2; int tmp1tabid,tmp1tmpid,tmp1type; int tmp2tabid,tmp2tmpid,tmp2type; if(symbol==LBKET) { getsym(); if(isFileEnd==TRUE) return; tmp1 = expression(); if(medstack[tmp1].tbindex!=-1) { tmp1tabid = medstack[tmp1].tbindex; tmp1type = table[tmp1tabid].type; } else if(medstack[tmp1].tpindex!=-1) { tmp1tmpid = medstack[tmp1].tpindex; tmp1type = tempv[tmp1tmpid].type; } if(tmp1type!=1) { error(62); } if(medstack[idenid].tbindex!=-1) { tmp1tabid = medstack[idenid].tbindex; tmp1type = table[tmp1tabid].type; } else if(medstack[idenid].tpindex!=-1) { tmp1tmpid = medstack[idenid].tpindex; tmp1type = tempv[tmp1tmpid].type; } if(symbol!=RBKET) { error(5); } else { getsym(); if(isFileEnd==TRUE) return; } if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; tmp2 = expression(); if(medstack[tmp2].tbindex!=-1) { tmp2tabid = medstack[tmp2].tbindex; tmp2type = table[tmp2tabid].type; } else if(medstack[tmp2].tpindex!=-1) { tmp2tmpid = medstack[tmp2].tpindex; tmp2type = tempv[tmp2tmpid].type; } if(tmp1type!=tmp2type) { error(61); } genmedi(SW,idenid,tmp1,tmp2); } } else if(symbol==ASSIGN) { getsym(); if(isFileEnd==TRUE) return; if(medstack[idenid].tbindex!=-1) { tmp1tabid = medstack[idenid].tbindex; tmp1type = table[tmp1tabid].type; } else if(medstack[idenid].tpindex!=-1) { tmp1tmpid = medstack[idenid].tpindex; tmp1type = tempv[tmp1tmpid].type; } tmp2 = expression(); if(medstack[tmp2].tbindex!=-1) { tmp2tabid = medstack[tmp2].tbindex; tmp2type = table[tmp2tabid].type; } else if(medstack[tmp2].tpindex!=-1) { tmp2tmpid = medstack[tmp2].tpindex; tmp2type = tempv[tmp2tmpid].type; } if(tmp1type!=tmp2type) { error(61); } genmedi(ASN,tmp2,0,idenid); } // printf("This is assign statement.\n"); } void readsta() { int tmp1; if(symbol==SCANFSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=LPAREN) { error(44); while(symbol!=LPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(46); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } tmp1 = ftableindex(id,1); if(tmp1<0) { error(51); tmp1 = 0; } else { if(table[tmp1].obj==1) { error(52); } else if(table[tmp1].obj==3) { error(53); } tmp1 = table[tmp1].index; } genmedi(RD,tmp1,0,0); getsym(); if(isFileEnd==TRUE) return; if(symbol==COMMA) { while(symbol==COMMA&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(46); break; } tmp1 = ftableindex(id,1); if(tmp1<0) { error(51); tmp1 = 0; } else { if(table[tmp1].obj==1) { error(52); } else if(table[tmp1].obj==3) { error(53); } else if(table[tmp1].obj==4) { error(54); } tmp1 = table[tmp1].index; } genmedi(RD,tmp1,0,0); getsym(); if(isFileEnd==TRUE) return; } } if(symbol!=RPAREN) { error(45); while(symbol!=RPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; //printf("This is read statement.\n"); } } void writesta() { int tmp1; if(symbol==PRINTFSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=LPAREN) { error(44); while(symbol!=LPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; if(symbol==STRING) { strcpy(strings[strindex],str); table[tableindex].obj = 5; table[tableindex].scope = curscope; table[tableindex].locate = strindex; malloctb(tableindex); genmedi(WRT,medsindex-1,0,0); tableindex++; strindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==COMMA) { getsym(); if(isFileEnd==TRUE) return; tmp1 = expression(); genmedi(WRT,tmp1,0,0); } } else { tmp1 = expression(); genmedi(WRT,tmp1,0,0); } if(symbol!=RPAREN) { error(45); while(symbol!=RPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; // printf("This is write statement.\n"); } } void returnsta() { int tmp1,tmpfuntableid; int tmp1tabid,tmp1tmpid,tmp1type; if(symbol==RETURNSYM) { returnstack.id = curcompifunid; returnstack.scope = curscope; getsym(); if(isFileEnd==TRUE) return; if(symbol==LPAREN) { getsym(); if(isFileEnd==TRUE) return; //returnstack.id = expression(); //returnstack.scope = curscope; tmp1 = expression(); if(symbol!=RPAREN) { error(47); while(symbol!=RPAREN) { getsym(); if(isFileEnd==TRUE) return; } } if(medstack[tmp1].tbindex!=-1) { tmp1tabid = medstack[tmp1].tbindex; tmp1type = table[tmp1tabid].type; } else if(medstack[tmp1].tpindex!=-1) { tmp1tmpid = medstack[tmp1].tpindex; tmp1type = tempv[tmp1tmpid].type; } //void but have return values tmpfuntableid = medstack[curcompifunid].tbindex; if(table[tmpfuntableid].type==3) { error(58); } if(table[tmpfuntableid].type!=tmp1type) { error(63); //强制转换 if(medstack[tmp1].tbindex!=-1) { table[tmp1tabid].type = table[tmpfuntableid].type; } else if(medstack[tmp1].tpindex!=-1) { tempv[tmp1tmpid].type = table[tmpfuntableid].type; } } genmedi(RETURN,tmp1,0,0); genmedi(END,curcompifunid,0,0); getsym(); if(isFileEnd==TRUE) return; } else { //have return value but return; tmpfuntableid = medstack[curcompifunid].tbindex; if(table[tmpfuntableid].type!=3) { error(50); genmedi(RETURN,0,0,0); } genmedi(END,curcompifunid,0,0); } genmedi(JR,0,0,0); // printf("This is return statement.\n"); } } int expression() { int tmp1,tmp2,tmp3,flag; int tmp1tabid,tmp1tmpid,tmp1type; int tmp2tabid,tmp2tmpid,tmp2type; if(symbol==PLUS||symbol==MINUS) { if(symbol==PLUS) flag = 1; else flag = 2; getsym(); if(isFileEnd==TRUE) return 0; } tmp1 = term(); if(flag==2) { mallocint(); tmp2 = medsindex-1; genmedi(NOT,tmp1,0,tmp2); } else { tmp2 = tmp1; } if(symbol==PLUS||symbol==MINUS) { while((symbol==PLUS||symbol==MINUS)&&isFileEnd==FALSE) { if(symbol==PLUS) flag = 1; else flag = 2; getsym(); if(isFileEnd==TRUE) return 0; tmp1 = term(); if(medstack[tmp1].tbindex!=-1) { tmp1tabid = medstack[tmp1].tbindex; tmp1type = table[tmp1tabid].type; } else if(medstack[tmp1].tpindex!=-1) { tmp1tmpid = medstack[tmp1].tpindex; tmp1type = tempv[tmp1tmpid].type; } if(medstack[tmp2].tbindex!=-1) { tmp2tabid = medstack[tmp2].tbindex; tmp2type = table[tmp2tabid].type; } else if(medstack[tmp2].tpindex!=-1) { tmp2tmpid = medstack[tmp2].tpindex; tmp2type = tempv[tmp2tmpid].type; } if(tmp1type==tmp2type&&tmp1type==2)//都是char { mallocchar(); tmp3 = medsindex-1; } else { mallocint(); tmp3 = medsindex-1; } if(flag==2) { genmedi(SUB,tmp2,tmp1,tmp3); } else { genmedi(ADD,tmp2,tmp1,tmp3); } tmp2 = tmp3; } } return tmp2; } int term() { int tmp1,tmp2,tmp3,flag; int tmp1tabid,tmp1tmpid,tmp1type; int tmp2tabid,tmp2tmpid,tmp2type; tmp1 = factor(); if(symbol==TIMES||symbol==DIVI) { while((symbol==TIMES||symbol==DIVI)&&isFileEnd==FALSE) { if(symbol==TIMES) flag = 1; else flag = 2; getsym(); if(isFileEnd==TRUE) return 0; tmp2 = factor(); if(medstack[tmp1].tbindex!=-1) { tmp1tabid = medstack[tmp1].tbindex; tmp1type = table[tmp1tabid].type; } else if(medstack[tmp1].tpindex!=-1) { tmp1tmpid = medstack[tmp1].tpindex; tmp1type = tempv[tmp1tmpid].type; } if(medstack[tmp2].tbindex!=-1) { tmp2tabid = medstack[tmp2].tbindex; tmp2type = table[tmp2tabid].type; } else if(medstack[tmp2].tpindex!=-1) { tmp2tmpid = medstack[tmp2].tpindex; tmp2type = tempv[tmp2tmpid].type; } if(tmp1type==tmp2type&&tmp1type==2)//都是char { mallocchar(); tmp3 = medsindex-1; } else { mallocint(); tmp3 = medsindex-1; } if(flag==1) { genmedi(MUL,tmp1,tmp2,tmp3); } else { genmedi(DIV,tmp1,tmp2,tmp3); } tmp1 = tmp3; } } return tmp1; } int factor() { int tmp1,tmp2,tmp3; int tmp1type; int tmp2tabid,tmp2tmpid,tmp2type; if(symbol==IDEN) { getsym(); if(isFileEnd==TRUE) return 0; if(symbol==LPAREN) { tmp1 = ftableindex(id,3); if(tmp1<0) { error(51); tmp1 = 0; tmp1type = table[tmp1].type; } else { if(table[tmp1].obj!=3) { error(56); } else if(table[tmp1].obj==3&&table[tmp1].type==3) { error(57); } tmp1type = table[tmp1].type; tmp1 = table[tmp1].index; } callsta(tmp1); if(tmp1type==1) mallocint(); else if(tmp1type==2) mallocchar(); genmedi(ASN,1,0,medsindex-1); return (medsindex-1); } else if(symbol==LBKET) { tmp1 = ftableindex(id,2); if(tmp1<0) { error(51); tmp1 = 0; tmp1type = table[tmp1].type; } else { if(table[tmp1].obj!=7) { error(55); } tmp1type = table[tmp1].type; tmp1 = table[tmp1].index; } getsym(); if(isFileEnd==TRUE) return 0; tmp2 = expression(); if(medstack[tmp2].tbindex!=-1) { tmp2tabid = medstack[tmp2].tbindex; tmp2type = table[tmp2tabid].type; } else if(medstack[tmp2].tpindex!=-1) { tmp2tmpid = medstack[tmp2].tpindex; tmp2type = tempv[tmp2tmpid].type; } if(tmp2type==2) error(62); if(tmp1type==1) { mallocint(); } else if(tmp1type==2) { mallocchar(); } tmp3 = medsindex-1; genmedi(LW,tmp1,tmp2,tmp3); if(symbol!=RBKET) { error(5); } else { getsym(); if(isFileEnd==TRUE) return 0; } return tmp3; } else { tmp1 = ftableindex(id,1); if(tmp1<0) { error(51); tmp1=0; } else { if(table[tmp1].obj==3) { error(53); } tmp1 = table[tmp1].index; } return tmp1; } } else if(symbol==PLUS||symbol==MINUS||symbol==NUMBER) { tmp1 = isint(); return tmp1; } else if(symbol==CHARCST) { table[tableindex].name[0] = '\0'; table[tableindex].obj = 1; table[tableindex].type = 2; table[tableindex].valuec = chconst; table[tableindex].scope = curscope; malloctb(tableindex); tmp1 = medsindex-1; tableindex++; getsym(); if(isFileEnd==TRUE) return 0; return tmp1; } else if(symbol==LPAREN) { getsym(); if(isFileEnd==TRUE) return 0; tmp1=expression(); if(symbol!=RPAREN) { error(27); while(symbol!=RPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return 0; } } getsym(); if(isFileEnd==TRUE) return 0; return tmp1; } else return 0; } int isint() { int tmp1; if(symbol!=PLUS&&symbol!=MINUS&&symbol!=NUMBER) { error(15); while(symbol!=PLUS&&symbol!=MINUS&&symbol!=NUMBER&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return 0; } } if(symbol==PLUS) { getsym(); if(isFileEnd==TRUE) return 0; if(symbol!=NUMBER) { error(16); while(symbol!=NUMBER&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return 0; } } table[tableindex].name[0] = '\0'; table[tableindex].obj = 1; table[tableindex].type = 1; table[tableindex].valuei = num; table[tableindex].scope = curscope; malloctb(tableindex); tmp1 = medsindex-1; tableindex++; //tmpoffset++; getsym(); if(isFileEnd==TRUE) return 0; return tmp1; } else if(symbol==MINUS) { getsym(); if(isFileEnd==TRUE) return 0; if(symbol!=NUMBER) { error(16); while(symbol!=NUMBER&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return 0; } } num = 0-num; table[tableindex].name[0] = '\0'; table[tableindex].obj = 1; table[tableindex].type = 1; table[tableindex].valuei = num; table[tableindex].scope = curscope; malloctb(tableindex); tmp1 = medsindex-1; tableindex++; getsym(); if(isFileEnd==TRUE) return 0; return tmp1; } else if(symbol==NUMBER) { table[tableindex].name[0] = '\0'; table[tableindex].obj = 1; table[tableindex].type = 1; table[tableindex].valuei = num; table[tableindex].scope = curscope; malloctb(tableindex); tmp1 = medsindex-1; tableindex++; getsym(); if(isFileEnd==TRUE) return 0; return tmp1; } else return 0; } void inttoconst() { if(symbol!=PLUS&&symbol!=MINUS&&symbol!=NUMBER) { error(15); while(symbol!=PLUS&&symbol!=MINUS&&symbol!=NUMBER&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(symbol==PLUS) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=NUMBER) { error(16); while(symbol!=NUMBER&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; } else if(symbol==MINUS) { getsym(); if(isFileEnd==TRUE) return; if(symbol!=NUMBER) { error(16); while(symbol!=NUMBER&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } num = 0-num; getsym(); if(isFileEnd==TRUE) return; } else if(symbol==NUMBER) { getsym(); if(isFileEnd==TRUE) return; } } void vartopro() { if(symbol==COMMA) { malloctb(tableindex); genmedi(GLOBEG,medsindex-1,0,0); tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(findtable(id,2)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].obj = 2; if(tmpstack[stackindex]==INTSYM) table[tableindex].type = 1; else if(tmpstack[stackindex]==CHARSYM) table[tableindex].type = 2; table[tableindex].offset = offset++; table[tableindex].scope = curscope; table[tableindex].length = 0; table[tableindex].distru = -1; table[tableindex].num = 0; getsym(); if(isFileEnd==TRUE) return; vartopro(); } else { error(2); } } if(symbol==LBKET) { table[tableindex].obj = 7; offset--; getsym(); if(isFileEnd==TRUE) return; if(symbol==NUMBER) { if(num==0) { error(4); num = 10; } getsym(); if(isFileEnd==TRUE) return; } else { error(3); num = 10; } table[tableindex].length = num; offset += num; if(symbol!=RBKET) { error(5); } else { getsym(); if(isFileEnd==TRUE) return; } if(symbol==COMMA) { malloctb(tableindex); genmedi(GLOBEG,medsindex-1,0,0); tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { if(findtable(id,2)>=0) error(49); strcpy(table[tableindex].name,id); //flag table[tableindex].obj = 2; if(tmpstack[stackindex]==INTSYM) table[tableindex].type = 1; else if(tmpstack[stackindex]==CHARSYM) table[tableindex].type = 2; table[tableindex].offset = offset++; table[tableindex].scope = curscope; table[tableindex].length = 0; table[tableindex].distru = -1; table[tableindex].num = 0; getsym(); if(isFileEnd==TRUE) return; vartopro(); } else { error(2); } } } if(symbol==SEMICOLON) { malloctb(tableindex); genmedi(GLOBEG,medsindex-1,0,0); //table[tableindex].offset = offset++; tableindex++; stackindex--; // printf("This is varaible declaration for program.\n"); getsym(); if(isFileEnd==TRUE) return; if(symbol==INTSYM||symbol==CHARSYM) { tmpstack[++stackindex] = symbol; if(symbol==INTSYM) table[tableindex].type = 1; else if(symbol==CHARSYM) table[tableindex].type = 2; table[tableindex].obj = 2; table[tableindex].offset = offset++; table[tableindex].scope = curscope; table[tableindex].length = 0; table[tableindex].distru = -1; table[tableindex].num = 0; getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } strcpy(table[tableindex].name,id); //flag getsym(); if(isFileEnd==TRUE) return; if(symbol==COMMA||symbol==SEMICOLON||symbol==LBKET) { if(findtable(table[tableindex].name,2)>=0) error(49); vartopro(); } if(symbol==LPAREN) { tmpoffset = 0; curscope++; if(findtable(table[tableindex].name,3)>=0) error(49); fictopro(); } } } } void parameter() { //int paraid; if(symbol==INTSYM||symbol==CHARSYM) { table[tableindex].obj = 4; if(symbol==INTSYM) { table[tableindex].type = 1; } else if(symbol==CHARSYM) { table[tableindex].type = 2; } getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,4)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].scope = curscope; table[tableindex].offset = tmpoffset++; malloctb(tableindex); //paraid = medsindex-1; table[tableindex].paraid = calmyparasum++; //genmedi(PARA,paraid,0,0); tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==COMMA) { getsym(); if(isFileEnd==TRUE) return; parameter(); } } else { error(8); } } void fictopro() { int tableid,funid; int tmpbegin,tmpend; if(symbol!=LPAREN) { error(7); while(symbol!=LPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } malloctb(tableindex); funid = medsindex-1; curcompifunid = funid; genmedi(LAB,funid,0,0); genmedi(BEGIN,funid,0,0); tmpoffset = 0; table[tableindex].obj = 3; if(tmpstack[stackindex]==INTSYM) table[tableindex].type = 1; else if(tmpstack[stackindex]==CHARSYM) table[tableindex].type = 2; table[tableindex].scope = curscope; tableid = tableindex; table[tableindex].beginid = medsindex-1; calmyparasum=0; tmpbegin = tempvindex; //table[tableindex].tmpbasic = tmpbegin; tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol==INTSYM||symbol==CHARSYM) { parameter(); } if(symbol!=RPAREN) { error(9); while(symbol!=RPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } table[tableid].myparasum = calmyparasum; calmyparasum = 0; getsym(); if(isFileEnd==TRUE) return; if(symbol!=LBRACE) { error(10); while(symbol!=LBRACE&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; mixsta(); if(symbol!=RBRACE) { error(11); while(symbol!=RBRACE&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } //have return values if(table[tableid].type!=3) { //no return statement if(returnstack.scope!=curscope||returnstack.id!=funid) { error(50); genmedi(RETURN,0,0,0); genmedi(END,funid,0,0); genmedi(JR,0,0,0); } } else { //void no return statement if(returnstack.scope!=curscope||returnstack.id!=funid) { genmedi(END,funid,0,0); genmedi(JR,0,0,0); } } table[tableid].offset = tmpoffset; tmpend = tempvindex; table[tableid].length = tmpoffset+tmpend-tmpbegin; table[tableid].endid = medsindex-1; // printf("This is valued function's declaration for program.\n"); getsym(); if(isFileEnd==TRUE) return; if(symbol!=INTSYM&&symbol!=CHARSYM&&symbol!=VOIDSYM) { error(12); while(symbol!=INTSYM&&symbol!=CHARSYM&&symbol!=VOIDSYM&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(symbol==INTSYM||symbol==CHARSYM) { tmpstack[++stackindex] = symbol; getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,3)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].offset = offset++; table[tableindex].obj = 3; getsym(); if(isFileEnd==TRUE) return; curscope++; fictopro(); } else if(symbol==VOIDSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { curscope++; fvotopro(); } } } void fvotopro() { int tableid,funid; int tmpbegin,tmpend; if(symbol!=IDEN) { error(13); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,3)>=0) error(49); strcpy(table[tableindex].name,id); malloctb(tableindex); funid = medsindex-1; curcompifunid = funid; genmedi(LAB,funid,0,0); genmedi(BEGIN,funid,0,0); tmpoffset=0; table[tableindex].obj = 3; table[tableindex].type = 3; table[tableindex].scope = curscope; table[tableindex].beginid = medsindex-1; tableid = tableindex; tmpbegin = tempvindex; // table[tableindex].tmpbasic = tmpbegin; calmyparasum=0; tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol!=LPAREN) { error(7); while(symbol!=LPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; if(symbol==INTSYM||symbol==CHARSYM) { parameter(); } if(symbol!=RPAREN) { error(9); while(symbol!=RPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } table[tableid].myparasum = calmyparasum; calmyparasum = 0; getsym(); if(isFileEnd==TRUE) return; if(symbol!=LBRACE) { error(10); while(symbol!=LBRACE&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; mixsta(); if(symbol!=RBRACE) { error(11); while(symbol!=RBRACE&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } //have return values if(table[tableid].type!=3) { //no return statement if(returnstack.scope!=curscope||returnstack.id!=funid) { error(50); genmedi(RETURN,0,0,0); genmedi(END,funid,0,0); genmedi(JR,0,0,0); } } else { //void no return statement if(returnstack.scope!=curscope||returnstack.id!=funid) { genmedi(END,funid,0,0); genmedi(JR,0,0,0); } } table[tableid].offset = tmpoffset; tmpend = tempvindex; table[tableid].length = tmpoffset+tmpend-tmpbegin; table[tableid].endid = medsindex-1; //printf("This is void function's declaration for program.\n"); getsym(); if(isFileEnd==TRUE) return; if(symbol!=INTSYM&&symbol!=CHARSYM&&symbol!=VOIDSYM) { error(12); while(symbol!=INTSYM&&symbol!=CHARSYM&&symbol!=VOIDSYM&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(symbol==INTSYM||symbol==CHARSYM) { tmpstack[++stackindex] = symbol; getsym(); if(isFileEnd==TRUE) return; if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(id,3)>=0) error(49); strcpy(table[tableindex].name,id); table[tableindex].offset = offset++; table[tableindex].obj = 3; getsym(); if(isFileEnd==TRUE) return; curscope++; fictopro(); } else if(symbol==VOIDSYM) { getsym(); if(isFileEnd==TRUE) return; if(symbol==IDEN) { curscope++; fvotopro(); } } } void ismain() { int tableid,funid,tmpbegin,tmpend; char name[10] = {"main"}; name[5] = '\0'; curscope++; if(symbol!=MAINSYM) { error(14); while(symbol!=MAINSYM&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } if(findtable(name,3)>=0) error(49); strcpy(table[tableindex].name,name); malloctb(tableindex); funid = medsindex-1; curcompifunid = funid; genmedi(LAB,funid,0,0); genmedi(BEGIN,funid,0,0); tmpoffset=0; table[tableindex].obj = 3; table[tableindex].type = 3; table[tableindex].scope = curscope; table[tableindex].beginid = medsindex-1; tableid = tableindex; tmpbegin = tempvindex; //table[tableindex].tmpbasic = tmpbegin; tableindex++; getsym(); if(isFileEnd==TRUE) return; if(symbol!=LPAREN) { error(7); while(symbol!=LPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; if(symbol!=RPAREN) { error(9); while(symbol!=RPAREN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; if(symbol!=LBRACE) { error(10); while(symbol!=LBRACE&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } getsym(); if(isFileEnd==TRUE) return; mixsta(); if(symbol!=RBRACE) { error(11); while(symbol!=RBRACE&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) return; } } //void no return statement if(returnstack.scope!=curscope||returnstack.id!=funid) { genmedi(END,funid,0,0); genmedi(JR,0,0,0); } table[tableid].offset = tmpoffset; tmpend = tempvindex; table[tableid].length = tmpoffset+tmpend-tmpbegin; table[tableid].endid = medsindex-1; //table[tableid].length = medsindex - funid; // printf("This is main function.\n"); return; } //注意声明的顺序 void program() { getsym(); if(isFileEnd==TRUE) { error(14); return; } /* labels[labelindex].name[0] = '$'; labels[labelindex].name[1]='e'; labels[labelindex].name[2]='n'; labels[labelindex].name[3]='d'; labels[labelindex].name[4]='\0'; */ table[tableindex].name[0] = '\0'; table[tableindex].obj = 1; table[tableindex].type = 1; table[tableindex].valuei = 0; table[tableindex].scope = curscope; malloctb(tableindex); tableindex++; /* tempv[tempvindex].type = 1; tempv[tempvindex].valuei = 0; medstack[medsindex].id = medsindex; medstack[medsindex].tbindex = -1; medstack[medsindex].tpindex = tempvindex; tempvindex=1; medsindex=1; */ table[tableindex].name[0] = '\0'; table[tableindex].obj = 6; table[tableindex].scope = curscope; malloctb(tableindex); tableindex++; medsindex = 2; malloclab(labelindex); labelindex=1; medsindex = 3; if(symbol==CONSTSYM) { constopro(); } if(symbol==INTSYM||symbol==CHARSYM) { tmpstack[stackindex] = symbol; if(symbol==INTSYM) table[tableindex].type = 1; else if(symbol==CHARSYM) table[tableindex].type = 2; table[tableindex].obj = 2; table[tableindex].offset = offset++; table[tableindex].scope = curscope; table[tableindex].length = 0; table[tableindex].distru = -1; table[tableindex].num = 0; getsym(); if(isFileEnd==TRUE) { error(14); return; } if(symbol!=IDEN) { error(1); while(symbol!=IDEN&&isFileEnd==FALSE) { getsym(); if(isFileEnd==TRUE) { error(14); return; } } } strcpy(table[tableindex].name,id); getsym(); if(isFileEnd==TRUE) { error(14); return; } if(symbol==COMMA||symbol==SEMICOLON||symbol==LBKET) { if(findtable(table[tableindex].name,2)>=0) error(49); vartopro(); } if(symbol==LPAREN) { tmpoffset = 0; curscope++; if(findtable(table[tableindex].name,3)>=0) error(49); fictopro(); } } if(symbol==VOIDSYM) { getsym(); if(isFileEnd==TRUE) { error(14); return; } if(symbol==IDEN) { tmpoffset = 0; curscope++; fvotopro(); } } if(symbol==MAINSYM) { tmpoffset = 0; curscope++; ismain(); } } void genblocks() { int i;//j,k; int funid,funtabid,curfunscope; for(i=0;i<medialindex;i++) { if(medial[i].op==BEGIN) { funid = medial[i].rs; funtabid = medstack[funid].tbindex; curfunscope = table[funtabid].scope; blocks[blocksindex].beginid = i; blocks[blocksindex].scope = curfunscope; while(i<medialindex&&medial[i].op!=END) { if(medial[i].op==LAB) { blocks[blocksindex].endid = i-1; blocksindex++; blocks[blocksindex].beginid = i; blocks[blocksindex].scope = curfunscope; } else if(medial[i].op==BEQ||medial[i].op==GOTO ||medial[i].op==CALL) { blocks[blocksindex].endid = i; blocksindex++; blocks[blocksindex].beginid = i+1; blocks[blocksindex].scope = curfunscope; } i++; } blocks[blocksindex].endid = i; } } } int finddagtable(int index) { int i,j; for(i=0;i<dagtabindex;i++) { if(dagtable[i].medsid==index) break; } //未找到,则新建一个节点 if(i==dagtabindex) { //建立节点 dagnodes[dagnodindex].id = dagnodindex; dagnodes[dagnodindex].op = -1; dagnodes[dagnodindex].left = -1; dagnodes[dagnodindex].right = -1; //填节点表 dagtable[dagtabindex].medsid = index; dagtable[dagtabindex].nodeid = dagnodindex; j = dagnodindex; dagnodindex++; dagtabindex++; return j; } return dagtable[i].nodeid; } //add,mul,equ,nequ void finddagnode1(int op,int left,int right,int result,int medindex) { int i,j; for(i=0;i<dagnodindex;i++) { if(dagnodes[i].op==op&&((dagnodes[i].left==left&&dagnodes[i].right==right) ||(dagnodes[i].left==right&&dagnodes[i].right==left))) { for(j=0;j<dagtabindex;j++) { if(dagtable[j].medsid==result) { dagtable[j].nodeid = dagnodes[i].id; medial[medindex].dagnodeid = dagnodes[i].id; break; } } if(j==dagtabindex) { dagtable[dagtabindex].medsid = result; dagtable[dagtabindex].nodeid = dagnodes[i].id; medial[medindex].dagnodeid = dagnodes[i].id; dagtabindex++; } break; } } if(i==dagnodindex) { dagnodes[dagnodindex].id = dagnodindex; dagnodes[dagnodindex].left = left; dagnodes[dagnodindex].right = right; dagnodes[dagnodindex].op = op; for(j = 0;j<dagtabindex;j++) { if(dagtable[j].medsid==result) { dagtable[j].nodeid = dagnodindex; medial[medindex].dagnodeid = dagnodindex; break; } } if(j==dagtabindex) { dagtable[dagtabindex].medsid = result; dagtable[dagtabindex].nodeid = dagnodindex; medial[medindex].dagnodeid = dagnodindex; dagtabindex++; } dagnodindex++; } } //sub,div,big,sma,bequ,sequ void finddagnode2(int op,int left,int right,int result,int medindex) { int i,j; for(i=0;i<dagnodindex;i++) { if(dagnodes[i].op==op&&dagnodes[i].left==left&&dagnodes[i].right==right) { for(j=0;j<dagtabindex;j++) { if(dagtable[j].medsid==result) { dagtable[j].nodeid = dagnodes[i].id; medial[medindex].dagnodeid = dagnodes[i].id; break; } } if(j==dagtabindex) { dagtable[dagtabindex].medsid = result; dagtable[dagtabindex].nodeid = dagnodes[i].id; medial[medindex].dagnodeid = dagnodes[i].id; dagtabindex++; } break; } } if(i==dagnodindex) { dagnodes[dagnodindex].id = dagnodindex; dagnodes[dagnodindex].left = left; dagnodes[dagnodindex].right = right; dagnodes[dagnodindex].op = op; for(j = 0;j<dagtabindex;j++) { if(dagtable[j].medsid==result) { dagtable[j].nodeid = dagnodindex; medial[medindex].dagnodeid = dagnodindex; break; } } if(j==dagtabindex) { dagtable[dagtabindex].medsid = result; dagtable[dagtabindex].nodeid = dagnodindex; medial[medindex].dagnodeid = dagnodindex; dagtabindex++; } dagnodindex++; } } //not,assign void finddagnode3(int op,int left,int result,int medindex) { int i,j; for(i=0;i<dagnodindex;i++) { if(dagnodes[i].op==op&&dagnodes[i].left==left) { for(j=0;j<dagtabindex;j++) { if(dagtable[j].medsid==result) { dagtable[j].nodeid = dagnodes[i].id; medial[medindex].dagnodeid = dagnodes[i].id; break; } } if(j==dagtabindex) { dagtable[dagtabindex].medsid = result; dagtable[dagtabindex].nodeid = dagnodes[i].id; medial[medindex].dagnodeid = dagnodes[i].id; dagtabindex++; } break; } } if(i==dagnodindex) { dagnodes[dagnodindex].id = dagnodindex; dagnodes[dagnodindex].left = left; dagnodes[dagnodindex].right = -1; dagnodes[dagnodindex].op = op; for(j = 0;j<dagtabindex;j++) { if(dagtable[j].medsid==result) { dagtable[j].nodeid = dagnodindex; medial[medindex].dagnodeid = dagnodindex; break; } } if(j==dagtabindex) { dagtable[dagtabindex].medsid = result; dagtable[dagtabindex].nodeid = dagnodindex; medial[medindex].dagnodeid = dagnodindex; dagtabindex++; } dagnodindex++; } } void dag() { int i,j,k,t,blobegin,bloend; int leftnodid; int rightnodid; int rs,rt,rd; int fir,sec,temp; int firtmp,sectmp; for(i=0;i<=blocksindex;i++) { //initial dagnodindex = 0; dagtabindex = 0; blobegin = blocks[i].beginid; bloend = blocks[i].endid; //构建dag图 for(j=blobegin;j<bloend;j++) { if(medial[j].op==ADD||medial[j].op==MUL ||medial[j].op==EQU||medial[j].op==NEQU) { rs = medial[j].rs; rt = medial[j].rt; rd = medial[j].rd; leftnodid = finddagtable(rs); rightnodid = finddagtable(rt); finddagnode1(medial[j].op,leftnodid,rightnodid,rd,j); } else if(medial[j].op==SUB||medial[j].op==DIV ||medial[j].op==BIG||medial[j].op==SMA ||medial[j].op==BEQU||medial[j].op==SEQU) { rs = medial[j].rs; rt = medial[j].rt; rd = medial[j].rd; leftnodid = finddagtable(rs); rightnodid = finddagtable(rt); finddagnode2(medial[j].op,leftnodid,rightnodid,rd,j); } else if(medial[j].op==NOT) { rs = medial[j].rs; rd = medial[j].rd; leftnodid = finddagtable(rs); finddagnode3(medial[j].op,leftnodid,rd,j); } else if(medial[j].op==ASN) { rs = medial[j].rs; rd = medial[j].rd; leftnodid = finddagtable(rs); finddagnode3(medial[j].op,leftnodid,rd,j); } } //消除公共子表达式 for(k=0;k<dagnodindex;k++) { for(t=blobegin;t<bloend&&!(medial[t].dagnodeid==k&&medstack[medial[t].rd].tpindex!=-1);t++); if(t!=bloend) { fir = t; firtmp = medial[fir].rd; while(t<bloend) { for(t=t+1;t<bloend&&!(medial[t].dagnodeid==k&&medstack[medial[t].rd].tpindex!=-1);t++); if(t!=bloend) { sec = t; sectmp = medial[sec].rd; medial[t].op = DEL; medial[t].dagnodeid = -1; medial[t].rs = 0; medial[t].rt = 0; medial[t].rd = 0; for(temp = t+1;temp<bloend;temp++) { if(medial[temp].op==ADD||medial[temp].op==SUB||medial[temp].op==MUL ||medial[temp].op==DIV||medial[temp].op==BIG||medial[temp].op==SMA ||medial[temp].op==EQU||medial[temp].op==BEQU||medial[temp].op==SEQU ||medial[temp].op==NEQU) { if(medial[temp].rs==sectmp) medial[temp].rs = firtmp; if(medial[temp].rt==sectmp) medial[temp].rt = firtmp; } else if(medial[temp].op==NOT||medial[temp].op==ASN||medial[temp].op==FORM ||medial[temp].op==RETURN||medial[temp].op==ADDI||medial[temp].op==SUBI) { if(medial[temp].rs==sectmp) medial[temp].rs = firtmp; } } } } } } } } //分配的时候地址已经是4的倍数,已经留出了参数的位置 void alloc() { int i,j,k,t; int rs,rt;//rd; int weight=1;//权值 int beginid,endid,funtabid;//scope; int temp1,parasum; int addr; int medid,tabid,tmpid; for(i=0;i<medialindex;i++) { if(medial[i].op==BEGIN) { rs = medial[i].rs; funtabid = medstack[rs].tbindex; beginid = table[funtabid].beginid; endid = table[funtabid].endid; //scope = table[funtabid].scope; parasum = table[funtabid].myparasum; addr = parasum*4; i++; //引用计数 while(i<medialindex&&medial[i].op!=END) { if(medial[i].op==ADD||medial[i].op==SUB ||medial[i].op==MUL||medial[i].op==DIV ||medial[i].op==BIG||medial[i].op==SMA ||medial[i].op==EQU||medial[i].op==BEQU ||medial[i].op==SEQU||medial[i].op==NEQU ||medial[i].op==SW||medial[i].op==LW) { rs = medial[i].rs; rt = medial[i].rt; medstack[rs].num+=weight; medstack[rt].num+=weight; } else if(medial[i].op==NOT||medial[i].op==ASN ||medial[i].op==FORM||medial[i].op==RETURN ||medial[i].op==ADDI||medial[i].op==SUBI ||medial[i].op==BEQ||medial[i].op==RD||medial[i].op==WRT) { rs = medial[i].rs; medstack[rs].num+=weight; } else if(medial[i].op==LOOPBEGIN) weight*=10; else if(medial[i].op==LOOPEND) weight/=10; i++; } //复制 for(k = 0,j=beginid;j<=endid;j++,k++) { statis[k].id = medstack[j].id; statis[k].num = medstack[j].num; } //排序 for(j=0;j<k;j++) { for(t=j+1;t<k;t++) { if(statis[t].num>statis[j].num) { temp1 = statis[t].id; statis[t].id = statis[j].id; statis[j].id = temp1; temp1 = statis[t].num; statis[t].num = statis[j].num; statis[j].num = temp1; } } } //alloc reg and memory for(j=0,t=0;j<k;j++) { medid = statis[j].id; if(t<REGGSUM) { if(medstack[medid].tbindex!=-1) { //全局变量和数组不用考虑 tabid = medstack[medid].tbindex; //参数 if(table[tabid].obj==4) { table[tabid].offset = -1; table[tabid].distru = t+REGGBASIC; t++; } //局部变量 else if(table[tabid].obj==2&&table[tabid].scope!=0) { table[tabid].offset = -1; table[tabid].distru = t+REGGBASIC; t++; } //局部数组 else if(table[tabid].obj==7&&table[tabid].scope!=0) { table[tabid].offset = addr; addr = addr+(table[tabid].length*4); } } else if(medstack[medid].tpindex!=-1) { tmpid = medstack[medid].tpindex; tempv[tmpid].regid = t+REGGBASIC; tempv[tmpid].addr = -1; t++; } } //全局寄存器已经分配完毕 else { if(medstack[medid].tbindex!=-1) { //全局变量和数组和参数不用考虑 tabid = medstack[medid].tbindex; //局部变量 if(table[tabid].obj==2&&table[tabid].scope!=0) { table[tabid].offset = addr; addr += 4; } //局部数组 else if(table[tabid].obj==7&&table[tabid].scope!=0) { table[tabid].offset = addr; addr = addr+(table[tabid].length*4); } } else if(medstack[medid].tpindex!=-1) { tmpid = medstack[medid].tpindex; tempv[tmpid].regid = -1; tempv[tmpid].addr = addr; addr += 4; } } } } } } int openoutput() { file1 = (char*)malloc((sizeof(char))*MAXPATH); printf("please input the test file path\n"); gets(file1); if(freopen(file1,"w",stdout)==NULL) { printf("file to open the output file\n"); return 0; } else { printf("success to open the output file\n"); return 1; } } void printsw() { int i = REGGBASIC,j = RESERVE*4,k=0; printf("sw $ra %d($sp)\n",j); j-=4; printf("sw $fp %d($sp)\n",j); for(k=0,j=j-4;k<REGGSUM;k++,i++,j=j-4) { printf("sw $%d %d($sp)\n",i,j); } } void printlw() { int i = REGGBASIC,j = RESERVE*4,k=0; printf("lw $ra %d($sp)\n",j); j-=4; printf("lw $fp %d($sp)\n",j); for(k=0,j=j-4;k<REGGSUM;k++,i++,j=j-4) { printf("lw $%d %d($sp)\n",i,j); } } void checkpara(int funtabid) { int parasum,addr,parareg; int i,j; parasum = table[funtabid].myparasum; for(i=0,j=funtabid;i<parasum&&j<tableindex;j++) { if(table[j].obj==4) { //参数已分配寄存器 if(table[j].offset==-1&&table[j].distru>0) { addr = table[j].paraid; addr *= 4; addr = -addr; parareg = table[j].distru; printf("lw $%d %d($fp)\n",parareg,addr); } i++; } } } //num:1-rs,2-rt,3-rd int calreg(int num,int medid) { int tabid,tmpid,regid,addr; if(medstack[medid].tbindex!=-1) { tabid = medstack[medid].tbindex; //局部变量 if(table[tabid].obj==2&&table[tabid].scope!=0) { //已分配全局寄存器 if(table[tabid].offset==-1&&table[tabid].distru>0) { return table[tabid].distru; } else { if(num==1) { regid = 8; addr = 0-table[tabid].offset; printf("lw $%d %d($fp)\n",regid,addr); return regid; } else if(num==2) { regid = 9; addr = 0-table[tabid].offset; printf("lw $%d %d($fp)\n",regid,addr); return regid; } else if(num==3) return 10; } } //全局变量 else if(table[tabid].obj==2&&table[tabid].scope==0) { if(num==1) { regid = 8; printf("lw $%d %s($0)\n",regid,table[tabid].name); return regid; } else if(num==2) { regid = 9; printf("lw $%d %s($0)\n",regid,table[tabid].name); return regid; } else if(num==3) return 10; } //参数 else if(table[tabid].obj==4) { //已分配全局寄存器 if(table[tabid].offset==-1&&table[tabid].distru>0) { return table[tabid].distru; } else { if(num==1) { regid = 8; addr = 0-table[tabid].paraid*4; printf("lw $%d %d($fp)\n",regid,addr); return regid; } else if(num==2) { regid = 9; addr = 0-table[tabid].paraid*4; printf("lw $%d %d($fp)\n",regid,addr); return regid; } else if(num==3) return 10; } } //函数返回值 else if(table[tabid].obj==6) { if(num==1||num==2) return 2; } } else if(medstack[medid].tpindex!=-1) { tmpid = medstack[medid].tpindex; //分配到了全局寄存器 if(tempv[tmpid].regid>0) { return tempv[tmpid].regid; } else { if(num==1) { regid = 8; addr = 0-tempv[tmpid].addr; printf("lw $%d %d($fp)\n",regid,addr); return regid; } else if(num==2) { regid = 9; addr = 0-tempv[tmpid].addr; printf("lw $%d %d($fp)\n",regid,addr); return regid; } else if(num==3) return 10; } } return 0; } void swreg(int medid,int regid) { int tabid,tmpid,addr; if(medstack[medid].tbindex!=-1) { tabid = medstack[medid].tbindex; //局部变量 if(table[tabid].obj==2&&table[tabid].scope!=0) { addr = 0-table[tabid].offset; printf("sw $%d %d($fp)\n",regid,addr); } //全局变量 else if(table[tabid].obj==2&&table[tabid].scope==0) { printf("sw $%d %s($0)\n",regid,table[tabid].name); } //参数 else if(table[tabid].obj==4) { addr = 0-table[tabid].paraid*4; printf("sw $%d %d($fp)\n",regid,addr); } } else if(medstack[medid].tpindex!=-1) { tmpid = medstack[medid].tpindex; addr = 0-tempv[tmpid].addr; printf("sw $%d %d($fp)\n",regid,addr); } } void genemips() { int i,rs,rt,rd; int rstabid,rttabid; int rstmpid; int rsreg,rtreg,rdreg; //int rsaddr,rtaddr,rdaddr; int rsv,rtv; int rsint,rtint;//是否为常量 //int rsdist,rtdist,rddist;//是否已分配全局寄存器 //int fend;//function end index int funid;//函数基地址index int funtabid; int labid; int addr; int addrreg; int basicreg; int j;//k,t,m,n; //int reserve = 16;//保留区的长度 //char tmp[10]={"str"}; //char no[5]; printf(".data\n"); i = 0; while(i<medialindex&&medial[i].op==GLOBEG) { rs = medial[i].rs; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //全局变量 if(table[rstabid].obj==2) { printf("%s: .word 0 \n",table[rstabid].name); } //数组 else { printf("%s: .word 0:%d \n",table[rstabid].name,table[rstabid].length); } } i++; } for(j=0;j<strindex;j++) { printf("$str%d: .asciiz \"%s\"\n",j,strings[j]); } printf(".text\n"); printf("j $end\n"); for(;i<medialindex;i++) { rs = medial[i].rs; rt = medial[i].rt; rd = medial[i].rd; switch(medial[i].op) { case ADD: rsint = FALSE; rtint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = calreg(3,rd); j = rsv+rtv; printf("addi $%d $0 %d\n",rdreg,j); } else { rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("addi $%d $%d %d\n",rdreg,rtreg,rsv); } } else { if(rtint==TRUE) { rsreg = calreg(1,rs); rdreg = calreg(3,rd); printf("addi $%d $%d %d\n",rdreg,rsreg,rtv); } else { rsreg = calreg(1,rs); rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("add $%d $%d $%d\n",rdreg,rsreg,rtreg); } } //写回内存 if(rdreg<14) swreg(rd,rdreg); break; case SUB: rsint = FALSE; rtint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = calreg(3,rd); j = rsv-rtv; printf("addi $%d $0 %d\n",rdreg,j); } else { rsreg = 13; rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("addi $%d $0 %d\n",rsreg,rsv); printf("sub $%d $%d $%d\n",rdreg,rsreg,rtreg); } } else { if(rtint==TRUE) { rsreg = calreg(1,rs); rdreg = calreg(3,rd); printf("subi $%d $%d %d\n",rdreg,rsreg,rtv); } else { rsreg = calreg(1,rs); rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("sub $%d $%d $%d\n",rdreg,rsreg,rtreg); } } //写回内存 if(rdreg<14) swreg(rd,rdreg); break; case MUL: rsint = FALSE; rtint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = calreg(3,rd); j = rsv*rtv; printf("addi $%d $0 %d\n",rdreg,j); } else { rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("mul $%d $%d %d\n",rdreg,rtreg,rsv); } } else { if(rtint==TRUE) { rsreg = calreg(1,rs); rdreg = calreg(3,rd); printf("mul $%d $%d %d\n",rdreg,rsreg,rtv); } else { rsreg = calreg(1,rs); rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("mul $%d $%d $%d\n",rdreg,rsreg,rtreg); } } //写回内存 if(rdreg<14) swreg(rd,rdreg); break; case DIV: rsint = FALSE; rtint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = calreg(3,rd); j = rsv/rtv; printf("addi $%d $0 %d\n",rdreg,j); } else { rsreg = 13; rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("addi $%d $0 %d\n",rsreg,rsv); printf("div $%d $%d $%d\n",rdreg,rsreg,rtreg); } } else { if(rtint==TRUE) { rsreg = calreg(1,rs); rdreg = calreg(3,rd); printf("div $%d $%d %d\n",rdreg,rsreg,rtv); } else { rsreg = calreg(1,rs); rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("div $%d $%d $%d\n",rdreg,rsreg,rtreg); } } //写回内存 if(rdreg<14) swreg(rd,rdreg); break; case BIG: rsint = FALSE; rtint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = calreg(3,rd); j = ((rsv>rtv)?1:0); printf("addi $%d $0 %d\n",rdreg,j); } else { rsreg = 13; rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("addi $%d $0 %d\n",rsreg,rsv); printf("sgt $%d $%d $%d\n",rdreg,rsreg,rtreg); } } else { if(rtint==TRUE) { rsreg = calreg(1,rs); rdreg = calreg(3,rd); printf("sgt $%d $%d %d\n",rdreg,rsreg,rtv); } else { rsreg = calreg(1,rs); rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("sgt $%d $%d $%d\n",rdreg,rsreg,rtreg); } } //写回内存 if(rdreg<14) swreg(rd,rdreg); break; case SMA: rsint = FALSE; rtint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = calreg(3,rd); j = ((rsv<rtv)?1:0); printf("addi $%d $0 %d\n",rdreg,j); } else { rsreg = 13; rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("addi $%d $0 %d\n",rsreg,rsv); printf("slt $%d $%d $%d\n",rdreg,rsreg,rtreg); } } else { if(rtint==TRUE) { rsreg = calreg(1,rs); rdreg = calreg(3,rd); printf("slti $%d $%d %d\n",rdreg,rsreg,rtv); } else { rsreg = calreg(1,rs); rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("slt $%d $%d $%d\n",rdreg,rsreg,rtreg); } } //写回内存 if(rdreg<14) swreg(rd,rdreg); break; case EQU: rsint = FALSE; rtint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = calreg(3,rd); j = ((rsv==rtv)?1:0); printf("addi $%d $0 %d\n",rdreg,j); } else { rsreg = 13; rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("addi $%d $0 %d\n",rsreg,rsv); printf("seq $%d $%d $%d\n",rdreg,rsreg,rtreg); } } else { if(rtint==TRUE) { rsreg = calreg(1,rs); rdreg = calreg(3,rd); printf("seq $%d $%d %d\n",rdreg,rsreg,rtv); } else { rsreg = calreg(1,rs); rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("seq $%d $%d $%d\n",rdreg,rsreg,rtreg); } } //写回内存 if(rdreg<14) swreg(rd,rdreg); break; case BEQU: rsint = FALSE; rtint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = calreg(3,rd); j = ((rsv>=rtv)?1:0); printf("addi $%d $0 %d\n",rdreg,j); } else { rsreg = 13; rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("addi $%d $0 %d\n",rsreg,rsv); printf("sge $%d $%d $%d\n",rdreg,rsreg,rtreg); } } else { if(rtint==TRUE) { rsreg = calreg(1,rs); rdreg = calreg(3,rd); printf("sge $%d $%d %d\n",rdreg,rsreg,rtv); } else { rsreg = calreg(1,rs); rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("sge $%d $%d $%d\n",rdreg,rsreg,rtreg); } } //写回内存 if(rdreg<14) swreg(rd,rdreg); break; case SEQU: rsint = FALSE; rtint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = calreg(3,rd); j = ((rsv<=rtv)?1:0); printf("addi $%d $0 %d\n",rdreg,j); } else { rsreg = 13; rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("addi $%d $0 %d\n",rsreg,rsv); printf("sle $%d $%d $%d\n",rdreg,rsreg,rtreg); } } else { if(rtint==TRUE) { rsreg = calreg(1,rs); rdreg = calreg(3,rd); printf("sle $%d $%d %d\n",rdreg,rsreg,rtv); } else { rsreg = calreg(1,rs); rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("sle $%d $%d $%d\n",rdreg,rsreg,rtreg); } } //写回内存 if(rdreg<14) swreg(rd,rdreg); break; case NOT: rsint = FALSE; rtint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(rsint==TRUE) { rdreg = calreg(3,rd); printf("subi $%d $0 %d\n",rdreg,rsv); } else { rsreg = calreg(1,rs); rdreg = calreg(3,rd); printf("sub $%d $0 $%d\n",rdreg,rsreg); } //写回内存 if(rdreg<14) swreg(rd,rdreg); break; case NEQU: rsint = FALSE; rtint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } if(rsint==TRUE) { if(rtint==TRUE) { rdreg = calreg(3,rd); j = ((rsv!=rtv)?1:0); printf("addi $%d $0 %d\n",rdreg,j); } else { rsreg = 13; rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("addi $%d $0 %d\n",rsreg,rsv); printf("sne $%d $%d $%d\n",rdreg,rsreg,rtreg); } } else { if(rtint==TRUE) { rsreg = calreg(1,rs); rdreg = calreg(3,rd); printf("sne $%d $%d %d\n",rdreg,rsreg,rtv); } else { rsreg = calreg(1,rs); rtreg = calreg(2,rt); rdreg = calreg(3,rd); printf("sne $%d $%d $%d\n",rdreg,rsreg,rtreg); } } //写回内存 if(rdreg<14) swreg(rd,rdreg); break; case ASN: rsint = FALSE; rtint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(rsint==TRUE) { rdreg = calreg(3,rd); printf("addi $%d $0 %d\n",rdreg,rsv); } else { rsreg = calreg(1,rs); rdreg = calreg(3,rd); printf("move $%d $%d\n",rdreg,rsreg); } //写回内存 if(rdreg<14) swreg(rd,rdreg); break; case BEQ: rsint = FALSE; rtint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(rsint==TRUE) { rsreg = 13; printf("addi $%d $0 %d\n",rsreg,rsv); if(medstack[rd].tbindex!=-1) { funtabid = medstack[rd].tbindex; if(rt==0) printf("beq $%d $0 %s\n",rsreg,table[funtabid].name); else if(rt==1) printf("bne $%d $0 %s\n",rsreg,table[funtabid].name); } else if(medstack[rd].lableindex!=-1) { labid = medstack[rd].lableindex; if(rt==0) printf("beq $%d $0 %s\n",rsreg,labels[labid].name); else if(rt==1) printf("bne $%d $0 %s\n",rsreg,labels[labid].name); } } else { rsreg = calreg(1,rs); if(medstack[rd].tbindex!=-1) { funtabid = medstack[rd].tbindex; if(rt==0) printf("beq $%d $0 %s\n",rsreg,table[funtabid].name); else if(rt==1) printf("bne $%d $0 %s\n",rsreg,table[funtabid].name); } else if(medstack[rd].lableindex!=-1) { labid = medstack[rd].lableindex; if(rt==0) printf("beq $%d $0 %s\n",rsreg,labels[labid].name); else if(rt==1) printf("bne $%d $0 %s\n",rsreg,labels[labid].name); } } break; case GOTO: //跳转到函数 if(medstack[rd].tbindex!=-1) { funtabid = medstack[rd].tbindex; printf("j %s\n",table[funtabid].name); } //跳转到条件标签 else { labid = medstack[rd].lableindex; printf("j %s\n",labels[labid].name); } break; case LAB: //设置函数标签 if(medstack[rs].tbindex!=-1) { funtabid = medstack[rs].tbindex; printf("%s:\n",table[funtabid].name); } //设置条件跳转标签 else { labid = medstack[rs].lableindex; printf("%s:\n",labels[labid].name); } break; case BEGIN: funid = rs; funtabid = medstack[funid].tbindex; j = table[funtabid].length+RESERVE; j*=4; printf("subi $sp $sp %d\n",j); printsw(); printf("addi $fp $sp %d\n",j); checkpara(funtabid); break; case END: funid = rs; funtabid = medstack[funid].tbindex; j = table[funtabid].length+RESERVE; j*=4; printlw(); printf("addi $sp $sp %d\n",j); break; case SW: rtint = FALSE; if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } rstabid = medstack[rs].tbindex; //基地址不需要*4,偏移量需要,不用将寄存器写回内存 //全局变量数组 if(table[rstabid].scope==0) { //偏移量为常数 if(rtint==TRUE) { addrreg = 6; rdreg = calreg(1,rd); printf("addi $%d $0 %d\n",addrreg,(rtv*4)); printf("sw $%d %s($%d)\n",rdreg,table[rstabid].name,addrreg); } else { rtreg = calreg(2,rt); rdreg = calreg(1,rd); addrreg = 6; printf("sll $%d $%d 2\n",addrreg,rtreg); printf("sw $%d %s($%d)\n",rdreg,table[rstabid].name,addrreg); } } //局部变量数组 else { //计算数组基地址 basicreg = 5; printf("addi $%d $0 %d\n",basicreg,(table[rstabid].offset)); //偏移量为常数 if(rtint==TRUE) { addrreg = 6; rdreg = calreg(1,rd); printf("addi $%d $%d %d\n",addrreg,basicreg,(rtv*4)); printf("sub $%d $fp $%d\n",addrreg,addrreg); printf("sw $%d 0($%d)\n",rdreg,addrreg); } else { rtreg = calreg(2,rt); rdreg = calreg(1,rd); addrreg = 6; printf("sll $%d $%d 2\n",addrreg,rtreg); printf("add $%d $%d $%d\n",addrreg,basicreg,addrreg); printf("sub $%d $fp $%d\n",addrreg,addrreg); printf("sw $%d 0($%d)\n",rdreg,addrreg); } } break; case LW: rtint = FALSE; if(medstack[rt].tbindex!=-1) { rttabid = medstack[rt].tbindex; //rt为常数 if(table[rttabid].obj==1) { rtint = TRUE; if(table[rttabid].type==1) rtv = table[rttabid].valuei; else rtv = table[rttabid].valuec; } } rstabid = medstack[rs].tbindex; //基地址不需要*4,偏移量需要,需要将寄存器写回内存 //全局变量数组 if(table[rstabid].scope==0) { //偏移量为常数 if(rtint==TRUE) { addrreg = 6; rdreg = calreg(3,rd); printf("addi $%d $0 %d\n",addrreg,(rtv*4)); printf("lw $%d %s($%d)\n",rdreg,table[rstabid].name,addrreg); } else { rtreg = calreg(2,rt); rdreg = calreg(3,rd); addrreg = 6; printf("sll $%d $%d 2\n",addrreg,rtreg); printf("lw $%d %s($%d)\n",rdreg,table[rstabid].name,addrreg); } } //局部变量数组 else { //计算数组基地址 basicreg = 5; printf("addi $%d $0 %d\n",basicreg,(table[rstabid].offset)); //偏移量为常数 if(rtint==TRUE) { addrreg = 6; rdreg = calreg(3,rd); printf("addi $%d $%d %d\n",addrreg,basicreg,(rtv*4)); printf("sub $%d $fp $%d\n",addrreg,addrreg); printf("lw $%d 0($%d)\n",rdreg,addrreg); } else { rtreg = calreg(2,rt); rdreg = calreg(3,rd); addrreg = 6; printf("sll $%d $%d 2\n",addrreg,rtreg); printf("add $%d $%d $%d\n",addrreg,basicreg,addrreg); printf("sub $%d $fp $%d\n",addrreg,addrreg); printf("lw $%d 0($%d)\n",rdreg,addrreg); } } //写回内存 if(rdreg<14) swreg(rd,rdreg); break; case CALL: rstabid = medstack[rs].tbindex; printf("jal %s\n",table[rstabid].name); break; case FORM: //不需要写回内存 while(i<medialindex&&medial[i].op==FORM) { rsint = FALSE; rs = medial[i].rs; rt = medial[i].rt; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(rsint==TRUE) { rsreg = 13; printf("addi $%d $0 %d\n",rsreg,rsv); addr = 0-(rt*4); printf("sw $%d %d($sp)\n",rsreg,addr); } else { rsreg = calreg(1,rs); addr = 0-(rt*4); printf("sw $%d %d($sp)\n",rsreg,addr); } i++; } i--; break; case RETURN: if(rs==0) printf("move $v0 $0\n"); //不需要写回内存 else { if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) printf("addi $v0 $0 %d\n",table[rstabid].valuei); else printf("addi $v0 $0 %d\n",table[rstabid].valuec); } else { rsreg = calreg(1,rs); printf("move $v0 $%d\n",rsreg); } } else { rsreg = calreg(1,rs); printf("move $v0 $%d\n",rsreg); } } break; case ADDI: rsint = FALSE; rtint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(rsint==TRUE) { rdreg = calreg(3,rd); j = rsv+rt; printf("addi $%d $0 %d\n",rdreg,j); } else { rdreg = calreg(3,rd); rsreg = calreg(1,rs); printf("addi $%d $%d %d\n",rdreg,rsreg,rt); } //写回内存 if(rdreg<14) swreg(rd,rdreg); break; case SUBI: rsint = FALSE; rtint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(rsint==TRUE) { rdreg = calreg(3,rd); j = rsv-rt; printf("addi $%d $0 %d\n",rdreg,j); } else { rdreg = calreg(3,rd); rsreg = calreg(1,rs); printf("subi $%d $%d %d\n",rdreg,rsreg,rt); } //写回内存 if(rdreg<14) swreg(rd,rdreg); break; case RD: rsreg = calreg(3,rs); if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //读int if(table[rstabid].type==1) { printf("li $v0 5\n"); printf("syscall\n"); printf("move $%d $v0\n",rsreg); } //读char else if(table[rstabid].type==2) { printf("li $v0 12\n"); printf("syscall\n"); printf("move $%d $v0\n",rsreg); } } else if(medstack[rs].tpindex!=-1) { rstmpid = medstack[rs].tpindex; //读int if(table[rstmpid].type==1) { printf("li $v0 5\n"); printf("syscall\n"); printf("move $%d $v0\n",rsreg); } //读char else if(table[rstmpid].type==2) { printf("li $v0 12\n"); printf("syscall\n"); printf("move $%d $v0\n",rsreg); } } //写回内存 if(rsreg<14) swreg(rs,rsreg); break; case WRT: rsint = FALSE; rtint = FALSE; if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //rs为常数 if(table[rstabid].obj==1) { rsint = TRUE; if(table[rstabid].type==1) rsv = table[rstabid].valuei; else rsv = table[rstabid].valuec; } } if(rsint==TRUE) { if(table[rstabid].type==1) { printf("li $v0 1\n"); printf("addi $a0 $0 %d\n",rsv); printf("syscall\n"); } else { printf("li $v0 11\n"); printf("addi $a0 $0 %d\n",rsv); printf("syscall\n"); } } else { //write string if(medstack[rs].tbindex!=-1) { rstabid = medstack[rs].tbindex; //写表达式的值 if(table[rstabid].obj!=5) { rsreg = calreg(1,rs); //写int if(table[rstabid].type==1) { printf("li $v0 1\n"); printf("move $a0 $%d\n",rsreg); printf("syscall\n"); } //写char else if(table[rstabid].type==2) { printf("li $v0 11\n"); printf("move $a0 $%d\n",rsreg); printf("syscall\n"); } } //写字符串 else { j = table[rstabid].locate; printf("li $v0 4\n"); printf("la $a0 $str%d\n",j); printf("syscall\n"); } } else if(medstack[rs].tpindex!=-1) { rstmpid = medstack[rs].tpindex; rsreg = calreg(1,rs); //写int if(tempv[rstmpid].type==1) { printf("li $v0 1\n"); printf("move $a0 $%d\n",rsreg); printf("syscall\n"); } //写char else if(tempv[rstmpid].type==2) { printf("li $v0 11\n"); printf("move $a0 $%d\n",rsreg); printf("syscall\n"); } } } break; case JR: printf("jr $ra\n"); break; } } printf("$end: jal main\n"); } int main() { int i; i = openfile(); if(i==0) return 0; program(); genblocks(); dag(); alloc(); freopen("C:\\Users\\forever\\Documents\\GitHub\\Compiler\\SourceCodes\\out.txt","w",stdout); //openoutput(); genemips(); // free(file); return 0; }
05f8bc26613baa33f76a08b1b89f908349bafcbf
[ "Markdown", "C" ]
4
C
organizations-loop/Compiler-7
805b40863a02ad0a9a12fbfbc1a4b871b3ebcace
57f57f00a6b83ed37d519ee6abe5cba79002bb51
refs/heads/master
<file_sep>/** * Created by Julian on 4/4/2015. */ "use strict"; var Utils = require('./utils.js'); var KeyboardController = require('./keyboardController.js'); var AnalogStick = require('./AnalogStick.js'); var listener = -1; function DPad(domid, options) { var CLICK_INTERVAL_IN_MS = 500; var INTERVAL_SPEED = 125; var self = this; var lastTimePressedMs = 0; var firstClick = true; var keyPressCheck = null; var iskeydown = false; var currentKey = -1; AnalogStick.call(this, domid,options); if ("WASDEvents" in options && options["WASDEvents"]){ if (listener !== -1) { clearInterval(listener); } if (Utils.isTouchDevice()) { this.onClick = function () { var now = new Date().getTime(); if (firstClick) { lastTimePressedMs = now; firstClick = false; switch (self.getDirection()){ case DPad.UP: if (self.onUp !== null) self.onUp.call(self); break; case DPad.DOWN: if (self.onDown !== null) self.onDown.call(self); break; case DPad.LEFT: if (self.onLeft !== null) self.onLeft.call(self); break; case DPad.RIGHT: if (self.onRight !== null) self.onRight.call(self); break; } } else { if ((now - lastTimePressedMs) > CLICK_INTERVAL_IN_MS) { lastTimePressedMs = now; switch (self.getDirection()){ case DPad.UP: if (self.onUp !== null) self.onUp.call(self); break; case DPad.DOWN: if (self.onDown !== null) self.onDown.call(self); break; case DPad.LEFT: if (self.onLeft !== null) self.onLeft.call(self); break; case DPad.RIGHT: if (self.onRight !== null) self.onRight.call(self); break; } } } }; this.onRelease = function(){ firstClick = true; }; keyPressCheck = function() { if (self.isPressed()) { var now = new Date().getTime(); if ((now - lastTimePressedMs) > CLICK_INTERVAL_IN_MS) { lastTimePressedMs = now; switch (self.getDirection()) { case DPad.UP: if (self.onUp !== null) self.onUp.call(self); break; case DPad.DOWN: if (self.onDown !== null) self.onDown.call(self); break; case DPad.LEFT: if (self.onLeft !== null) self.onLeft.call(self); break; case DPad.RIGHT: if (self.onRight !== null) self.onRight.call(self); break; } } } }; } else { // NOT TOUCH DEVICE var keyPressed = { "87": false, "65": false, "68": false, "83": false }; document.onkeydown = function(e){ var keyCode = e.keyCode; if (keyCode === 87 || keyCode === 65 || keyCode === 68 || keyCode === 83) { currentKey = keyCode; keyPressed[""+keyCode] = true; self.keyDirection = currentKey; iskeydown = true; var now = new Date().getTime(); if (firstClick) { lastTimePressedMs = now; firstClick = false; switch (keyCode){ case DPad.UP: if (self.onUp !== null) self.onUp.call(self); break; case DPad.DOWN: if (self.onDown !== null) self.onDown.call(self); break; case DPad.LEFT: if (self.onLeft !== null) self.onLeft.call(self); break; case DPad.RIGHT: if (self.onRight !== null) self.onRight.call(self); break; } } else { if ((now - lastTimePressedMs) > CLICK_INTERVAL_IN_MS) { lastTimePressedMs = now; switch (keyCode){ case DPad.UP: if (self.onUp !== null) self.onUp.call(self); break; case DPad.DOWN: if (self.onDown !== null) self.onDown.call(self); break; case DPad.LEFT: if (self.onLeft !== null) self.onLeft.call(self); break; case DPad.RIGHT: if (self.onRight !== null) self.onRight.call(self); break; } } } } }; KeyboardController.onWASDUp(domid, function (keyCode) { if (keyCode === 87 || keyCode === 65 || keyCode === 68 || keyCode === 83) { keyPressed[""+keyCode] = false; if (!keyPressed["87"] && !keyPressed["65"] && !keyPressed["68"] && !keyPressed["83"]){ self.keyDirection = DPad.NONE; iskeydown = false; firstClick = true; } } }); keyPressCheck = function() { if (iskeydown) { var now = new Date().getTime(); if ((now - lastTimePressedMs) > CLICK_INTERVAL_IN_MS) { lastTimePressedMs = now; switch (currentKey){ case DPad.UP: if (self.onUp !== null) self.onUp.call(self); break; case DPad.DOWN: if (self.onDown !== null) self.onDown.call(self); break; case DPad.LEFT: if (self.onLeft !== null) self.onLeft.call(self); break; case DPad.RIGHT: if (self.onRight !== null) self.onRight.call(self); break; } } } }; } listener = setInterval(keyPressCheck, INTERVAL_SPEED); this.onUp = null; this.onDown = null; this.onLeft = null; this.onRight = null; } this.keyDirection = DPad.NONE; } DPad.prototype = Object.create(AnalogStick.prototype); DPad.UP = 87; DPad.DOWN = 83; DPad.LEFT = 65; DPad.RIGHT = 68; DPad.NONE = -1; if (Utils.isTouchDevice()) { DPad.prototype.getDirection = function(){ if (this.isPressed()) { var deg = this.getDegree(); if (deg < 45 || deg >= 315){ return DPad.LEFT; } else if (deg < 315 && deg >= 225) { return DPad.UP; } else if (deg < 225 && deg >= 135) { return DPad.RIGHT; } else { return DPad.DOWN; } } else { return DPad.NONE; } }; } else { DPad.prototype.getDirection = function(){ return this.keyDirection; }; } module.exports = DPad;<file_sep>//Server "use strict"; var port = 9000; console.log("start remote server on port " + port); var PeerServer = require('peer').PeerServer; var server = PeerServer({port: port, path: '/touchController'});<file_sep><!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Taking_still_photos <div class="camera"> <video id="video">Video stream not available.</video> <button id="startbutton">Take photo</button> </div> <canvas id="canvas"> </canvas> <div class="output"> <img id="photo" alt="The screen capture will appear in this box."> </div> </body> <script> </script> </html><file_sep>/** * Created by Julian on 4/4/2015. */ "use strict"; var Utils = require('./utils.js'); var KeyboardController = require('./keyboardController.js'); var nextID = 0; function Button(domid, name, options) { // ============ H E L P E R F U N C T I O N S ============ function handleStart(e) { document.getElementById(id).className = "touchBtn pressed"; e.preventDefault(); } function handleEnd(e) { if (self.onClick !== null) { self.onClick.call(self); } document.getElementById(id).className = "touchBtn"; e.preventDefault(); } function handleCancel(e){ document.getElementById(id).className = "touchBtn"; e.preventDefault(); } // ============ H E L P E R F U N C T I O N S ============ var self = this; var el = document.getElementById(domid); var keyToButton = KeyboardController.keyToButton(); if (Utils.isTouchDevice()) { var style = ""; if (typeof options === "undefined") { options = {}; } if ("bottom" in options){ style += "bottom:" +options.bottom + "px;"; } else if ("top" in options) { style += "top:" +options.top + "px;"; } if ("left" in options){ style += "left:" +options.left + "px;"; } else if ("right" in options) { style += "right:" +options.right + "px;"; } var id = "touchBtn" + nextID++; el.innerHTML = '<div style="'+ style+ '" id="'+ id +'" class="touchBtn"><div class="touchBtnTxt">' + name +'</div></div>'; el.addEventListener("touchstart", handleStart, false); el.addEventListener("touchend", handleEnd, false); el.addEventListener("touchcancel", handleCancel, false); } else { // NON TOUCH DEVICE el.parentNode.removeChild(el); if ("key" in options) { keyToButton[options["key"]] = this; } } this.onClick = null; } module.exports = Button;<file_sep>/** * Created by Julian on 4/4/2015. */ "use strict"; //require('./touchController.js'); var Utils = require('./utils.js'); var AnalogStick = require('./AnalogStick.js'); var DPad = require('./DPad.js'); var Button = require('./Button.js'); var KEYS = require('./KEYS.js'); var _diameter = Utils.diameter(); var _btnDiameter = Utils.btnDiameter(); if (Utils.isTouchDevice()) { document.write("<style id='touchControllerStyle'>.touchController{ " + "width:"+_diameter+"px;height:"+_diameter+"px;border:2px solid black;position:absolute;border-radius:50%;" + " } .innerTouchController {" + "width:5px;height:5px;margin-left:auto;margin-right:auto;margin-top:"+(Math.ceil(_diameter/2))+ "px;background-color:black;}" + ".touchBtn{position:absolute;border:2px solid black;position:absolute;border-radius:50%;" + "width:"+_btnDiameter+"px;height:"+_btnDiameter+"px;}" + ".touchBtnTxt{text-align:center;line-height:"+_btnDiameter+"px;}" + ".touchBtn.pressed{background-color:cornflowerblue;}" + "</style>"); } module.exports = { /** * Checks weather the current device can use touch or not * @returns {*} */ isTouchDevice: function () { return Utils.isTouchDevice(); }, /** * strips away the default style */ stripStyle: function () { var element = document.getElementById('touchControllerStyle'); element.outerHTML = ""; }, AnalogStick: AnalogStick, DPad: DPad, Button: Button, KEYS: KEYS };<file_sep>TouchController - Browser-Touch-Controller with Fallback to Keyboard following HTML is given: ```html <div id="dpad"></div> <div id="analog"></div> <div id="abtn"></div> ``` ```javascript // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ANALOG STICK // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Create a analog stick that measures the user input // in a 360Deg manner. var analogStick = new TouchController.AnalogStick( "analog", {left: 100, bottom: 5} ); // querying the analog stick: var isPressed = analogStick.isPressed(); // BOOLEAN var degree = analogStick.getDegree(); // DOUBLE // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // DPAD // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // When WSADEvents=true, the dpad will be mapped to the // W A S D-Buttons on a keyboard, if no touch device is available var dpad = new TouchController.DPad( "dpad", {top: 10, right: 5, WASDEvents: true} ); // querying the dpad: // The result is one of the following Values: // * TouchController.DPad.UP // * TouchController.DPad.DOWN // * TouchController.DPad.LEFT // * TouchController.DPad.RIGHT // * TouchController.DPad.NONE var direction = dpad.getDirection(); // ENUM // the DPad also provides callbacks for direction events, when // WASDEvents=true: dpad.onUp = function() { ... } dpad.onDown = function() { ... } dpad.onLeft = function() { ... } dpad.onRight = function() { ... } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // BUTTON // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // create a new Button with the Text: "A" // When no touch device is available, the button event // will be mapped to the Key, provided as "key"-paramter var a = new TouchController.Button( "abtn", "A", {bottom:2, left: 180, key: TouchController.KEYS.SPACE} ); // listen to the click-Event: a.onClick = function(){ ... } ```<file_sep>/** * Created by Julian on 4/4/2015. */ "use strict"; var Utils = require('./utils.js'); var KEYS = require('./KEYS.js'); var _keyToButton = {}; function testAndExecKey(keycode, expectedKeycode, value) { if (expectedKeycode === keycode && value in _keyToButton) { var btn = _keyToButton[value]; if (btn.onClick !== null) { btn.onClick.call(btn); } return true; } return false; } if (!Utils.isTouchDevice()) { document.onkeyup = function (e) { var keyCode = e.keyCode; // ignore WASD if (keyCode !== 87 && keyCode !== 65 && keyCode !== 83 && keyCode !== 68) { if (!testAndExecKey(keyCode, 32, KEYS.SPACE)) if (!testAndExecKey(keyCode, 13, KEYS.ENTER)) if (!testAndExecKey(keyCode, 27, KEYS.ESC)) if (!testAndExecKey(keyCode, 81, KEYS.Q)) if (!testAndExecKey(keyCode, 69, KEYS.E)) { } } else { var i = 0, L = _wasdCallbacks.length; for (; i < L; i++) { _wasdCallbacks[i].callback(keyCode); } } }; } var _wasdCallbacks = []; function deleteById(domId, list) { var i = 0, L = list.length; for (; i < L; i++) { if (list[i].id === domId) { list.splice(i, 1); break; } } } module.exports = { /** * Event will be called when a WASD key was pressed and is up again * @param domId to make it removable * @param callback {function} */ onWASDUp: function (domId, callback) { deleteById(domId, _wasdCallbacks); _wasdCallbacks.push({id: domId, callback: callback}); }, keyToButton: function () { return _keyToButton; } };
670bf9b565223948035bdeaef1b5ceddaedebc83
[ "JavaScript", "HTML", "Markdown" ]
7
JavaScript
jutanke/touchController
ce3b79f33d377394a6f3f684ef461858ce1613b1
5a9ed70b18d227c730863d6a140553c3f9eb68d6
refs/heads/main
<repo_name>YutaSakane/kadai1<file_sep>/README.md # kadai1 This is a kadai1 repository. <file_sep>/hoge.bash #!/bin/bash echo hoge echo hoge
85afa60e3f89b9d5ed3144df4f3807e4fd7e0d7a
[ "Markdown", "Shell" ]
2
Markdown
YutaSakane/kadai1
e405553b73f9b412337fd0e2532fcfbc97e1a43b
1e4e38998eae16b3a152c0306f3c0f5601034bca
refs/heads/master
<file_sep>// // Test_testUITests.swift // Test_testUITests // // Created by <NAME> on 21.10.2021. // import XCTest class Test_testUITests: XCTestCase { let timeout: TimeInterval = 60 * 60 * 24 private var expectation: XCTestExpectation? private let app = XCUIApplication() override func setUp() { super.setUp() expectation = XCTestExpectation(description: "All tests are finished.") continueAfterFailure = false app.launch() } func testLaunc() { print("iPhone App should launch") wait(for: [expectation!], timeout: timeout) } } <file_sep>// // Test_test_WatchKit_AppUITests.swift // Test_test WatchKit AppUITests // // Created by <NAME> on 21.10.2021. // import XCTest class Test_test_WatchKit_AppUITests: XCTestCase { let timeout: TimeInterval = 60 * 60 * 24 private var expectation: XCTestExpectation? private let app = XCUIApplication() override func setUp() { super.setUp() expectation = XCTestExpectation(description: "All tests are finished.") continueAfterFailure = false app.launch() } func testLaunc() { print("Watch App should launch") wait(for: [expectation!], timeout: timeout) } }
ad730eed0aef65af92cbb53564a1831ec353f940
[ "Swift" ]
2
Swift
moskaliukzhanna/Test_test
c47e75f225d31ab49114a96b6c6d9d0b89f34c07
e54d644916e629d799508060d75f86a1a487f04b
refs/heads/master
<repo_name>middle2tw/middle2<file_sep>/scripts/update-docker-registry-ssl.php <?php // restart docker registry if ssl key changed // // Usage: php update-docker-registry-ssl.php {le_docker_cert_dir} {docker_cert_dir} $le_docker_cert_dir = $_SERVER['argv'][1]; $docker_cert_dir = $_SERVER['argv'][2]; if (!file_Exists("{$le_docker_cert_dir}/privkey.pem")) { throw new Exception("{$le_docker_cert_dir}/privkey.pem not found"); } if (!file_Exists("{$le_docker_cert_dir}/privkey.pem")) { throw new Exception("{$le_docker_cert_dir}/privkey.pem not found"); } if (file_get_contents("{$docker_cert_dir}/privkey.pem") == file_get_contents("{$le_docker_cert_dir}/privkey.pem")) { error_log("not change"); exit; } foreach (array('cert', 'fullchain', 'privkey') as $f) { copy("{$le_docker_cert_dir}/{$f}.pem", "{$docker_cert_dir}/{$f}.pem"); } system("docker restart registry"); <file_sep>/webdata/config.sample.php <?php putenv('DOCKER_REGISTRY=docker-registry-linode-1.middle2.com:5000'); putenv('MYSQL_USER=hisoku'); putenv('MYSQL_PASS=___'); putenv('MYSQL_HOST=___'); putenv('MYSQL_DATABASE=hisoku'); putenv('MYSQL_USERDB_USER=hisoku_userdb'); putenv('MYSQL_USERDB_PASS=___'); putenv('PGSQL_USERDB_HOST='); putenv('PGSQL_USERDB_PORT=5432'); putenv('PGSQL_USERDB_USER=middle2'); putenv('PGSQL_USERDB_PASS=___'); putenv('MEMCACHE_PRIVATE_HOST=127.0.0.1'); putenv('MEMCACHE_PRIVATE_PORT=11211'); putenv('MAINPAGE_HOST=127.0.0.1'); putenv('MAINPAGE_PORT=9999'); putenv('MAINPAGE_DOMAIN=middle2.com'); putenv('APP_SUFFIX=.middle2.me'); putenv('SCRIBE_HOST=127.0.0.1'); putenv('SCRIBE_PORT=1463'); putenv('SESSION_SECRET=____'); // random putenv('GIT_PUBLIC_SERVER=git.middle2.com'); putenv('GIT_PRIVATE_SERVER=git.middle2.com'); putenv('GIT_SERVER=git.middle2.com'); putenv('HEALTHCHECK_KEY=____'); putenv('HEALTHCHECK_SECRET=____'); putenv('ELASTIC_SECRET=_____'); putenv('SES_MAIL=<EMAIL>'); putenv('SES_SECRET=______'); putenv('SES_KEY=_______'); putenv('LE_ROOT=/srv/certs/acme-challenges'); <file_sep>/cron/1day/clean-machine-status.php #!/usr/bin/env php <?php include(__DIR__ . '/../../webdata/init.inc.php'); Pix_Table::getDefaultDb()->query("DELETE FROM machine_status WHERE updated_at < " . time() . " - 7 * 86400"); Pix_Table::getDefaultDb()->query("OPTIMIZE TABLE machine_status"); <file_sep>/scripts/cron-worker-loop #!/bin/bash while [ 1 ] do ./cron-worker sleep 1 done <file_sep>/webdata/models/Addon/PgSQLDB.php <?php class Addon_PgSQLDBRow extends Pix_Table_Row { public function saveProjectVariable($key = 'DATABASE_URL') { Addon_PgSQLDBMember::search(array('addon_id' => $this->id, 'project_id' => $this->project_id))->first()->saveProjectVariable($key); } public function isMember($user) { return $this->project->isMember($user); } public function isAdmin($user) { return $this->project->isAdmin($user); } public function getEAVs() { return EAV::search(array('table' => 'AddonPgSQLDB', 'id' => $this->id)); } public function addProject($project, $readonly = true) { $username = Hisoku::uniqid(16); $password = <PASSWORD>); $db = new Pix_Table_Db_Adapter_PgSQL(array( 'host' => getenv('PGSQL_USERDB_HOST'), 'port' => getenv('PGSQL_USERDB_PORT'), 'user' => getenv('PGSQL_USERDB_USER'), 'password' => getenv('<PASSWORD>'), )); try { $addon_member = Addon_PgSQLDBMember::insert(array( 'project_id' => $project->id, 'addon_id' => $this->id, 'username' => $username, 'password' => $<PASSWORD>, )); $db->query("CREATE USER \"{$username}\" WITH LOGIN PASSWORD '{$password}' NOINHERIT"); $db->query("ALTER GROUP \"appdb\" ADD USER \"{$username}\""); } catch (Pix_Table_DuplicateException $e) { $addon_member = Addon_PgSQLDBMember::find(array($this->id, $project->id)); $db->query("REVOKE ALL PRIVILEGES ON DATABASE \"{$this->database}\" FROM \"{$addon_member->username}\""); } $db->query("ALTER DATABASE \"{$this->database}\" OWNER TO \"{$username}\""); $addon_member->update(array( 'readonly' => $readonly ? 1: 0, )); $db->query("GRANT ALL PRIVILEGES ON DATABASE \"{$this->database}\" TO \"{$addon_member->username}\""); // TODO: 需要研究 postgresql 怎麼對整個 db readonly /* if ($readonly) { $db->query("GRANT SELECT ON DATABASE \"{$this->database}\" TO \"{$addon_member->username}\""); } else { }*/ } } class Addon_PgSQLDB extends Pix_Table { public function init() { $this->_name = 'addon_pgsqldb'; $this->_rowClass = 'Addon_PgSQLDBRow'; $this->_primary = array('id'); $this->_columns['id'] = array('type' => 'int', 'auto_increment' => true); $this->_columns['project_id'] = array('type' => 'int'); $this->_columns['host'] = array('type' => 'varchar', 'size' => 255); $this->_columns['user_name'] = array('type' => 'varchar', 'size' => 32); $this->_columns['password'] = array('type' => 'varchar', 'size' => 32); $this->_columns['database'] = array('type' => 'varchar', 'size' => 32); $this->_relations['project'] = array('rel' => 'has_one', 'type' => 'Project', 'foreign_key' => 'project_id'); $this->_relations['members'] = array('rel' => 'has_many', 'type' => 'Addon_PgSQLDBMember', 'foreign_key' => 'addon_id'); $this->addIndex('project_id', array('project_id')); $this->_hooks['eavs'] = array('get' => 'getEAVs'); $this->addRowHelper('Pix_Table_Helper_EAV', array('getEAV', 'setEAV')); } public static function addDB($project, $key = 'DATABASE_URL') { if ($addon = self::search(array('project_id' => $project->id))->first()) { $addon->saveProjectVariable($key); return; } $host = getenv('PGSQL_USERDB_HOST'); $database = 'user_' . $project->name; $db = new Pix_Table_Db_Adapter_PgSQL(array( 'host' => getenv('PGSQL_USERDB_HOST'), 'port' => getenv('PGSQL_USERDB_PORT'), 'user' => getenv('PGSQL_USERDB_USER'), 'password' => getenv('<PASSWORD>'), )); $db->query("CREATE DATABASE \"{$database}\""); $db->query("REVOKE ALL PRIVILEGES ON DATABASE \"{$database}\" FROM PUBLIC"); $addon = self::insert(array( 'project_id' => $project->id, 'host' => $host, 'database' => $database, 'user_name' => '', 'password' => '', )); $addon->addProject($project, false); $addon->saveProjectVariable($key); } } <file_sep>/webdata/models/UserKey.php <?php class UserKeyRow extends Pix_Table_Row { public function postSave() { UserKey::updateKey(); } public function postDelete() { UserKey::updateKey(); } public function getKeyUser() { list($type, $body, $user) = explode(' ', $this->key_body); return $user; } } class UserKey extends Pix_Table { public function init() { $this->_name = 'user_key'; $this->_primary = array('id'); $this->_rowClass = 'UserKeyRow'; $this->_columns['id'] = array('type' => 'int', 'auto_increment' => true); $this->_columns['user_id'] = array('type' => 'int'); // ex: 23:47:08:1d:57:09:1b:f5:df:fe:96:52:0d:1d:57:5d $this->_columns['key_fingerprint'] = array('type' => 'char', 'size' => 32); $this->_columns['key_body'] = array('type' => 'text'); $this->_indexes['userid_id'] = array('type' => 'unique', 'columns' => array('user_id', 'id')); $this->_indexes['key_fingerprint'] = array('type' => 'unique', 'columns' => array('key_fingerprint')); $this->_relations['user'] = array('rel' => 'has_one', 'type' => 'User', 'foreign_key' => 'user_id'); } public static function updateKey() { $ip = GIT_SERVER; $session = ssh2_connect($ip, 22); ssh2_auth_pubkey_file($session, 'git', WEB_PUBLIC_KEYFILE, WEB_KEYFILE); ssh2_exec($session, "update-keys"); } } <file_sep>/cron/1day/analytics #!/usr/bin/env php <?php include(__DIR__ . '/../../webdata/init.inc.php'); $date = date('Y-m-d', time() - 86400); // 找出有 log 的 project $cmd = sprintf('find /srv/logs/scribed/ -size +0 -name "*-%s_*"', $date); $logs = explode("\n", trim(`$cmd`)); $logs = array_values(array_filter($logs, function($log) { return (strpos($log, '-error/') or strpos($log, '-node/')) ? false : true; })); // 找出有哪些 group $groups = array_values(array_unique(array_map(function($log) { return explode('/', $log)[4]; }, $logs))); $project_stats = array(); foreach ($groups as $group) { if (strpos($group, 'app-') === 0) { $project = substr($group, 4); $project_stats[$project] = array( 'count' => 0, 'ips' => 0, 'top' => '', ); $cmd = sprintf('cat /srv/logs/scribed/app-%s/app-%s-%s_* | wc -l', $project, $project, $date); $project_stats[$project]['count'] = intval(`$cmd`); $cmd = sprintf("cat /srv/logs/scribed/app-%s/app-%s-%s_* | awk '{print $2}' | sort | uniq | wc -l", $project, $project, $date); $project_stats[$project]['ips'] = intval(`$cmd`); if ($project_stats[$project]['count'] > 10000) { $cmd = sprintf("cat /srv/logs/scribed/app-%s/app-%s-%s_* | awk '{print $2}' | sort | uniq -c | sort -n -r | head -n 5", $project, $project, $date); $project_stats[$project]['top'] = (`$cmd`); } } } uasort($project_stats, function($a, $b) { return $b['count'] - $a['count']; }); $project_ids = array(); foreach (Project::search(1)->searchIn('name', array_keys($project_stats)) as $project) { $project_ids[$project->name] = $project->id; } $domains = array(); foreach (CustomDomain::search(1)->searchIn('project_id', array_values($project_ids)) as $domain) { if (array_key_exists($domain->project_id, $domains)) { continue; } $domains[$domain->project_id] = $domain->domain; } ob_start(); echo "======各專案瀏覽數======\n"; printf("%-24s %-32s %-8s %-8s\n", 'project-id', 'desc', 'count', 'ips'); foreach ($project_stats as $project => $stats) { $project_id = $project_ids[$project]; if (array_key_exists($project_id, $domains)) { $desc = $domains[$project_id]; } else { $desc = ''; } echo sprintf("%-24s %-32s %-8d %-8d", $project, $desc, $stats['count'], $stats['ips']) . "\n"; } echo "======過萬專案最大使用者======\n"; foreach ($project_stats as $project => $stats) { if ($stats['count'] > 10000) { echo "----{$project}----\n"; echo ($stats['top']) . "\n"; } } $content = ob_get_contents(); Hisoku::alert("Middle2 每日報表: {$date}", $content); <file_sep>/webdata/models/Addon/MySQLDBMember.php <?php class Addon_MySQLDBMemberRow extends Pix_Table_Row { public function getDatabaseURL() { return "mysql://{$this->username}:{$this->password}@{$this->addon->host}/{$this->addon->database}"; } public function saveProjectVariable($key = 'DATABASE_URL') { try { $this->project->variables->insert(array( 'key' => $key, 'value' => "Addon_MySQLDB:{$this->addon_id}:DatabaseURL", 'is_magic_value' => 1, )); } catch (Pix_Table_DuplicateException $e) { $this->project->variables->search(array( 'key' => $key, ))->update(array( 'value' => "Addon_MySQLDB:{$this->addon_id}:DatabaseURL", 'is_magic_value' => 1, )); } } } class Addon_MySQLDBMember extends Pix_Table { public function init() { $this->_name = 'addon_mysqldb_member'; $this->_primary = array('addon_id', 'project_id'); $this->_rowClass = 'Addon_MySQLDBMemberRow'; $this->_columns['addon_id'] = array('type' => 'int'); $this->_columns['project_id'] = array('type' => 'int'); $this->_columns['username'] = array('type' => 'varchar', 'size' => 64); $this->_columns['password'] = array('type' => 'varchar', 'size' => 64); $this->_columns['readonly'] = array('type' => 'int', 'default' => 0); $this->addIndex('project_id', array('project_id')); $this->_relations['addon'] = array('rel' => 'has_one', 'type' => 'Addon_MySQLDB', 'foreign_key' => 'addon_id'); $this->_relations['project'] = array('rel' => 'has_one', 'type' => 'Project', 'foreign_key' => 'project_id'); } } <file_sep>/scripts/update-machine-status #!/usr/bin/php <?php include(__DIR__ . '/../webdata/init.inc.php'); // 回傳這台機器的 uptime, cpu load, disk, maximum process 等資訊 $ret = new StdClass; $ret->hostname = gethostname(); $ret->uname = trim(`uname -a`); // 硬碟資訊 $disks = array(); $df_result = explode("\n", trim(`df -P -a`)); for ($i = 1; $i < count($df_result); $i ++) { $rows = preg_split('/\s+/', trim($df_result[$i])); $columns = array('id', 'disk_total', 'disk_usage', 'disk_available', 'disk_capacity', 'mount_point'); $disks[$rows[0]] = array_combine($columns, $rows); } $df_result = explode("\n", trim(`df -P -i`)); for ($i = 1; $i < count($df_result); $i ++) { $rows = preg_split('/\s+/', trim($df_result[$i])); $columns = array('id', 'inode_total', 'inode_usage', 'inode_available', 'inode_capacity', 'mount_point'); $disks[$rows[0]] = array_merge($disks[$rows[0]], array_combine($columns, $rows)); } $ret->disk = array_values($disks); // cpu 資訊 if ($ret->process = trim(`top -w 200 -b -n 1 -c`)) { } else if ($ret->process = trim(`top -b -n 1 -c`)) { } $ret->dmesg = trim(`dmesg | tail -n 100`); // memory info $ret->memory = new StdClass; foreach (explode("\n", trim(file_get_contents('/proc/meminfo'))) as $line) { list($key, $value) = array_map('trim', explode(':', $line)); $ret->memory->{$key} = $value; } // docker memory info $fp = popen("docker ps --format '{{json .}}'", 'r'); $container_pid = array(); while ($line = fgets($fp)) { $container_obj = json_decode($line); $pid = trim(`docker inspect -f '{{.State.Pid}}' {$container_obj->Names}`); $container_obj->pid = $pid; $container_pid[$container_obj->Names] = $container_obj; } fclose($fp); $fp = popen("ps -eo pid,ppid,%mem,%cpu,size,vsize,rssize,cmd --sort=-%mem", "r"); // PID PPID %MEM %CPU SIZE VSZ RSS CMD $columns = preg_split('/\s+/', trim(fgets($fp))); $pid_children = new StdClass; $pid_data = array(); while (false !== ($line = fgets($fp))) { $rows = preg_split('/\s+/', trim($line), count($columns)); $values = array_combine($columns, $rows); if (!property_exists($pid_children, $values['PPID'])) { $pid_children->{$values['PPID']} = array(); } $pid_children->{$values['PPID']}[] = $values['PID']; $pid_data[$values['PID']] = $values; } fclose($fp); uasort($pid_data, function($a, $b) { return $b['RSS'] - $a['RSS']; }); $get_all_children = null; $get_all_children = function($pid) use (&$pid_children, &$get_all_children) { if (!property_exists($pid_children, $pid)) { return array(); } $ret = $pid_children->{$pid}; foreach ($pid_children->{$pid} as $child_pid) { $ret = array_merge($ret, $get_all_children($child_pid)); } return $ret; }; foreach ($container_pid as $cid => $obj) { $pid = $obj->pid; $ppid = $pid_data[$pid]['PPID']; $pids = $get_all_children($ppid); $total = 0; $process_data = array(); foreach ($pids as $pid) { $total += $pid_data[$pid]['RSS']; $process_data[] = $pid_data[$pid]; } $container_pid[$cid]->total_memory = $total; $container_pid[$cid]->process_data = $process_data; } uasort($container_pid, function($a, $b) { return $b->total_memory - $a->total_memory; }); $ret->docker_container_memory = $container_pid; $pgsql_info = posix_getpwnam('postgres'); if ($pgsql_info) { $ret->pgsql_info = new StdClass; foreach (glob($pgsql_info['dir'] . '/*/main/base/*') as $db_path) { $terms = explode('/', $db_path); $oid = array_pop($terms); foreach (glob($db_path . '/*') as $f) { if (!property_exists($ret->pgsql_info, $oid)) { $ret->pgsql_info->{$oid} = 0; } $ret->pgsql_info->{$oid} = max($ret->pgsql_info->{$oid}, filemtime($f)); } } } // TODO: 增加 firewall 是否有正常跑起來的資訊 $curl = curl_init('https://' . getenv('MAINPAGE_DOMAIN') . '/api/updatemachinestatus'); curl_setopt($curl, CURLOPT_POSTFIELDS, 'status=' . urlencode(json_encode($ret, JSON_UNESCAPED_UNICODE))); curl_exec($curl); curl_close($curl); <file_sep>/scripts/sftp-server #!/usr/bin/env php <?php include(__DIR__ . '/../webdata/init.inc.php'); ini_set('error_log', '/tmp/sftp-err'); $server = new SFTPServer; $server->main($_SERVER['argv'][1]); <file_sep>/dockers/config/etc/php.d/common.ini extension=mbstring.so extension=memcached.so extension=zip.so <file_sep>/webdata/models/CronJob.php <?php class CronJobRow extends Pix_Table_Row { public function getEAVs() { return EAV::search(array('table' => 'CronJob', 'id' => $this->id)); } public function runJob() { $this->update(array('last_run_at' => time())); $node = $this->project->getCronNode(); $node->update(array( 'status' => WebNode::STATUS_CRONNODE, )); $node->updateAccessAt(); $node->update(array('cron_id' => $this->id)); $ret = $node->runJob($this->job); stream_set_blocking($ret->stderr, true); stream_set_blocking($ret->stdio, true); $output = new StdClass; $output->node = array($node->ip, $node->port); $output->stderr = (stream_get_contents($ret->stderr)); $lines = explode("\n", trim(stream_get_contents($ret->stdio))); $return_code = array_pop($lines); $output->stdout = implode("\n", $lines); $output->status = json_decode($return_code); $recent_logs = json_decode($this->getEAV('recent_logs')) ?: array(); array_unshift($recent_logs, $output); $recent_logs = array_slice($recent_logs, 0, 10); $this->setEAV('recent_logs', json_encode($recent_logs)); if ($output->status->code != 0) { $recent_logs = json_decode($this->getEAV('recent_error_logs')) ?: array(); array_push($recent_logs, $output); $recent_logs = array_slice($recent_logs, 0, 10); $this->setEAV('recent_error_logs', json_encode($recent_logs)); } $node->markAsWait(); $node->update(array('cron_id' => 0)); return $output; } public function getNextRunAt() { if ($this->start_at > time()) { return $this->start_at; } if (!$this->last_run_at) { return time(); } return $this->last_run_at + CronJob::getPeriodTime($this->period); } } class CronJob extends Pix_Table { protected static $_period_map = array( 0 => 0, 1 => 600, 2 => 3600, 3 => 86400, 4 => 60, 99 => 0, ); public function init() { $this->_name = 'cron_job'; $this->_rowClass = 'CronJobRow'; $this->_primary = 'id'; $this->_columns['id'] = array('type' => 'int', 'auto_increment' => true); $this->_columns['project_id'] = array('type' => 'int'); // 0 - disable, 1 - 10minutes, 2 - hourly, 3 - daily, 4 - 1munute, 99 - worker $this->_columns['period'] = array('type' => 'tinyint'); $this->_columns['start_at'] = array('type' => 'int', 'default' => 0); $this->_columns['last_run_at'] = array('type' => 'int'); $this->_columns['job'] = array('type' => 'text'); $this->_relations['project'] = array('rel' => 'has_one', 'type' => 'Project', 'foreign_key' => 'project_id'); $this->addIndex('project', array('project_id')); $this->addIndex('period_lastrunat', array('period', 'last_run_at')); $this->_hooks['eavs'] = array('get' => 'getEAVs'); $this->addRowHelper('Pix_Table_Helper_EAV', array('getEAV', 'setEAV')); } public static function getPeriodTime($period_id) { return self::$_period_map[$period_id]; } public static function loopCronWorker() { Pix_Table::$_save_memory = true; $stats = array( 'last_action_time' => date('c', time()), // 最近反應時間,隨時更新,會有另一隻 cron 檢查超過 60 秒沒反應就該警告 'start_time' => date('c', time()), // 開始執行時間 'pid' => getmypid(), // 自己的 PID 'crons' => array(), // 執行中的 cron ); file_put_contents('/tmp/hisoku-cron-worker', json_encode($stats)); while (true) { $stats['last_action_time'] = date('c', time()); foreach (self::$_period_map as $period_id => $time) { if (!$time) { continue; } foreach (self::search(array('period' => $period_id))->search("last_run_at < " . (time() - $time)) as $cronjob) { Logger::reconnectScribe(); // fork 之前就 reconnect, 因為 fork 之後好像 child, parent 都有可能出問題 $pid = pcntl_fork(); if ($pid) { Logger::logOne(array('category' => 'cron', 'message' => time() . ' fork from PID=' . getmypid() . ', new PID=' . $pid . ", project={$cronjob->project->name} job={$cronjob->job}")); $stats['crons'][$pid] = array( 'pid' => $pid, 'project' => $cronjob->project->name, 'cron_id' => $cronjob->id, 'start_at' => date('c', time()), 'command' => $cronjob->job, ); Pix_Table_Db_Adapter_MysqlConf::resetConnect(); continue; } if (function_exists('setthreadtitle')) { setthreadtitle("php-fpm: Cron {$cronjob->project->name}: {$cronjob->job}"); } $output = $cronjob->runJob(); if ($output->status->code) { $error_logs = json_decode(file_get_contents('/tmp/hisoku-cron-error')) ?: array(); if ($filtered = array_filter($error_logs, function($log) use ($cronjob) { return $log[1] == $cronjob->id; })) { foreach (array_keys($filtered) as $k) { unset($error_logs[$k]); } $error_logs = array_values($error_logs); } array_unshift($error_logs, array($cronjob->project->name, $cronjob->id, $output->status->start)); $error_logs = array_slice($error_logs, 0, 10); file_put_contents("/tmp/hisoku-cron-error", json_encode($error_logs)); } //echo "{$cronjob->project->name} {$cronjob->job}:"; $output->stderr = mb_substr($output->stderr, mb_strlen($output->stderr) - 128); $output->stdout = mb_substr($output->stdout, mb_strlen($output->stderr) - 128); //print_r($output); //echo "\n"; Logger::logOne(array('category' => 'cron', 'message' => time() . ' fork cron finish from PID=' . getmypid() . ', new PID=' . $pid . ", project={$cronjob->project->name} job={$cronjob->job}")); exit; } } $status = 0; while ($pid = pcntl_wait($status, WNOHANG)) { if ($pid == -1) { break; } unset($stats['crons'][$pid]); } Logger::logOne(array('category' => 'test', 'message' => 'test')); file_put_contents('/tmp/hisoku-cron-worker', json_encode($stats)); sleep(1); } } public function runWorker() { // 檢查所有 Worker 是否活著或是版本有更新 foreach (self::search(array('period' => 99)) as $workerjob) { $nodes = WebNode::search(array('cron_id' => $workerjob->id)); if (count($nodes) > 1) { // TODO: 跑了多隻 worker ,應該要砍掉一隻,未來再支援同時多隻 worker } $node = $nodes->first(); if ($node) { // 線上跑的版本不相同,表示該砍掉重跑 if ($node->commit != $workerjob->project->commit) { // 砍掉重跑 $pid = pcntl_fork(); if ($pid) { Pix_Table_Db_Adapter_MysqlConf::resetConnect(); continue; } if (function_exists('setthreadtitle')) { setthreadtitle("php-fpm: Worker {$workerjob->project->name}: {$workerjob->job}"); error_log("php-fpm: Worker {$workerjob->project->name}: {$workerjob->job}"); } Hisoku::alert("Middle2 Worker Notice", "Project {$workerjob->project->name} run worker {$workerjob->job}, with commit change"); $node->markAsUnused('commit change from runWorker'); $node->resetNode(); $workerjob->runJob(); exit; } $processes = $node->getNodeProcesses(); if (0 == count($processes)) { // 沒有任何 process 了,應該要重跑 worker (不需要 resetNode ,因為在 WebNode 那邊會做) $pid = pcntl_fork(); if ($pid) { Pix_Table_Db_Adapter_MysqlConf::resetConnect(); continue; } if (function_exists('setthreadtitle')) { setthreadtitle("php-fpm: Worker {$workerjob->project->name}: {$workerjob->job}"); error_log("php-fpm: Worker {$workerjob->project->name}: {$workerjob->job}"); } Hisoku::alert("Middle2 Worker Notice", "Project {$workerjob->project->name} run worker {$workerjob->job} with no process found on " . long2ip($node->ip) . ":{$node->port}"); $workerjob->runJob(); exit; } } else { // 沒有任何 process 了,應該要重跑 worker (不需要 resetNode ,因為在 WebNode 那邊會做) $pid = pcntl_fork(); if ($pid) { Pix_Table_Db_Adapter_MysqlConf::resetConnect(); continue; } if (function_exists('setthreadtitle')) { setthreadtitle("php-fpm: Worker {$workerjob->project->name}: {$workerjob->job}"); error_log("php-fpm: Worker {$workerjob->project->name}: {$workerjob->job}"); } Hisoku::alert("Middle2 Worker Notice", "Project {$workerjob->project->name} run worker {$workerjob->job}"); $workerjob->runJob(); exit; } } $status = 0; foreach (WebNode::search("cron_id > 0") as $webnode) { // 如果找不到 job 了,或者是他已經變成 disable job 了,就殺了他 if (!$job = CronJob::find($webnode->cron_id) or $job->period == 0) { $webnode->markAsUnused('job not found or is disabled'); } } } } <file_sep>/scripts/update-ssl-keys.php <?php include(__DIR__ . '/../webdata/init.inc.php'); if (is_dir($_SERVER['argv'][1])) { chdir($_SERVER['argv'][1]); } $fp = fopen('domains.txt', 'r'); $time = 0; while ($domain = fgets($fp)) { if (!$domain = trim($domain)) { continue; } if (!is_dir("certs/{$domain}")) { throw new Exception("domain {$domain} not found"); } if (preg_match('#cert-(.*).pem#', readlink("certs/{$domain}/cert.pem"), $matches)) { $time = max($time, $matches[1]); } $cert_pattern = '/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/s'; $key_pattern = '/-----BEGIN RSA PRIVATE KEY-----[^-]+-----END RSA PRIVATE KEY-----/s'; $config = new StdClass; preg_match_all($cert_pattern, trim(file_get_contents("certs/{$domain}/fullchain.pem")), $matches); $config->ca = $matches[0]; preg_match($cert_pattern, trim(file_get_contents("certs/{$domain}/cert.pem")), $matches); $config->cert = $matches[0]; $config->key = trim(file_get_contents("certs/{$domain}/privkey.pem")); if ($k = SSLKey::find($domain)) { $k->update(array( 'config' => json_encode($config), )); } else { SSLKey::insert(array( 'domain' => $domain, 'config' => json_encode($config), )); } } $fp = fopen('dns-domains.txt', 'r'); while ($domains = fgets($fp)) { $domains = explode(' ', trim($domains)); $first_domain = $domains[0]; foreach ($domains as $domain) { if (!$domain = trim($domain)) { continue; } if (!is_dir("certs/{$first_domain}")) { throw new Exception("domain {$first_domain} not found"); } if (preg_match('#cert-(.*).pem#', readlink("certs/{$first_domain}/cert.pem"), $matches)) { $time = max($time, $matches[1]); } $cert_pattern = '/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/s'; $config = new StdClass; preg_match_all($cert_pattern, trim(file_get_contents("certs/{$first_domain}/fullchain.pem")), $matches); $config->ca = $matches[0]; preg_match($cert_pattern, trim(file_get_contents("certs/{$first_domain}/cert.pem")), $matches); $config->cert = $matches[0]; $config->key = trim(file_get_contents("certs/{$first_domain}/privkey.pem")); if ($k = SSLKey::find($domain)) { $k->update(array( 'config' => json_encode($config), )); } else { SSLKey::insert(array( 'domain' => $domain, 'config' => json_encode($config), )); } } } if ($time != trim(file_get_contents('/tmp/le_version'))) { error_log('restart web server'); system("systemctl reload m2-lb.service"); file_put_contents('/tmp/le_version', $time); } <file_sep>/webdata/models/Addon/Elastic.php <?php class Addon_ElasticRow extends Pix_Table_Row { public function saveProjectVariable($key = 'SEARCH_URL') { try { $this->project->variables->insert(array( 'key' => $key, 'value' => "Addon_Elastic:{$this->id}:SearchURL", 'is_magic_value' => 1, )); } catch (Pix_Table_DuplicateException $e) { $this->project->variables->search(array( 'key' => $key, ))->update(array( 'value' => "Addon_Elastic:{$this->id}:SearchURL", 'is_magic_value' => 1, )); } } public function getSearchURL() { return 'https://elastic.middle2.com/' . $this->index . ':' . $this->secret; } } class Addon_Elastic extends Pix_Table { public function init() { $this->_name = 'addon_elastic'; $this->_rowClass = 'Addon_ElasticRow'; $this->_primary = array('id'); $this->_columns['id'] = array('type' => 'int', 'auto_increment' => true); $this->_columns['project_id'] = array('type' => 'int'); $this->_columns['host'] = array('type' => 'varchar', 'size' => 255); $this->_columns['index'] = array('type' => 'varchar', 'size' => 32); $this->_columns['secret'] = array('type' => 'int'); $this->_relations['project'] = array('rel' => 'has_one', 'type' => 'Project', 'foreign_key' => 'project_id'); $this->addIndex('project_id', array('project_id')); } public static function addDB($project, $key = 'SEARCH_URL') { if ($addon = self::search(array('project_id' => $project->id))->first()) { $addon->saveProjectVariable($key); return; } $ips = Hisoku::getIPsByGroup('search'); $host = array_pop($ips); $index = $project->name; $secret = crc32(uniqid()); $addon = self::insert(array( 'project_id' => $project->id, 'host' => $host, 'index' => $index, 'secret' => $secret, )); $addon->saveProjectVariable($key); } } <file_sep>/webdata/models/SignupConfirm.php <?php class SignupConfirmRow extends Pix_Table_Row { public function sendMail() { $p = new Pix_Partial(__DIR__ . '/../views/'); $expired_at = time() + 3600; $mail = $this->email; $sig = crc32($mail . $expired_at . $this->code); $body = $p->partial('mail/signupconfirm.phtml', array( 'email' => $this->email, 'code' => $this->code, 'domain' => getenv('MAINPAGE_DOMAIN'), 'signup_url' => 'https://' . getenv('MAINPAGE_DOMAIN') . '/index/signupconfirm?mail=' . urlencode($this->email) . '&expired_at=' . $expired_at . '&sig=' . $sig, )); NotifyLib::alert( sprintf("[%s] 註冊信", getenv('MAINPAGE_DOMAIN')), $body, $this->email ); } } class SignupConfirm extends Pix_Table { public function init() { $this->_name = 'signup_confirm'; $this->_primary = 'id'; $this->_rowClass = 'SignupConfirmRow'; $this->_columns['id'] = array('type' => 'int', 'auto_increment' => true); $this->_columns['email'] = array('type' => 'varchar', 'size' => 255); $this->_columns['created_at'] = array('type' => 'int'); $this->_columns['sent_at'] = array('type' => 'int'); $this->_columns['code'] = array('type' => 'int'); $this->addIndex('email', array('email')); } public static function sendSignupConfirm($email) { if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new Exception("{$email} 不是合法的信箱"); } if (User::find_by_name($email)) { throw new Exception("{$email} 已被註冊"); } if ($sc = SignupConfirm::search(array('email' => $email))->order('created_at DESC')->first()) { if ($sc->sent_at > time() - 3600) { throw new Exception("一小時內才寄過認證信,請稍後再試"); } } else { $sc = SignupConfirm::insert(array( 'created_at' => time(), 'email' => $email, 'code' => rand(10000000, 99999999), )); } $sc->sendMail(); } } <file_sep>/scripts/deploy-key-archive-only #!/usr/bin/env php <?php include(__DIR__ . '/../webdata/init.inc.php'); function error($message) { error_log($message); } function buildDockerProjectBase($args) { $project_name = trim($args, "' "); if (preg_match('#^(.*)\.git( clean-build)?( base=.*)?$#', $project_name, $matches)) { $project_name = $matches[1]; } if (FALSE !== strpos($project_name, '.')) { return error('invalid project name: ' . $project_name); } if (!$project = Project::find_by_name(strval($project_name))) { return error('project not found: ' . $project_name); } if (strpos($args, 'clean-build')) { $clean_build = true; } else { $clean_build = false; } if ($matches[3]) { $base = explode('=', $matches[3])[1]; } else { $base = 'middle2'; } $ret = GitHelper::buildDockerProjectBase($project, 'HEAD', $clean_build, $base); echo "success:{$ret}"; exit; } function main() { if (!getenv('SSH_ORIGINAL_COMMAND')) { return error('There is no SSH_ORIGINAL_COMMAND env'); } list($command, $args) = explode(' ', getenv('SSH_ORIGINAL_COMMAND'), 2); if ('build-docker-project-image' == $command) { buildDockerProjectBase($args); return; } elseif (!in_array($command, array('git-upload-archive'))) { return error("Unknown command: {$command} (full: " . getenv('SSH_ORIGINAL_COMMAND') . ")"); } $project_name = trim($args, "' "); if (preg_match('#^(.*)\.git$#', $project_name, $matches)) { $project_name = $matches[1]; } if (FALSE !== strpos($project_name, '.')) { return error('invalid project name: ' . $project_name); } if (!$project = Project::find_by_name(strval($project_name))) { return error('project not found: ' . $project_name); } $absolute_path = getenv('HOME') . '/git/' . $project->id . '.git'; if (!file_exists($absolute_path)) { return error('project not found: ' . $project_name); } passthru('git shell -c ' . escapeshellarg($command . ' ' . escapeshellarg($absolute_path))); return; } main(); <file_sep>/firewall/gen.php <?php include(__DIR__ . '/../webdata/init.inc.php'); class FirewallGenerator { public function getBaseRules() { return array( '#!/bin/sh', 'iptables --flush INPUT', 'iptables --zero INPUT', 'iptables --policy INPUT DROP', 'iptables --policy OUTPUT ACCEPT', 'iptables --policy FORWARD ACCEPT', 'iptables --append INPUT --in-interface lo --jump ACCEPT', 'iptables --append INPUT --match state --state RELATED,ESTABLISHED --jump ACCEPT', 'iptables --append INPUT --protocol icmp --icmp-type 8 --source 0/0 --match state --state NEW,ESTABLISHED,RELATED --jump ACCEPT', 'iptables --append OUTPUT --protocol icmp --icmp-type 0 --destination 0/0 --match state --state ESTABLISHED,RELATED --jump ACCEPT', ); } public function testSuffix() { return array( 'sleep 30', 'iptables --flush INPUT', 'iptables --zero INPUT', 'iptables --policy INPUT ACCEPT', 'iptables --policy OUTPUT ACCEPT', 'iptables --policy FORWARD ACCEPT', ); } protected $_server_categories = array(); protected $_category_servers = array(); protected function _addServer($ip, $category) { if (!$this->_category_servers[$category]) { $this->_category_servers[$category] = array(); } $this->_category_servers[$category][$ip] = $ip; if (!$this->_server_categories[$ip]) { $this->_server_categories[$ip] = array(); } $this->_server_categories[$ip][$category] = $category; } public function initServers() { $dev_servers = Hisoku::getDevServers(); $scribe_servers = $dev_servers; $mainpage_servers = $dev_servers; $git_servers = $dev_servers; $private_memcache_servers = $dev_servers; $this->_server_categories = $this->_category_servers = array(); foreach (Machine::search(1) as $machine) { $this->_server_categories[long2ip($machine->ip)] = array(); } // dev server foreach ($dev_servers as $ip) { $this->_addServer($ip, 'dev'); } // load balancers foreach (Hisoku::getLoadBalancers() as $ip) { $this->_addServer($ip, 'loadbalancer'); } // mysql foreach (Hisoku::getMySQLServers() as $ip) { $this->_addServer($ip, 'mysql'); } // pgsql foreach (Hisoku::getPgSQLServers() as $ip) { $this->_addServer($ip, 'pgsql'); } // node servers foreach (Hisoku::getNodeServers() as $ip) { $this->_addServer($ip, 'node'); } // scribe server foreach ($scribe_servers as $ip) { $this->_addServer($ip, 'scribe'); } foreach (Hisoku::getSearchServers() as $ip) { $this->_addServer($ip, 'elastic_search'); } // mainpage server foreach ($mainpage_servers as $ip) { $this->_addServer($ip, 'mainpage'); } // git server foreach ($git_servers as $ip) { $this->_addServer($ip, 'git'); } // docker registry foreach (Hisoku::getIPsByGroup('docker-registry') as $ip) { $this->_addServer($ip, 'docker-registry'); } // private memcache server foreach ($private_memcache_servers as $ip) { $this->_addServer($ip, 'private_memcache'); } // mysql_old, pgsql_old for migration foreach (Hisoku::getIPsByGroup('mysql_old') as $ip) { $this->_addServer($ip, 'mysql_old'); } foreach (Hisoku::getIPsByGroup('pgsql_old') as $ip) { $this->_addServer($ip, 'pgsql_old'); } foreach (Hisoku::getIPsByGroup('mysql_new') as $ip) { $this->_addServer($ip, 'mysql_new'); } foreach (Hisoku::getIPsByGroup('pgsql_new') as $ip) { $this->_addServer($ip, 'pgsql_new'); } } public function getAllowRules() { return array( 'node' => array( array('20001:29999', array('loadbalancer')), array('22', array('mainpage', 'loadbalancer')), ), 'elastic_search' => array( array('9200', array('node', 'mainpage')), ), 'mainpage' => array( array('9999', array('loadbalancer')), ), 'loadbalancer' => array( array('80', array('PUBLIC')), array('443', array('PUBLIC')), ), 'docker-registry' => array( array('5000', array('node')), ), 'git' => array( array('22', array('PUBLIC')), ), 'private_memcache' => array( array('11211', array('loadbalancer', 'mainpage')), ), 'mysql' => array( array('3306', array('loadbalancer', 'mainpage', 'node')), ), 'mysql_old' => array( array('3306', array('mysql_new')), ), 'pgsql_old' => array( array('5432', array('pgsql_new')), ), 'pgsql' => array( array('5432', array('loadbalancer', 'mainpage', 'node')), ), 'scribe' => array( array('1463', array('loadbalancer', 'node')), ), 'dev' => array( array('22', array('PUBLIC')), // 以後要用 VPN 把這個 rule 拿掉 ), 'ALL' => array( array('22', array('dev')), array('10050', array('dev')), // add zabbix ), ); } public function getIPsFromCategories($categories) { $ips = array(); foreach ($categories as $category) { $ips = array_merge($ips, $this->_category_servers[$category]); } return array_unique($ips); } public static function updateFile($file, $content) { if (!file_exists($file) or md5_file($file) != md5($content)) { file_put_contents($file, $content); } } public function main() { $this->initServers(); $allow_rules = $this->getAllowRules(); foreach ($this->_server_categories as $ip => $categories) { $rules = $this->getBaseRules(); $match_rules = array(); $match_rule_categories = array(); // 先把 ALL 放進來 foreach ($allow_rules['ALL'] as $rule) { $match_rules[$rule[0]] = $rule[1]; $match_rule_categories[$rule[0]] = array('ALL'); } // 把分類符合的塞進來 foreach ($categories as $category) { if (!array_key_exists($category, $allow_rules)) { error_log('category ' . $category . ' is not found'); continue; } foreach ($allow_rules[$category] as $rule) { if (!$match_rules[$rule[0]]) { $match_rules[$rule[0]] = array(); $match_rule_categories[$rule[0]] = array(); } $match_rules[$rule[0]] = array_unique(array_merge($match_rules[$rule[0]], $rule[1])); $match_rule_categories[$rule[0]][] = $category; } } foreach ($match_rules as $port => $categories) { $protocol = 'tcp'; if (preg_match('#^u(.*)#', $port, $matches)) { $port = $matches[1]; $protocol = 'udp'; } if (in_array('PUBLIC', $categories)) { $rules[] = '# allow all from categories ' . implode(', ', $match_rule_categories[$port]); $rules[] = 'iptables --append INPUT --protocol ' . $protocol . ' --dport ' . $port . ' --jump ACCEPT'; } else { $rules[] = '# allow ' . implode(', ', $categories) . ' from categories ' . implode(', ', $match_rule_categories[$port]); foreach ($this->getIPsFromCategories($categories) as $src_ip) { if ($ip == $src_ip) { continue; } $rules[] = 'iptables --append INPUT --protocol ' . $protocol . ' --source ' . $src_ip . ' --dport ' . $port . ' --jump ACCEPT'; } } } self::updateFile(__DIR__ . '/outputs/' . $ip . '.sh', implode("\n", $rules) . "\n"); self::updateFile(__DIR__ . '/outputs/' . $ip . '_test.sh', implode("\n", array_merge($rules, $this->testSuffix())) . "\n"); chmod(__DIR__ . '/outputs/' . $ip . '.sh', 0755); chmod(__DIR__ . '/outputs/' . $ip . '_test.sh', 0755); } } } $g = new FirewallGenerator; $g->main(); <file_sep>/webdata/models/NotifyLib.php <?php class NotifyLib { public function alert($title, $body, $to) { if (!class_exists('AmazonSES')) { define('AWS_DISABLE_CONFIG_AUTO_DISCOVERY', true); include(__DIR__ . '/../stdlibs/sdk-1.6.0/sdk.class.php'); if (!getenv('SES_KEY') or !getenv('SES_SECRET')) { throw new Exception('env SES_KEY & SES_SECRET not found'); } CFCredentials::set(array( 'development' => array( 'key' => getenv('SES_KEY'), 'secret' => getenv('SES_SECRET'), ), )); } $ses = new AmazonSES(); //$ses->set_region(AmazonSES::REGION_TOKYO); $ret = $ses->send_email( getenv('SES_MAIL'), array( 'ToAddresses' => array($to), ), array( 'Subject.Data' => $title, 'Body.Text.Data' => $body, ) ); return $ret; } } <file_sep>/dockers/Dockerfile FROM debian:bullseye RUN apt-get update RUN apt-get install -y git ca-certificates locales curl debian-archive-keyring g++ gcc make dpkg-dev RUN echo 'zh_TW.UTF-8 UTF-8' >> /etc/locale.gen RUN echo 'en_US.UTF-8 UTF-8' >> /etc/locale.gen RUN locale-gen RUN apt-get install -y php php-mysql php-pgsql libapache2-mod-rpaf php-fpm apache2 php-curl php-gd php-mbstring php-xml composer RUN curl -sL https://deb.nodesource.com/setup_14.x | bash - RUN apt-get install -y nodejs RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - RUN echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list RUN apt-get update RUN apt-get install yarn RUN apt-get install -y ruby ruby-dev RUN apt-get install -y python3 python3-pip python3-dev libpq-dev gunicorn RUN apt-get install -y sysvinit-core RUN update-rc.d -f apache2 remove RUN update-rc.d -f php7.4-fpm remove RUN mkdir /run/php/ COPY config/ / <file_sep>/webdata/controllers/DeployController.php <?php class DeployController extends Pix_Controller { public function init() { if (!$this->user = Hisoku::getLoginUser()) { return $this->redirect('/'); } $this->view->user = $this->user; if (getenv('TRY_MODE')) { $this->try_mode = getenv('TRY_MODE'); $this->view->try_mode = $this->try_mode; $this->project_limit = 3; $this->view->project_limit = $this->project_limit; } } public function indexAction() { if (!$_GET['template']) { return $this->redirect('/'); } if (!preg_match('/^https?:\/\/github\.com\/(?P<user>[^\/]+)\/(?P<repo>[^\/]+)(\.git)?$/U', $_GET['template'], $matches)) { return $this->alert("template must be GitHub web URL", '/'); } $curl = curl_init("https://raw.githubusercontent.com/{$matches['user']}/{$matches['repo']}/master/app.json"); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $content = curl_exec($curl); curl_close($curl); if (!$app_json = json_decode($content)) { return $this->alert("app.json parse error", '/'); } // TODO: check app.json if ($this->try_mode) { $project_count = Project::search(array('created_by' => $this->user->id))->count(); if (intval($project_count) >= $this->project_limit) { return $this->alert('目前為試用模式,project 數量上限為 ' . $this->project_limit, '/'); } } try { $project = $this->user->addProject(); } catch (InvalidException $e) { // TODO: error return $this->redirect('/'); } catch (Pix_Table_DuplicateException $e) { // TODO: error return $this->redirect('/'); } $project->setEAV('note', strval($app_json->name)); $prepare_addons = array(); if ($app_json->addons) { foreach ($app_json->addons as $addon) { if ("string" === gettype($addon)) { $prepare_addons[$addon] = 'DATABASE_URL'; } else if ("object" === gettype($addon)) { $prepare_addons[$addon->plan] = $addon->as ? $addon->as : 'DATABASE_URL'; } } } foreach ($prepare_addons as $key => $value) { switch (strtolower($key)) { case 'mysql': Addon_MySQLDB::addDB($project, $value); break; case 'pgsql': case 'postgresql': case 'heroku-postgresql': Addon_PgSQLDB::addDB($project, $value); break; default: } } if ($app_json->env) { foreach (get_object_vars($app_json->env) as $key => $obj) { if ($obj->value && strlen($obj->value) > 0) { $project->variables->insert(array( 'key' => $key, 'value' => $obj->value, 'is_magic_value' => 0, )); } } } $from = 'https://github.com/' . $matches['user'] . '/' . $matches['repo']; $ip = GIT_SERVER; $session = ssh2_connect($ip, 22); ssh2_auth_pubkey_file($session, 'git', WEB_PUBLIC_KEYFILE, WEB_KEYFILE); $stream = ssh2_exec($session, "import-project-repo " . $project->name . " " . $from); stream_set_blocking($stream, true); $ret = stream_get_contents($stream); if ($app_json->success_url) { return $this->redirect("http://" . $project->name . getenv('APP_SUFFIX') . $app_json->success_url); } return $this->redirect("https://" . getenv('MAINPAGE_DOMAIN') . "/project/detail/" . $project->name); } } <file_sep>/dockers/config/post-clone.sh #!/bin/sh if [ -d "/srv/web/_public" ]; then sed -i "s/\/srv\/web/\/srv\/web\/_public/" /etc/apache2/sites-enabled/000-default.conf fi <file_sep>/cron/1min/run-worker #!/usr/bin/env php <?php include(__DIR__ . '/../../webdata/init.inc.php'); define('LOCK_FILE', '/tmp/hisoku-run-worker'); $fp = fopen(LOCK_FILE, 'w+'); if (!flock($fp, LOCK_EX | LOCK_NB)) { list($time, $pid) = explode(' ', file_get_contents(LOCK_FILE . '.pid')); if ($time < time() - 3600) { file_put_contents(LOCK_FILE . '.pid', time() . ' ' . $pid); Hisoku::alert("Middle2 Cron error", "Cron is locking since " . date('Y/m/d H:i:s', $time)); } throw new Exception(LOCK_FILE . ' is locking'); } ftruncate($fp, 0); // truncate file file_put_contents(LOCK_FILE . '.pid', time() . ' ' . getmypid()); fwrite($fp, getmypid()); fflush($fp); // flush output before releasing the lock CronJob::runWorker(); flock($fp, LOCK_UN); // release the lock fclose($fp); unlink(LOCK_FILE); <file_sep>/webdata/models/Logger.php <?php define('THRIFT_ROOT', __DIR__ . '/../stdlibs/Thrift'); require_once THRIFT_ROOT.'/packages/FacebookService.php'; require_once THRIFT_ROOT.'/packages/scribe.php'; require_once THRIFT_ROOT.'/packages/Types.php'; class Logger { protected static $_scribe_client = null; protected static $_scribe_socket = null; public static function getScribeClient() { if (is_null(self::$_scribe_client)) { $socket = new Thrift\Transport\TSocket(getenv('SCRIBE_HOST'), getenv('SCRIBE_PORT'), false); $transport = new Thrift\Transport\TFramedTransport($socket); $protocol = new Thrift\Protocol\TBinaryProtocol($transport, false, false); $scribeClient = new Scribe\Thrift\scribeClient($protocol, $protocol); $transport->open(); self::$_scribe_socket = $socket; self::$_scribe_client = $scribeClient; } return self::$_scribe_client; } public static function reconnectScribe() { if (!is_null(self::$_scribe_socket)) { self::$_scribe_socket->close(); self::$_scribe_socket = null; } self::$_scribe_client = null; } /** * 記錄進 scirbe * * @param array $messages array(array('category' => xxx, 'message' => xxx), ...) * @static * @access public * @return void */ public static function log($messages) { $scribeClient = self::getScribeClient(); $log_entries = array(); foreach ($messages as $message) { $log_entry = new Scribe\Thrift\LogEntry($message); $log_entries[] = $log_entry; } $scribeClient->Log($log_entries); } /** * 只塞一筆記錄進 scribe * * @param array $message array('category' => 'xxx', 'message' => 'xxx') * @static * @access public * @return void */ public static function logOne($message) { return self::log(array($message)); } /** * 取得這個 category 的 log,預設一次抓 20 行 * * @param string $category * @param array $options cursor-after * cursor-before * line (default: 20) * @static * @access public * @return array(logs, cursor[start-pos, end-pos]) */ public static function getLog($category, $options = array()) { // 抓最新的 $perbyte bytes ,想辦法湊到 20 行 $perbyte = 1024; $line = array_key_exists('line', $options) ? intval($options['ine']) : 20; $log_files = glob("/srv/logs/scribed/{$category}/{$category}-*"); $return_logs = array(); $return_cursor = array(); if (array_key_exists('cursor-after', $options)) { foreach ($log_files as $log_file) { $filename = substr(basename($log_file), strlen($category) + 1); $cursor = 0; if (array_key_exists('cursor-after', $options)) { if ($options['cursor-after']['file'] != $filename) { continue; } $cursor = $options['cursor-after']['cursor']; unset($options['cursor-after']); } //error_log("opening {$log_file}..."); $filesize = filesize($log_file); if (0 == $filesize) { continue; } $fp = fopen($log_file, 'r'); if ($cursor) { fseek($fp, $cursor); } // 每次爬一行 while ($log = fgets($fp)) { // 從 $cursor 往前爬 $perbyte byte $log = trim($log); if ('' == $log) { $cursor ++; continue; } // 第一筆 log ,需要記錄 cursor-start if (count($return_logs) == 0) { $return_cursor['cursor-start'] = array($filename, $cursor); } array_push($return_logs, $log); $cursor += (strlen($log) + 1); if (count($return_logs) >= $line) { break 2; } } } $return_cursor['cursor-end'] = array($filename, $cursor); return array($return_logs, $return_cursor); } rsort($log_files); // 照時間排序的 log 檔 foreach ($log_files as $log_file) { $filename = substr(basename($log_file), strlen($category) + 1); $cursor = null; if (array_key_exists('cursor-before', $options)) { if ($options['cursor-before']['file'] != $filename) { continue; } $cursor = $options['cursor-before']['cursor']; unset($options['cursor-before']); } if (0 == filesize($log_file)) { continue; } if (strpos($log_file, '.gz')) { $fp = gzopen($log_file, 'r'); } else { $fp = fopen($log_file, 'r'); } if (is_null($cursor)) { $cursor = filesize($log_file); } $current_perbyte = $perbyte; // 每次爬 $perbyte byte while ($cursor > 0) { // 從 $cursor 往前爬 $current_perbyte byte if ($cursor > $current_perbyte) { //error_log("loading {$log_file} before {$cursor} - {$current_perbyte}..."); fseek($fp, $cursor - $current_perbyte); $content = fread($fp, $current_perbyte); $head = false; } else { fseek($fp, 0); //error_log("loading {$log_file} from start..."); $content = fread($fp, $cursor); $head = true; } $logs = explode("\n", $content); // 換成新到舊 $logs = array_reverse($logs); if (!$head) { // 如果沒有到頭的話,第一行拿掉,因為可能是被腰斬 array_pop($logs); // pop 完後沒任何東西,就表示只有一行被腰斬還超過 $current_perbyte, 所以應該加倍再來一次 if (!$logs) { $current_perbyte *= 2; continue; } } $current_perbyte = $perbyte; foreach ($logs as $log) { if ('' == $log) { $cursor --; continue; } // 第一筆 log ,需要記錄 cursor-start if (count($return_logs) == 0) { $return_cursor['cursor-end'] = array($filename, $cursor); } array_unshift($return_logs, $log); $cursor -= (strlen($log) + 1); if (count($return_logs) >= $line) { break 3; } } } } $return_cursor['cursor-start'] = array($filename, $cursor); return array($return_logs, $return_cursor); } } <file_sep>/scripts/build-project-base/ruby20.php #!/usr/bin/env php <?php // 每次 post-commit 之後,將 requirements.txt 內的東西先抓好 // 包成一個 tar gz ,之後就解開 tar gz 就好了,速度超快! // // 每次 post-commit 時 // 1. 先找 /srv/chroot/1000~1999 之間是否有可以用的 chroot // 2. 找到後,在 /srv/chroot/1xxx.lock 加上 lock 避免衝突 // 3. 把 /srv/code/images/lang-ruby20.tar.gz 解壓縮進 chroot 中 // 4. 把所有檔案的修改日期都改成 2000/01/01 ,以方便作完 bundler 可以找出新增加的檔 // 5. 把需要的 Gemfile 搬到 /srv/chroot/1xxx/ 下面 // 6. bundle 裝進 chroot 內 // 7. 找出新裝的東西,搬出來放進 tar gz 中,完工 // // 之後要 clone 的時候 // 1. 把 tar gz 解開就好了 // // 用法 php ruby-prebuild.php [requirements.txt file] class Prebuilder { public function error($message) { die($message); } public function findAvailableRootAndLock() { $shuffled_roots = glob('/srv/chroot/1???'); shuffle($shuffled_roots); foreach ($shuffled_roots as $root) { $lock_file = "{$root}.lock"; if (file_exists("{$root}.initing") or file_exists("{$root}.used")) { continue; } $fp = fopen($lock_file, 'w+'); if (!flock($fp, LOCK_EX | LOCK_NB)) { continue; } $this->fp = $fp; return $root; } return $this->error("No avaiabled root"); } public function main($req_file, $force_rebuild = false) { if (0 !== posix_getuid()) { return $this->error("Muse be root"); } if (!file_exists($req_file)) { return $this->error("File not found"); } $project_file = '/tmp/project-ruby20-' . md5_file($req_file); // 已經有了,不需要再做了 if (!$force_rebuild and file_exists($project_file . '.tar.gz')) { return; } // 先找可以用的 chroot error_log('find available root...'); $root = $this->findAvailableRootAndLock(); error_log('untar ruby20.tar.gz...'); // 把 ruby20 package 解進去 system("tar zxf /srv/code/images/lang-ruby20.tar.gz --directory={$root}"); error_log('find diff file...'); // 把新解進去的檔案都改成 2001/1/1 system("find {$root} -printf '%TY%Tm%Td %p\n' | grep -v ',,,/proc' | grep -v '^20000101' | awk '{print $2}' | xargs -n 100 touch --no-dereference --date=20000101"); error_log('bundle installing ...'); // 安裝 ruby20 package chdir("{$root}"); system("cp $req_file {$root}/Gemfile"); system("chroot {$root} gem install bundler"); passthru("chroot {$root} bundle install --without development test"); system("rm -rf {$root}/.bundle {$root}/Gemfile {$root}/Gemfile.lock {$root}/vendor"); // 把檔案弄進去 chdir($root); error_log('build tar.gz...'); // TODO: 處理過程中會不會處理到一半的檔案被人拿走... // 處理檔案 system("find . -type f -printf \"%TY%Tm%Td,,,%p\n\" | grep -v ',,,/proc' | grep -v '^20000101' | awk -F,,, '{print \"\\\"\"$2\"\\\"\"}' | xargs -n 100 tar -uf " . escapeshellarg($project_file . '.tar')); // 處理 symbolic link system("find . -type l -printf \"%TY%Tm%Td,,,%p\n\" | grep -v ',,,/proc' | grep -v '^20000101' | awk -F,,, '{print \"\\\"\"$2\"\\\"\"}' | xargs -n 100 tar -uf " . escapeshellarg($project_file . '.tar')); system("gzip {$project_file}.tar"); // 標示為已用完,並解除 lock touch("{$root}.used"); flock($this->fp, LOCK_UN); // release the lock fclose($this->fp); unlink("{$root}.lock"); } } $p = new Prebuilder; $p->main($_SERVER['argv'][1], array_key_exists(2, $_SERVER['argv']) ? true : false); <file_sep>/webdata/models/Machine.php <?php class MachineRow extends Pix_Table_Row { public function getGroups() { return explode(',', $this->groups); } public function setGroups($groups) { $this->groups = $groups; $this->save(); } } class Machine extends Pix_Table { public function init() { $this->_name = 'machine'; $this->_primary = 'machine_id'; $this->_rowClass = 'MachineRow'; $this->_columns['machine_id'] = array('type' => 'int', 'auto_increment' => true); $this->_columns['name'] = array('type' => 'varchar', 'size' => 32); $this->_columns['ip'] = array('type' => 'int', 'unsigned' => true); // TODO: 之後搬出另一個 model $this->_columns['groups'] = array('type' => 'text'); $this->_relations['statuses'] = array('rel' => 'has_many', 'type' => 'MachineStatus'); } public static function getMachinesByGroup($group) { $return_machines = array(); foreach (Machine::search("groups LIKE '%" . urlencode($group) . "%'") as $machine) { if (in_array($group, explode(',', $machine->groups))) { $return_machines[] = $machine; } } return $return_machines; } } <file_sep>/config/README.md update systemd config ===================== * cp m2-lb.service /lib/systemd/system/ * systemctl daemon-reload <file_sep>/cron/1min/health-check #!/usr/bin/env php <?php define('LOCK_FILE', '/tmp/hisoku-health-check'); $fp = fopen(LOCK_FILE, 'w+'); if (!flock($fp, LOCK_EX | LOCK_NB)) { throw new Exception(LOCK_FILE . ' is locking'); } ftruncate($fp, 0); // truncate file fwrite($fp, getmypid()); fflush($fp); // flush output before releasing the lock include(__DIR__ . '/../../webdata/init.inc.php'); if (getenv('TRY_MODE')) { exit; } # check loadbalancer foreach (Hisoku::getLoadBalancers() as $host) { $curl = curl_init('http://' . $host . '/'); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Host: healthcheck')); curl_setopt($curl, CURLOPT_TIMEOUT, 10); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $ret = curl_exec($curl); if (!preg_match("#OK#", $ret)) { Hisoku::alert("LoadBalancer error", "LoadBalancer IP: {$host}: Return: {$ret}"); continue; } $info = curl_getinfo($curl); if ($info['total_time'] > 1) { Hisoku::alert("LoadBalancer warning", "LoadBalancer IP: {$host}\nhealth check time: " . json_encode($info, JSON_PRETTY_PRINT)); } } # check search foreach (Hisoku::getSearchServers() as $search_server) { $curl = curl_init('http://' . $search_server . ':9200/_stats'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 10); $content = curl_exec($curl); $info = curl_getinfo($curl); if ($info['http_code'] != 200) { Hisoku::alert("Search error", "Search IP: {$search_server}\n Return: {$info['http_code']}\n"); continue; } if (!$json = json_decode($content)) { Hisoku::alert("Search error", "Search IP: {$search_server}\n return is not valid json\n{$content}"); continue; } if (!$json->ok) { Hisoku::alert("Search error", "Search IP: {$search_server}\n json is not ok\n" . print_r($json, true)); continue; } } flock($fp, LOCK_UN); // release the lock fclose($fp); unlink(LOCK_FILE); <file_sep>/dockers/config/start-web.sh #!/bin/sh export LOG_FILE=/srv/logs/web.log export PORT=80 export HOME=/srv/web cd /srv/web if [ -f "/srv/web/Procfile" ]; then CMD=`cat /srv/web/Procfile | grep '^web:' | awk '{print substr($0, 5);}' | sed "s/\\$PORT/$PORT/"` echo "$CMD" > ${LOG_FILE} echo "$CMD" | sh >> ${LOG_FILE} 2>&1 & elif [ -f "/srv/web/manage.py" ]; then # python django python ./manage.py runserver 0.0.0.0:80 --noreload > ${LOG_FILE} 2>&1 & elif [ -f "/srv/web/app.py" ]; then # python app.py gunicorn app:app -b 0.0.0.0:80 > ${LOG_FILE} & elif [ -f "/srv/web/web.rb" ]; then # ruby export RACK_ENV=production ruby web.rb -p 80 > ${LOG_FILE} 2>&1 & elif [ -f "/srv/web/artisan" ]; then echo 'APP_KEY=' > /srv/web/.env php artisan key:generate php artisan serve --port=80 --host=0.0.0.0 2>&1 & #elif [ -f "/srv/web/index.php" ]; then else # build /srv/env.conf env | awk -F '=' '{print "env[" $1 "]=\"" substr($0, index($0, "=") + 1) "\""}' > /srv/logs/env.conf # stop all php-fpm killall php-fpm7.4 # start php-fpm /usr/sbin/php-fpm7.4 # start apache /usr/sbin/apache2ctl start fi START_AT=`date +%s` END_AT=`expr 300 + $START_AT` HTTP_CODE=0 while [ $END_AT -gt `date +%s` ] do HTTP_CODE=`curl --connect-timeout 3 --stderr /dev/null --include http://0:$PORT | head -n 1 | awk '{print $2}'` echo $HTTP_CODE | grep '^[0-9]\+$' > /dev/null if [ "$?" -eq "1" ]; then sleep 1 else if [ "$HTTP_CODE" = "" ]; then sleep 1 elif [ $HTTP_CODE -eq 0 ]; then sleep 1 else END_AT=0 fi fi done #TODO 失敗的話要讓 loadbalancer 知道, 可以從 END_AT 判斷 <file_sep>/webdata/models/CustomDomain.php <?php class CustomDomain extends Pix_Table { public function init() { $this->_name = 'custom_domain'; $this->enableTableCache(); $this->_primary = array('domain'); // RFC 1035 $this->_columns['domain'] = array('type' => 'varchar', 'size' => 255); $this->_columns['project_id'] = array('type' => 'int'); $this->_relations['project'] = array('rel' => 'has_one', 'type' => 'Project', 'foreign_key' => 'project_id'); $this->addIndex('project_id', array('project_id')); } } <file_sep>/cron/1min/cron-health-check #!/usr/bin/env php <?php include(__DIR__ . '/../../webdata/init.inc.php'); if (!file_exists('/tmp/hisoku-cron-worker')) { Hisoku::alert("Cron error", "/tmp/hisoku-cron-worker not found"); exit; } if (!$obj = json_decode(file_get_contents("/tmp/hisoku-cron-worker"))) { Hisoku::alert("Cron error", "/tmp/hisoku-cron-worker is not valid JSON"); exit; } if (!$last_action_time = strtotime($obj->last_action_time)) { Hisoku::alert("Cron error", "/tmp/hisoku-cron-worker has no last_action_time"); exit; } if (time() - $last_action_time > 60) { Hisoku::alert("Cron error", "cron is not action from " . $obj->last_action_time); exit; } <file_sep>/scripts/root@nodes-ssh_serve #!/usr/bin/env php <?php include(__DIR__ . '/../webdata/init.inc.php'); function error($message, $log_file = null) { echo json_encode(array( 'error' => true, 'message' => $message, )); if (!is_null($log_file)) { file_put_contents($log_file, date('c') . " [error] $message\n", FILE_APPEND); } die(); } function exec_m2($cmd) { $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"), ); $cwd = __DIR__; $env = array(); //'some_option' => 'aeiou'); $proc = proc_open($cmd, $descriptorspec, $pipes, $cwd, $env); $stdout = stream_get_contents($pipes[1]); $stderr = stream_get_contents($pipes[2]); $ret = proc_close($proc); return array( 'stdout' => $stdout, 'stderr' => $stderr, 'code' => $ret, ); } function main() { if (!getenv('SSH_ORIGINAL_COMMAND')) { return error('There is no SSH_ORIGINAL_COMMAND env'); } $command = getenv('SSH_ORIGINAL_COMMAND'); list($method) = explode(' ', $command, 2); switch ($method) { case 'init': list(, $id, $option) = explode(' ', getenv('SSH_ORIGINAL_COMMAND')); if (!$id) { echo json_encode(array('error' => true, 'message' => 'id is not found')); break; } $port = 20000 + $id; $start = microtime(true); $log_file = "/srv/chroot/{$id}.log"; touch("/srv/chroot/{$id}.docker"); file_put_contents($log_file, date('c') . " [init] start\n", FILE_APPEND); // init 在 docker 下甚麼都不用做 $aaspent = microtime(true) - $start; file_put_contents($log_file, date('c') . " [init] done(spent: {$spent})\n", FILE_APPEND); echo json_encode(array('error' => false, 'port' => $port)); break; case 'clone': list(, $project_name, $id, $flag) = explode(' ', getenv('SSH_ORIGINAL_COMMAND')); $start = microtime(true); $log_file = "/srv/chroot/{$id}.log"; if (!$id) { die("invalid $id"); } if (!$project = Project::find_by_name(strval($project_name))) { return error('project not found: ' . $project_name); } file_put_contents($log_file, date('c') . " [clone] project: {$project_name}\n", FILE_APPEND); file_put_contents($log_file, date('c') . " [clone] init lang base\n", FILE_APPEND); file_put_contents("/srv/chroot/{$id}.project", $project_name); $weblog_dir = "/srv/chroot/{$id}/srv/logs"; if (file_exists($weblog_dir)) { system("rm -rf " . escapeshellarg($weblog_dir)); } mkdir($weblog_dir, 0777, true); $cmd = "ssh git@" . GIT_SERVER . " build-docker-project-image " . $project_name; $build_image_result = `$cmd`; if (!preg_match('#success:(.*)#', $build_image_result, $matches)) { return error('build project base failed: ' . $project_name); } $docker_registry = getenv('DOCKER_REGISTRY'); $image = "{$docker_registry}/image-{$project_name}"; $ret = exec_m2("docker --config /srv/config/docker pull $image"); if ($ret['code']) { $ret['error'] = true; $ret['message'] = "docker pull $image failed"; file_put_contents($log_file, date('c') . " [clone] code={$ret} error: " . json_encode($ret) . "(spent: $spent)\n", FILE_APPEND); echo json_encode($ret); exit($ret['code']); break; } $port = 20000 + $id; $ret = exec_m2("docker create --oom-kill-disable -v /srv/chroot/{$id}/srv/logs:/srv/logs --publish {$port}:80 --name c-{$id} {$image} init"); if ($ret['code']) { $ret['error'] = true; $ret['message'] = "docker create $image to c-{$id} failed"; file_put_contents($log_file, date('c') . " [clone] code={$ret} error: " . json_encode($ret) . "(spent: $spent)\n", FILE_APPEND); echo json_encode($ret); exit($ret['code']); break; } $ret = exec_m2("docker start c-{$id}"); if ($ret['code']) { $ret['error'] = true; $ret['message'] = "docker start c-{$id} failed"; file_put_contents($log_file, date('c') . " [clone] code={$ret} error: " . json_encode($ret) . "(spent: $spent)\n", FILE_APPEND); echo json_encode($ret); exit($ret['code']); break; } file_put_contents($log_file, date('c') . " [clone] post-clone.sh\n", FILE_APPEND); if ('no-post-clone' != $flag) { exec("docker exec c-{$id} /post-clone.sh {$port}"); } $spent = microtime(true) - $start; file_put_contents($log_file, date('c') . " [clone] done(spent: $spent)\n", FILE_APPEND); echo json_encode(array('error' => false, 'port' => $port)); break; case 'restart-web': list(, $project_name, $id) = explode(' ', getenv('SSH_ORIGINAL_COMMAND')); $start = microtime(true); if (!$id = intval($id)) { error('invalid id: ' . $id); } $log_file = "/srv/chroot/{$id}.log"; if (!$project = Project::find_by_name(strval($project_name))) { return error('project not found: ' . $project_name); } file_put_contents($log_file, date('c') . " [restart-web] loading project variables\n", FILE_APPEND); $params = array('project=' . escapeshellcmd($project->name)); $params[] = 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'; foreach ($project->variables as $variable) { if (strpos($variable->key, 'file:') === 0) { list($filepath, $content) = explode("\n", $variable->getValue(), 2); $tmpfile = tempnam('/tmp/', 'config-'); chmod($tmpfile, 0644); file_put_contents($tmpfile, $content); $ret = exec_m2(sprintf("docker cp %s c-%d:%s", escapeshellarg($tmpfile), $id, escapeshellarg($filepath))); unlink($tmpfile); } else { $params[] = escapeshellcmd($variable->key) . '=' . escapeshellarg($variable->getValue()); } } $uid = 20000 + $id; if (file_exists('/srv/code/hisoku/dockers/generated-config/')) { $ret = exec_m2("docker cp /srv/code/hisoku/dockers/generated-config/* c-{$id}:/"); } $ret = exec_m2("docker exec c-{$id} mkdir /srv/logs"); file_put_contents($log_file, date('c') . " [restart-web] start-web.sh\n", FILE_APPEND); $ret = exec_m2("docker exec c-{$id} env " . implode(" ", $params) . " /start-web.sh", $ret); if ($ret['code']) { $ret['error'] = true; $ret['message'] = "docker exec start-web failed"; file_put_contents($log_file, date('c') . " [restart-web] code={$ret} error: " . json_encode($ret) . "(spent: $spent)\n", FILE_APPEND); echo json_encode($ret); exit($ret['code']); break; } $spent = microtime(true) - $start; file_put_contents($log_file, date('c') . " [restart-web] code={$ret} done(spent: $spent)\n", FILE_APPEND); echo json_encode(array('error' => false, 'port' => $port)); break; case 'run': list(, $project_name, $id, $run_cmd, $without_status) = explode(' ', getenv('SSH_ORIGINAL_COMMAND')); $start = microtime(true); if (!$id = intval($id)) { error('invalid id: ' . $id); } $log_file = "/srv/chroot/{$id}.log"; if (!$project = Project::find_by_name(strval($project_name))) { return error('project not found: ' . $project_name); } file_put_contents($log_file, date('c') . " [run] run project: {$project_name} command: \"" . urldecode($run_cmd) . "\"\n", FILE_APPEND); file_put_contents($log_file, date('c') . " [run] loading project variables\n", FILE_APPEND); $params = array('project=' . escapeshellarg($project->name)); foreach ($project->variables as $variable) { if (strpos($variable->key, 'file:') === 0) { list($filepath, $content) = explode("\n", $variable->getValue(), 2); $tmpfile = tempnam('/tmp/', 'config-'); file_put_contents($tmpfile, $content); $ret = exec_m2(sprintf("docker cp %s c-%d:%s", escapeshellarg($tmpfile), $id, escapeshellarg($filepath))); unlink($tmpfile); } else { $params[] = escapeshellcmd($variable->key) . '=' . escapeshellarg($variable->getValue()); } } $params[] = 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'; $run_cmd = 'cd /srv/web; ' . urldecode($run_cmd); file_put_contents($log_file, date('c') . " [run] start\n", FILE_APPEND); $uid = 20000 + $id; if (getenv('TERM')) { $term_opt = ' -i -t'; $params[] = 'TERM=' . escapeshellarg(getenv('TERM')); } else { $term_opt = ''; } $cmd = "docker exec {$term_opt} c-{$id} env -i " . implode(" ", $params) . " sh -c " . escapeshellarg($run_cmd); $ret = 0; passthru($cmd, $ret); $spent = microtime(true) - $start; file_put_contents($log_file, date('c') . " [run] done(spent: {$spent})\n", FILE_APPEND); if (!$without_status) { echo "\n" . json_encode(array( 'id' => $id, 'code' => $ret, 'start' => date('c', $start), 'spent' => $spent, 'term' => getenv('TERM'), )); } break; case 'check_alive': list(, $id) = explode(' ', getenv('SSH_ORIGINAL_COMMAND')); if (!$id = intval($id)) { error('invalid id: ' . $id); } $uid = 20000 + $id; $jobs = array(); $output = trim(`docker top c-{$id} -o pid,start`); if (!$output) { echo json_encode(array('error' => true)); exit; } foreach (array_slice(explode("\n", $output), 1) as $line) { list($pid, $start) = preg_split("/\s+/", $line, 2); $jobs[$pid] = new StdClass; $jobs[$pid]->pid = $pid; $jobs[$pid]->start_time = strtotime($start); } $output = trim(`docker top c-{$id} -o pid,comm`); foreach (array_slice(explode("\n", $output), 1) as $line) { list($pid, $comm) = preg_split("/\s+/", $line, 2); $jobs[$pid]->comm = trim($comm); } $output = trim(`docker top c-{$id} -o pid,cmd`); foreach (array_slice(explode("\n", $output), 1) as $line) { list($pid, $cmd) = preg_split("/\s+/", $line, 2); $jobs[$pid]->cmdline = trim($cmd); } $jobs = array_filter($jobs, function($job){ return $job->comm != 'systemd'; }); $jobs = array_values($jobs); echo json_encode($jobs); break; case 'shutdown': list(, $id) = explode(' ', getenv('SSH_ORIGINAL_COMMAND')); if (!$id = intval($id)) { error('invalid id: ' . $id); } $log_file = "/srv/chroot/{$id}.log"; $start = microtime(true); file_put_contents($log_file, date('c') . " [shutdown] start\n", FILE_APPEND); file_put_contents($log_file, date('c') . " [shutdown] /shutdown.sh\n", FILE_APPEND); $ret = exec_m2("docker stop c-{$id}"); if ($ret['code']) { $ret['error'] = true; $ret['message'] = "docker stop c-{$id} failed"; file_put_contents($log_file, date('c') . " [shutdown] code={$ret['code']} error: " . json_encode($ret) . "(spent: $spent)\n", FILE_APPEND); echo json_encode($ret); break; } $ret = exec_m2("docker rm -f c-{$id}"); if ($ret['code']) { $ret['error'] = true; $ret['message'] = "docker rm c-{$id} failed"; file_put_contents($log_file, date('c') . " [shutdown] code={$ret['code']} error: " . json_encode($ret) . "(spent: $spent)\n", FILE_APPEND); echo json_encode($ret); break; } exec_m2("docker network disconnect -f bridge c-{$id}"); echo json_encode(array('error' => false, 'port' => $port)); $spent = microtime(true) - $start; file_put_contents($log_file, date('c') . " [shutdown] done(spent: {$spent})\n", FILE_APPEND); if (file_exists("/srv/chroot/{$id}.project")) { unlink("/srv/chroot/{$id}.project"); } break; default: return error('unknown command: ' . $method); } return; } main(); <file_sep>/cron/1min/check-500 #!/usr/bin/env php <?php include(__DIR__ . '/../../webdata/init.inc.php'); $log_file = '/srv/logs/scribed/500-log/500-log_current'; $cursor_file = '/tmp/check-500.cursor'; if (!file_exists($cursor_file)) { file_put_contents($cursor_file, sprintf("%s %d", readlink($log_file), filesize($log_file))); exit; } list($real_file, $cursor) = explode(' ', trim(file_get_contents($cursor_file))); if ($real_file != readlink($log_file)) { file_put_contents($cursor_file, sprintf("%s %d", readlink($log_file), filesize($log_file))); exit; } $fp = fopen($log_file, 'r'); fseek($fp, $cursor); $count = 0; $logs = ''; error_log('checking'); while (false !== ($log = fgets($fp))) { $logs .= trim($log) . "\n"; $count ++; } fclose($fp); if ($count >= 10) { Hisoku::alert("500 warning", "一分鐘內出現 {$count} 個 5xx requests\n" . $logs); } file_put_contents($cursor_file, sprintf("%s %d", readlink($log_file), filesize($log_file))); <file_sep>/cron/1min/reset-init-base #!/usr/bin/php <?php // 把 /srv/chroot/1xxx 建立好,留著拿來做 project_base 用的 // chroot 有五個狀態 // 1. notexists (根本不存在): 不存在 /srv/chroot/1xxx/ 資料夾 // 2. initing (建立中): 存在 /srv/chroot/1xxx.initing 和 /srv/chroot/1xxx/ 資料夾 // 3. available (可使用): 只存在 /srv/chroot/1xxx/ 資料夾 // 4. using (正在使用): 存在 /srv/chroot/1xxx.locking 和 /srv/chroot/1xxx/ 資料夾 // 5. used (用完了): 存在 /srv/chroot/1xxx.used 和 /srv/chroot/1xxx/ 資料夾 // // 這個 script 只需要對 1 和 5 做事就行了 // define('LOCK_FILE', '/tmp/hisoku-reset-init-base'); $fp = fopen(LOCK_FILE, 'w+'); if (!flock($fp, LOCK_EX | LOCK_NB)) { throw new Exception(LOCK_FILE . ' is locking'); } ftruncate($fp, 0); // truncate file fwrite($fp, getmypid()); fflush($fp); // flush output before releasing the lock include(__DIR__ . '/../../webdata/init.inc.php'); class Initer { public function initChroot($id) { // 只有 notexists 和 used 兩個狀況需要做事 if (file_exists("/srv/chroot/{$id}.lock")) { $fp = fopen("/srv/chroot/{$id}.lock", 'w+'); // 被 lock 住了,先不用管他 if (!flock($fp, LOCK_EX | LOCK_NB)) { return; } // 已經沒有被 lock 了,換成 used 狀態 touch("/srv/chroot/{$id}.used"); flock($fp, LOCK_UN); // release the lock fclose($fp); unlink("/srv/chroot/{$id}.lock"); } elseif (file_exists("/srv/chroot/{$id}") and !file_exists("/srv/chroot/{$id}.used")) { return; } error_log("initing node $id..."); // 先建立 initing file ,表示在 init 中 touch("/srv/chroot/{$id}.initing"); // 先清空舊檔案 system("rm -rf /srv/chroot/{$id} /srv/chroot/{$id}.used"); // init 新的 chroot $session = ssh2_connect('localhost', 22); $ret = ssh2_auth_pubkey_file($session, 'root', WEB_PUBLIC_KEYFILE, WEB_KEYFILE); $stream = ssh2_exec($session, "init {$id}"); stream_set_blocking($stream, true); stream_get_contents($stream); // 把修改時間全改成 2000/1/1 以方便之後找出 diff system("find /srv/chroot/{$id} -not \( -path /srv/chroot/{$id}/proc -prune \) -exec touch --no-dereference --date=20000101 {} \;"); // 完工,把 initing 拿掉進入 available 狀態 unlink("/srv/chroot/{$id}.initing"); } public function error($message) { throw new Exception($message); } public function main() { if (0 !== posix_getuid()) { return $this->error("Muse be root"); } for ($id = 1000; $id < 1010; $id ++) { $this->initChroot($id); } } } $i = new Initer; $i->main(); flock($fp, LOCK_UN); // release the lock fclose($fp); unlink(LOCK_FILE); <file_sep>/webdata/models/AWS.php <?php class AWS { public static function getHostIP() { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, 'http://169.254.169.254/latest/meta-data/local-hostname'); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); if (!$hostname = curl_exec($curl)) { trigger_error(curl_error($curl)); return false; } curl_close($curl); // match ip-10-0-0-xx if (preg_match('#^ip-([0-9-]*)$#', $hostname, $matches)) { return ip2long(str_replace('-', '.', $matches[1])); } if (!$ip = gethostbyname($hostname)) { return false; } return ip2long($ip); } } <file_sep>/dockers/gen.php <?php include(__DIR__ . '/../webdata/init.inc.php'); if (file_exists(__DIR__ .'/generated-config')) { system('rm -rf ' . __DIR__ . '/generated-config'); } mkdir(__DIR__ . '/generated-config'); // add loadbalancer ip for apache proxy mkdir(__DIR__ . '/generated-config/etc/apache2/sites-enabled/', 0777, true); $content = ''; foreach (Hisoku::getLoadBalancers() as $ip) { $content .= "RemoteIPTrustedProxy {$ip}/32\n"; } file_put_contents(__DIR__ . '/generated-config/etc/apache2/sites-enabled/loadbalancer.conf', $content); <file_sep>/cron/1min/updatenodes.php #!/usr/bin/env php <?php define('LOCK_FILE', '/tmp/hisoku-updatenodes'); $fp = fopen(LOCK_FILE, 'w+'); if (!flock($fp, LOCK_EX | LOCK_NB)) { throw new Exception(LOCK_FILE . ' is locking'); } ftruncate($fp, 0); // truncate file fwrite($fp, getmypid()); fflush($fp); // flush output before releasing the lock include(__DIR__ . '/../../webdata/init.inc.php'); WebNode::updateNodeInfo(); flock($fp, LOCK_UN); // release the lock fclose($fp); unlink(LOCK_FILE); <file_sep>/scripts/build-project-base/python27.php #!/usr/bin/env php <?php // 每次 post-commit 之後,將 requirements.txt 內的東西先抓好 // 包成一個 tar gz ,之後就解開 tar gz 就好了,速度超快! // // 每次 post-commit 時 // 1. 先找 /srv/chroot/1000~1999 之間是否有可以用的 chroot // 2. 找到後,在 /srv/chroot/1xxx.lock 加上 lock 避免衝突 // 3. 把 /srv/code/images/dev-pythonXX.tar.gz 解壓縮進 chroot 中 // 4. 把所有檔案的修改日期都改成 2000/01/01 ,以方便作完 pip 可以找出新增加的檔 // 5. 把需要的 requirements.txt 搬到 /srv/chroot/1xxx/ 下面 // 6. pip install 裝進 chroot 內 // 7. 找出新裝的東西,搬出來放進 tar gz 中,完工 // // 之後要 clone 的時候 // 1. 把 tar gz 解開就好了 // // 用法 php python-prebuild.php [requirements.txt file] // define('TEMPLATE', 'python27'); class Prebuilder { public function error($message) { die($message); } public function findAvailableRootAndLock() { $shuffled_roots = glob('/srv/chroot/1???'); shuffle($shuffled_roots); foreach ($shuffled_roots as $root) { $lock_file = "{$root}.lock"; if (file_exists("{$root}.initing") or file_exists("{$root}.used")) { continue; } $fp = fopen($lock_file, 'w+'); if (!flock($fp, LOCK_EX | LOCK_NB)) { continue; } $this->fp = $fp; return $root; } return $this->error("No avaiabled root"); } public function main($req_file, $force_rebuild = false) { if (0 !== posix_getuid()) { return $this->error("Muse be root"); } if (!file_exists($req_file)) { return $this->error("File not found"); } $project_file = '/tmp/project-' . TEMPLATE . '-' . md5_file($req_file); // 已經有了,不需要再做了 if (!$force_rebuild and file_exists($project_file . '.tar.gz')) { return; } if (file_exists($project_file . '.tar.gz')) { unlink($project_file . '.tar.gz'); } // 先找可以用的 chroot error_log('find available root...'); $root = $this->findAvailableRootAndLock(); error_log('untar python.tar.gz...'); // 把 python package 解進去 system("tar zxf /srv/code/images/lang-" . TEMPLATE . ".tar.gz --directory={$root}"); error_log('find diff file...'); // 把新解進去的檔案都改成 2001/1/1 system("find {$root} -printf '%TY%Tm%Td,,,%p\n' | grep -v ',,,/proc' | grep -v '^20000101' | awk -F,,, '{print \"\\\"\"$2\"\\\"\"}' | xargs -n 100 touch --no-dereference --date=20000101"); error_log('pip installing ...'); // 安裝 python package copy($req_file, $root . "/requirements.txt"); $cmd = "chroot {$root} /usr/local/bin/pip --log /srv/logs/pip.log install --requirement /requirements.txt"; $fp = proc_open($cmd, array(0 => array('pipe', 'r'), 1 => array('pipe' , 'w'), 2 => array('pipe', 'w')), $pipes, NULL, array('PYTHONUNBUFFERED' => 'x')); while (false !== ($line = fgets($pipes[1], 4096))) { if (feof($pipes[1])) { break; } if ($line === '') { continue; } if (0 === strpos($line, 'Downloading/unpacking')) { echo trim(str_replace($req_file, 'requirements.txt', $line)) . "\n"; } } $status = proc_get_status($fp); if ($status['exitcode'] != 0) { // TODO: 要 log 起來錯誤原因參考 return $this->error('build failed'); } proc_close($fp); unlink($root . '/requirements.txt'); system("rm -rf {$root}/tmp"); // 把檔案弄進去 chdir($root); error_log('build tar.gz...'); // TODO: 處理過程中會不會處理到一半的檔案被人拿走... // 處理檔案 system("find . -type f -printf \"%TY%Tm%Td %p\n\" | grep -v ',,,/proc' | grep -v '^20000101' | awk '{print $2}' | xargs -n 100 tar -uf " . escapeshellarg($project_file . '.tar')); // 處理 symbolic link system("find . -type l -printf \"%TY%Tm%Td %p\n\" | grep -v ',,,/proc' | grep -v '^20000101' | awk '{print $2}' | xargs -n 100 tar -uf " . escapeshellarg($project_file . '.tar')); system("gzip --force {$project_file}.tar"); // 標示為已用完,並解除 lock touch("{$root}.used"); flock($this->fp, LOCK_UN); // release the lock fclose($this->fp); unlink("{$root}.lock"); } } $p = new Prebuilder; $p->main($_SERVER['argv'][1], array_key_exists(2, $_SERVER['argv']) ? true : false); <file_sep>/webdata/models/GitHelper.php <?php class GitHelper { public static function system_without_error($command) { $return_var = 0; system($command, $return_var); if ($return_var != 0) { throw new Exception("Run {$command} failed, code: {$return_var}"); } } public static function getGitFileInfo($file_name, $branch = 'HEAD') { $ls_tree_cmd = "git ls-tree {$branch} " . $file_name; $ls_result = trim(`$ls_tree_cmd`); // Got '100644 blob 433ee4e878d82d375ea2311dcd4f0046a8eb12b6 requirements.txt' if (!trim($ls_result)) { return null; } list($perm, $type, $object_id, $file) = preg_split('/\s+/', trim($ls_result)); $ret = new stdClass; $ret->perm = $perm; $ret->type = $type; $ret->object_id = $object_id; $ret->file = $file; return $ret; } public static function getGitFileContent($file_name, $branch = 'HEAD') { $show_cmd = "git show {$branch}:{$file_name}"; $show_result = `$show_cmd`; return $show_result; } public static function getLatestCommitLog($project, $branch = 'HEAD') { // XXX: should through ssh $absolute_path = '/srv/git/git/' . $project->id . '.git'; if (!file_exists($absolute_path)) { throw new Exception('project not found: ' . $project->name); } chdir($absolute_path); $git_log_cmd = `git log -n 3 {$branch}`; return trim($git_log_cmd); } /** * buildDockerProjectBase 建立這個 project 自己的額外檔案,這個 method 必需以 git 帳號身份執行 * * @param mixed $project * @access public * @return void */ public static function buildDockerProjectBase($project, $branch = 'HEAD', $clean_build = false, $base = 'middle2') { $absolute_path = getenv('HOME') . '/git/' . $project->id . '.git'; if (!file_exists($absolute_path)) { throw new Exception('project not found: ' . $project->name); } chdir($absolute_path); $rev_parse_cmd = "git rev-parse {$branch}"; $commit_id = trim(`$rev_parse_cmd`); $apt_packages = explode("\n", self::getGitFileContent('Aptfile', $branch)); if ('' == trim(implode('', $apt_packages))) { $apt_packages = array(); } $actions = array(); foreach (array('requirements.txt', 'Gemfile', 'package.json', 'composer.json') as $file) { if ($info = self::getGitFileInfo($file, $branch)) { $actions[] = array( 'file' => $file, 'info' => $info, ); } } // pull from remote image $docker_registry = getenv('DOCKER_REGISTRY'); // check container is exists $cmd = "docker inspect container-{$project->name}"; $obj = json_decode(`$cmd`)[0]; if ($obj) { self::system_without_error("docker rm -f container-{$project->name}"); } try { if ($clean_build) { throw new Exception("clean build"); } self::system_without_error("docker --config /srv/config/docker pull {$docker_registry}/image-{$project->name}"); $cmd = "docker inspect {$docker_registry}/image-{$project->name}"; $obj = json_decode(`$cmd`)[0]; if ($obj->Comment == $commit_id) { return $commit_id; } self::system_without_error("docker create --name container-{$project->name} {$docker_registry}/image-{$project->name} init"); } catch (Exception $e) { // image is not on remote self::system_without_error("docker create --name container-{$project->name} {$base} init"); } self::system_without_error("docker start container-{$project->name}"); self::system_without_error("docker exec container-{$project->name} mkdir -p /srv/web"); self::system_without_error("docker exec container-{$project->name} find /srv/web/ -not -path '/srv/web/node_modules/*' -not -path '/srv/web/node_modules' -not -path '/srv/web/' -delete"); self::system_without_error("git archive --format=tar {$branch}| docker exec -i container-{$project->name} tar -xf - -C /srv/web/"); if (count($apt_packages)) { $apt_install_cmd = "apt-get update -y"; self::system_without_error("docker exec --tty container-{$project->name} {$apt_install_cmd}"); $apt_install_cmd = "apt-get upgrade -y"; self::system_without_error("docker exec --tty container-{$project->name} {$apt_install_cmd}"); $apt_install_cmd = "apt-get install -y " . implode(' ', $apt_packages); self::system_without_error("docker exec --tty container-{$project->name} {$apt_install_cmd}"); } $config = json_decode($project->config) ?: new StdClass; if ( (property_exists($config, 'no-build') or !$config->{'no-build'}) and self::getGitFileContent('m2-build.sh', $branch) ) { self::system_without_error("docker exec --tty container-{$project->name} env -i PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin sh -c 'cd /srv/web; ./m2-build.sh'"); } foreach ($actions as $action) { $info = $action['info']; try { if ($action['file'] == 'requirements.txt') { self::system_without_error("docker exec --tty container-{$project->name} pip3 install --requirement /srv/web/requirements.txt"); } elseif ($action['file'] == 'Gemfile') { self::system_without_error("docker exec --tty container-{$project->name} sh -c 'cd /srv/web; gem install bundler'"); self::system_without_error("docker exec --tty container-{$project->name} sh -c 'cd /srv/web; bundle install --without development test'"); } elseif ($action['file'] == 'package.json') { self::system_without_error("docker exec --tty container-{$project->name} env -i PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin sh -c 'cd /srv/web; npm install --unsafe-perm'"); } elseif ($action['file'] == 'composer.json') { self::system_without_error("docker exec --tty container-{$project->name} sh -c 'cd /srv/web; composer install'"); } } catch (Exception $e) { self::system_without_error("docker stop container-{$project->name}"); //self::system_without_error("docker rm container-{$project->name}"); throw $e; } } self::system_without_error("docker stop container-{$project->name}"); self::system_without_error("docker commit --message {$commit_id} container-{$project->name} {$docker_registry}/image-{$project->name}"); self::system_without_error("docker --config /srv/config/docker push {$docker_registry}/image-{$project->name}"); self::system_without_error("docker rm container-{$project->name}"); return $commit_id; } } <file_sep>/test-repo/check-node-server #!/usr/bin/env php <?php $host = $_SERVER['argv'][1]; $test_id = 5566; foreach (glob("test-*") as $test_path) { // skip shutdown error `ssh root@{$host} shutdown {$test_id}`; // init $ret = json_decode(`ssh root@{$host} init {$test_id}`); if (!$ret) { throw new Exception("init {$host} failed, return invalid json"); } if ($ret->error) { throw new Exception("init {$host} failed, message: " . $ret->message); } // clone $ret = json_decode(`ssh root@{$host} clone {$test_path} {$test_id}`); if (!$ret) { throw new Exception("clone {$host} failed, return invalid json"); } if ($ret->error) { throw new Exception("clone {$host} failed, message: " . $ret->message); } // start-web $ret = json_decode(`ssh root@{$host} restart-web {$test_path} {$test_id}`); if (!$ret) { throw new Exception("restart-web {$host} failed, return invalid json"); } if ($ret->error) { throw new Exception("restart-web {$host} failed, message: " . $ret->message); } // check web $cases = json_decode(file_get_contents("{$test_path}/test-case.json")); foreach ($cases as $case) { $curl = curl_init("http://{$host}:" . (20000 + $test_id) . $case->path); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $ret = curl_exec($curl); if (trim($ret) != $case->result) { throw new Exception("testing {$test_path} {$case->path} failed"); } } // shutdown $ret = json_decode(`ssh root@{$host} shutdown {$test_id}`); if (!$ret) { throw new Exception("init {$host} failed, return invalid json"); } if ($ret->error) { throw new Exception("init {$host} failed, message: " . $ret->message); } } echo "All tests pass\n"; <file_sep>/webdata/models/EAV.php <?php class EAV extends Pix_Table { public function init() { $this->_name = 'eav'; $this->_primary = array('table', 'id', 'key'); $this->_columns['table'] = array('type' => 'varchar', 'size' => 16); $this->_columns['id'] = array('type' => 'int'); $this->_columns['key'] = array('type' => 'varchar', 'size' => 32); $this->_columns['value'] = array('type' => 'text'); } } <file_sep>/webdata/controllers/UserController.php <?php class UserController extends Pix_Controller { public function init() { if (!$this->user = Hisoku::getLoginUser()) { return $this->rediect('/'); } $this->view->user = $this->user; if (getenv('TRY_MODE')) { $this->try_mode = getenv('TRY_MODE'); $this->view->try_mode = $this->try_mode; $this->project_limit = 3; $this->view->project_limit = $this->project_limit; } } public function indexAction() { $this->view->project_count = Project::search(array('created_by' => $this->user->id))->count(); } public function deletekeyAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: error return $this->redirect('/'); } list(, /*user*/, /*deletekey*/, $id) = explode('/', $this->getURI()); if (!$userkey = $this->user->keys->search(array('id' => $id))->first()) { // TODO: error return $this->redirect('/'); } $userkey->delete(); return $this->redirect('/'); } public function addkeyAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: error return $this->redirect('/'); } try { $this->user->addKey($_POST['key']); } catch (InvalidArgumentException $e) { return $this->alert('Failed. Message: ' . $e->getMessage(), '/'); } catch (Pix_Table_DuplicateException $e) { // TODO: error } return $this->redirect('/'); } public function addprojectAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: error return $this->redirect('/'); } if ($this->try_mode) { $project_count = Project::search(array('created_by' => $this->user->id))->count(); if (intval($project_count) >= $this->project_limit) { return $this->alert('目前為試用模式,project 數量上限為 ' . $this->project_limit, '/'); } } try { $project = $this->user->addProject(); } catch (InvalidException $e) { // TODO: error return $this->redirect('/'); } catch (Pix_Table_DuplicateException $e) { // TODO: error return $this->redirect('/'); } $project->setEAV('note', strval($_POST['name'])); return $this->redirect('/'); } public function changepasswordAction() { if (Hisoku::getStoken() != $_POST['sToken']) { return $this->alert('Error', '/'); } if (!$this->user->verifyPassword($_POST['oldpassword'])) { Logger::log(array(array('category' => 'login', 'message' => time() . " change-password-wrong-password {$_SERVER['REMOTE_ADDR']} user=" . urlencode($this->user->name) . ",agent=" . urlencode($_SERVER['HTTP_USER_AGENT'])))); return $this->alert('Wrong password', '/'); } if ($_POST['newpassword'] != $_POST['newpassword2']) { return $this->alert('Password mismatch', '/'); } if (strlen($_POST['newpassword']) < 4) { return $this->alert('Password is too short', '/'); } $this->user->setPassword($_POST['newpassword']); Logger::log(array(array('category' => 'login', 'message' => time() . " change-password {$_SERVER['REMOTE_ADDR']} user=" . urlencode($this->user->name) . ",agent=" . urlencode($_SERVER['HTTP_USER_AGENT'])))); return $this->alert('success!', '/'); } public function nodbAction() { return $this->alert('沒有任何 database 可用', '/'); } } <file_sep>/webdata/models/Elastic.php <?php class Elastic { protected static $_url; protected static $_user; protected static $_password; public static function login($url, $user, $password) { self::$_url = $url; self::$_user = $user; self::$_password = $password; } public static function esQuery($url, $method = 'GET', $data = null) { $curl = curl_init(self::$_url . $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); if ($method != 'GET') { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method); } curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', ]); curl_setopt($curl, CURLOPT_USERPWD, self::$_user . ':' . self::$_password); if (!is_null($data)) { curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } $content = curl_exec($curl); if ($content === false) { throw new Exception('curl_exec error: ' . curl_error($curl)); } $info = curl_getinfo($curl); curl_close($curl); $ret = json_decode($content); if (is_object($ret) and property_exists($ret, 'error')) { throw new Exception(json_encode($ret->error->root_cause), $ret->status); } return $ret; } public static function getUsers() { $users = []; $roles = []; $ret = new StdClass; foreach (self::esQuery('/_security/user/') as $data) { if (!preg_match('#.*-.*-.*#', $data->username)) { continue; } $users[$data->username] = new StdClass; $users[$data->username]->user_name = $data->username; foreach ($data->roles as $role) { $roles[$role] = $role; } } foreach (self::esQuery('/_security/role/') as $role_name => $data) { if (!array_key_exists($role_name, $roles)) { continue; } $users[$role_name]->prefix = $data->indices[0]->names[0]; } return $users; } public static function createUser($user, $password, $prefix) { self::esQuery('/_security/role/' . $user, 'PUT', json_encode([ 'cluster' => ['all'], 'indices' => [ [ 'names' => [ $prefix . '*' ], "privileges" => ["all"], ], ], ])); return self::esQuery('/_security/user/' . $user, 'PUT', json_encode([ 'username' => $user, 'password' => $<PASSWORD>, 'roles' => [$user], ])); } public static function dropUser($user) { self::esQuery('/_security/user/' . $user, 'DELETE', ''); self::esQuery('/_security/role/' . $user, 'DELETE', ''); } } <file_sep>/webdata/models/WebNodeEAV.php <?php class WebNodeEAV extends Pix_Table { public function init() { $this->_name = 'webnode_eav'; $this->_primary = array('ip', 'port', 'key'); $this->_columns['ip'] = array('type' => 'int', 'unsigned' => true); $this->_columns['port'] = array('type' => 'int'); $this->_columns['key'] = array('type' => 'varchar', 'size' => 32); $this->_columns['value'] = array('type' => 'text'); } } <file_sep>/webdata/models/Hisoku.php <?php class Hisoku { public static function getIPsByGroup($group) { $ips = array(); foreach (Machine::getMachinesByGroup($group) as $machine) { $ips[] = long2ip($machine->ip); } return $ips; } public static function getDevServers() { return self::getIPsByGroup('dev'); } public static function getLoadBalancers() { return self::getIPsByGroup('loadbalancer'); } public static function getMySQLServers() { return self::getIPsByGroup('mysql'); } public static function getNodeServers() { return self::getIPsByGroup('nodes'); } public static function getPgSQLServers() { return self::getIPsByGroup('pgsql'); } public static function getSearchServers() { return self::getIPsByGroup('search'); } public static function getLoginUser() { if ($u = User::find(intval(Pix_Session::get('user')))) { return $u; } return false; } public static function getStoken() { if (!$sToken = Pix_Session::get('sToken')) { $sToken = crc32(uniqid()); Pix_Session::set('sToken', $sToken); } return $sToken; } public static function uniqid($length) { $set = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $ret = ''; for ($i = 0; $i < $length; $i ++) { $ret .= $set[rand(0, strlen($set) - 1)]; } return $ret; } public static function alert($title, $body) { if (!class_exists('AmazonSNS')) { define('AWS_DISABLE_CONFIG_AUTO_DISCOVERY', true); include(__DIR__ . '/../stdlibs/sdk-1.6.0/sdk.class.php'); if (!getenv('HEALTHCHECK_KEY') or !getenv('HEALTHCHECK_SECRET')) { throw new Exception('env HEALTHCHECK_KEY & HEALTHCHECK_SECRET not found'); } CFCredentials::set(array( 'development' => array( 'key' => getenv('HEALTHCHECK_KEY'), 'secret' => getenv('HEALTHCHECK_SECRET'), ), )); } $sns = new AmazonSNS(); $sns->set_region(AmazonSNS::REGION_TOKYO); $sns->publish('arn:aws:sns:ap-northeast-1:391093844476:Hisoku-Health', $body, array('Subject' => $title)); } } <file_sep>/test-repo/README.md test-repo ========= There are some testing repositories in this directory. <file_sep>/scripts/change-ip #!/usr/bin/env php <?php $test_mode = true; $from = $to = null; if (count($_SERVER['argv']) > 2) { $from = $_SERVER['argv'][1]; $to = $_SERVER['argv'][2]; } if (!filter_var($from, FILTER_VALIDATE_IP) or !filter_var($to, FILTER_VALIDATE_IP)) { throw new Exception("Usage: ./change-ip From-IP To-IP"); } include(__DIR__ . '/../webdata/init.inc.php'); $restart_project_ids = array(); $effected_magic_prefixes = array(); foreach (array('Addon_Elastic', 'Addon_MySQLDB', 'Addon_PgSQLDB') as $table_name) { $table = Pix_Table::getTable($table_name); foreach ($table->search(array('host' => $from)) as $addon) { $effected_magic_prefixes[] = $table_name . ':' . $addon->id; error_log("change $table_name addon(id={$addon->id}): " . json_encode($addon->toArray())); if ($test_mode) { continue; } $addon->update(array('host' => $to)); } } foreach ($effected_magic_prefixes as $effected_magic_prefix) { foreach (ProjectVariable::search("is_magic_value = 1 AND `value` LIKE '{$effected_magic_prefix}:%'") as $pv) { $restart_project_ids[$pv->project_id] = true; error_log("reset project_id={$pv->project_id} because magic value {$pv->key} is change: " .json_encode($pv->toArray())); } } foreach (ProjectVariable::search("is_magic_value = 0 AND `value` LIKE '%{$from}%'") as $pv) { error_log("reset project_id={$pv->project_id} because value {$pv->key} is change: " .json_encode($pv->toArray())); unset($restart_project_ids[$pv->project_id]); if ($test_mode) { continue; } $pv->update(array( 'value' => str_replace($from, $to, $pv->value), )); } foreach (WebNode::search(1)->searchIn('project_id', array_keys($restart_project_ids)) as $webnode) { error_log(sprintf("reset webnode %s:%d", $webnode->ip, $webnode->port)); if ($test_mode) { continue; } $webnode->markAsUnused('change project variable'); } <file_sep>/cron/1day/rotate-log #!/bin/sh cd /srv/logs/scribed/ find -size 0 -mtime +10 -delete -print find -mtime +3 -not -name '*.gz' -type f -print -exec gzip {} \; find -mtime +90 -name '*-error-*.gz' -type f -print -delete <file_sep>/webdata/models/Project.php <?php class ProjectRow extends Pix_Table_Row { public function isAdmin($user) { return count($this->members->search(array('is_admin' => 1, 'user_id' => $user->id))); } public function isMember($user) { return count($this->members->search(array('user_id' => $user->id))); } public function getFirstDomain() { // TODO: add custom domain return $this->name . USER_DOMAIN; } public function getEAVs() { return EAV::search(array('table' => 'Project', 'id' => $this->id)); } public function getTemplate() { if ($template = $this->getEAV('template')) { return $template; } return 'mixed'; } public function preSave() { $this->commit = substr($this->commit, 0, 32); } /** * getCronNode 取得一個新的 Cron node * * @access public * @return void */ public function getCronNode() { // 先拿 wait node 來用 if ($node = WebNode::search(array('project_id' => $this->id, 'commit' => $this->commit, 'status' => WebNode::STATUS_WAIT))->first()) { $db = WebNode::getDB(); $db->query(sprintf("UPDATE webnode SET `status` = %d WHERE `ip` = %d AND `port` = %d AND `project_id` = %d AND `commit` = '%s' AND `status` = %d LIMIT 1", WebNode::STATUS_CRONPROCESSING, $node->ip, $node->port, $this->id, $this->commit, WebNode::STATUS_WAIT)); // 如果上面那個動作沒有修改成功,表示遇到 race condition 兩個 job 同時改到一個,那就跳過重來 if (!$db->getAffectedRows()) { return $this->getCronNode(); } return $node; } $project_config = json_decode($this->config); $project_group = property_exists($project_config, 'node-group') ? $project_config->{'node-group'} : ''; WebNode::getDb()->query("BEGIN"); $node_pools = array(); foreach (WebNode::search(array('project_id' => 0, 'status' => WebNode::STATUS_UNUSED)) as $webnode) { $node_pools[] = $webnode; } // random pick nodes, if project has node-group, pick same group webnodes first // if project has no node-group, pick webnodes without group first usort($node_pools, function($a, $b) use ($project_group) { $a_config = json_decode($a->config); $b_config = json_decode($b->config); $a_group = property_exists($a_config, 'node-group') ? $a_config->{'node-group'} : ''; $b_group = property_exists($b_config, 'node-group') ? $b_config->{'node-group'} : ''; if ($project_group) { // same group first if ($project_group == $a_group) { return -1; } if ($project_group == $b_group) { return 1; } // then no group if ($a_group == '') { return -1; } if ($b_group == '') { return 1; } } else { // no group first if ($a_group == '') { return -1; } if ($b_group == '') { return 1; } } return rand(-1, 1); }); $random_node = array_shift($node_pools); if (!$random_node) { WebNode::getDb()->query("ROLLBACK"); throw new Exception('free node not found'); } $random_node->update(array( 'project_id' => $this->id, 'commit' => $this->commit, 'start_at' => time(), 'access_at' => 0, 'status' => WebNode::STATUS_CRONPROCESSING, )); WebNode::getDb()->query("COMMIT"); $node_id = $random_node->port - 20000; $ip = long2ip($random_node->ip); $session = ssh2_connect($ip, 22); $ret = ssh2_auth_pubkey_file($session, 'root', WEB_PUBLIC_KEYFILE, WEB_KEYFILE); $stream = ssh2_exec($session, "clone {$this->name} {$node_id}"); stream_set_blocking($stream, true); $ret = stream_get_contents($stream); return $random_node; } /** * getWebNodes 取得現在 Project 有哪些 Web node, 如果沒有會自動產生 * * @return array WebNode */ public function getWebNodes($ip = null, $new = false) { $c = new Pix_Cache; if (is_null($ip)) { // find current $nodes = WebNode::search(array( 'project_id' => $this->id, 'status' => WebNode::STATUS_WEBNODE, 'commit' => $this->commit, )); if (!$new and count($nodes)) { return $nodes; } // 如果處理中就等 0.1 秒後再說 if ($c->get("Project:processing:{$this->id}")) { // sleep 0.1s usleep(100000); return $this->getWebNodes($ip, $new); } } $c->set("Project:processing:{$this->id}", time()); $choosed_nodes = array(); while (true) { $node_pools = WebNode::search(array('project_id' => 0, 'status' => WebNode::STATUS_UNUSED)); if (!is_null($ip)) { $node_pools = $node_pools->search(array('ip' => ip2long($ip))); } $free_nodes_count = count($node_pools); if (!$free_nodes_count) { // TODO; log it $c->delete("Project:processing:{$this->id}"); throw new Exception('No free nodes'); } if (!$random_node = $node_pools->offset(rand(0, $free_nodes_count - 1))->first()) { continue; } $random_node->update(array( 'project_id' => $this->id, 'commit' => $this->commit, 'start_at' => time(), 'status' => WebNode::STATUS_WEBPROCESSING, )); $node_id = $random_node->port - 20000; $ip = long2ip($random_node->ip); $session = ssh2_connect($ip, 22); $ret = ssh2_auth_pubkey_file($session, 'root', WEB_PUBLIC_KEYFILE, WEB_KEYFILE); $stream = ssh2_exec($session, "clone {$this->name} {$node_id}"); stream_set_blocking($stream, true); $ret = stream_get_contents($stream); $session = ssh2_connect($ip, 22); ssh2_auth_pubkey_file($session, 'root', WEB_PUBLIC_KEYFILE, WEB_KEYFILE); $stream = ssh2_exec($session, "restart-web {$this->name} {$node_id}"); stream_set_blocking($stream, true); $ret = stream_get_contents($stream); $random_node->update(array( 'status' => WebNode::STATUS_WEBNODE, )); $choosed_nodes[] = $random_node; if (count($choosed_nodes) >= 1) { break; } } $c->delete("Project:processing:{$this->id}"); return $choosed_nodes; } public function getCommitLog() { try { return GitHelper::getLatestCommitLog($this); } catch (Exception $e) { return array(); } } } class Project extends Pix_Table { public function init() { $this->_name = 'project'; $this->_primary = 'id'; $this->_rowClass = 'ProjectRow'; $this->enableTableCache(); $this->_columns['id'] = array('type' => 'int', 'auto_increment' => true); $this->_columns['name'] = array('type' => 'varchar', 'size' => 64); $this->_columns['commit'] = array('type' => 'char', 'size' => 32); // 0 - actived, 1 - dev (robots.txt disallow all), 2 - 503 service unaviable $this->_columns['status'] = array('type' => 'int', 'default' => 0); $this->_columns['config'] = array('type' => 'text', 'default' => '{}'); $this->_columns['created_at'] = array('type' => 'int'); $this->_columns['created_by'] = array('type' => 'int'); $this->_indexes['name'] = array('type' => 'unique', 'columns' => array('name')); $this->_relations['members'] = array('rel' => 'has_many', 'type' => 'ProjectMember', 'foreign_key' => 'project_id'); $this->_relations['custom_domains'] = array('rel' => 'has_many', 'type' => 'CustomDomain', 'foreign_key' => 'project_id'); $this->_relations['variables'] = array('rel' => 'has_many', 'type' => 'ProjectVariable', 'foreign_key' => 'project_id'); $this->_relations['webnodes'] = array('rel' => 'has_many', 'type' => 'WebNode', 'foreign_key' => 'project_id'); $this->_relations['cronjobs'] = array('rel' => 'has_many', 'type' => 'CronJob', 'foreign_key' => 'project_id'); $this->_hooks['eavs'] = array('get' => 'getEAVs'); $this->addRowHelper('Pix_Table_Helper_EAV', array('getEAV', 'setEAV')); } public static function getRandomName() { $areas = array('taipei', 'taoyuan', 'hsinchu', 'yilan', 'hualien', 'miaoli', 'taichung', 'changhua', 'nantou', 'chiayi', 'yunlin', 'tainan', 'penghu', 'kaohiung', 'pingtung', 'kinmen', 'matsu', 'taitung'); $first_names = array('An', 'Chang', 'Chao', 'Chen', 'Cheng', 'Chi', 'Chiang', 'Chien', 'Chin', 'Chou', 'Chu', 'Fan', 'Fang', 'Fei', 'Feng', 'Fu', 'Han', 'Hao', 'Ho', 'Hsi', 'Hsiao', 'Hsieh', 'Hsu', 'Hsueh', 'Hua', 'Huang', 'Jen', 'Kang', 'Ko', 'Ku', 'Kung', 'Lang', 'Lei', 'Li', 'Lien', 'Liu', 'Lo', 'Lu', 'Ma', 'Meng', 'Miao', 'Mu', 'Ni', 'Pai', 'Pan', 'Pao', 'Peng', 'Pi', 'Pien', 'Ping', 'Pu', 'Shen', 'Shih', 'Shui', 'Su', 'Sun', 'Tang', 'Tao', 'Teng', 'Tou', 'Tsao', 'Tsen', 'Tsou', 'Wang', 'Wei', 'Wu', 'Yang', 'Yen', 'Yin', 'Yu', 'Yuan', 'Yueh', 'Yun'); for ($i = 0; $i < 10; $i ++) { $random = strtolower($areas[rand(0, count($areas) - 1)] . '-' . $first_names[rand(0, count($first_names) - 1)] . '-' . rand(100000, 1000000)); if (!Project::find_by_name($random)) { break; } } if ($i > 5) { trigger_error("random {$i} times... too much times", E_USER_WARNING); } return $random; } public static function getTemplates() { return array( 'mixed' => 'PHP 5.4 + Python 2.7 + NodeJS + Ruby2.0', ); } } <file_sep>/webdata/models/MachineStatus.php <?php class MachineStatusRow extends Pix_Table_Row { protected $_obj = null; public function getObject() { if (is_null($this->_obj)) { $this->_obj = json_decode($this->status); } return $this->_obj; } public function getDiskInfos() { $obj = $this->getObject(); usort($obj->disk, function($a, $b) { return intval($b->disk_total) - intval($a->disk_total); }); return $obj->disk; } public function getLoads() { $obj = $this->getObject(); if (!preg_match('#, load average: ([0-9.]*), ([0-9.]*), ([0-9.]*)#', $obj->process, $matches)) { return array(-1, -1, -1); throw new Exception("process info not found"); } return array(floatval($matches[1]), floatval($matches[2]), floatval($matches[3])); } } class MachineStatus extends Pix_Table { public function init() { $this->_name = 'machine_status'; $this->_primary = array('machine_id', 'updated_at'); $this->_rowClass = 'MachineStatusRow'; $this->_columns['machine_id'] = array('type' => 'int'); $this->_columns['status'] = array('type' => 'text'); $this->_columns['updated_at'] = array('type' => 'int'); $this->_relations['machine'] = array('rel' => 'has_one', 'type' => 'Machine'); } } <file_sep>/webdata/models/SSLKey.php <?php class SSLKeyRow extends Pix_Table_Row { public function get($k) { return json_decode($this->config)->{$k}; } } class SSLKey extends Pix_Table { public function init() { $this->_primary = 'domain'; $this->_name = 'ssl_keys'; $this->_rowClass = 'SSLKeyRow'; $this->_columns['domain'] = array('type' => 'char', 'size' => 64); $this->_columns['config'] = array('type' => 'text'); } } <file_sep>/webdata/controllers/IndexController.php <?php class IndexController extends Pix_Controller { public function indexAction() { if (Hisoku::getLoginUser()) { return $this->redirect('/user'); } } public function loginAction() { $alert_message = "Invalid user name or password"; if (!$u = User::find_by_name(strval($_POST['user']))) { Logger::log(array(array('category' => 'login', 'message' => time() . " user-not-found {$_SERVER['REMOTE_ADDR']} user=" . urlencode($_POST['user']) . ",agent=" . urlencode($_SERVER['HTTP_USER_AGENT'])))); return $this->alert($alert_message, '/'); } if (!$u->verifyPassword($_POST['password'])) { Logger::log(array(array('category' => 'login', 'message' => time() . " wrong-password {$_SERVER['REMOTE_ADDR']} user=" . urlencode($_POST['user']) . ",agent=" . urlencode($_SERVER['HTTP_USER_AGENT'])))); return $this->alert($alert_message, '/'); } Pix_Session::set('user', $u->id); Logger::log(array(array('category' => 'login', 'message' => time() . " ok {$_SERVER['REMOTE_ADDR']} user=" . urlencode($_POST['user']) . ",agent=" . urlencode($_SERVER['HTTP_USER_AGENT'])))); return $this->redirect('/'); } public function logoutAction() { $user = Hisoku::getLoginUser(); Logger::log(array(array('category' => 'login', 'message' => time() . " logout {$_SERVER['REMOTE_ADDR']} user=" . urlencode($user->name) . ",agent=" . urlencode($_SERVER['HTTP_USER_AGENT'])))); Pix_Session::delete('user'); return $this->redirect('/'); } public function signupAction() { if (!getenv('SIGNUP_ENABLE')) { return $this->alert("Signup is not allowed.", '/'); } } public function sendsignupAction() { if (!getenv('SIGNUP_ENABLE')) { return $this->alert("Signup is not allowed.", '/'); } $email = $_POST['email']; try { SignupConfirm::sendSignupConfirm($email); } catch (Exception $e) { return $this->alert($e->getMessage(), '/index/signup'); } return $this->alert("已寄出認證信,請至您的信箱點擊認證連結", "/"); } public function signupconfirmAction() { if (!getenv('SIGNUP_ENABLE')) { return $this->alert("Signup is not allowed.", '/'); } $mail = $_GET['mail']; $expired_at = $_GET['expired_at']; $sig = $_GET['sig']; if ($expired_at < time()) { return $this->alert('signup is expired', '/index/signup'); } if (!$sc = SignupConfirm::search(array('email' => $mail))->order('created_at DESC')->first()) { return $this->alert('signup is not found', '/index/signup'); } if (crc32($mail . $expired_at . $sc->code) != $sig) { return $this->alert('signup is not valid', '/index/signup'); } $this->view->mail = $mail; $this->view->expired_at = $expired_at; $this->view->sig = $sig; } public function signupfinalAction() { if (!getenv('SIGNUP_ENABLE')) { return $this->alert("Signup is not allowed.", '/'); } $mail = $_GET['mail']; $expired_at = $_GET['expired_at']; $sig = $_GET['sig']; if ($expired_at < time()) { return $this->alert('signup is expired', '/index/signup'); } if (!$sc = SignupConfirm::search(array('email' => $mail))->order('created_at DESC')->first()) { return $this->alert('signup is not found', '/index/signup'); } if (crc32($mail . $expired_at . $sc->code) != $sig) { return $this->alert('signup is not valid', '/index/signup'); } $url = '/index/signupconfirm?mail=' . urlencode($mail) . '&expired_at=' . intval($expired_at) . '&sig=' . intval($sig); if (strlen($_POST['password']) < 4) { return $this->alert('your password is too short', $url); } if ($_POST['password'] != $_POST['repassword']) { return $this->alert('password is not the same', $url); } $u = User::insert(array( 'name' => $mail, 'status' => 1, )); $u->setPassword($_POST['password']); Logger::logOne(array('category' => "user-signup", 'message' => json_encode(array( 'mail' => $mail, 'message' => $_POST['message'], 'time' => date('c'), 'ip' => $_SERVER['REMOTE_ADDR'], )))); return $this->alert('註冊成功,請至首頁登入', '/'); } } <file_sep>/scripts/m2-management-ssh-serve #!/usr/bin/env php <?php include(__DIR__ . '/../webdata/init.inc.php'); if ('git' !== getenv('USER')) { die('git user only' . PHP_EOL); } function updateKeys() { # call by UserKey::updateKey() from mainpage for updating ~git/.ssh/authorized_keys $update_git_config_keys = explode("\n", trim(file_get_contents('/srv/config/update-git-config-keys'))); # call by scripts/root@nodes-ssh_serve from node servers for git clone repository $deploy_keys = explode("\n", trim(file_get_contents('/srv/config/deploy-keys'))); $content = '### generated at ' . date('Y/m/d H:i:s') . "\n"; $content .= "# deploy-keys\n"; foreach ($deploy_keys as $deploy_key) { if (trim($deploy_key) == '') { continue; } $content .= 'command="/srv/code/hisoku/scripts/deploy-key-archive-only",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ' . $deploy_key . "\n"; } $content .= "# m2-management-ssh-serve\n"; foreach ($update_git_config_keys as $key) { $content .= 'command="/srv/code/hisoku/scripts/m2-management-ssh-serve",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ' . $key . "\n"; } $content .= "# user keys\n"; // 可以對 mysql 和 pgsql 的 IP 開 ssh tunnel $forward_ports = array_merge( array_map(function($ip){ return "{$ip}:3306"; }, Hisoku::getIPsByGroup('mysql')), array_map(function($ip){ return "{$ip}:5432"; }, Hisoku::getIPsByGroup('pgsql')) ); $permitopen = implode(',', array_map(function($ip_port) { return "permitopen=\"{$ip_port}\""; }, $forward_ports)); foreach (UserKey::search(1) as $user_key) { $content .= "command=\"/srv/code/hisoku/scripts/ssh-serve {$user_key->user->name} {$user_key->id}\",no-X11-forwarding,no-agent-forwarding,{$permitopen} {$user_key->key_body}\n"; } file_put_contents(getenv('HOME') . '/.ssh/authorized_keys', $content); } function importProjectRepo($args) { list($project_name, $from) = explode(' ', $args); if (FALSE !== strpos($project_name, '.')) { return error('invalid project name: ' . $project_name); } if (!$project = Project::find_by_name(strval($project_name))) { return error('project not found: ' . $project_name); } $absolute_path = getenv('HOME') . '/git/' . $project->id . '.git'; if (!file_exists($absolute_path)) { exec('git clone --bare ' . $from . ' ' . escapeshellarg($absolute_path)); symlink('/srv/code/hisoku/scripts/pre-receive', $absolute_path . '/hooks/pre-receive'); } } function error($message) { error_log($message); } function main() { if (!getenv('SSH_ORIGINAL_COMMAND')) { return error('There is no SSH_ORIGINAL_COMMAND env'); } list($command, $args) = explode(' ', getenv('SSH_ORIGINAL_COMMAND'), 2); switch ($command) { case 'update-keys': return updateKeys(); case 'import-project-repo': return importProjectRepo($args); default: return error('Unknown command: ' . getenv('SSH_ORIGINAL_COMMAND')); } } main(); <file_sep>/scripts/crawler-web-log #!/usr/bin/env php <?php // 爬各 node 的 /srv/logs/web.log 並把他傳到 if (file_exists('/srv/config/config.php')) { include('/srv/config/config.php'); } class Crawler { protected $_file_objects = array(); public function getFileObj($id) { $path = "/srv/chroot/{$id}/srv/logs/web.log"; $inode = fileinode($path); if (!array_key_exists($id, $this->_file_objects) or $this->_file_objects[$id]->inode != $inode) { error_log('loading ' . $id); if (array_key_exists($id, $this->_file_objects)) { fclose($this->_file_objects[$id]->fp); } $obj = new StdClass; $obj->id = $id; $obj->inode = $inode; $obj->path = $path; $obj->file_size = filesize($path); $obj->fp = fopen($path, 'r'); // 如果建立時間超過 10 秒,就不用從頭開始取資料了,以免 script 重跑時 log 會重噴一次 if (time() - filectime($path) > 10) { fseek($obj->fp, $obj->file_size); } $obj->project = file_get_contents("/srv/chroot/{$id}.project"); $this->_file_objects[$id] = $obj; } return $this->_file_objects[$id]; } public function loop() { clearstatcache(); foreach (glob("/srv/chroot/*/srv/logs/web.log") as $log_file) { if (!preg_match("#/srv/chroot/(\d+)/srv/logs/web\.log#", $log_file, $matches)) { continue; } $id = $matches[1]; if (!file_exists("/srv/chroot/{$id}.project")) { continue; } $file_obj = $this->getFileObj($id); if (filesize($log_file) == $file_obj->file_size) { continue; } $fp = $file_obj->fp; fseek($fp, $file_obj->file_size); while (false !== ($line = fgets($fp))) { $this->insertLog($file_obj, trim($line)); } $this->_file_objects[$id]->file_size = ftell($fp); } $this->commitLog(); } protected $_logs = array(); public function insertLog($file_obj, $line) { $obj = new StdClass; $obj->project = $file_obj->project; $obj->id = $file_obj->id; $obj->log = $line; $obj->time = time(); $this->_logs[] = $obj; if (count($this->_logs) > 100) { $this->commitLog(); } } public function commitLog() { if (!$this->_logs) { return; } error_log('commit ' . count($this->_logs) . ' log'); $curl = curl_init(); // TODO: 需要加上 secret key 檢查 curl_setopt($curl, CURLOPT_URL, 'https://' . getenv('MAINPAGE_DOMAIN') . '/api/weblog'); curl_setopt($curl, CURLOPT_POST, true); $params = array( 'data' => json_encode($this->_logs), ); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_exec($curl); curl_close($curl); $this->_logs = array(); } public function main() { while (true) { $this->loop(); sleep(1); } } } $c = new Crawler; $c->main(); <file_sep>/webdata/models/WebNode.php <?php class WebNodeRow extends Pix_Table_Row { /** * markAsUnused 將這個 node 標為需要 reset, 不能再做任何事 * * @access public * @return void */ public function markAsUnused($reason = '') { Logger::logOne(array('category' => "app-{$this->project->name}-node", 'message' => json_encode(array( 'time' => microtime(true), 'ip' => $this->ip, 'port' => $this->port, 'commit' => $this->commit, 'spent' => (time() - $this->start_at), 'type' => WebNode::getNodeTypeByStatus($this->status), 'status' => 'over', 'reason' => $reason, )))); if (in_array($this->status, array(WebNode::STATUS_WEBNODE, WebNode::STATUS_WEBPROCESSING))) { WebNode::cleanLoadBalancerCache(); } $this->update(array( 'project_id' => 0, 'commit' => '', 'cron_id' => 0, 'status' => WebNode::STATUS_OVER, )); } public function deletePort() { if (in_array($this->status, array(WebNode::STATUS_WEBNODE, WebNode::STATUS_WEBPROCESSING))) { WebNode::cleanLoadBalancerCache(); } $this->delete(); } public function getStatusWord() { $node_status = WebNode::getTable()->_columns['status']['note']; $word = isset($node_status[$this->status]) ? $node_status[$this->status] : 'Unknown'; if ($this->status == WebNode::STATUS_CRONNODE) { $word .= ':' . $this->getEAV('job'); } return $word; } public function getServiceProject() { return Addon_Memcached::search(array('host' => long2ip($this->ip), 'port' => $this->port))->first()->project; } /** * markAsWait 將這個 node 標為 waiting, 之後同 repository 還可以用 * * @access public * @return void */ public function markAsWait() { Logger::logOne(array('category' => "app-{$this->project->name}-node", 'message' => json_encode(array( 'time' => microtime(true), 'ip' => $this->ip, 'port' => $this->port, 'commit' => $this->commit, 'type' => WebNode::getNodeTypeByStatus($this->status), 'spent' => (time() - $this->start_at), 'status' => 'wait', )))); $this->update(array( 'status' => WebNode::STATUS_WAIT, )); } protected function _sshDeletePort() { $session = ssh2_connect(long2ip($this->ip), 22); if (false === $session) { return false; } $ret = ssh2_auth_pubkey_file($session, 'root', WEB_PUBLIC_KEYFILE, WEB_KEYFILE); if (false === $session) { return false; } $stream = ssh2_exec($session, "shutdown " . ($this->port - 20000)); stream_set_blocking($stream, true); $ret = stream_get_contents($stream); if (!$ret = json_decode($ret)) { return false; } if ($ret->error) { return false; } return true; } public function resetNode() { $session = ssh2_connect(long2ip($this->ip), 22); if (false === $session) { throw new Exception('ssh connect failed'); } $ret = ssh2_auth_pubkey_file($session, 'root', WEB_PUBLIC_KEYFILE, WEB_KEYFILE); if (false === $ret) { throw new Exception('key failed'); } $stream = ssh2_exec($session, "shutdown " . ($this->port - 20000)); stream_set_blocking($stream, true); $ret = stream_get_contents($stream); if (!$ret = json_decode($ret)) { //throw new Exception('wrong json'); } if ($ret->error) { //throw new Exception('json error'); } $stream = ssh2_exec($session, "init " . ($this->port - 20000)); stream_set_blocking($stream, true); $ret = stream_get_contents($stream); if (!$ret = json_decode($ret)) { throw new Exception('wrong json'); } if ($ret->error) { throw new Exception('json error'); } $this->update(array( 'status' => WebNode::STATUS_UNUSED, )); return true; } public function preInsert() { $this->created_at = time(); } public function postDelete() { $this->_sshDeletePort(); } /** * getAccessAt 取得 access at ,如果 cache 有就取比較新的時間 * * @return int timestamp */ public function getAccessAt() { $cache = WebNode::getServerAccessCache(); return max($this->access_at, property_exists($cache->webnode_access_at, "{$this->ip}:{$this->port}") ? intval($cache->webnode_access_at->{"{$this->ip}:{$this->port}"}) : 0); } public function updateAccessAt() { $this->update(array('access_at' => time())); } /** * getNodeProcesses get the process list on node * * @access public * @return array */ public function getNodeProcesses() { $session = ssh2_connect(long2ip($this->ip), 22); if (false === $session) { return false; } $ret = ssh2_auth_pubkey_file($session, 'root', WEB_PUBLIC_KEYFILE, WEB_KEYFILE); if (false === $session) { return false; } $stream = ssh2_exec($session, "check_alive " . ($this->port - 20000)); stream_set_blocking($stream, true); $ret = stream_get_contents($stream); $ret = json_decode($ret); return $ret; } public function runJob($command, $options = array()) { $this->setEAV('job', $command); $session = ssh2_connect(long2ip($this->ip), 22); if (false === $session) { throw new Exception('connect failed'); } $ret = ssh2_auth_pubkey_file($session, 'root', WEB_PUBLIC_KEYFILE, WEB_KEYFILE); if (false === $ret) { throw new Exception('ssh key is wrong'); } Logger::logOne(array('category' => "app-{$this->project->name}-node", 'message' => json_encode(array( 'time' => microtime(true), 'ip' => $this->ip, 'port' => $this->port, 'commit' => $this->commit, 'type' => 'cron', 'status' => 'start', 'command' => $command, )))); $node_id = $this->port - 20000; $options['without_status'] = array_key_exists('without_status', $options) ? intval($options['without_status']) : 0; if ($options['term']) { $stream = ssh2_exec($session, "run {$this->project->name} {$node_id} " . urlencode($command) . " {$options['without_status']}", $options['term'], array(), $options['width'], $options['height']); } else { $stream = ssh2_exec($session, "run {$this->project->name} {$node_id} " . urlencode($command) . " {$options['without_status']}"); } if ($session === false) { throw new Exception("ssh2_exec failed"); } $ret = new StdClass; $ret->stdout = $stream; $ret->stdio = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO); $ret->stderr = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); return $ret; } } class WebNode extends Pix_Table { const STATUS_UNUSED = 0; const STATUS_WEBPROCESSING = 1; const STATUS_CRONPROCESSING = 2; const STATUS_WEBNODE = 10; const STATUS_CRONNODE = 11; const STATUS_STOP = 100; const STATUS_OVER = 101; // 等待資源再被放出來 const STATUS_WAIT = 102; // 這個 node 還保有完整的某個 repository 環境,還可以繼續使用 const STATUS_SERVICE = 103; // 被 service 拿去用了,這些是不會死的 public function init() { $this->_name = 'webnode'; $this->_primary = array('ip', 'port'); $this->_rowClass = 'WebNodeRow'; $this->enableTableCache(); $this->_columns['ip'] = array('type' => 'int', 'unsigned' => true); $this->_columns['port'] = array('type' => 'int'); $this->_columns['project_id'] = array('type' => 'int', 'default' => 0); $this->_columns['commit'] = array('type' => 'char', 'size' => 32, 'default' => ''); // status: 0-unused, // 1-webprocessing, 2-cronprocessing // 10-webnode, 11-cronnode $this->_columns['status'] = array('type' => 'tinyint', 'note' => array( 0 => 'unused', 1 => 'WebNode processing', 2 => 'CronNode processing', 10 => 'WebNode', 11 => 'CronNode', 100 => 'Stop', 101 => 'Over', 102 => 'Wait', 103 => 'Service', )); $this->_columns['config'] = array('type' => 'text', 'default' => '{}'); $this->_columns['created_at'] = array('type' => 'int'); $this->_columns['start_at'] = array('type' => 'int', 'default' => 0); $this->_columns['access_at'] = array('type' => 'int', 'default' => 0); // 記錄他是哪個 cron 生出來的 $this->_columns['cron_id'] = array('type' => 'int', 'default' => 0); $this->_relations['project'] = array('rel' => 'has_one', 'type' => 'Project', 'foreign_key' => 'project_id'); $this->_relations['eavs'] = array('rel' => 'has_many', 'type' => 'WebNodeEAV', 'foreign_key' => array('ip', 'port')); $this->addRowHelper('Pix_Table_Helper_EAV', array('getEAV', 'setEAV')); $this->addIndex('projectid_status_commit', array( 'project_id', 'status', 'commit', )); } public static function getGroupedNodes() { $return = array(); foreach (WebNode::search(1)->order(array('ip', 'port')) as $node) { $return[$node->ip][] = $node; } return $return; } public static function initNode($ip, $port, $config = null) { $session = ssh2_connect($ip, 22); if (false === $session) { throw new Exception('connect failed'); } $ret = ssh2_auth_pubkey_file($session, 'root', WEB_PUBLIC_KEYFILE, WEB_KEYFILE); if (false === $session) { throw new Exception('ssh key is wrong'); } $stream = ssh2_exec($session, "init $port"); stream_set_blocking($stream, true); $ret = stream_get_contents($stream); if (!$ret = json_decode($ret)) { throw new Exception('result is not json'); } if ($ret->error) { throw new Exception('init failed, message: ' . $ret->message); } $values = array( 'ip' => ip2long($ip), 'port' => $port + 20000, 'status' => WebNode::STATUS_UNUSED, ); if ($config) { $values['config'] = json_encode($config); } WebNode::insert($values); } /** * updateNodeInfo 把所有的 WebNode 檢查一次,把 cache 的時間和 counter 更新到 db,清除異常的 node 等 * * @return void */ public static function updateNodeInfo() { foreach (WebNode::search(1) as $node) { // 更新 access_at $node->update(array('access_at' => $node->getAccessAt())); // 放出 commit 版本不正確的 commit if ($project = $node->project) { if (in_array($node->status, array(WebNode::STATUS_WEBNODE, WebNode::STATUS_WAIT)) and $project->commit != $node->commit) { $node->markAsUnused('commit change from updateNodeInfo'); } } $processes = $node->getNodeProcesses(); if (is_object($processes) and property_exists($processes, 'error') and !in_array($node->status, array(WebNode::STATUS_OVER, WebNode::STATUS_UNUSED))) { trigger_error("{$node->ip}:{$node->port} error, release it", E_USER_WARNING); $node->markAsUnused('node error'); } // 如果是 webnode 卻沒有任何 process 就 end if (time() - $node->start_at > 60 and in_array($node->status, array(WebNode::STATUS_WEBNODE))) { if (is_array($processes) and 0 == count($processes)) { trigger_error("{$node->ip}:{$node->port} had no alive process, release it", E_USER_WARNING); $node->markAsUnused('no alive process'); } } // 如果是 cronnode ,在 access 過後超過 60 秒沒有任何 process ,把他切回 wait mode if (time() - $node->getAccessAt() > 60 and in_array($node->status, array(WebNode::STATUS_CRONNODE))) { if (is_array($processes) and 0 == count($processes)) { trigger_error("{$node->ip}:{$node->port} had no alive process, change to wait mode", E_USER_WARNING); $node->markAsWait(); $node->update(array('cron_id' => 0)); } } // WebNode 超過一小時沒人看就 end if (in_array($node->status, array(WebNode::STATUS_WEBNODE)) and (time() - $node->getAccessAt()) > 3600) { if ($project = $node->project and $project->getEAV('always-alive')) { } else { $node->markAsUnused('wait 1hour'); } } // 如果 processing node 太久也要踢掉 if (in_array($node->status, array(WebNode::STATUS_CRONPROCESSING, WebNode::STATUS_WEBPROCESSING)) and (time() - $node->getAccessAt()) > 600 and (time() - $node->start_at) > 600) { // TODO: 寄信 $node->markAsUnused('process too long'); } // Wait node 保留兩小時 if (in_array($node->status, array(WebNode::STATUS_WAIT)) and (time() - $node->getAccessAt()) > 7200) { $node->markAsUnused('wait over'); } // 如果是 over 要放出來 if (in_array($node->status, array(WebNode::STATUS_OVER))) { // 該主機沒有任何 cron/web processing 才做 reset, 以免 cpu/io loading 過高 $node->resetNode(); } } } public static function getNodeTypeByStatus($status) { $type_map = array( WebNode::STATUS_WEBNODE => 'web', WebNode::STATUS_CRONNODE => 'cron', WebNode::STATUS_WAIT => 'wait', ); return array_key_exists($status, $type_map) ? $type_map[$status] : ("other-{$status}"); } public static function cleanLoadBalancerCache() { foreach (Hisoku::getLoadBalancers() as $ip) { $curl = curl_init('http://' . $ip); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Host: cleancache')); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $ret = curl_exec($curl); curl_close($curl); } } protected static $_access_cache = null; public static function getServerAccessCache() { if (!is_null(self::$_access_cache) and (time() - self::$_access_cache->time < 5)) { return self::$_access_cache; } $curl = curl_init('http://localhost/'); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Host: healthcheck')); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $content = curl_exec($curl); $obj = json_decode($content); $obj->access_cache->time = time(); self::$_access_cache = $obj->access_cache; return self::$_access_cache; } } <file_sep>/webdata/models/Addon/Elastic2.php <?php class Addon_Elastic2Row extends Pix_Table_Row { public function removeElastic() { Elastic::dropUser($this->user); } public function updateElastic() { Elastic::login($this->getURL(), getenv('ELASTIC_ADMIN_USER'), getenv('ELASTIC_ADMIN_PASSWORD')); Elastic::createUser($this->user, $this->password, $this->prefix); } public function saveProjectVariable() { foreach (['ELASTIC_URL', 'ELASTIC_USER', 'ELASTIC_PASSWORD', 'ELASTIC_PREFIX'] as $k) { try { $this->project->variables->insert(array( 'key' => $k, 'value' => "Addon_Elastic2:{$this->id}:{$k}", 'is_magic_value' => 1, )); } catch (Pix_Table_DuplicateException $e) { $this->project->variables->search(array( 'key' => $k, ))->update(array( 'value' => "Addon_Elastic2:{$this->id}:{$k}", 'is_magic_value' => 1, )); } } } public function getURL() { return sprintf("https://%s:9200", $this->host); } } class Addon_Elastic2 extends Pix_Table { public function init() { $this->_name = 'addon_elastic2'; $this->_rowClass = 'Addon_Elastic2Row'; $this->_primary = array('id'); $this->_columns['id'] = array('type' => 'int', 'auto_increment' => true); $this->_columns['project_id'] = array('type' => 'int'); $this->_columns['host'] = array('type' => 'varchar', 'size' => 255); $this->_columns['prefix'] = array('type' => 'varchar', 'size' => 16); $this->_columns['user'] = array('type' => 'varchar', 'size' => 32); $this->_columns['password'] = array('type' => 'varchar', 'size' => 32); $this->_relations['project'] = array('rel' => 'has_one', 'type' => 'Project', 'foreign_key' => 'project_id'); $this->addIndex('project_id', array('project_id')); } public static function addDB($project) { if ($addon = self::search(array('project_id' => $project->id))->first()) { $addon->saveProjectVariable(); return; } // TODO: from config $host = 'elastic-1.middle2.com'; $prefix = strtolower(Hisoku::uniqid(10)); $password = <PASSWORD>::<PASSWORD>(20); $addon = self::insert(array( 'project_id' => $project->id, 'host' => $host, 'prefix' => $prefix, 'user' => $project->name, 'password' => <PASSWORD>, )); $addon->saveProjectVariable(); $addon->updateElastic(); } } <file_sep>/scripts/ssh-serve #!/usr/bin/env php <?php include(__DIR__ . '/../webdata/init.inc.php'); class SSHServe { public function error($message) { error_log($message); } public function main() { if (!getenv('SSH_ORIGINAL_COMMAND')) { return $this->error('There is no SSH_ORIGINAL_COMMAND env'); } list($command, $args) = explode(' ', getenv('SSH_ORIGINAL_COMMAND'), 2); Logger::log(array(array( 'category' => 'git-ssh-serve', 'message' => time() . " {$_SERVER['argv'][1]}({$_SERVER['argv'][2]}) {$_SERVER['SSH_CLIENT']} {$command} {$args}" ))); switch ($command) { case 'git-upload-pack': case 'git-receive-pack': return $this->gitCommand($command, $args); case 'run': return $this->runCommand($command, $args); case 'tunnel': return $this->tunnelCommand($command, $args); case 'log': return $this->logCommand($command, $args); case '/usr/lib/openssh/sftp-server': $server = new SFTPServer; $server->main($_SERVER['argv'][1]); return; default: return $this->error('Unknown command: ' . getenv('SSH_ORIGINAL_COMMAND')); } } public function logCommand($command, $args) { list($project_name, $type) = explode(' ', $args, 2); if (FALSE !== strpos($project_name, '.')) { return $this->error('invalid project name: ' . $project_name); } if (!$project = Project::find_by_name(strval($project_name))) { return $this->error('project not found: ' . $project_name); } if (!$user = User::find_by_name(strval($_SERVER['argv'][1]))) { return $this->error('invalid ssh key'); } if (!$project->isMember($user)) { return $this->error('project not found: ' . $project_name); } if ($type == 'error') { $category = "app-{$project_name}-error"; } else { $category = "app-{$project_name}"; } system("tail -f /srv/logs/scribed/{$category}/{$category}_current"); } public function tunnelCommand($command, $args) { list($project_name) = explode(' ', $args, 2); if (FALSE !== strpos($project_name, '.')) { return $this->error('invalid project name: ' . $project_name); } if (!$project = Project::find_by_name(strval($project_name))) { return $this->error('project not found: ' . $project_name); } if (!$user = User::find_by_name(strval($_SERVER['argv'][1]))) { return $this->error('invalid ssh key'); } if (!$project->isMember($user)) { return $this->error('project not found: ' . $project_name); } echo "tunnel is up\r\n"; sleep(3600); } public function signal_handler($signal) { if ($signal == SIGINT) { fwrite($this->node_stdio, chr(3)); } } public function runCommand($command, $args) { list($project_name, $run_command) = explode(' ', $args, 2); if (FALSE !== strpos($project_name, '.')) { return $this->error('invalid project name: ' . $project_name); } if (!$project = Project::find_by_name(strval($project_name))) { return $this->error('project not found: ' . $project_name); } if (!$user = User::find_by_name(strval($_SERVER['argv'][1]))) { return $this->error('invalid ssh key'); } if (!$project->isMember($user)) { return $this->error('project not found: ' . $project_name); } error_log('allocate node...'); $node = $project->getCronNode(); $node->update(array( 'status' => WebNode::STATUS_CRONNODE, )); $node->updateAccessAt(); $term = getenv('TERM'); if ($term) { if (function_exists('ncurses_init')) { ncurses_init(); ncurses_getmaxyx(STDSCR, $y, $x); } system('clear'); error_log("start with term: {$term} (width: {$x}, height: {$y})\r" ); $ret = $node->runJob($run_command, array( 'term' => $term, 'width' => $x, 'height' => $y, 'without_status' => 1, )); } else { error_log('start without term'); $ret = $node->runJob($run_command, array('without_status' => 1)); } $user_input = fopen('php://stdin', 'r'); $user_output = fopen('php://stdout', 'w'); $user_stderr = fopen('php://stderr', 'w'); $read_streams = array( 'node_output' => $ret->stdout, 'node_stderr' => $ret->stderr, 'user_input' => $user_input, ); stream_set_blocking($ret->stdout, false); stream_set_blocking($ret->stderr, false); stream_set_blocking($user_input, false); declare(ticks = 1); $this->node_stdio = $ret->stdio; pcntl_signal(SIGINT, array($this, "signal_handler")); while (array_key_exists('node_output', $read_streams)) { foreach ($read_streams as $key => $read_stream) { if (!is_resource($read_stream)) { unset($read_stream[$key]); continue; } if (false !== ($line = fread($read_stream, 4096))) { if (feof($read_stream)) { if ($key === 'user_input') { break 2; } unset($read_streams[$key]); break; } if ($line === '') { continue; } if ('node_output' == $key) { fwrite($user_output, $line); } elseif ('node_stderr' == $key) { fwrite($user_stderr, $line); } elseif ('user_input' == $key) { fwrite($ret->stdio, $line); } } } usleep(100); } $node->markAsWait(); } public function gitCommand($command, $args) { $project_name = trim($args, "' "); if (preg_match('#^(.*)\.git$#', $project_name, $matches)) { $project_name = $matches[1]; } if (FALSE !== strpos($project_name, '.')) { return $this->error('invalid project name: ' . $project_name); } if (!$project = Project::find_by_name(strval($project_name))) { return $this->error('project not found: ' . $project_name); } if (!$user = User::find_by_name(strval($_SERVER['argv'][1]))) { return $this->error('invalid ssh key'); } if (!$project->isMember($user)) { return $this->error('project not found: ' . $project_name); } $absolute_path = getenv('HOME') . '/git/' . $project->id . '.git'; if (!file_exists($absolute_path)) { exec('git init --bare ' . escapeshellarg($absolute_path)); // add hooks symlink('/srv/code/hisoku/scripts/pre-receive', $absolute_path . '/hooks/pre-receive'); } passthru('git shell -c ' . escapeshellarg($command . ' ' . escapeshellarg($absolute_path))); } } $ssh_serve = new SSHServe; $ssh_serve->main(); <file_sep>/webroot/index.php <?php include(__DIR__ . '/../webdata/init.inc.php'); if (function_exists('setproctitle')) { setproctitle('middle2: ' . $_SERVER['REQUEST_URI']); } if (!getenv('SESSION_KEY')) { putenv('SESSION_KEY=MIDDLE2_SESSION'); } Pix_Session::setAdapter('cookie', array( 'secret' => getenv('SESSION_SECRET'), 'cookie_key' => getenv('SESSION_KEY'), )); Pix_Controller::addCommonHelpers(); Pix_Controller::dispatch(__DIR__ . '/../webdata/'); if (function_exists('setproctitle')) { setproctitle('php-fpm'); } <file_sep>/scripts/cron-worker #!/usr/bin/env php <?php include(__DIR__ .'/../webdata/init.inc.php'); CronJob::loopCronWorker(); <file_sep>/cron/5min/check-machine-status #!/usr/bin/env php <?php // 處理 MachineStatus 的資料,如果遇到沒有更新資料、CPU 過高、硬碟快滿等狀況 // 就要寄信警告 include(__DIR__ . '/../../webdata/init.inc.php'); if (getenv('TRY_MODE')) { exit; } // 先睡 20 秒,這樣可以等各機器的資料傳好,比較即時判斷 sleep(20); $messages = array(); foreach (Machine::search(1) as $machine) { $machine_status = $machine->statuses->order('updated_at DESC')->first(); // 看看十分鐘內有沒有記錄 if (!$machine_status or (time() - $machine_status->updated_at > 600)) { $messages[] = array($machine, "超過十分鐘沒有回傳記錄了, 上次時間:" . date('c', $machine_status->updated_at)); continue; } // 處理 CPU Loads if (!$loads = $machine_status->getLoads()) { $messages[] = array($machine, "無法正確取得 cpu load", $machine_status); } else { if ($loads[1] > 10) { $messages[] = array($machine, "CPU Loading 過高: " . implode(',', $loads), $machine_status); } } // 處理硬碟 quota if (!$disk_infos = $machine_status->getDiskInfos()) { $messages[] = array($machine, "無法正確取得硬碟資訊", $machine_status); } else { foreach ($disk_infos as $disk_info) { if ($disk_info->disk_capacity and trim($disk_info->disk_capacity, '%') > 90) { $messages[] = array($machine, "硬碟 {$disk_info->mount_point} 使用空間超過 90%: " . $disk_info->disk_capacity, $machine_status); } elseif ($disk_info->disk_capacity and trim($disk_info->disk_capacity, '%') > 85) { // 一小時只噴一次,以免被信件灌爆 $cache_key = "/tmp/MachineStatus:{$machine->machine_id}:diskover85-sent"; $last_sent = 0; if (file_exists($cache_key)) { $last_sent = intval(file_get_contents($cache_key)); } if (!$last_sent or time() - $last_sent > 3600) { $messages[] = array($machine, "硬碟 {$disk_info->mount_point} 使用空間超過 85%: " . $disk_info->disk_capacity, $machine_status); file_put_contents($cache_key, time()); } } if ($disk_info->inode_capacity and trim($disk_info->inode_capacity, '%') > 90) { $messages[] = array($machine, "iNode {$disk_info->mount_point} 使用空間超過 90%: " . $disk_info->inode_capacity, $machine_status); } elseif ($disk_info->inode_capacity and trim($disk_info->inode_capacity, '%') > 85) { // 一小時只噴一次,以免被信件灌爆 $cache_key = "/tmp/MachineStatus:{$machine->machine_id}:inodeover85-sent"; $last_sent = 0; if (file_exists($cache_key)) { $last_sent = intval(file_get_contents($cache_key)); } if (!$last_sent or time() - $last_sent > 3600) { $messages[] = array($machine, "iNode {$disk_info->mount_point} 使用空間超過 85%: " . $disk_info->inode_capacity, $machine_status); file_put_contents($cache_key, time()); } } } } } if ($messages) { $content = ''; foreach ($messages as $message) { $content .= sprintf("%s %s (%s) %s\n", Machine::find_by_ip($message[0]->ip)->name, long2ip($message[0]->ip), $message[0]->groups, $message[1]); if ($status = $message[2]) { $content .= "https://" . getenv("MAINPAGE_DOMAIN") . "/admin/machinelog/{$status->machine_id}/{$status->updated_at}\n"; } } Hisoku::alert("Middle2 警告: " . date('Y/m/d H:i:s'), $content); } <file_sep>/dockers/config/shutdown.sh #!/bin/sh if [ -f "/srv/logs/php-fpm.pid" ]; then kill `cat /srv/logs/php-fpm.pid` fi if [ -f "/srv/logs/httpd.pid" ]; then kill `cat /srv/logs/httpd.pid` fi kill -1 <file_sep>/scripts/pre-receive #!/usr/bin/env php <?php // 當使用者 git push 時,會在 git server 以 git 使用者的身份執行這個 script include(__DIR__ . '/../webdata/init.inc.php'); $fp = fopen('php://stdin', 'r'); $content = ''; while (false !== ($line = fgets($fp))) { $content .= $line; } list($oldrev, $newrev, $refname) = explode(' ', trim($content)); // {id}.git $path = basename(getcwd()); if (!preg_match('#^(\d+)\.git$#', $path, $matches)) { // FIXME error_log('invalid path name: ' . $path); exit -1; } if (!$project = Project::find(intval($matches[1]))) { // FIXME error_log('invalid project id: ' . $matches[1]); exit -1; } // 處理先下載好各 repository 需要的內容 try { GitHelper::buildDockerProjectBase($project, $newrev); } catch (Exception $e) { error_log($e->getMessage()); exit(1); } // TODO: deploy to webnode $project->update(array('commit' => $newrev)); WebNode::cleanLoadBalancerCache(); // 修改 commit 後就清空 cache error_log('deploy finished. visit http://' . $project->getFirstDomain() . '/'); foreach ($project->custom_domains as $domain) { error_log(' or http://' . $domain->domain); } <file_sep>/dockers/config/etc/php.ini allow_url_fopen = On allow_url_include = Off display_errors = Off error_log = /srv/logs/web.log expose_php = Off file_uploads = On log_errors = On magic_quotes_gpc = Off max_execution_time = 3000 max_file_uploads = 40 max_input_time = 1200 realpath_cache_size = 1M memory_limit = 3100M post_max_size = 3100M upload_max_filesize = 3100M upload_tmp_dir = /var/tmp/ [Date] date.timezone = Asia/Taipei [Session] session.name = HISOKU session.cookie_lifetime = 86400 session.gc_divisor = 1000 session.bug_compat_42 = 0 session.hash_bits_per_character = 5 session.save_path = "/dev/null" [APC] apc.enable_cli = 1 apc.shm_size = 32M apc.stat_ctime = 1 <file_sep>/webdata/controllers/MysqldbController.php <?php class MysqldbController extends Pix_Controller { public function init() { if (!$this->user = Hisoku::getLoginUser()) { return $this->rediect('/'); } $this->view->user = $this->user; } public function detailAction() { list(, /*mysqldb*/, /*detail*/, $id) = explode('/', $this->getURI()); if (!$addon = Addon_MySQLDB::find(intval($id))) { return $this->alert('Addon not found', '/'); } if (!$addon->isMember($this->user) and !$this->user->isAdmin()) { return $this->alert('Project not found', '/'); } $this->view->addon_mysqldb = $addon; } public function addprojectAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } list(, /*mysqldb*/, /*addproject*/, $id) = explode('/', $this->getURI()); if (!$addon = Addon_MySQLDB::find(intval($id))) { return $this->alert('Addon not found', '/'); } if (!$addon->isAdmin($this->user)) { return $this->alert('Addon not found', '/'); } if (!$project = Project::find_by_name(strval($_POST['project']))) { return $this->alert('Project not found', '/mysqldb/detail/' . $addon->id); } $addon->addProject($project, $_POST['readonly'] ? 1 : 0); return $this->redirect('/mysqldb/detail/' . $addon->id); } public function editnoteAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } list(, /*mysqldb*/, /*editnote*/, $id, $key) = explode('/', $this->getURI()); if (!$addon = Addon_MySQLDB::find(intval($id))) { return $this->alert('Addon not found', '/'); } if (!$addon->isAdmin($this->user)) { return $this->alert('Addon not found', '/'); } $addon->setEAV('note', strval($_POST['note'])); return $this->redirect('/mysqldb/detail/' . $addon->id); } } <file_sep>/webdata/controllers/ProjectController.php <?php class ProjectController extends Pix_Controller { public function init() { if (!$this->user = Hisoku::getLoginUser()) { return $this->rediect('/'); } $this->view->user = $this->user; if (getenv('TRY_MODE')) { $this->try_mode = getenv('TRY_MODE'); $this->view->try_mode = $this->try_mode; } } public function detailAction() { list(, /*project*/, /*detail*/, $name) = explode('/', $this->getURI()); if (preg_match('#^\d+$#', $name) and $this->user->isAdmin()) { $project = Project::find($name); return $this->redirect('/project/detail/' . $project->name); } if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user) and !$this->user->isAdmin()) { return $this->alert('Project not found', '/'); } $enable_addons = array( 'mysql' => count(Machine::getMachinesByGroup('mysql')), 'pgsql' => count(Machine::getMachinesByGroup('pgsql')), 'elastic' => count(Machine::getMachinesByGroup('elastic')), ); $this->view->project = $project; $this->view->enable_addons = $enable_addons; } public function deletedomainAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } list(, /*project*/, /*adddomain*/, $name) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user)) { return $this->alert('Project not found', '/'); } if (!$domain = $project->custom_domains->search(array('domain' => $_GET['domain']))->first()) { return $this->alert('domain not found', '/'); } $domain->delete(); WebNode::cleanLoadBalancerCache(); // 更改 domain 後要清空 lb cache return $this->redirect('/project/detail/' . $project->name); } public function adddomainAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } if ($this->try_mode) { return $this->alert('目前為試用模式,此功能暫不開放', '/'); } list(, /*project*/, /*adddomain*/, $name) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user)) { return $this->alert('Project not found', '/'); } // from http://regexlib.com/REDetails.aspx?regexp_id=306 if (!preg_match('#^(([\w][\w\-\.]*)\.)?([\w][\w\-]+)(\.([\w][\w\.]*))?$#', $_POST['domain'])) { return $this->alert('Invalid domain', "/project/detail/{$project->name}"); } if (stripos($_POST['domain'], getenv('APP_SUFFIX'))) { return $this->alert('Invalid domain', "/project/detail/{$project->name}"); } try { $project->custom_domains->insert(array( 'domain' => strval($_POST['domain']), )); } catch (Pix_Table_DuplicateException $e) { return $this->alert('duplicate domain: ' . $_POST['domain'], "/project/detail/{$project->name}"); } WebNode::cleanLoadBalancerCache(); // 更改 domain 後要清空 lb cache return $this->redirect('/project/detail/' . $project->name); } public function deletevariableAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } list(, /*project*/, /*addvariable*/, $name, $key) = explode('/', $this->getURI()); $key = urldecode($key); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user)) { return $this->alert('Project not found', '/'); } if (!$variable = $project->variables->search(array('key' => $key))->first()) { return $this->alert('variable not found', '/'); } $variable->delete(); return $this->redirect('/project/detail/' . $project->name); } public function addvariableAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } list(, /*project*/, /*addvariable*/, $name) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user)) { return $this->alert('Project not found', '/'); } if ($_POST['file-config']) { $key = 'file:' . time(); $value = strval($_POST['filename']) . "\n" . strval($_POST['value']); } else { $key = strval($_POST['key']); $value = strval($_POST['value']); } // TODO: check valid key & value $project->variables->insert(array( 'key' => $key, 'value' => $value, 'is_magic_value' => 0, )); return $this->redirect('/project/detail/' . $project->name); } public function editnoteAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } list(, /*project*/, /*editnote*/, $name, $key) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user)) { return $this->alert('Project not found', '/'); } $project->setEAV('note', strval($_POST['note'])); return $this->redirect('/project/detail/' . $project->name); } public function edittemplateAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } list(, /*project*/, /*edittemplate*/, $name, $key) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user)) { return $this->alert('Project not found', '/'); } $templates = Project::getTemplates(); if (!array_key_exists($_POST['template'], $templates)) { return $this->error('template not found', '/'); } $project->setEAV('template', strval($_POST['template'])); return $this->redirect('/project/detail/' . $project->name); } public function addelastic2addonAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } if (!count(Machine::getMachinesByGroup('elastic'))) { return $this->alert('目前未支援 ElasticSearch', '/'); } list(, /*project*/, /*addelasticaddon*/, $name, $addon_id) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user)) { return $this->alert('Project not found', '/'); } if ($addon_id) { if (!$addon = Addon_Elastic2::find(intval($addon_id))) { return $this->alert('Addon not found', '/'); } $addon->saveProjectVariable(); } else { Addon_Elastic2::addDB($project); } return $this->redirect('/project/detail/' . $project->name); } public function addpgsqladdonAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } if (!count(Machine::getMachinesByGroup('pgsql'))) { return $this->alert('目前未支援 PgSQL', '/'); } list(, /*project*/, /*addpgsqladdon*/, $name, $addon_id) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user)) { return $this->alert('Project not found', '/'); } $key = is_scalar($_POST['key']) ? $_POST['key'] : 'DATABASE_URL'; if ($addon_id) { if (!$addon = Addon_PgSQLDB::find(intval($addon_id))) { return $this->alert('Addon not found', '/'); } if (!$addon_member = $addon->members->search(array('project_id' => $project->id))->first()) { return $this->alert('Addon not found', '/'); } $addon_member->saveProjectVariable($key); } else { Addon_PgSQLDB::addDB($project, $key); } return $this->redirect('/project/detail/' . $project->name); } public function addmysqladdonAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } if (!count(Machine::getMachinesByGroup('mysql'))) { return $this->alert('目前未支援 MySQL', '/'); } list(, /*project*/, /*addmysqladdon*/, $name, $addon_id) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user)) { return $this->alert('Project not found', '/'); } $key = is_scalar($_POST['key']) ? $_POST['key'] : 'DATABASE_URL'; if ($addon_id) { if (!$addon = Addon_MySQLDB::find(intval($addon_id))) { return $this->alert('Addon not found', '/'); } if (!$addon_member = $addon->members->search(array('project_id' => $project->id))->first()) { return $this->alert('Addon not found', '/'); } $addon_member->saveProjectVariable($key); } else { Addon_MySQLDB::addDB($project, $key); } return $this->redirect('/project/detail/' . $project->name); } public function addmemcacheaddonAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } list(, /*project*/, /*addmemcacheaddon*/, $name) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user)) { return $this->alert('Project not found', '/'); } Addon_Memcached::addDB($project); return $this->redirect('/project/detail/' . $project->name); } public function editvariableAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } list(, /*project*/, /*editvariable*/, $name, $key) = explode('/', $this->getURI()); $key = urldecode($key); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user)) { return $this->alert('Project not found', '/'); } if (!$variable = $project->variables->search(array('key' => $key))->first()) { return $this->alert('Variable not found', '/'); } if ($_POST['file-config']) { $value = strval($_POST['filename']) . "\n" . strval($_POST['value']); } else { $value = strval($_POST['value']); } $variable->update(array( 'value' => strval($value), 'is_magic_value' => 0, )); return $this->redirect('/project/detail/' . $project->name); } public function addcronjobAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } if ($this->try_mode) { return $this->alert('目前為試用模式,此功能暫不開放', '/'); } list(, /*project*/, /*addcronjob*/, $name) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user)) { return $this->alert('Project not found', '/'); } $project->cronjobs->insert(array( 'job' => strval($_POST['job']), 'period' => intval($_POST['period']), )); return $this->redirect('/project/detail/' . $project->name); } public function deletecronjobAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } list(, /*project*/, /*deletecronjob*/, $name, $id) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user)) { return $this->alert('Project not found', '/'); } if (!$cronjob = $project->cronjobs->search(array('id' => $id))->first()) { return $this->alert('Cronjob not found', '/'); } $cronjob->delete(); return $this->redirect('/project/detail/' . $project->name); } public function cronlogAction() { ini_set('memory_limit', '2g'); list(, /*project*/, /*cronlog*/, $name) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } $this->view->project = $project; if (!$project->isMember($this->user) and !$this->user->isAdmin()) { return $this->alert('Project not found', '/'); } } public function downloadcronlogAction() { ini_set('memory_limit', '2g'); list(, /*project*/, /*downloadcronlog*/, $name, $start, $cron_id, $type) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user)) { return $this->alert('Project not found', '/'); } $logs = array(); if (!$cronjob = $project->cronjobs->find($cron_id)) { return $this->alert('Cronjob not found', '/'); } header('Content-Type: text/plain'); foreach (json_decode($cronjob->getEAV('recent_logs')) ?: array() as $log) { if ($log->status->start != $start) { continue; } if ($type == 'stdout') { echo $log->stdout; } else { echo $log->stderr; } } return $this->noview(); } public function editcronjobAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } list(, /*project*/, /*editcronjob*/, $name, $id) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user)) { return $this->alert('Project not found', '/'); } if (!$cronjob = $project->cronjobs->search(array('id' => $id))->first()) { return $this->alert('Cronjob not found', '/'); } $cronjob->update(array( 'job' => strval($_POST['job']), 'period' => intval($_POST['period']), )); return $this->redirect('/project/detail/' . $project->name); } public function deletememberAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } list(, /*project*/, /*deletemember*/, $name) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isAdmin($this->user)) { return $this->alert('You are not admin', '/'); } if (!$user = User::find_by_name(strval($_GET['account']))) { return $this->alert('User not found', '/'); } if (!$project_member = $project->members->search(array('user_id' => $user->id))->first()) { return $this->alert('project member not found', '/'); } if ($project_member->is_admin and count($project->members->search(array('is_admin' => 1))) == 1) { return $this->alert('there is only one admin', '/'); } $project_member->delete(); return $this->redirect('/project/detail/' . $project->name); } public function addmemberAction() { if (Hisoku::getStoken() != $_POST['sToken']) { // TODO: log it return $this->alert('error', '/'); } list(, /*project*/, /*addmember*/, $name) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isAdmin($this->user)) { return $this->alert('You are not admin', '/'); } if (!$user = User::find_by_name(strval($_POST['account']))) { return $this->alert('User not found', '/'); } try { $project->members->insert(array( 'user_id' => $user->id, )); } catch (Pix_Table_DuplicateException $e) { } return $this->redirect('/project/detail/' . $project->name); } public function getlogAction() { list(, /*project*/, /*getlog*/, $name, $type) = explode('/', $this->getURI()); if (!$project = Project::find_by_name($name)) { return $this->alert('Project not found', '/'); } if (!$project->isMember($this->user) and !$this->user->isAdmin()) { return $this->alert('Project not found', '/'); } if ($type == 'error') { $category = "app-{$name}-error"; $log_filter = function($line){ list($timestamp, $node_id, $log) = explode(' ', $line); return date('c', $timestamp) . ' [' . $node_id . ']' . urldecode($log); }; } elseif ('node' == $type) { $category = "app-{$name}-node"; $log_filter = function($line){ $data = json_decode($line); if ('start' == $data->status) { $message = "Start a {$data->type} node"; if ($data->type == 'cron') { $message .= ': ' . $data->command; } } elseif ('over' == $data->status or 'wait' == $data->status) { $message = "Stop the {$data->type} node, spent: {$data->spent}"; } $message .= ' ' . json_encode($data); return date('c', $data->time) . "[{$data->ip}-{$data->port}] {$message}"; }; } else { $category = "app-{$name}"; $log_filter = null; } if ($_GET['before']) { list($file, $cursor) = explode(",", $_GET['before']); $logs = Logger::getLog($category, array('cursor-before' => array('file' => $file, 'cursor' => $cursor))); } elseif ($_GET['after']) { list($file, $cursor) = explode(",", $_GET['after']); $logs = Logger::getLog($category, array('cursor-after' => array('file' => $file, 'cursor' => $cursor))); } else { $logs = Logger::GetLog($category); } if (!is_null($log_filter)) { for ($i = 0; $i < count($logs[0]); $i ++) { $logs[0][$i] = $log_filter($logs[0][$i]); } } return $this->json($logs); } } <file_sep>/webdata/models/SFTPServer.php <?php // from http://tools.ietf.org/html/draft-ietf-secsh-filexfer-00 define('SSH_FXP_INIT', 1); define('SSH_FXP_VERSION', 2); define('SSH_FXP_OPEN', 3); define('SSH_FXP_CLOSE', 4); define('SSH_FXP_READ', 5); define('SSH_FXP_WRITE', 6); define('SSH_FXP_LSTAT', 7); define('SSH_FXP_FSTAT', 8); define('SSH_FXP_SETSTAT', 9); define('SSH_FXP_FSETSTAT', 10); define('SSH_FXP_OPENDIR', 11); define('SSH_FXP_READDIR', 12); define('SSH_FXP_REMOVE', 13); define('SSH_FXP_MKDIR', 14); define('SSH_FXP_RMDIR', 15); define('SSH_FXP_REALPATH', 16); define('SSH_FXP_STAT', 17); define('SSH_FXP_RENAME', 18); define('SSH_FXP_STATUS', 101); define('SSH_FXP_HANDLE', 102); define('SSH_FXP_DATA', 103); define('SSH_FXP_NAME', 104); define('SSH_FXP_ATTRS', 105); define('SSH_FXP_EXTENDED', 200); define('SSH_FXP_EXTENDED_REPLY', 201); define('SSH_FILEXFER_ATTR_SIZE', 0x00000001); define('SSH_FILEXFER_ATTR_UIDGID', 0x00000002); define('SSH_FILEXFER_ATTR_PERMISSIONS', 0x00000004); define('SSH_FILEXFER_ATTR_ACMODTIME', 0x00000008); define('SSH_FILEXFER_ATTR_EXTENDED', 0x80000000); define('SSH_FX_OK', 0); define('SSH_FX_EOF', 1); define('SSH_FX_NO_SUCH_FILE', 2); define('SSH_FX_PERMISSION_DENIED', 3); define('SSH_FX_FAILURE', 4); define('SSH_FX_BAD_MESSAGE', 5); define('SSH_FX_NO_CONNECTION', 6); define('SSH_FX_CONNECTION_LOST', 7); define('SSH_FX_OP_UNSUPPORTED', 8); define('SSH_FXF_READ', 0x00000001); define('SSH_FXF_WRITE', 0x00000002); define('SSH_FXF_APPEND', 0x00000004); define('SSH_FXF_CREAT', 0x00000008); define('SSH_FXF_TRUNC', 0x00000010); define('SSH_FXF_EXCL', 0x00000020); class SFTPServer { protected $_handle_serial = 1; protected $_handle_infos = array(); public function logger($message) { file_put_contents('/tmp/sftp-log', $message . "\n", FILE_APPEND); } public function getPermWord($perms) { // From http://tw2.php.net/manual/en/function.fileperms.php if (($perms & 0xC000) == 0xC000) { // Socket $info = 's'; } elseif (($perms & 0xA000) == 0xA000) { // Symbolic Link $info = 'l'; } elseif (($perms & 0x8000) == 0x8000) { // Regular $info = '-'; } elseif (($perms & 0x6000) == 0x6000) { // Block special $info = 'b'; } elseif (($perms & 0x4000) == 0x4000) { // Directory $info = 'd'; } elseif (($perms & 0x2000) == 0x2000) { // Character special $info = 'c'; } elseif (($perms & 0x1000) == 0x1000) { // FIFO pipe $info = 'p'; } else { // Unknown $info = 'u'; } // Owner $info .= (($perms & 0x0100) ? 'r' : '-'); $info .= (($perms & 0x0080) ? 'w' : '-'); $info .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-')); // Group $info .= (($perms & 0x0020) ? 'r' : '-'); $info .= (($perms & 0x0010) ? 'w' : '-'); $info .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-')); // World $info .= (($perms & 0x0004) ? 'r' : '-'); $info .= (($perms & 0x0002) ? 'w' : '-'); $info .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-')); return $info; } public function getRealPath($project, $project_path) { return "/srv/project_data/{$project}{$project_path}"; } public function read() { while (true) { if (feof($this->fp)) { return false; } // 先取得 4 個 byte 的 packet length $length = fread($this->fp, 4); if ('' !== $length) { break; } usleep(1000); } $array = unpack('NLength', $length); $length = $array['Length']; if (!$length) { exit; } // 再來把資料取出來 $packet = fread($this->fp, 1); $array = unpack('CType', $packet); $length = $length - 1; $data = ''; while ($length > strlen($data)) { $data .= fread($this->fp, $length - strlen($data)); } return array($array['Type'], $data); } public function send($packet_type, $datas) { $length = 1; $args = func_get_args(); for ($i = 1; $i < count($args); $i ++) { $length += strlen($args[$i]); } $ret = pack('NC', $length, $packet_type); for ($i = 1; $i < count($args); $i ++) { $ret .= $args[$i]; } fwrite($this->output, $ret); } public function parsePath($path) { if ($path == '/') { return array(null, '/'); } $terms = explode('/', trim($path, '/')); $project = array_shift($terms); if (!in_array($project, $this->getProjectsByUser())) { throw new Exception('project not found', 404); } return array($project, '/' . implode('/', $terms)); } public function getFileSize($project, $path) { return filesize($this->getRealPath($project, $path)); } public function getFilePermission($project, $path) { return fileperms($this->getRealPath($project, $path)); } public function getFileTime($project, $path) { $path = $this->getRealPath($project, $path); return array(fileatime($path), filemtime($path)); } public function getFTPAbsolutePath($base, $dir) { if ($dir[0] == '/') { $terms = array(); } else { $terms = ($base == '/') ? array() : explode('/', trim($base, '/')); } foreach (explode('/', trim($dir, '/')) as $term) { if ('.' == $term) { continue; } if ('..' == $term) { array_pop($terms); continue; } $terms[] = $term; } return '/' . implode('/', $terms); } public function parseAttrs($attrs) { $ret = array(); $r = unpack('Nflags', $attrs); $attrs = substr($attrs, 4); $ret = array_merge($ret, $r); $flags = $r['flags']; if ($flags & SSH_FILEXFER_ATTR_SIZE) { $r = unpack('Nsize', $attrs); $attrs = substr($attrs, 4); $ret = array_merge($ret, $r); } if ($flags & SSH_FILEXFER_ATTR_UIDGID) { $r = unpack('Nuid/Ngid', $attrs); $attrs = substr($attrs, 8); $ret = array_merge($ret, $r); } if ($flags & SSH_FILEXFER_ATTR_PERMISSIONS) { $r = unpack('Npermissions', $attrs); $attrs = substr($attrs, 4); $ret = array_merge($ret, $r); } if ($flags & SSH_FILEXFER_ATTR_ACMODTIME) { $r = unpack('Natime/Nmtime', $attrs); $attrs = substr($attrs, 8); $ret = array_merge($ret, $r); } // XXX: 還有 SSH_FILEXFER_ATTR_EXTENDED return $ret; } public function getattrs($path, $options = array()) { $full = array_key_exists('full', $options) ? intval($options['full']) : 0; $absolute_path = array_key_exists('absolute_path', $options) ? intval($options['absolute_path']) : 0; list($project, $path) = $this->parsePath($path); if (!file_exists($this->getRealPath($project, $path))) { throw new Exception("file not found", 404); } if ($full) { $flag = SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_UIDGID | SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_ACMODTIME; } else { $flag = 0; } $data = ''; $data .= pack('N', $flag); if ($flag & SSH_FILEXFER_ATTR_SIZE) { if ($project) { $size = $this->getFileSize($project, $path); } else { $size = 0; } $data .= pack('NN', $size / 0x100000000, $size); } if ($flag & SSH_FILEXFER_ATTR_UIDGID) { // 這邊沒有 uid, gid 的概念 $uid = 1000; $gid = 1000; $data .= pack('NN', $uid, $gid); } if ($flag & SSH_FILEXFER_ATTR_PERMISSIONS) { if ($project) { $permission = $this->getFilePermission($project, $path); } else { $permission = 0x4700; } $data .= pack('N', $permission); } if ($flag & SSH_FILEXFER_ATTR_ACMODTIME) { if ($project) { list($atime, $mtime) = $this->getFileTime($project, $path); } else { $atime = $mtime = strtotime('2013/1/1'); } $data .= pack('NN', $atime, $mtime); } if ($flag & SSH_FILEXFER_ATTR_EXTENDED) { // 用不到吧... $data .= pack('N', 0); } return $data; } public function getAccount() { return substr($this->user->name, 0, 8); } public function return_name_info($request_id, $base, $filenames, $options = array()) { $full = array_key_exists('full', $options) ? intval($options['full']) : 0; $absolute_path = array_key_exists('absolute_path', $options) ? intval($options['absolute_path']) : 0; $data = pack('NN', $request_id, count($filenames)); foreach ($filenames as $filename) { $path = $this->getFTPAbsolutePath($base, $filename); if ($path == '/') { if ($absolute_path) { $filename = '/'; } $longname = sprintf("%10s %3d %8s %8s %-8d %12s %s", 'drwx------', 1, $this->getAccount(), $this->getAccount(), 4096, 'Feb 31 00:00', $filename); } else { if ($absolute_path) { $filename = $path; } list($project, $project_path) = $this->parsePath($path); list($atime, $mtime) = $this->getFileTime($project, $project_path); $longname = sprintf("%10s %3d %8s %8s %-8d %12s %s", $this->getPermWord($this->getFilePermission($project, $project_path)), 1, $this->getAccount(), $this->getAccount(), $this->getFileSize($project, $project_path), date('M j H:i', $mtime), $filename ); } $data .= pack('Na*Na*a*', strlen($filename), $filename, strlen($longname), $longname, $this->getattrs($path, $options) ); } $this->send(SSH_FXP_NAME, $data); } protected $_projects = null; public function getProjectsByUser() { if (is_null($this->_projects)) { $project_ids = $this->user->project_members->toArray('project_id'); $projects = array(); foreach (Project::search(1)->searchIn('id', $project_ids)->toArray('name') as $name) { if (file_exists($this->getRealPath($name, '/'))) { $projects[] = $name; } } $this->_projects = $projects; } return $this->_projects; } public function openFile($request_id, $filename, $pflags, $attrs) { list($project, $project_path) = $this->parsePath($filename); $handle = $this->_handle_serial ++; $infos = array(); $infos['path'] = $filename; if (!$project) { $this->send(SSH_FXP_STATUS, pack('NN', $request_id, SSH_FX_NO_SUCH_FILE)); return; } $flag = ''; if ($pflags & SSH_FXF_CREAT) { $flag .= 'c'; } elseif ($pflags & SSH_FXF_APPEND) { $flag .= 'a'; } elseif ($pflags & SSH_FXF_WRITE) { $flag .= 'w'; } $path = $this->getRealPath($project, $project_path); if ($flag != '') { $attrs = $this->parseAttrs($attrs); if ($attrs['mtime'] and $attrs['atime']) { touch($path, $attrs['mtime'], $attrs['atime']); } if ($attrs['permissions']) { chmod($path, $attrs['permissions']); } } if ($pflags & SSH_FXF_READ) { if ($flag == '') { $flag .= 'r'; } else { $flag .= '+'; } } $flag .= 'b'; $infos['fp'] = fopen($path, $flag); if (!$infos['fp']) { $this->send(SSH_FXP_STATUS, pack('NN', $request_id, SSH_FX_FAILURE)); return; } $infos['filesize'] = filesize($path); $this->_handle_infos[$handle] = $infos; $this->send(SSH_FXP_HANDLE, pack('NN', $request_id, strlen($handle)) . $handle); } public function main($user) { $this->fp = fopen('php://stdin', 'r'); $this->output = fopen('php://stdout', 'w'); $this->path = '/'; if (!$user = User::find_by_name($user)) { return; } $this->user = $user; while (true) { $ret = $this->read(); if (false === $ret) { break; } list($type, $data) = $ret; switch ($type) { case SSH_FXP_INIT: $this->send(SSH_FXP_VERSION, pack('N', 3)); break; case SSH_FXP_REALPATH: $ret = unpack('Nid/Npath_length/a*path', $data); $path = $this->getFTPAbsolutePath($this->path, $ret['path']); try { $this->return_name_info($ret['id'], $path, array(''), array('absolute_path' => true)); $this->path = $path; } catch (Exception $e) { if ($e->getCode() == 404) { $this->send(SSH_FXP_STATUS, pack('NN', $ret['id'], SSH_FX_NO_SUCH_FILE)); } else { throw $e; } } break; case SSH_FXP_OPENDIR: $ret = unpack('Nid/Npath_length/a*path', $data); $path = $this->getFTPAbsolutePath($this->path, $ret['path']); list($project, $project_path) = $this->parsePath($path); $handle = $this->_handle_serial ++; $infos = array(); $infos['path'] = $path; if (!$project) { $infos['files'] = $this->getProjectsByUser(); } else { $infos['dir'] = opendir($this->getRealPath($project, $project_path)); } $this->_handle_infos[$handle] = $infos; $this->send(SSH_FXP_HANDLE, pack('NN', $ret['id'], strlen($handle)), $handle); break; case SSH_FXP_READDIR: $ret = unpack('Nid/Nhandle_length/a*handle', $data); $handle = $ret['handle']; if (!array_key_exists($handle, $this->_handle_infos)) { $this->send(SSH_FXP_STATUS, pack('NN', $ret['id'], SSH_FX_FAILURE)); break; } if (array_key_exists('files', $this->_handle_infos[$handle])) { if (0 == count($this->_handle_infos[$handle]['files'])) { $this->send(SSH_FXP_STATUS, pack('NN', $ret['id'], SSH_FX_EOF)); break; } $filenames = array(); for ($i = 0; $i < 100 and count($this->_handle_infos[$handle]['files']); $i ++) { $filenames[] = array_pop($this->_handle_infos[$handle]['files']); } $this->return_name_info($ret['id'], $this->_handle_infos[$handle]['path'], $filenames, array('full' => true)); } elseif (array_key_exists('dir', $this->_handle_infos[$handle])) { $filenames = array(); while ($dir = readdir($this->_handle_infos[$handle]['dir'])) { $filenames[] = $dir; if (count($filenames) >= 100) { break; } } if (!$filenames) { $this->send(SSH_FXP_STATUS, pack('NN', $ret['id'], SSH_FX_EOF)); break; } $this->return_name_info($ret['id'], $this->_handle_infos[$handle]['path'], $filenames, array('full' => true)); } else { $this->send(SSH_FXP_STATUS, pack('NN', $ret['id'], SSH_FX_FAILURE)); break; } break; case SSH_FXP_CLOSE: $ret = unpack('Nid/Nhandle_length/a*handle', $data); $handle = $ret['handle']; if (!array_key_exists($handle, $this->_handle_infos)) { $this->send(SSH_FXP_STATUS, pack('NN', $ret['id'], SSH_FX_FAILURE)); break; } if (array_key_exists('dir', $this->_handle_infos[$handle])) { closedir($this->_handle_infos[$handle]['dir']); } elseif (array_key_exists('fp', $this->_handle_infos[$handle])) { fclose($this->_handle_infos[$handle]['fp']); } unset($this->_handle_infos[$handle]); $this->send(SSH_FXP_STATUS, pack('NN', $ret['id'], SSH_FX_OK)); break; case SSH_FXP_STAT: case SSH_FXP_LSTAT: $ret = unpack('Nid/Npath_length/a*path', $data); try { $this->send(SSH_FXP_ATTRS, pack('N', $ret['id']) . $this->getattrs($ret['path'], array('full' => true))); } catch (Exception $e) { if ($e->getCode() == 404) { $this->send(SSH_FXP_STATUS, pack('NN', $ret['id'], SSH_FX_NO_SUCH_FILE)); } else { throw $e; } } break; case SSH_FXP_MKDIR: $ret = unpack('Nid/Npath_length', $data); $path = substr($data, 8, $ret['path_length']); $path = $this->getFTPAbsolutePath($this->path, $path); list($project, $project_path) = $this->parsePath($path); $real_path = $this->getRealPath($project, $project_path); $this->logger($real_path); if (mkdir($real_path)) { $this->send(SSH_FXP_STATUS, pack('NN', $ret['id'], SSH_FX_OK)); } else { $this->send(SSH_FXP_STATUS, pack('NN', $ret['id'], SSH_FX_FAILURE)); } break; case SSH_FXP_RMDIR: $ret = unpack('Nid/Npath_length', $data); $path = substr($data, 8, $ret['path_length']); $path = $this->getFTPAbsolutePath($this->path, $path); list($project, $project_path) = $this->parsePath($path); $real_path = $this->getRealPath($project, $project_path); if (rmdir($real_path)) { $this->send(SSH_FXP_STATUS, pack('NN', $ret['id'], SSH_FX_OK)); } else { $this->send(SSH_FXP_STATUS, pack('NN', $ret['id'], SSH_FX_FAILURE)); } break; case SSH_FXP_OPEN: $ret = unpack('Nid/Nfilename_length', $data); $request_id = $ret['id']; $filename_length = $ret['filename_length']; $filename = substr($data, 8, $filename_length); $ret = unpack('Npflags/a*attrs', substr($data, 8 + $filename_length)); $this->openFile($request_id, $filename, $ret['pflags'], $ret['attrs']); break; case SSH_FXP_WRITE: $ret = unpack('Nid/Nhandle_length', $data); $request_id = $ret['id']; $handle_length = $ret['handle_length']; $handle = substr($data, 8, $handle_length); $ret = unpack('Noffset_upper/Noffset_lower/Ndata_length', substr($data, 8 + $handle_length)); $offset = $ret['offset_upper'] * 0x100000000 + $ret['offset_lower']; $data = substr($data, 8 + $handle_length + 12, $ret['data_length']); if (!array_key_exists($handle, $this->_handle_infos) or !array_key_exists('fp', $this->_handle_infos[$handle])) { $this->send(SSH_FXP_STATUS, pack('NN', $ret['id'], SSH_FX_FAILURE)); break; } $fp = $this->_handle_infos[$handle]['fp']; // TODO: 檢查不合法的 offset, len if (fseek($fp, $offset) < 0) { $this->send(SSH_FXP_STATUS, pack('NN', $request_id, SSH_FX_FAILURE)); break; } fwrite($fp, $data); $this->send(SSH_FXP_STATUS, pack('NN', $request_id, SSH_FX_OK)); break; case SSH_FXP_READ: $ret = unpack('Nid/Nhandle_length', $data); $request_id = $ret['id']; $handle_length = $ret['handle_length']; $handle = substr($data, 8, $handle_length); $ret = unpack('Noffset_upper/Noffset_lower/Nlen', substr($data, 8 + $handle_length)); $offset = $ret['offset_upper'] * 0x100000000 + $ret['offset_lower']; $len = $ret['len']; if (!array_key_exists($handle, $this->_handle_infos) or !array_key_exists('fp', $this->_handle_infos[$handle])) { $this->send(SSH_FXP_STATUS, pack('NN', $ret['id'], SSH_FX_FAILURE)); break; } $fp = $this->_handle_infos[$handle]['fp']; $filesize = $this->_handle_infos[$handle]['filesize']; // TODO: 檢查不合法的 offset, len if (fseek($fp, $offset) < 0) { $this->send(SSH_FXP_STATUS, pack('NN', $request_id, SSH_FX_FAILURE)); break; } $data = fread($fp, $len); if (false === $data) { $this->send(SSH_FXP_STATUS, pack('NN', $request_id, SSH_FX_FAILURE)); } else if (strlen($data) == 0) { $this->send(SSH_FXP_STATUS, pack('NN', $request_id, SSH_FX_EOF)); } else { $this->send(SSH_FXP_DATA, pack('NN', $request_id, strlen($data)), $data); } break; case SSH_FXP_FSETSTAT: case SSH_FXP_SETSTAT: $ret = unpack('Nid/Npathhandle_length', $data); $request_id = $ret['id']; $pathhandle = substr($data, 8, $ret['pathhandle_length']); $attrs = substr($data, 8 + $ret['pathhandle_length']); if (SSH_FXP_FSETSTAT == $type) { $handle = $pathhandle; if (!array_key_exists($handle, $this->_handle_infos) or !array_key_exists('fp', $this->_handle_infos[$handle])) { $this->send(SSH_FXP_STATUS, pack('NN', $ret['id'], SSH_FX_FAILURE)); break; } $path = $this->_handle_infos[$handle]['path']; } else { $path = $pathhandle; } $ftp_path = $this->getFTPAbsolutePath($this->path, $path); list($project, $project_path) = $this->parsePath($ftp_path); $path = $this->getRealPath($project, $project_path); if (!file_exists($path)) { $this->send(SSH_FXP_STATUS, pack('NN', $request_id, SSH_FX_NO_SUCH_FILE)); break; } $attrs = $this->parseAttrs($attrs); if ($attrs['mtime'] and $attrs['atime']) { touch($path, $attrs['mtime'], $attrs['atime']); } if ($attrs['permissions']) { chmod($path, $attrs['permissions']); } $this->send(SSH_FXP_STATUS, pack('NN', $request_id, SSH_FX_OK)); break; case SSH_FXP_REMOVE: $ret = unpack('Nid/Nfilename_length', $data); $request_id = $ret['id']; $filename = substr($data, 8, $ret['filename_length']); $path = $this->getFTPAbsolutePath($this->path, $filename); list($project, $project_path) = $this->parsePath($path); $real_path = $this->getRealPath($project, $project_path); if (unlink($real_path)) { $this->send(SSH_FXP_STATUS, pack('NN', $request_id, SSH_FX_OK)); } else { $this->send(SSH_FXP_STATUS, pack('NN', $request_id, SSH_FX_FAILURE)); } break; case SSH_FXP_RENAME: $ret = unpack('Nid/Noldpath_length', $data); $request_id = $ret['id']; $oldpath = substr($data, 8, $ret['oldpath_length']); $ret = unpack('Nnewpath_length', substr($data, 8 + $ret['oldpath_length'])); $newpath = substr($data, 8 + strlen($oldpath) + 4, $ret['newpath_length']); $this->logger($oldpath); $this->logger($newpath); $path = $this->getFTPAbsolutePath($this->path, $oldpath); list($project, $project_path) = $this->parsePath($path); $old_real_path = $this->getRealPath($project, $project_path); $path = $this->getFTPAbsolutePath($this->path, $newpath); list($project, $project_path) = $this->parsePath($path); $new_real_path = $this->getRealPath($project, $project_path); if (rename($old_real_path, $new_real_path)) { $this->send(SSH_FXP_STATUS, pack('NN', $request_id, SSH_FX_OK)); } else { $this->send(SSH_FXP_STATUS, pack('NN', $request_id, SSH_FX_FAILURE)); } break; default: $ret = unpack('Nid', $data); $this->send(SSH_FXP_STATUS, pack('NN', $ret['id'], SSH_FX_OP_UNSUPPORTED)); return; } } } } <file_sep>/webdata/controllers/ApiController.php <?php class ApiController extends Pix_Controller { public function init() { } public function checkelasticAction() { $index = strval($_GET['index']); $secret = $_GET['secret']; $sig = crc32($index . $secret . getenv('ELASTIC_SECRET')); if ($_GET['sig'] != $sig) { return $this->json(array('error' => true, 'message' => 'wrong sig')); } if (!$addon = Addon_Elastic::search(array('index' => $index))->first()) { return $this->json(array('error' => true, 'message' => 'wrong index')); } if ($addon->secret != $secret) { return $this->json(array('error' => true, 'message' => 'wrong secret')); } return $this->json(array('error' => false)); } public function weblogAction() { // TODO: 要限內網並且加上 secret key if (!$logs = json_decode($_POST['data'])) { throw new Exception('invalid data'); } $messages = array(); foreach ($logs as $log) { $messages[] = array( 'category' => "app-{$log->project}-error", 'message' => $log->time . ' ' . $log->id . ' ' . urlencode($log->log), ); } Logger::log($messages); return $this->json(1); } public function updatemachinestatusAction() { // TODO: 要判斷只有內網可以 $name = strval($_GET['name']); $status = $_POST['status']; $machine = Machine::find_by_ip(ip2long($_SERVER['REMOTE_ADDR'])); if (!$machine) { return $this->json(1); } MachineStatus::insert(array( 'machine_id' => $machine->machine_id, 'status' => $status, 'updated_at' => time(), )); return $this->json(1); } } <file_sep>/scripts/getip #!/usr/bin/env php <?php include(__DIR__ . '/../webdata/init.inc.php'); $ips = array(); for ($i = 1; $i < count($_SERVER['argv']); $i ++) { foreach (Hisoku::getIPsByGroup($_SERVER['argv'][$i]) as $ip) { $ips[$ip] = true; } } echo implode(' ', array_keys($ips)); <file_sep>/scripts/initdb #!/usr/bin/env php <?php include(__DIR__ . '/../webdata/init.inc.php'); Addon_Elastic::createTable(); Addon_Memcached::createTable(); Addon_MySQLDB::createTable(); Addon_MySQLDBMember::createTable(); Addon_PgSQLDB::createTable(); Addon_PgSQLDBMember::createTable(); Admin::createTable(); CronJob::createTable(); CustomDomain::createTable(); EAV::createTable(); Machine::createTable(); MachineStatus::createTable(); Project::createTable(); ProjectMember::createTable(); ProjectVariable::createTable(); SSLKey::createTable(); SignupConfirm::createTable(); User::createTable(); UserKey::createTable(); WebNode::createTable(); WebNodeEAV::createTable(); <file_sep>/cron/1day/nodes-count.php #!/usr/bin/env php <?php include(__DIR__ . '/../../webdata/init.inc.php'); $pv_count = $size_count = array(); foreach (glob("/srv/logs/scribed/app-*") as $log_directory) { if (!preg_match('#/srv/logs/scribed/app-([^-]*-[^-]*-[0-9]*)$#', $log_directory, $matches)) { continue; } $app_name = $matches[1]; foreach (glob("{$log_directory}/app-{$app_name}-" . date('Y-m-d', time() - 86400) . '_*') as $log_file) { $fp = fopen($log_file, 'r'); while ($line = fgets($fp)) { list($hostname_ip_none_none_datetime_timezone, $method_uri_version, $rescode_size, $referer) = explode('"', $line); list($rescode, $size) = explode(' ', $rescode_size); $pv_count[$app_name] ++; $size_count[$app_name] += $size; } fclose($fp); } } $node_count = array(); $today = mktime(0, 0, 0); $yesterday = $today - 86400; foreach (glob("/srv/logs/scribed/app-*-node") as $log_directory) { if (!preg_match('#/srv/logs/scribed/app-([^-]*-[^-]*-[0-9]*)-node$#', $log_directory, $matches)) { continue; } $app_name = $matches[1]; // 從昨天到今天 foreach (array($yesterday, $today) as $day) { foreach (glob("{$log_directory}/app-{$app_name}-node-" . date('Y-m-d', $day) . '_*') as $log_file) { $fp = fopen($log_file, 'r'); while ($line = fgets($fp)) { $data = json_decode($line); $ip_port = $data->ip . '-' . $data->port; if ($data->status == 'over' or $data->status == 'wait') { if ($day == $yesterday) { // 昨天的檢查看看是不是有跨天,有的話就要只從零點算起 $node_count[$app_name][$data->type] += min($data->spent, $data->time - $yesterday); } else { // 今天的話就要看看是不是跨天的 $node_count[$app_name][$data->type] += min(86400, max(0, $today - ($data->time - $data->spent))); } } } fclose($fp); } } } foreach (WebNode::search(1) as $node) { if ($node->start_at > $today) { continue; } if (WebNode::STATUS_CRONNODE == $node->status) { $node_count[$node->project->name]['cron'] += max(0, $today - max($node->start_at, $yesterday)); } elseif (WebNode::STATUS_WEBNODE == $node->status) { $node_count[$node->project->name]['web'] += max(0, $today - max($node->start_at, $yesterday)); } } $output = fopen('/srv/logs/nodes-count/' . date('Ymd', $yesterday), 'w'); foreach (array_unique(array_merge(array_keys($pv_count), array_keys($size_count), array_keys($node_count))) as $app_name) { fputcsv($output, array( $app_name, Project::find_by_name($app_name)->getEAV('note'), $pv_count[$app_name], $size_count[$app_name], floor($node_count[$app_name]['web']), floor($node_count[$app_name]['cron']), )); } fclose($output); <file_sep>/webdata/models/Addon/MySQLDB.php <?php class Addon_MySQLDBRow extends Pix_Table_Row { public function saveProjectVariable($key = 'DATABASE_URL') { Addon_MySQLDBMember::search(array('addon_id' => $this->id, 'project_id' => $this->project_id))->first()->saveProjectVariable($key); } public function isMember($user) { return $this->project->isMember($user); } public function isAdmin($user) { return $this->project->isAdmin($user); } public function getEAVs() { return EAV::search(array('table' => 'AddonMySQLDB', 'id' => $this->id)); } public function addProject($project, $readonly = true) { $username = Hisoku::uniqid(16); $password = <PASSWORD>::<PASSWORD>(16); $link = new mysqli($this->host, getenv('MYSQL_USERDB_USER'), getenv('MYSQL_USERDB_PASS')); $db = new Pix_Table_Db_Adapter_Mysqli($link); try { $addon_member = Addon_MySQLDBMember::insert(array( 'project_id' => $project->id, 'addon_id' => $this->id, 'username' => $username, 'password' => $<PASSWORD>, )); $db->query("CREATE USER '{$username}'@'%' IDENTIFIED BY '{$password}'"); } catch (Pix_Table_DuplicateException $e) { $addon_member = Addon_MySQLDBMember::find(array($this->id, $project->id)); $db->query("REVOKE ALL PRIVILEGES, GRANT OPTION FROM '{$addon_member->username}'@'%'"); } $addon_member->update(array( 'readonly' => $readonly ? 1: 0, )); if ($readonly) { $db->query("GRANT SELECT ON `{$this->database}` . * TO '{$addon_member->username}'@'%'"); } else { $db->query("GRANT ALL PRIVILEGES ON `{$this->database}` . * TO '{$addon_member->username}'@'%'"); } } } class Addon_MySQLDB extends Pix_Table { public function init() { $this->_name = 'addon_mysqldb'; $this->_rowClass = 'Addon_MySQLDBRow'; $this->_primary = array('id'); $this->_columns['id'] = array('type' => 'int', 'auto_increment' => true); $this->_columns['project_id'] = array('type' => 'int'); $this->_columns['host'] = array('type' => 'varchar', 'size' => 255); $this->_columns['database'] = array('type' => 'varchar', 'size' => 32); $this->_relations['project'] = array('rel' => 'has_one', 'type' => 'Project', 'foreign_key' => 'project_id'); $this->_relations['members'] = array('rel' => 'has_many', 'type' => 'Addon_MySQLDBMember', 'foreign_key' => 'addon_id'); $this->addIndex('project_id', array('project_id')); $this->_hooks['eavs'] = array('get' => 'getEAVs'); $this->addRowHelper('Pix_Table_Helper_EAV', array('getEAV', 'setEAV')); } public static function addDB($project, $key = 'DATABASE_URL') { if ($addon = self::search(array('project_id' => $project->id))->first()) { $addon->saveProjectVariable($key); return; } $project_config = json_decode($project->config); $project_group = property_exists($project_config, 'node-group') ? $project_config->{'node-group'} : ''; if ($project_group and $ips = Machine::getIPsByGroup('mysql_' . $project_group)) { } else { $ips = array(); foreach (Machine::getMachinesByGroup('mysql') as $machine) { $groups = $machine->getGroups(); foreach ($groups as $group) { if (strpos($group, 'mysql_') === 0) { // skip mysql with group continue 2; } } $ips[] = long2ip($machine->ip); } } $host = array_pop($ips); $database = 'user_' . $project->name; $link = new mysqli($host, getenv('MYSQL_USERDB_USER'), getenv('MYSQL_USERDB_PASS')); $db = new Pix_Table_Db_Adapter_Mysqli($link); $db->query("CREATE DATABASE IF NOT EXISTS`{$database}` CHARACTER SET utf8"); $addon = self::insert(array( 'project_id' => $project->id, 'host' => $host, 'database' => $database, )); $addon->addProject($project, false); $addon->saveProjectVariable($key); } } <file_sep>/webdata/models/User.php <?php class UserRow extends Pix_Table_Row { /** * addKey * * @param string $keybody * @access public * @throw InvalidArgumentException * @throw Pix_Table_DuplicateException * @return UserKeyRow */ public function addKey($keybody) { $keybody = trim($keybody); $terms = explode(' ', $keybody); if (3 !== count($terms)) { throw new InvalidArgumentException('invalid key, there should be 3 terms in key'); } list($type, $body, $user) = $terms; if (!in_array($type, array('ssh-rsa', 'ssh-dsa'))) { throw new InvalidArgumentException('invalid ssh type, first term must be ssh-rsa or ssh-dsa'); } if (preg_match('#[^a-zA-Z0-9/+=]#', $body)) { throw new InvalidArgumentException('invalid ssh key, include invalid char'); } $key = $this->keys->insert(array( 'key_fingerprint' => md5(base64_decode($body)), 'key_body' => $keybody, )); return $key; } public function addProject($name = '') { $name = trim($name); if ('' == $name) { $name = null; } if (!is_null($name)) { $name = strtolower($name); if (!preg_match('#^[a-z][a-z0-9-]+$#', $name)) { throw new InvalidArgumentException('invalid project name'); } if (strlen($name) > 32 or strlen($name) < 6) { throw new InvalidArgumentException('project length in 6 ~ 32'); } } $project = null; for ($i = 0; $i < 3; $i ++) { try { $project = Project::insert(array( 'name' => is_null($name) ? Project::getRandomName() : strval($name), 'created_at' => time(), 'created_by' => $this->id, )); break; } catch (Pix_Table_DuplicateException $e) { if (!is_null($name)) { throw $e; } } } if (is_null($project)) { throw new Exception('generate name failed'); } $project->members->insert(array( 'user_id' => $this->id, 'is_admin' => 1, )); if ($this->getEAV('try-user')) { $project->update(array('config' => json_encode(array('node-group' => 'try')))); } return $project; } public function verifyPassword($password) { return $this->hashPassword($password) == $this->password; } public function setPassword($password) { $this->password_type = 1; $this->password = $this-><PASSWORD>($password); $this->save(); } public function hashPassword($password) { switch ($this->password_type) { case 1: return base64_encode(hash_hmac('sha256', $password, $this->name, true)); default: throw new Excpetion('unknown password_type'); } } public function isAdmin() { return Admin::find($this->id) ? true : false; } public function getOwnedMySQLDatabases() { $project_ids = $this->project_members->toArray('project_id'); if (!$project_ids) { return array(); } return Addon_MySQLDB::search(1)->searchIn('project_id', $project_ids); } public function getEAVs() { return EAV::search(array('table' => 'User', 'id' => $this->id)); } } class User extends Pix_Table { public function init() { $this->_name = 'user'; $this->_primary = 'id'; $this->_rowClass = 'UserRow'; $this->_columns['id'] = array('type' => 'int', 'auto_increment' => true); $this->_columns['name'] = array('type' => 'varchar', 'size' => 128); // password_type: <PASSWORD> $this->_columns['password_type'] = array('type' => 'tinyint'); $this->_columns['password'] = array('type' => 'char', 'size' => 64); // 0 - created (wait confirm) // 1 - actived // 2 - disasbled $this->_columns['status'] = array('type' => 'int'); $this->_indexes['name'] = array('type' => 'unique', 'columns' => array('name')); $this->_relations['keys'] = array('rel' => 'has_many', 'type' => 'UserKey', 'foreign_key' => 'user_id', 'delete' => true); $this->_relations['project_members'] = array('rel' => 'has_many', 'type' => 'ProjectMember', 'foreign_key' => 'user_id'); $this->_hooks['eavs'] = array('get' => 'getEAVs'); $this->addRowHelper('Pix_Table_Helper_EAV', array('getEAV', 'setEAV')); } } <file_sep>/README.md hisoku ====== Hisoku 是 ronnywang 開發的 PaaS 平台,目前 ronnywang 的服務如 [新聞小幫手](https://newshelper.g0v.ronny.tw), [求職小幫手](https://jobhelper.g0v.ronny.tw), [台灣公司資料](http://company.g0v.ronny.tw) 等都是運行在這個 PaaS 上面。 hisoku 特點 ----------- * 支援 git deployment * 可建立 mysql, postgresql, elasticsearch 給專案使用 * 支援 php, python(requirements.txt), ruby(Gemfile), nodejs(package.json) * 專案運行在 docker 內,專案和專案之間無法互相存取 系統架構說明 ------------ TODO License ------- * BSD License <file_sep>/webdata/controllers/AdminController.php <?php class AdminController extends Pix_Controller { public function init() { // TODO: admin 應該要再登入一次,最好還意加上 2-step if (!$this->user = Hisoku::getLoginUser()) { return $this->rediect('/'); } if (!$this->user->isAdmin()) { return $this->rediect('/'); } $this->view->user = $this->user; $this->view->action = $this->getActionName(); } public function indexAction() { return $this->redirect('/admin/nodeservers'); } public function nodeserversAction() { } public function databasesAction() { } public function pgsqlsAction() { } public function loadbalancersAction() { } public function logAction() { list(, /*admin*/, /*getlog*/, $category) = explode('/', $this->getURI()); if (!$category) { $category = 'login'; } $this->view->category = $category; } public function getlogAction() { list(, /*admin*/, /*getlog*/, $category) = explode('/', $this->getURI()); if (in_array($category, array('login', 'git-ssh-serve'))) { $log_filter = function($line){ $terms = explode(' ', $line); $time = date('c', array_shift($terms)); return $time . ' ' . implode( ' ' , $terms); }; } else { $log_filter = null; } if ($_GET['before']) { list($file, $cursor) = explode(",", $_GET['before']); $logs = Logger::getLog($category, array('cursor-before' => array('file' => $file, 'cursor' => $cursor))); } elseif ($_GET['after']) { list($file, $cursor) = explode(",", $_GET['after']); $logs = Logger::getLog($category, array('cursor-after' => array('file' => $file, 'cursor' => $cursor))); } else { $logs = Logger::GetLog($category); } if (!is_null($log_filter)) { for ($i = 0; $i < count($logs[0]); $i ++) { $logs[0][$i] = $log_filter($logs[0][$i]); } } return $this->json($logs); } public function nodeserverbulkaddportAction() { list(, /*admin*/, /*nodeserverbulkaddport*/, $ip, $num) = explode('/', $this->getURI()); if ($_POST['sToken'] != Hisoku::getStoken()) { return $this->alert('wrong stoken', '/admin'); } if (!filter_var($ip, FILTER_VALIDATE_IP)) { return $this->alert('wrong ip', '/admin'); } $num = intval($_REQUEST['count']); if ($num <= 0 or $num > 100) { return $this->alert('num must in 1 ~ 100', '/admin'); } $group = strval($_REQUEST['group']); $config = null; if ($group) { $config = array("node-group" => $group); } for ($i = 1; $i <= $num ; $i ++) { if (WebNode::find(array(ip2long($ip), 20000 + $i))) { continue; } try { WebNode::initNode($ip, $i, $config); } catch (Exception $e) { return $this->alert($e->getMessage(), '/admin'); } } return $this->alert('done', '/admin'); } public function nodeserveraddportAction() { list(, /*admin*/, /*nodeserveraddport*/, $ip, $port) = explode('/', $this->getURI()); if ($_POST['sToken'] != Hisoku::getStoken()) { return $this->alert('wrong stoken', '/admin'); } if (!filter_var($ip, FILTER_VALIDATE_IP)) { return $this->alert('wrong ip', '/admin'); } $port = intval($port); if ($port <= 0 or $port > 100) { return $this->alert('port must in 1 ~ 100', '/admin'); } if (WebNode::find(array(ip2long($ip), 20000 + $port))) { return $this->alert('port ' . (20000 + $port) . ' is existed', '/admin'); } $group = strval($_REQUEST['group']); $config = null; if ($group) { $config = array("node-group" => $group); } try { WebNode::initNode($ip, $port, $config); } catch (Exception $e) { return $this->alert($e->getMessage(), '/admin'); } return $this->alert('done', '/admin'); } public function nodeserverdeleteportAction() { list(, /*admin*/, /*nodeserverdeleteport*/, $ip, $port) = explode('/', $this->getURI()); if ($_POST['sToken'] != Hisoku::getStoken()) { return $this->alert('wrong stoken', '/admin'); } if (!filter_var($ip, FILTER_VALIDATE_IP)) { return $this->alert('wrong ip', '/admin'); } $port = intval($port); if ($port <= 0 or $port > 100) { return $this->alert('port must in 1 ~ 100', '/admin'); } if (!$node = WebNode::find(array(ip2long($ip), 20000 + $port))) { return $this->alert('port ' . (20000 + $port) . ' is not found', '/admin'); } $node->delete(); return $this->alert('done', '/admin'); } public function nodeserverreleaseportAction() { list(, /*admin*/, /*nodeserverreleaseport*/, $ip, $port) = explode('/', $this->getURI()); if ($_POST['sToken'] != Hisoku::getStoken()) { return $this->alert('wrong stoken', '/admin'); } if (!filter_var($ip, FILTER_VALIDATE_IP)) { return $this->alert('wrong ip', '/admin'); } $port = intval($port); if ($port <= 0 or $port > 100) { return $this->alert('port must in 1 ~ 100', '/admin'); } if (!$node = WebNode::find(array(ip2long($ip), 20000 + $port))) { return $this->alert('port ' . (20000 + $port) . ' is not found', '/admin'); } $node->markAsUnused(); return $this->alert('done', '/admin'); } public function nodeserverstopportAction() { list(, /*admin*/, /*nodeserverstopport*/, $ip, $port) = explode('/', $this->getURI()); if ($_POST['sToken'] != Hisoku::getStoken()) { return $this->alert('wrong stoken', '/admin'); } if (!filter_var($ip, FILTER_VALIDATE_IP)) { return $this->alert('wrong ip', '/admin'); } $port = intval($port); if ($port <= 0 or $port > 100) { return $this->alert('port must in 1 ~ 100', '/admin'); } if (!$node = WebNode::find(array(ip2long($ip), 20000 + $port))) { return $this->alert('port ' . (20000 + $port) . ' is not found', '/admin'); } $node->update(array( 'project_id' => 0, 'commit' => '', 'status' => WebNode::STATUS_STOP, )); return $this->alert('done', '/admin'); } public function machinesAction() { if ($machine_id = intval($_GET['machine_id']) and $machine = Machine::find($machine_id)) { $this->view->machine = $machine; } } public function addmachineAction() { if ($_POST['sToken'] != Hisoku::getStoken()) { return $this->alert('wrong stoken', '/admin/machines'); } if (!filter_var($_REQUEST['ip'], FILTER_VALIDATE_IP)) { return $this->alert('wrong ip', '/admin/machines'); } if ($machine = Machine::find(intval($_GET['machine_id']))) { $machine->update(array( 'name' => strval($_POST['name']), 'ip' => ip2long($_REQUEST['ip']), )); } else { $machine = Machine::insert(array( 'name' => strval($_POST['name']), 'ip' => ip2long($_REQUEST['ip']), )); } $machine->setGroups($_REQUEST['groups']); return $this->alert('add machine done!', '/admin/machines'); } public function searchesAction() { } public function elasticAction() { } public function elasticindexAction() { if (!$machine = Machine::find(intval($_GET['machine']))) { return $this->json(0); } if (!$index = $_GET['index']) { return $this->json(0); } if (strpos($index, '/') !== false or strpos($index, '?') !== false) { return $this->json(0); } Elastic::login('https://elastic-1.middle2.com:9200', getenv('ELASTIC_ADMIN_USER'), getenv('ELASTIC_ADMIN_PASSWORD')); // TODO: change url try { return $this->json(Elastic::esQuery('/' . $_GET['index'] . '/')); } catch (Exception $e) { return $this->json([ 'error' => true, 'message' => $e->getMessage(), ]); } } public function machinelogAction() { list(, /*admin*/, /*machinelog*/, $machine_id, $time) = explode('/', $this->getURI()); if (!$status = MachineStatus::find(array(intval($machine_id), intval($time)))) { return $this->redirect('/admin/machines'); } $this->view->status = $status; } public function sslkeyAction() { if ($_GET['domain']) { $this->view->sslkey = SSLKey::find($_GET['domain']); } } public function addsslkeyAction() { if ($_POST['sToken'] != Hisoku::getStoken()) { return $this->alert('wrong stoken', '/admin/sslkey'); } $config = new StdClass; $config->ca = $_POST['ca']; $config->key = $_POST['key']; $config->cert = $_POST['cert']; SSLKey::insert(array( 'domain' => $_POST['domain'], 'config' => json_encode($config), )); return $this->alert('add key done!', '/admin/sslkey'); } public function editsslkeyAction() { if ($_POST['sToken'] != Hisoku::getStoken()) { return $this->alert('wrong stoken', '/admin/sslkey'); } if (!$sslkey = SSLKey::find($_GET['domain'])) { return $this->alert('wrong stoken', '/admin/sslkey'); } $config = new StdClass; $config->ca = array_filter($_POST['ca'], function($a) { return $a; }); $config->key = $_POST['key']; $config->cert = $_POST['cert']; $sslkey->update(array( 'config' => json_encode($config), )); return $this->alert('update key done!', '/admin/sslkey'); } public function deletesslkeyAction() { if ($_POST['sToken'] != Hisoku::getStoken()) { return $this->alert('wrong stoken', '/admin/sslkey'); } $d = SSLKey::find($_GET['domain']); $d->delete(); return $this->alert('delete done', '/admin/sslkey'); } public function usersAction() { } } <file_sep>/webdata/models/Addon/Memcached.php <?php class Addon_MemcachedRow extends Pix_Table_Row { public function saveProjectVariable() { $key_value = array( 'MEMCACHE_SERVER' => $this->host, 'MEMCACHE_PORT' => $this->port, 'MEMCACHE_USERNAME' => $this->user_name, 'MEMCACHE_PASSWORD' => $this->password, ); foreach ($key_value as $key => $value) { try { $this->project->variables->insert(array( 'key' => $key, 'value' => $value, 'is_magic_value' => 0, )); } catch (Pix_Table_DuplicateException $e) { $this->project->variables->search(array( 'key' => $key, ))->update(array( 'value' => $value, 'is_magic_value' => 0, )); } } } } class Addon_Memcached extends Pix_Table { public function init() { $this->_name = 'addon_memcache'; $this->_rowClass = 'Addon_MemcachedRow'; $this->_primary = array('id'); $this->_columns['id'] = array('type' => 'int', 'auto_increment' => true); $this->_columns['project_id'] = array('type' => 'int'); $this->_columns['host'] = array('type' => 'varchar', 'size' => 255); $this->_columns['user_name'] = array('type' => 'varchar', 'size' => 32); $this->_columns['password'] = array('type' => 'varchar', 'size' => 32); $this->_columns['port'] = array('type' => 'int'); $this->_relations['project'] = array('rel' => 'has_one', 'type' => 'Project', 'foreign_key' => 'project_id'); $this->addIndex('project_id', array('project_id')); } public static function addDB($project) { $free_nodes_count = count(WebNode::search(array('project_id' => 0, 'status' => WebNode::STATUS_UNUSED))); if (!$free_nodes_count) { // TODO; log it throw new Exception('No free nodes'); } if (!$random_node = WebNode::search(array('project_id' => 0, 'status' => WebNode::STATUS_UNUSED))->offset(rand(0, $free_nodes_count - 1))->first()) { throw new Exception('free node not found'); } $random_node->update(array( 'project_id' => 0, 'commit' => '', 'start_at' => time(), 'status' => WebNode::STATUS_SERVICE, )); $node_id = $random_node->port - 20000; $ip = long2ip($random_node->ip); $user_name = Hisoku::uniqid(16); $password = <PASSWORD>); $session = ssh2_connect($ip, 22); $ret = ssh2_auth_pubkey_file($session, 'root', WEB_PUBLIC_KEYFILE, WEB_KEYFILE); $stream = ssh2_exec($session, "service {$node_id} memcache-sasl {$user_name}+{$password}"); stream_set_blocking($stream, true); $ret = stream_get_contents($stream); $addon = self::insert(array( 'project_id' => $project->id, 'host' => $ip, 'user_name' => $user_name, 'password' => <PASSWORD>, 'port' => $random_node->port, )); $addon->saveProjectVariable(); } } <file_sep>/webdata/models/ProjectVariable.php <?php class ProjectVariableRow extends Pix_Table_Row { protected function _releaseNodes() { foreach ($this->project->webnodes as $webnode) { $webnode->markAsUnused('change project variable'); } } public function postSave() { $this->_releaseNodes(); } public function postDelete() { $this->_releaseNodes(); } public function getValue() { if ($this->is_magic_value) { list($table, $id, $type) = explode(':', $this->value); switch ($table . '-' . $type) { case 'Addon_MySQLDB-DatabaseURL': return Addon_MySQLDBMember::find(array(intval($id), $this->project_id))->getDatabaseURL(); case 'Addon_PgSQLDB-DatabaseURL': return Addon_PgSQLDBMember::find(array(intval($id), $this->project_id))->getDatabaseURL(); case 'Addon_Elastic-SearchURL': return Addon_Elastic::find(array(intval($id)))->getSearchURL(); case 'Addon_Elastic2-ELASTIC_URL': return Addon_Elastic2::find(array(intval($id)))->getURL(); case 'Addon_Elastic2-ELASTIC_USER': return Addon_Elastic2::find(array(intval($id)))->user; case 'Addon_Elastic2-ELASTIC_PASSWORD': return Addon_Elastic2::find(array(intval($id)))->password; case 'Addon_Elastic2-ELASTIC_PREFIX': return Addon_Elastic2::find(array(intval($id)))->prefix . '_'; } // TODO } else { return $this->value; } } } class ProjectVariable extends Pix_Table { public function init() { $this->_name = 'project_variable'; $this->_primary = array('project_id', 'key'); $this->_rowClass = 'ProjectVariableRow'; $this->_columns['project_id'] = array('type' => 'int'); $this->_columns['key'] = array('type' => 'varchar', 'size' => 32); $this->_columns['value'] = array('type' => 'text'); $this->_columns['is_magic_value'] = array('type' => 'text'); $this->_relations['project'] = array('rel' => 'has_one', 'type' => 'Project', 'foreign_key' => 'project_id'); } } <file_sep>/scripts/log2irc #!/usr/bin/env php <?php class Log2IRC { protected $_configs; protected $_log_cursors = null; public function initLogFile() { error_log('init log'); $this->_configs = json_decode(file_get_contents('/srv/config/log2irc.json')); if (!is_null($this->_log_cursors)) { foreach ($this->_log_cursors as $id => $log_cursor) { fclose($log_cursor->fp); } } $this->_log_cursors = array(); } protected $_last_check = null; protected $_config_hash = null; public function checkConfig() { $now = microtime(true); if (is_null($this->_last_check) and abs($now - $this->_last_check) < 1) { return; } if (date('Ymd', $this->_last_check) !== date('Ymd')) { $this->initLogFile(); $this->_config_hash = md5_file('/srv/config/log2irc.json'); $this->_last_check = $now; return; } $this->_last_check = $now; if (!is_null($this->_config_hash) and $this->_config_hash == md5_file('/srv/config/log2irc.json')) { return; } $this->initLogFile(); $this->_config_hash = md5_file('/srv/config/log2irc.json'); } public function toIRC($message) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, 'http://10.0.0.26:30001/?message=' . urlencode($message) . '&channel=' . urlencode('#hisoku_log')); curl_exec($curl); curl_close($curl); } public function loopLog() { while (true) { file_put_contents('/tmp/irc2log.updated', time()); $this->checkConfig(); foreach ($this->_configs as $id => $config) { if (!array_key_exists($id, $this->_log_cursors)) { $file_name = strftime($config->file); clearstatcache($file_name); if (!file_exists($file_name)) { usleep(100000); continue; } $fp = fopen($file_name, 'r'); $log_cursor = new StdClass; $log_cursor->filename = $file_name; $log_cursor->fp = $fp; $log_cursor->cursor = filesize($file_name); $this->_log_cursors[$id] = $log_cursor; } $log_cursor = $this->_log_cursors[$id]; $fp = $log_cursor->fp; fseek($fp, $log_cursor->cursor); $line = fgets($fp); if (false === $line) { usleep(100000); continue; } foreach ($this->_configs->{$id}->matches as $match) { if (preg_match($match, $line)) { $message = $line; if ($this->_configs->{$id}->prefix) { $message = $this->_configs->{$id}->prefix . $message; } $this->toIRC($message); break; } } $this->_log_cursors[$id]->cursor = ftell($fp); } } } public function main() { $fp = fopen('/tmp/irc2log.pid', 'w'); fwrite($fp, getmypid()); date_default_timezone_set('Asia/Taipei'); // 開始 loop 檔案 $this->loopLog(); } } $l = new Log2IRC; $l->main(); <file_sep>/cron/cron.php #!/usr/bin/env php <?php $type = $_SERVER['argv'][1]; foreach (glob(__DIR__ . '/' . $type . '/*') as $cronfile) { system($cronfile); } <file_sep>/firewall/m2-fw.sh #!/bin/bash outputs_dir=/srv/code/hisoku/firewall/outputs dev='eth0' ip_pattern='([0-9]+\.){3}[0-9]+' docker_rules=() function save_docker_rules() { rules=`iptables -S` while read -r line; do if echo "$line" | grep -iq docker; then docker_rules+=("$line") fi done <<< "$rules" } function restore_docker_rules() { for ((i = 0; i < ${#docker_rules[@]}; i++)); do iptables ${docker_rules[$i]} done } function run() { ip=`ip addr show dev "$dev" | grep -Eo "inet $ip_pattern" | grep -Eo "$ip_pattern" | grep -v '127.0.0.1'` script="$outputs_dir/$ip.sh" /bin/bash $script } function reload() { save_docker_rules run restore_docker_rules } case $1 in reload) reload ;; *) echo "Usage: $0 reload" ;; esac <file_sep>/webdata/init.inc.php <?php error_reporting(E_ALL ^ E_STRICT ^ E_NOTICE); include(__DIR__ . '/stdlibs/pixframework/Pix/Loader.php'); set_include_path(__DIR__ . '/stdlibs/pixframework/' . PATH_SEPARATOR . __DIR__ . '/models' ); Pix_Loader::registerAutoLoad(); if (file_exists(__DIR__ . '/config.php')) { include(__DIR__ . '/config.php'); } elseif (file_exists('/srv/config/config.php')) { include('/srv/config/config.php'); } define('GIT_SERVER', getenv('GIT_SERVER') ?: 'git.middle2.com'); define('USER_DOMAIN', getenv('APP_SUFFIX') ?: '.hisokuapp.ronny.tw'); define('WEB_KEYFILE', '/srv/config/web-key'); define('WEB_PUBLIC_KEYFILE', '/srv/config/web-key.pub'); define('MEMCACHE_PRIVATE_HOST', getenv('MEMCACHE_PRIVATE_HOST')); define('MEMCACHE_PRIVATE_PORT', getenv('MEMCACHE_PRIVATE_PORT')); // TODO: 之後要搭配 geoip date_default_timezone_set('Asia/Taipei'); $db = new StdClass; $db->host = getenv('MYSQL_HOST'); $db->username = getenv('MYSQL_USER'); $db->password = getenv('MYSQL_PASS'); $db->dbname = getenv('MYSQL_DATABASE'); $config = new StdClass; $config->master = $config->slave = $db; Pix_Table::setDefaultDb(new Pix_Table_Db_Adapter_MysqlConf(array($config))); if (MEMCACHE_PRIVATE_HOST) { Pix_Cache::addServer('Pix_Cache_Adapter_Memcached', array( 'servers' => array( array('host' => MEMCACHE_PRIVATE_HOST, 'port' => MEMCACHE_PRIVATE_PORT, 'weight' => 1), // 256M ), )); } <file_sep>/scripts/update-keys #!/usr/bin/env php <?php include(__DIR__ . '/../webdata/init.inc.php'); if ('git' !== getenv('USER')) { die('git user only' . PHP_EOL); } # call by UserKey::updateKey() from mainpage for updating ~git/.ssh/authorized_keys $update_git_config_keys = explode("\n", trim(file_get_contents('/srv/config/update-git-config-keys'))); # call by scripts/root@nodes-ssh_serve from node servers for git clone repository $deploy_keys = explode("\n", trim(file_get_contents('/srv/config/deploy-keys'))); $content = '### generated at ' . date('Y/m/d H:i:s') . "\n"; $content .= "# deploy-keys\n"; foreach ($deploy_keys as $deploy_key) { $content .= 'command="/srv/code/hisoku/scripts/deploy-key-archive-only",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ' . $deploy_key . "\n"; } $content .= "# update-keys\n"; foreach ($update_git_config_keys as $key) { $content .= 'command="/srv/code/hisoku/scripts/update-keys",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ' . $key . "\n"; } $content .= "# user keys\n"; // 可以對 mysql 和 pgsql 的 IP 開 ssh tunnel $forward_ports = array_merge( array_map(function($ip){ return "{$ip}:3306"; }, Hisoku::getIPsByGroup('mysql')), array_map(function($ip){ return "{$ip}:5432"; }, Hisoku::getIPsByGroup('pgsql')) ); $permitopen = implode(',', array_map(function($ip_port) { return "permitopen=\"{$ip_port}\""; }, $forward_ports)); foreach (UserKey::search(1) as $user_key) { $content .= "command=\"/srv/code/hisoku/scripts/ssh-serve {$user_key->user->name} {$user_key->id}\",no-X11-forwarding,no-agent-forwarding,{$permitopen} {$user_key->key_body}\n"; } file_put_contents(getenv('HOME') . '/.ssh/authorized_keys', $content); <file_sep>/Makefile HOSTS?= `./scripts/getip dev loadbalancer nodes mysql pgsql search elastic` all: @git pull -v npm: package.json npm install deploy: npm php firewall/gen.php php dockers/gen.php @for HOST in ${HOSTS} ; do \ rsync -avz --exclude .git --exclude .gitignore --exclude '.*.swp' --exclude 'webdata/config.php' --delete --delete-excluded -e ssh . code@$${HOST}:~/hisoku ; \ done <file_sep>/scripts/get-queries-per-minute.php <?php $log_file = '/tmp/hisoku-query-counter'; $now = time(); $curl = curl_init('http://localhost/'); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Host: healthcheck')); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $content = curl_exec($curl); $obj = json_decode($content); if (!file_exists($log_file)) { file_put_contents($log_file, "{$now} {$obj->request_serial}"); echo 0; exit; } list($prev_time, $prev_serial) = explode(' ', file_get_contents($log_file)); echo max(0, ($obj->request_serial - $prev_serial) / ($now - $prev_time)); file_put_contents($log_file, "{$now} {$obj->request_serial}"); <file_sep>/scripts/init.sh #!/bin/sh /usr/sbin/php-fpm /usr/local/apache2/bin/apachectl graceful <file_sep>/webdata/models/Admin.php <?php class Admin extends Pix_Table { public function init() { $this->_name = 'admin'; $this->_primary = 'id'; $this->_columns['id'] = array('type' => 'int'); } } <file_sep>/webdata/models/ProjectMember.php <?php class ProjectMember extends Pix_Table { public function init() { $this->_name = 'project_member'; $this->_primary = array('id'); $this->_columns['id'] = array('type' => 'int', 'auto_increment' => true); $this->_columns['project_id'] = array('type' => 'int'); $this->_columns['user_id'] = array('type' => 'int'); $this->_columns['is_admin'] = array('type' => 'int'); $this->_indexes['project_user'] = array('type' => 'unique', 'columns' => array('project_id', 'user_id')); $this->_indexes['user_project'] = array('type' => 'unique', 'columns' => array('user_id', 'project_id')); $this->_relations['project'] = array('rel' => 'has_one', 'type' => 'Project', 'foreign_key' => 'project_id'); $this->_relations['user'] = array('rel' => 'has_one', 'type' => 'User', 'foreign_key' => 'user_id'); } } <file_sep>/webdata/stdlibs/pixframework/prompt.php <?php include('Pix/Prompt.php'); Pix_Prompt::init(); <file_sep>/test-repo/import-test-repo.php <?php include(__DIR__ . '/../webdata/init.inc.php'); // add user test@middle2 try { $user = User::insert(array('name' => 'test@middle2')); } catch (Pix_Table_DuplicateException $e) { $user = User::find_by_name('test@middle2'); } // generate key-pair for test@middle2 if (!file_exists('git-key')) { system("ssh-keygen -f git-key -N ''"); } $keybody = file_get_contents('git-key.pub'); $keybody = trim($keybody); $terms = explode(' ', $keybody); if (3 !== count($terms)) { throw new InvalidArgumentException('invalid key'); } list($type, $body, $user_host) = $terms; if (!in_array($type, array('ssh-rsa', 'ssh-dsa'))) { throw new InvalidArgumentException('invalid ssh type'); } if (preg_match('#[^a-zA-Z0-9/+=]#', $body)) { throw new InvalidArgumentException('invalid ssh key'); } if (!$user->keys->search(array('key_fingerprint' => md5(base64_decode($body))))->first()) { $user->keys->insert(array( 'key_fingerprint' => md5(base64_decode($body)), 'key_body' => $keybody, )); } // import testing repository system("rm -rf tmp_repo"); foreach (glob("test-*") as $test_path) { try { $project = $user->addProject($test_path); } catch (Pix_Table_DuplicateException $exception) { $project = Project::find_by_name($test_path); if (!$project->members->search(array('user_id' => $user->id))->first()) { throw new Exception("project '{$test_path}' is not owned by user 'test@middle2'"); } } error_log("cloning {$test_path} to tmp_repo/"); system("ssh-agent bash -c 'ssh-add git-key; git clone git@" . getenv('GIT_SERVER') . ':' . $test_path . ' tmp_repo\''); system("cp -r {$test_path}/* tmp_repo"); system("git -C tmp_repo/ add ."); system("git -C tmp_repo/ commit -m 'update'"); system("ssh-agent bash -c 'ssh-add git-key; git -C tmp_repo/ push -f'"); system("rm -rf tmp_repo"); }
6e4ce0fe212e8b2e52d6b71c82542f32d16be2bc
[ "Markdown", "Makefile", "INI", "PHP", "Dockerfile", "Shell" ]
87
PHP
middle2tw/middle2
484b2301d88fbde6215b1748c969be702b9d2467
91d137628345940d01f7066e18d4f55efe181761
refs/heads/master
<file_sep># taken from https://github.com/ropenscilabs/packagemetrics/blob/master/R/get_cran.R memoise_cran_db <- memoise::memoise({ function() { cran <- tools::CRAN_package_db() # remove first instance of column name MD5Sum cran <- cran[, -dplyr::first(which(names(cran) == "MD5sum"))] # make it a tibble cran <- dplyr::tbl_df(cran) if (packageVersion("janitor") > "0.3.1") { cran <- cran %>% janitor::clean_names(case = "old_janitor") %>% janitor::remove_empty("cols") } else { cran <- cran %>% janitor::clean_names() %>% janitor::remove_empty_cols() } cran }} ) <file_sep>--- title: "R Package Risk Metrics" author: "" date: "`r Sys.Date()`" output: github_document vignette: > %\VignetteIndexEntry{Vignette Title} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>") ``` ```{r} library(riskmetric) ``` <file_sep># riskmetric [![Travis build status](https://travis-ci.org/pharmaR/riskmetric.svg?branch=master)](https://travis-ci.org/pharmaR/riskmetric) [![Coverage status](https://codecov.io/gh/pharmaR/riskmetric/branch/master/graph/badge.svg)](https://codecov.io/github/pharmaR/riskmetric?branch=master) `riskmetric` is a collection of risk metrics to evaluate the quality of R packages. This page represents our current thinking. The R package are currently being reviewed and under development. ## Background The value of R lies not within the official distribution but within the many R packages that support it. R packages provide the means to extend the language, implementing new statistical methods, graphics and code structures. However, this is also where the majority of risk lies for an organisation. R packages can be written by anyone. The author/maintainer could be an organisation but they are perhaps more likely to be an individual and no qualification is required in order to develop an R package and submit it to CRAN (or any other package repository). Unlike the base distribution, R packages may or may not follow any software development best practices. Packages on CRAN must pass a series of technical checks, including an “R CMD check”. These checks are designed to ensure that examples run successfully, tests pass and that packages on CRAN are compatible with each other. However, there is no requirement for package authors to write tests or implement a formal unit-testing framework. In fact, less than 26% of the >13,500 packages on CRAN are known to implement a formal test framework. In addition, there is no obligation to maintain bug reports and unless a bug in a package affects another package on CRAN, the bugs may never be identified nor fixed. Unlike the base distribution, the amount of user testing can also vary widely. Popular packages such as dplyr may have been downloaded and used by tens of thousands of individuals, whilst others might never have been used by anyone except the package author. In order to apportion an appropriate level of validation effort across different R packages, it is important to establish a risk assessment framework that can be applied to any R package in order to determine a base level of risk. ## Risk Assessment The following tables highlight metrics that could be used in order to assess the risk of an R package. The risk assessment has been grouped into two areas: 1. Unit testing metrics 2. Documentation metrics 3. Community engagement metrics 4. Maintainability and reuse metrics ### Unit Testing Metrics * Code Coverage: a percentage range between 0-100 to measure the degree to which the source code of an R package is executed when unit test runs. * Code Coverage of all dependent packages (%) a continvalue range between 0-100 to measure the degree to which the source code of an R package and all its dependencies are executed when unit test runs. ### Documentation Metrics * Vignette * Website * Source control * Formal bug tracking * News * Release rate * Size of codebase * License ### Community Engagement Metrics * Author reputation * Package maturity * Average number of downloads per month over past 6 monthes * Number of active contributors * Number of authors / maintainers <file_sep>#' Convert into a package object #' #' @param x character value representing a package name, path to a package #' source directory or a git remote url or a package object #' @param ... additional arguments passed to class-specific handlers #' #' @return a package object #' #' @export as.pkg_ref <- function(x, ...) { # called this class "package_meta" as to not conflict with devtools "package" UseMethod("as.pkg_ref") } #' @export as.pkg_ref.default <- function(x, ...) { stop(sprintf( "Don't know how to convert object class '%s' to class 'pkg_ref'", paste(class(x), collapse = ", "))) } #' @export as.pkg_ref.pkg_ref <- function(x, ...) { x } #' @importFrom utils installed.packages available.packages #' @export as.pkg_ref.character <- function(x, repos = getOption("repos"), ...) { ip <- utils::installed.packages() ap <- utils::available.packages(repos = repos) # case when only a package name is provided # e.g. 'dplyr' if (grepl("^[[:alpha:]][[:alnum:].]*[[:alnum:]]$", x)) { # regex from available:::valid_package_name_regexp # if locally installed if (x %in% ip[,"Package"]) { return(pkg_ref(x, path = find.package(x), "pkg_install")) # if available at a provided repo } else if (x %in% ap[,"Package"]) { info <- ap[ap[,"Package"] == x,] repo <- info[,"Repository"] url <- sprintf("%s/%s_%s.tar.gz", repo, x, info[,"Version"]) return(pkg_ref(x, url = url, repo = repo, "pkg_remote")) # otherwise, it's valid but unidentified } else { return(pkg_ref(x, "pkg_missing")) } # case when a directory path to source code is provided # e.g. '../dplyr' } else if (dir.exists(x) & file.exists(file.path(x, "DESCRIPTION"))) { desc <- read.dcf(file.path(x, "DESCRIPTION")) name <- unname(desc[,"Package"]) return(pkg_ref(name, path = normalizePath(x), source = "pkg_source")) } pkg_ref(x, "pkg_missing") } pkg_ref <- function(name, source, ...) { dots <- list(...) if (length(dots) && is.null(names(dots)) || any(names(dots) == "")) stop("pkg_ref ellipses arguments must be named") source <- match.arg( source, c("pkg_remote", "pkg_install", "pkg_source", "pkg_missing"), several.ok = FALSE) pkg_data <- as.environment(append(list( name = name, source = source ), dots)) structure(pkg_data, class = c(source, "pkg_ref", "environment")) }
382a2a2ac9e079ed49aa956e7f3b658817ea87b0
[ "Markdown", "R", "RMarkdown" ]
4
R
matthiazzz/riskmetric
082f269ecfcc6797f7833e606c88d2e99c3666bf
c1e5302389f4799067c2d5dc930f2dc4cc1620de
refs/heads/master
<repo_name>cocoalexand/practica<file_sep>/punto/Models/tbevento_m.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace punto.Models { [MetadataType(typeof(itbevento))] public partial class tbevento { public void prueba() { //this.estado = 1*5; } } public interface itbevento { [Required]//debe tener algo de informacion object estado { get; set; } [MinLength(2)]// debe tener por lo menos 2 caracteres object titulo { get; set; } [Key]//indicamos que es l llave de la tabla object idevento { get; set; } } public interface itbevento { [Display(Name = "idevento")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object idevento { get; set; }//nombre de la column [ScaffoldColumn(false)] object idevento { get; set; } } public interface itbevento { [Display(Name = "titulo")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object titulo { get; set; }//nombre de la column [ScaffoldColumn(false)] object titulo { get; set; } } public interface itbevento { [Display(Name = "fecha")]//nombre de los labels [DataType(DataType.Date, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object fecha { get; set; }//nombre de la column [ScaffoldColumn(false)] object fecha { get; set; } } public interface itbevento { [Display(Name = "idtipo")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object idtipo { get; set; }//nombre de la column [ScaffoldColumn(false)] object idtipo { get; set; } } public interface itbevento { [Display(Name = "idlugar")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object idlugar { get; set; }//nombre de la column [ScaffoldColumn(false)] object idlugar { get; set; } } public interface itbevento { [Display(Name = "fechacreacion")]//nombre de los labels [DataType(DataType.Date, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object fechacreacion { get; set; }//nombre de la column [ScaffoldColumn(false)] object fechacreacion { get; set; } } public interface itbevento { [Display(Name = "fechamodificacion")]//nombre de los labels [DataType(DataType.Date, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object fechamodificacion { get; set; }//nombre de la column [ScaffoldColumn(false)] object fechamodificacion { get; set; } } public interface itbevento { [Display(Name = "estado")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object estado { get; set; }//nombre de la column [ScaffoldColumn(false)] object estado { get; set; } } }<file_sep>/punto/Models/tbusuario_m.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace punto.Models { [MetadataType(typeof(itbusuario))] public class tbusuario { } public interface itbusuario { [Display(Name = "id usuario")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object idusuario { get; set; }//nombre de la column [Key] [ScaffoldColumn(false)] object idusuario { get; set; } } public interface itbusuario { [Display(Name = "login")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object login { get; set; }//nombre de la column [ScaffoldColumn(false)] object login { get; set; } } public interface itbusuario { [Display(Name = "contraseña")]//nombre de los labels [DataType(DataType.Password, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object pass { get; set; }//nombre de la colum [ScaffoldColumn(false)] object pass { get; set; } } public interface itbusuario { [Display(Name = "fid")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object fid { get; set; }//nombre de la column [ScaffoldColumn(false)] object fid { get; set; } } public interface itbusuario { [Display(Name = "email")]//nombre de los labels [DataType(DataType.EmailAddress, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object femail { get; set; }//nombre de la column [ScaffoldColumn(false)] object femail { get; set; } } public interface itbusuario { [Display(Name = "creado")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object creado { get; set; }//nombre de la column [ScaffoldColumn(false)] object creado { get; set; } } public interface itbusuario { [Display(Name = "fecha de creacion")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object fechacreacion { get; set; }//nombre de la column [ScaffoldColumn(false)] object fechacreacion { get; set; } } public interface itbusuario { [Display(Name = "fecha de modificacion")]//nombre de los labels [DataType(DataType.Date, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object fechamodificacion { get; set; }//nombre de la column [ScaffoldColumn(false)] object fechamodificacion { get; set; } } public interface itbusuario { [Display(Name = "estado")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object estado { get; set; }//nombre de la column [ScaffoldColumn(false)] object estado { get; set; } } }<file_sep>/punto/Models/tblugares_m.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace punto.Models { [MetadataType(typeof(itblugares))] public class tblugares { } public interface itblugares { [Display(Name = "idlugar")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object idlugar { get; set; }//nombre de la column [ScaffoldColumn(false)] object idlugar { get; set; } } public interface itblugares { [Display(Name = "titulo")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object titulo { get; set; }//nombre de la column [ScaffoldColumn(false)] object titulo { get; set; } } public interface itblugares { [Display(Name = "direccion")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object direccion { get; set; }//nombre de la column [ScaffoldColumn(false)] object direccion { get; set; } } public interface itblugares { [Display(Name = "descripcion")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object descripcion { get; set; }//nombre de la column [ScaffoldColumn(false)] object descripcion { get; set; } } public interface itblugares { [Display(Name = "web")]//nombre de los labels [DataType(DataType.Html, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object web { get; set; }//nombre de la column [ScaffoldColumn(false)] object web { get; set; } } public interface itblugares { [Display(Name = "imagen")]//nombre de los labels [DataType(DataType.MultilineText, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object imagen { get; set; }//nombre de la column [ScaffoldColumn(false)] object imagen { get; set; } } public interface itblugares { [Display(Name = "email")]//nombre de los labels [DataType(DataType.EmailAddress, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object email { get; set; }//nombre de la column [ScaffoldColumn(false)] object email { get; set; } } public interface itblugares { [Display(Name = "lat")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object lat { get; set; }//nombre de la column [ScaffoldColumn(false)] object lat { get; set; } } public interface itblugares { [Display(Name = "long")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object longi { get; set; }//nombre de la column [ScaffoldColumn(false)] object longi { get; set; } } public interface itblugares { [Display(Name = "fechacreacion")]//nombre de los labels [DataType(DataType.Date, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object fechacreacion { get; set; }//nombre de la column [ScaffoldColumn(false)] object fechacreacion { get; set; } } public interface itblugares { [Display(Name = "fechamodificacion")]//nombre de los labels [DataType(DataType.Date, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object fechamodificacion { get; set; }//nombre de la column [ScaffoldColumn(false)] object fechamodificacion { get; set; } } public interface itblugares { [Display(Name = "estado")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object estado { get; set; }//nombre de la column [ScaffoldColumn(false)] object estado { get; set; } } }<file_sep>/punto/Models/tbpersona_m.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace punto.Models { [MetadataType(typeof(itbpersona))] public partial class tbpersona { } public interface itbpersona { [Display(Name="<NAME>")]//nombre de los labels [DataType(DataType.Text,ErrorMessage="Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20,ErrorMessage="no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000,15000000)] object nombre { get; set; }//nombre de la column [Key] [ScaffoldColumn(false)] object idpersona { get; set; } } public interface itbpersona { [Display(Name="<NAME>")]//nombre de los labels [DataType(DataType.Text,ErrorMessage="Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20,ErrorMessage="no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000,15000000)] object paterno{ get; set; }//nombre de la column [ScaffoldColumn(false)] object paterno { get; set; } } public interface itbpersona { [Display(Name="<NAME>")]//nombre de los labels [DataType(DataType.Text,ErrorMessage="Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20,ErrorMessage="no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000,15000000)] object materno { get; set; }//nombre de la column [ScaffoldColumn(false)] object materno { get; set; } } public interface itbpersona { [Display(Name = "cedula de identidad")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object ci { get; set; }//nombre de la column [ScaffoldColumn(false)] object ci { get; set; } } public interface itbpersona { [Display(Name="fecha nacimiento")]//nombre de los labels [DataType(DataType.Text,ErrorMessage="Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20,ErrorMessage="no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000,15000000)] object fechanac { get; set; }//nombre de la column [ScaffoldColumn(false)] object fechanac { get; set; } } public interface itbpersona { [Display(Name="fecha creacion")]//nombre de los labels [DataType(DataType.Text,ErrorMessage="Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20,ErrorMessage="no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000,15000000)] object fechacreacion { get; set; }//nombre de la column [ScaffoldColumn(false)] object fechacreacion { get; set; } } public interface itbpersona { [Display(Name="fecha modificacion")]//nombre de los labels [DataType(DataType.Text,ErrorMessage="Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20,ErrorMessage="no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000,15000000)] object fechamodificacion { get; set; }//nombre de la column [ScaffoldColumn(false)] object fechamodificacion { get; set; } } public interface itbpersona { [Display(Name="estado")]//nombre de los labels [DataType(DataType.Text,ErrorMessage="Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20,ErrorMessage="no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000,15000000)] object estado { get; set; }//nombre de la column [ScaffoldColumn(false)] object estado { get; set; } } }<file_sep>/punto/Models/tbtelefonos_m.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace punto.Models { [MetadataType(typeof(itbtelefonos))] public class tbtelefonos { } public interface itbtelefonos { [Display(Name = "Tu telefono")]//nombre de los labels [DataType(DataType.PhoneNumber, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object idtelefonos{ get; set; }//nombre de la column [Key] [ScaffoldColumn(false)] object idtelefonos { get; set; } } public interface itbtelefonos { [Display(Name = "numero")]//nombre de los labels [DataType(DataType.PhoneNumber, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object numero { get; set; }//nombre de la column [ScaffoldColumn(false)] object numero { get; set; } } public interface itbtelefonos { [Display(Name = "tipo")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object tipo { get; set; }//nombre de la column [ScaffoldColumn(false)] object tipo{ get; set; } } public interface itbtelefonos { [Display(Name = "codigo area")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object codigoarea { get; set; }//nombre de la column [ScaffoldColumn(false)] object codigoarea { get; set; } } public interface itbtelefonos { [Display(Name = "id lugares")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object idlugares { get; set; }//nombre de la column [ScaffoldColumn(false)] object idlugares { get; set; } } public interface itbtelefonos { [Display(Name = "fecha creacion")]//nombre de los labels [DataType(DataType.Date, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object fechacreacion { get; set; }//nombre de la column [ScaffoldColumn(false)] object fechacreacion { get; set; } } public interface itbtelefonos { [Display(Name = "fecha modificacion")]//nombre de los labels [DataType(DataType.Date, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object fechamodificacion { get; set; }//nombre de la column [ScaffoldColumn(false)] object fechamodificacion { get; set; } } public interface itbtelefonos { [Display(Name = "estado")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object estado { get; set; }//nombre de la column [ScaffoldColumn(false)] object estado { get; set; } } }<file_sep>/punto/Models/tbvotousuario_m.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace punto.Models { [MetadataType(typeof(itbvotousuario))] public class tbvotousuario { } public interface itbvotousuario { [Display(Name = "id voto usuario")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object idvotousuario { get; set; }//nombre de la column [ScaffoldColumn(false)] object idvotousuario { get; set; } } public interface itbvotousuario { [Display(Name = "id lugar")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object idlugar { get; set; }//nombre de la column [ScaffoldColumn(false)] object idlugar{ get; set; } } public interface itbvotousuario { [Display(Name = "id usuario")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object iduser { get; set; }//nombre de la column [ScaffoldColumn(false)] object iduser { get; set; } } public interface itbvotousuario { [Display(Name = "scor")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object scor { get; set; }//nombre de la column [ScaffoldColumn(false)] object scor { get; set; } } public interface itbvotousuario { [Display(Name = "fecha de creacion")]//nombre de los labels [DataType(DataType.Date, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object fechacreacion { get; set; }//nombre de la column [ScaffoldColumn(false)] object fechacreacion { get; set; } } public interface itbvotousuario { [Display(Name = "fecha de modificacion")]//nombre de los labels [DataType(DataType.Date, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object fechamodificacion { get; set; }//nombre de la column [ScaffoldColumn(false)] object fechamodificacion { get; set; } } public interface itbvotousuario { [Display(Name = "estado")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object estado { get; set; }//nombre de la column [ScaffoldColumn(false)] object estado{ get; set; } } }<file_sep>/punto/Models/tbhorario_m.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace punto.Models { [MetadataType(typeof(itbhorario))] public class tbhorario { } public interface itbhorario { [Display(Name = "idhorario")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object idhorario { get; set; }//nombre de la column [ScaffoldColumn(false)] object idhorario { get; set; } } public interface itbhorario { [Display(Name = "inicio")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object inicio { get; set; }//nombre de la column [ScaffoldColumn(false)] object inicio { get; set; } } public interface itbhorario { [Display(Name = "fin")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object fin { get; set; }//nombre de la column [ScaffoldColumn(false)] object fin { get; set; } } public interface itbhorario { [Display(Name = "idlugares")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object idlugares { get; set; }//nombre de la column [ScaffoldColumn(false)] object idlugares { get; set; } } public interface itbhorario { [Display(Name = "tipo")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object tipo { get; set; }//nombre de la column [ScaffoldColumn(false)] object tipo { get; set; } } public interface itbhorario { [Display(Name = "fechacreacion")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object fechacreacion { get; set; }//nombre de la column [ScaffoldColumn(false)] object fechacreacion { get; set; } } public interface itbhorario { [Display(Name = "estado")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Error")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Editable(false)] [Required] [Range(60000, 15000000)] object estado { get; set; }//nombre de la column [ScaffoldColumn(false)] object estado { get; set; } } }<file_sep>/punto/Models/votos_m.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace punto.Models { [MetadataType(typeof(itbvotos))] public class votos { } public interface itbvotos { [Display(Name = "idusuario")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object id { get; set; }//nombre de la column [ScaffoldColumn(false)] object id{ get; set; } } public interface itbvotos { [Display(Name = "titulo")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object titulo { get; set; }//nombre de la column [ScaffoldColumn(false)] object titulo { get; set; } } public interface itbvotos { [Display(Name = "total votos")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object total_votes { get; set; }//nombre de la column [ScaffoldColumn(false)] object total_votes { get; set; } } public interface itbvotos { [Display(Name = "total value")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object total_value { get; set; }//nombre de la column [ScaffoldColumn(false)] object total_value { get; set; } } public interface itbvotos { [Display(Name = "usep_ips")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object usep_ips { get; set; }//nombre de la column [ScaffoldColumn(false)] object usep_ips { get; set; } } public interface itbvotos { [Display(Name = "fecha de creacion")]//nombre de los labels [DataType(DataType.Date, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object fechacreacion { get; set; }//nombre de la column [ScaffoldColumn(false)] object fechacreacion { get; set; } } public interface itbvotos { [Display(Name = "estado")]//nombre de los labels [DataType(DataType.Text, ErrorMessage = "Tonto!!!!...")]//tipo de dato //[DisplayColumn("campo de nombre","Nom.")]//nombre en la columna [Editable(false)]//no se podra editar [MaxLength(20, ErrorMessage = "no maximo de 20 caracteres")] [StringLength(20)]//max 20 [Required] [Range(60000, 15000000)] object estado{ get; set; }//nombre de la column [ScaffoldColumn(false)] object estado { get; set; } } }
69282aea5cbc146d1e9d56d53f5edb5b4d6c64c1
[ "C#" ]
8
C#
cocoalexand/practica
b12734142a4c107f8d077c8a8dc2b335684101d9
e0e1547b776ce27d54e67a3912b8c8b03dcc1cf8
refs/heads/master
<file_sep>using StudentManagement.Data.Entities; using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentManagement.Data.Mapping { public class CourseMapping : EntityTypeConfiguration<CourseEntity> { public CourseMapping() { ToTable("Course").HasKey(k => k.ID); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentManagement.Business.Dtos { public class EnrollmentDto : BaseDto { public int CourseID { get; set; } public int StudentID { get; set; } public int? Grade { get; set; } public DateTime EnrollmentDate { get; set; } public virtual StudentDto Student { get; set; } public virtual CourseDto Course { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentManagement.Data.Entities { public class CourseEntity : BaseEntity { public string Title { get; set; } public int Credits { get; set; } public virtual ICollection<EnrollmentEntity> Enrollments { get; set; } } } <file_sep>using StudentManagement.Business.Dtos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentManagement.Business.Contracts { public interface ICourseBusinessService { IList<CourseDto> GetAllCourses(); IList<CourseDto> SearchCourseByName(string courseName, int pageIndex, int pageSize, out int total); CourseDto InsertCourse(CourseDto courseDto); void UpdateCourse(CourseDto courseDto); void DeleteCourse(CourseDto courseDto); CourseDto GetCourseById(Guid Id); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentManagement.Business.Dtos { public class CourseDto : BaseDto { public string Title { get; set; } public int Credits { get; set; } public virtual ICollection<EnrollmentDto> Enrollments { get; set; } } } <file_sep>using StudentManagement.Business.Contracts; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudentManagement.Business.Dtos; using StudentManagement.Data.Contracts; using StudentManagement.Data.Entities; using AutoMapper; namespace StudentManagement.Business { public class StudentBusinessService : BaseBusinessService, IStudentBusinessService { private IRepository<StudentEntity> studentRepository; public StudentBusinessService(IRepository<StudentEntity> repo) { studentRepository = repo; } public void DeleteStudent(StudentDto studentDto) { var student = Mapper.Map<StudentEntity>(studentDto); studentRepository.Delete(student); studentRepository.SaveChanges(); } public IList<StudentDto> GetAllStudents() { var student = studentRepository.GetAll(); var studentDtos = (IList<StudentDto>)Mapper.Map(student, student.GetType(), typeof(IList<StudentDto>)); return studentDtos; } public StudentDto GetStudentById(Guid Id) { var student = studentRepository.GetById(Id); return Mapper.Map<StudentEntity, StudentDto>(student); } public StudentDto InsertStudent(StudentDto studentDto) { var student = Mapper.Map<StudentEntity>(studentDto); student = studentRepository.Insert(student); studentRepository.SaveChanges(); return Mapper.Map<StudentEntity, StudentDto>(student); } public IList<StudentDto> SearchStudentByName(string studentName, int pageIndex, int pageSize, out int total) { var student = studentRepository.Search(p => p.FristName.Contains(studentName), o => o.FristName, pageIndex, pageSize, out total); var studentDtos = (IList<StudentDto>)Mapper.Map(student, student.GetType(), typeof(IList<StudentDto>)); return studentDtos; } public void UpdateStudent(StudentDto studentDto) { var student = Mapper.Map<StudentEntity>(studentDto); studentRepository.Update(student); studentRepository.SaveChanges(); } } } <file_sep>using Autofac; using AutoMapper; using StudentManagement.Business.Contracts; using StudentManagement.Business.Dtos; using StudentManagement.Data; using StudentManagement.Data.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentManagement.Business { public class BusinessModule : Module { private string connectionString; public BusinessModule(string connString) { connectionString = connString; } protected override void Load(ContainerBuilder builder) { builder.RegisterType<StudentBusinessService>().As<IStudentBusinessService>().InstancePerRequest(); builder.RegisterType<CourseBusinessService>().As<ICourseBusinessService>().InstancePerRequest(); builder.RegisterModule(new DataModule(connectionString)); base.Load(builder); } private void RegisterMapper() { Mapper.CreateMap<BaseEntity, BaseDto>(); Mapper.CreateMap<BaseDto, BaseEntity>(); Mapper.CreateMap<StudentEntity, StudentDto>(); Mapper.CreateMap<StudentDto, StudentEntity>(); Mapper.CreateMap<CourseEntity, CourseDto>(); Mapper.CreateMap<CourseDto, CourseEntity>(); Mapper.CreateMap<EnrollmentEntity, EnrollmentDto>(); Mapper.CreateMap<EnrollmentDto, EnrollmentEntity>(); } } } <file_sep>using StudentManagement.Data.Contracts; using StudentManagement.Data.Entities; using StudentManagement.Data.Mapping; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentManagement.Data { public class SchoolDbContext : DbContext, IDbContext { public SchoolDbContext(string connectString) : base(connectString) { } public IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity { return base.Set<TEntity>(); } public DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : BaseEntity { return base.Entry(entity); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new StudentMapping()); modelBuilder.Configurations.Add(new CourseMapping()); modelBuilder.Configurations.Add(new EnrollmentMapping()); base.OnModelCreating(modelBuilder); } } } <file_sep>using StudentManagement.Business.Contracts; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudentManagement.Business.Dtos; using StudentManagement.Data.Contracts; using StudentManagement.Data.Entities; using AutoMapper; namespace StudentManagement.Business { public class CourseBusinessService : BaseBusinessService, ICourseBusinessService { private IRepository<CourseEntity> courseRepository; public CourseBusinessService(IRepository<CourseEntity> repo) { courseRepository = repo; } public void DeleteCourse(CourseDto courseDto) { var course = Mapper.Map<CourseEntity>(courseDto); courseRepository.Delete(course); courseRepository.SaveChanges(); } public IList<CourseDto> GetAllCourses() { var course = courseRepository.GetAll(); var courseDtos = (IList<CourseDto>)Mapper.Map(course, course.GetType(), typeof(IList<CourseDto>)); return courseDtos; } public CourseDto GetCourseById(Guid Id) { var course = courseRepository.GetById(Id); return Mapper.Map<CourseEntity, CourseDto>(course); } public CourseDto InsertCourse(CourseDto courseDto) { var course = Mapper.Map<CourseEntity>(courseDto); course = courseRepository.Insert(course); courseRepository.SaveChanges(); return Mapper.Map<CourseEntity, CourseDto>(course); } public IList<CourseDto> SearchCourseByName(string courseName, int pageIndex, int pageSize, out int total) { var course = courseRepository.Search(p => p.Title.Contains(courseName), o => o.Title, pageIndex, pageSize, out total); var courseDtos = (IList<CourseDto>)Mapper.Map(course, course.GetType(), typeof(IList<CourseDto>)); return courseDtos; } public void UpdateCourse(CourseDto courseDto) { var course = Mapper.Map<CourseEntity>(courseDto); courseRepository.Update(course); courseRepository.SaveChanges(); } } } <file_sep>using StudentManagement.Data.Entities; using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentManagement.Data.Mapping { public class StudentMapping : EntityTypeConfiguration<StudentEntity> { public StudentMapping() { ToTable("Student").HasKey(k => k.ID); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentManagement.Data.Entities { public class EnrollmentEntity : BaseEntity { public int CourseID { get; set; } public int StudentID { get; set; } public int? Grade { get; set; } public DateTime EnrollmentDate { get; set; } public virtual StudentEntity Student { get; set; } public virtual CourseEntity Course { get; set; } } } <file_sep>using StudentManagement.Business.Dtos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentManagement.Business.Contracts { public interface IStudentBusinessService { IList<StudentDto> GetAllStudents(); IList<StudentDto> SearchStudentByName(string studentName, int pageIndex, int pageSize, out int total); StudentDto InsertStudent(StudentDto studentDto); void UpdateStudent(StudentDto studentDto); void DeleteStudent(StudentDto studentDto); StudentDto GetStudentById(Guid Id); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentManagement.Data.Entities { public class StudentEntity : BaseEntity { public string LastName { get; set; } public string FristName { get; set; } public string Address { get; set; } public string Phone { get; set; } public DateTime DOB { get; set; } public virtual ICollection<EnrollmentEntity> Enrollments { get; set; } } } <file_sep>using Autofac; using StudentManagement.Data.Contracts; using StudentManagement.Data.Entities; using StudentManagement.Data.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentManagement.Data { public class DataModule : Module { private string connectionString; public DataModule(string connString) { connectionString = connString; } protected override void Load(ContainerBuilder builder) { builder.Register(c => new SchoolDbContext(this.connectionString)).As<IDbContext>().InstancePerRequest(); RegisterRepository<StudentEntity>(builder); RegisterRepository<CourseEntity>(builder); RegisterRepository<EnrollmentEntity>(builder); base.Load(builder); } private void RegisterRepository<TEntity>(ContainerBuilder builder) where TEntity : BaseEntity { builder.RegisterType<BaseRepository<TEntity>>().As<IRepository<TEntity>>().InstancePerRequest(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentManagement.Business.Dtos { public class StudentDto : BaseDto { public string LastName { get; set; } public string FristName { get; set; } public string Address { get; set; } public string Phone { get; set; } public DateTime DOB { get; set; } public virtual ICollection<EnrollmentDto> Enrollments { get; set; } } }
d57933e3753b83a01ddeef10b017f6547bfe66e4
[ "C#" ]
15
C#
WesternCivilization/HomeWork1
a4c2a41a459f33221fbad8a9b2789d0a9714d379
0ecfdaec240e536ab377b2bdc3fdaea5a5d4ff02
refs/heads/master
<file_sep><html> <head> <script type="text/javascript"> //create ajax engine line 1 function getXmlHttpObject() { var xmlHttpRequest; if (window.ActiveXObject) { xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } else { xmlHttpRequest = new XMLHttpRequest(); } return xmlHttpRequest; } var myXmlHttpRequest = ""; function getCities() { myXmlHttpRequest = getXmlHttpObject(); if (myXmlHttpRequest) { //line 2 var url = "/ajax/showCitiesPro.php"; //post var data = "country=" + $('country').value; myXmlHttpRequest.open("post", url, true); //Asynchronous true myXmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //assign callback function myXmlHttpRequest.onreadystatechange = proc; //send myXmlHttpRequest.send(data); } } function proc() { if (myXmlHttpRequest.readyState == 4) { if (myXmlHttpRequest.status == 200) { //get data from server var state = myXmlHttpRequest.responseXML.getElementsByTagName("state"); $('state').length = 0; var myOption = document.createElement("option"); myOption.innerText = "--State/Province--"; $('state').appendChild(myOption); for (var i = 0; i < state.length; i++) { var state_name = state[i].childNodes[0].nodeValue; //create new element option var myOption = document.createElement("option"); myOption.value = state_name; myOption.innerText = state_name; $('state').appendChild(myOption); } } } } function $(id) { return document.getElementById(id); } </script> </head> <body> <select id="country" onchange="getCities();"> <option value="">---Country---</option> <option value="United States">United States</option> <option value="China" >China</option> </select> <select id="state"> <option value="">--State/Province--</option> </select> <select id="city"> <option value="">--City--</option> </select> </body> </html> <file_sep><?php //server side header("Content-Type:text/xml; charset=utf-8"); header("Cache-Control:no-cache"); //get coountry name $country = $_POST['country']; //file_put_contents("d:/mylog.log",$country."\r\n", FILE_APPEND ); $info = ""; if ($country == "China") { $info = "<country><state>Hebei</state><state>Beijing</state><state>Hubei</state></country>"; } else if ($country == "United States") { $info = "<country><state>PA</state><state>CA</state><state>FL</state></country>"; } //line 3 echo $info; ?>
fdebf20029ddba6493c8a436c13a115e60bbe320
[ "PHP" ]
2
PHP
pitthehan/Load_Cities
bd96acf139ea7143f4ea3103c56f487d62fae066
48e690a418a5a0dadef833cbfe733d159f88423b
refs/heads/main
<file_sep># APP_nutrition_calculator - Una herramienta para calcular las propiedades nutricionales y las calorías de una receta según sus ingredientes.Para ellos se utilizará un dataset de ingredientes y propiedades nutricionales de ellos. - Se añade un buscador de alimentos altos en un nutriente (elegido por el usuario) y un juego de comparación denutrientes en el que el usuario tiene que adivinar cuál de las dos propuestas tiene más cantidad de un nutriente. <file_sep>#Librerías library(shiny) library(plyr) library(readxl) require(shiny) require(DT) require(D3partitionR) require(magrittr) require(shinyWidgets) require(ggplot2) require(stringr) require(shinydashboard) require(data.table) library(readr) library(dplyr) # dataset para el menu personalizado alimentos_tipo <- fread("./data/alimentos_tipo.csv",sep = ";") # dataset para Top en propiedad alimentos <- read_excel("./data/alimentos.xlsx") # dataset para preguntas questions <- read.csv(file = './data/preguntas.csv', colClasses = 'character', header = TRUE, sep = ";") # Puntuación maxima para cada pregunta tscore1 <- 1 # Cada pregunta como mucho obtendra un punto tscore2 <- 1 tscore3 <- 1 # Función para obtener el resultado de la pregunta chkQuestion <- function(answer, correct, index) { mensaje <- if (answer == correct) 'Correct' else 'False' return(mensaje)} # Funcion para calcular la puntuacion de las preguntas scrQuestion1 <- function(result1) { vscore1 <- (result1 == 'False') * -1 tscore1 <- tscore1 + vscore1 return(as.numeric(max(0,tscore1)))} ui <- dashboardPage( skin = "green",dashboardHeader(title = "App Nutrientes"), # formato y título del dashboard dashboardSidebar( sidebarMenu( # Menu con las distintas ventanas menuItem("Menu Personalizado", tabName = "Menu", icon = icon("fas fa-utensils")), # icono y título de cada pestaña menuItem("Top en Nutrientes", tabName = "Top", icon = icon("fas fa-sort-numeric-up")),#icono y título de cada pestaña menuItem("Quiz", tabName = "Quiz", icon = icon("fas fa-question")),#icono y título de cada pestaña menuItem("Sobre Nosotros", tabName = "SobreNosotros", icon = icon("address-card"))#icono y título de cada pestaña ) ), dashboardBody( # cuerpo del dashboard tabItems( # tabItems y dentro cada tabItem tabItem(tabName = "Quiz",h1("Quiz 🧠"), # nombre y título que verá el usuario fluidRow( imageOutput("picture", height = "auto"), box(width = 8,h4("Pruebe aquí su conocimiento de las propiedades de los alimentos. ¡Recuerde que es importante conocerlos para tomar mejores decisiones!")),# caja con la explicación de lo que peude hacer la pestaña uiOutput("ui"), # guardar una expresión en una variable box(width = 5,list(h4('Resultados'), # caja con los resultados del quiz por pregunta verbatimTextOutput('result1'), # Respuesta de la pregunta 1 verbatimTextOutput('result2'), # Respuesta de la pregunta 2 verbatimTextOutput('result3'), # Respuesta de la pregunta 3 verbatimTextOutput('total'), # Resultado final obtenido actionButton("update", label = "Nuevo test")))) # botón reactividad para hacer un nuevo test con nuevas preguntas ), tabItem( tabName = "Top",h1("Alimentos con un macronutriente destacado 🥚🍅🍝🦐"),# nombre y título que verá el usuario fluidRow( box(width = 8, h4("Explore aquí los alimentos ricos en un macronutriente")), # caja con la explicación de lo que peude hacer la pestaña box(selectInput("propiedad", #inputID label = "Elige una propiedad del alimento", # Explicacion para el usuario choices = list("Proteinas" = "proteinas", "Grasas" = "grasas", "Carbohidratos" = "carbohidratos"), selected = "unif")),# ninguna seleccion predeterminada box(width = 10,tableOutput('table')))), # output de la tabla de datos tabItem(tabName = "Menu", h1("Alimentos consumidos hoy 😋"),# nombre y título que verá el usuario fluidRow( box(width = 8,h4("Complete con los alimentos hoy ingeridos. ¡Hay muchos tipos!")), valueBoxOutput("calories"), # caja con la explicación de lo que peude hacer la pestaña tabPanel("Menu selection", column(3, uiOutput('seleccion_tipo')), # En esta columna de la pantalla se encuentra el boton reactivo a la seleccion de tipo de alimento column(5, uiOutput('seleccion_alimento')), # En esta columna de la pantalla se encuentra el boton reactivo a la seleccion del alimento column(12, dataTableOutput('selected_items')) # Output de la tabla ) ) ), tabItem(tabName = "SobreNosotros", h1("Sobre Nosotros 👥"),# nombre y título que verá el usuario fluidRow( imageOutput("foto", height = "auto"), box(width = 8, h4("<NAME> e <NAME>. Proyecto para la asignatura 'Técnicas de Visualización' en el Máster de Data Science. Profesor: <NAME>")), # Descripcion box(width = 8, h4(" <NAME>: https://www.linkedin.com/in/ignacio-ruiz-de-zuazu-echevarr%C3%ADa-7a7191183/")), #Linkedin box(width = 8, h4(" <NAME>: https://www.linkedin.com/in/sergio-ca%C3%B1%C3%B3n-laiz/")) )) ))) server <- function(input, output) { ###### Menu personalizado ##### vals <- reactiveValues(switch_origin_cal = F) # Cuando lee un valor de él, la expresión reactiva que llama toma una # dependencia reactiva de ese valor output$seleccion_tipo <- renderUI( # Los componentes de la interfaz de usuario # se generan como HTML en el servidor dentro de un bloque renderUI () # y se envían al cliente, que los muestra con uiOutput (). # Cada vez que se envía un nuevo componente al cliente, reemplaza completamente # al componente anterior. selectizeInput('seleccion_tipo','Selecciona el tipo de ingrediente', # Tabla para el menú personalizado c('All',unique(alimentos_tipo[['Category']])), # Se pueden elegir todas y por categoria de cada alimento multiple = T, # permitimos elegir múltiples valores selected = 'All') # Todos como predeterminado ) output$seleccion_alimento <- renderUI( # El mismo caso que el anterior, en este caso se realiza para la selección de los alimentos selectizeInput('seleccion_alimento','Añade un ingrediente', split(alimentos_tipo[Category %in% input$seleccion_tipo | input$seleccion_tipo == 'All']$Item, # Cuando se selecciona un tipo de alimentos, unicamente se muestran esos elementos salvo si se selecciona All que son todos los tipos de alimentos alimentos_tipo[Category %in% input$seleccion_tipo | input$seleccion_tipo == 'All',Category]),multiple = T) ) output$selected_items <- renderDataTable( # Output de la tabla { alimentos_tipo[Item %in% input$seleccion_alimento,colnames(alimentos_tipo), # Para todos aquellos items en el boton obtiene todos los datos con el nombre de las columnas with = F] },options = list(scrollX = T,dom = 't'),rownames = FALSE # scroll activado para ver toda la tabla ) ###### Parte del Quiz ######## pregunta <- reactive({# reactivo y el objeto pregunta pasa a función como "pregunta()" input$update # botón activo para hacer un nuevo conjunto de r questions[sample(nrow(questions), size = 3),]}) # mezlamos las posibles preguntas y eligimos 3 output$ui <- renderUI({box( radioButtons('answ1', paste('Q1 -',pregunta()[[1,3]]), # pregunta, fila 1 de la muestra c(pregunta()[[1,5]], # alternativa pregunta()[[1,6]],# alternativa pregunta()[[1,7]],# alternativa pregunta()[[1,4]]), selected = 0),# respuesta radioButtons('answ2', paste('Q2 -',pregunta()[[2,3]]),# pregunta, fila 2 de la muestra c(pregunta()[[2,5]],# alternativa pregunta()[[2,6]],# alternativa pregunta()[[2,7]],# alternativa pregunta()[[2,4]]), selected = 0),# respuesta radioButtons('answ3', paste('Q3 -',pregunta()[[3,3]]),# pregunta, fila 3 de la muestra c(pregunta()[[3,5]],# alternativa pregunta()[[3,6]],# alternativa pregunta()[[3,7]],# alternativa pregunta()[[3,4]]), selected = 0),# respuesta actionButton('enviar', 'Enviar') # boton reactibo para enviar resultados a la función chkQuestion() ) }) rltInput1 <- reactive({input$enviar # boton para comprobar el input del usuario con la respuesta correcta (columna 4) isolate(try_default(chkQuestion(input$answ1, pregunta()[[1,4]],3), # aplicamos la funcion para ver si es correcta o no default = 'Choose', quiet = TRUE)) }) rltInput2 <- reactive({input$enviar # boton para comprobar el input del usuario con la respuesta correcta (columna 4) isolate(try_default(chkQuestion(input$answ2, pregunta()[[2,4]],3), default = 'Choose', quiet = TRUE)) }) rltInput3 <- reactive({input$enviar #nboton para comprobar el input del usuario con la respuesta correcta (columna 4) isolate(try_default(chkQuestion(input$answ3, pregunta()[[3,4]],3), default = 'Choose', quiet = TRUE)) }) output$result1 <- renderText({paste('Q1:',rltInput1())}) # damos formato a la salida del resultado que verá el usuario output$result2 <- renderText({paste('Q2:',rltInput2())}) output$result3 <- renderText({paste('Q3:',rltInput3())}) totalInput1 <- reactive({ scrQuestion1(rltInput1())*(rltInput1() == 'Correct')}) # si es correcta sumamos un punto. Usamos funcion scrQuestion totalInput2 <- reactive({ scrQuestion1(rltInput2())*(rltInput2() == 'Correct')}) # si es correcta sumamos un punto . Usamos funcion scrQuestion totalInput3 <- reactive({ scrQuestion1(rltInput3())*(rltInput3() == 'Correct')}) # si es correcta sumamos un punto . Usamos funcion scrQuestion output$total <- renderText(paste0("Tu puntuación es: ",totalInput1() + totalInput2() + totalInput3())) # resultado total output$picture <- renderImage({# Salida de la imagen return(list(src = "./imagenes/Foto.jpg",contentType = "image/jpg", alt = "Alignment")) }, deleteFile = FALSE) ############ Parte de Top en propiedad ########## dataset <- alimentos[,1:5] # tabla solamente con macronutrientes, calorias y nombre del alimento output$table <- renderTable({# salida de tabla if (input$propiedad == "proteinas") { head(dataset[order(dataset[,5], decreasing = TRUE),], 100) # muestra los 100 alimentos con mayor cantidad del macronutriente elegido } else if (input$propiedad == "grasas") { # En el caso en el que la opcion seleccionada no sea la de proteinas, la siguiente opción pasará a ser o grasas o carbohidratos head(dataset[order(dataset[,4], decreasing = TRUE),], 100) } else if (input$propiedad == "carbohidratos") { head(dataset[order(dataset[,3], decreasing = TRUE),], 100) } }) ######### Sobre nosotros ######### output$foto <- renderImage({ # Salida de la imagen return(list(src = "./imagenes/cunef.jpg",contentType = "image/jpg", alt = "Alignment")) # output imagen sobre nosotros }, deleteFile = FALSE) } shinyApp(ui = ui, server = server)
4a9a8ac764fa037ffabc678ed6d2cfdadd20f700
[ "Markdown", "R" ]
2
Markdown
sercala97/APP_nutrition_calculator
afa4353e018e17e4bcba8d54ec36e97bcff579b0
b3c9dfc9a75abc57b4a3c0f253bf51da900aad58
refs/heads/master
<repo_name>niusmallnan/cloudx5-gate-demo<file_sep>/README.md # cloudx5-gate-demo ### test ``` curl -H "X-CLOUDX5-ZONE: zoneb" http://127.0.0.1:18080 curl -H "X-CLOUDX5-ZONE: zonea" http://127.0.0.1:18080 curl -H http://127.0.0.1:18080 ``` <file_sep>/run.sh # Proxy docker run -d --name ga-proxy -p 18080:80 \ -v `pwd`/conf.d/:/etc/nginx/conf.d/ \ nginx # User login docker run -d --name login -p 10000:80 \ -v `pwd`/login/:/usr/share/nginx/html \ nginx # Zone A docker run -d --name zonea -p 10001:80 \ -v `pwd`/zonea/:/usr/share/nginx/html \ nginx # Zone B docker run -d --name zoneb -p 10002:80 \ -v `pwd`/zoneb/:/usr/share/nginx/html \ nginx # curl -H "X-CLOUDX5-ZONE: zona" http://127.0.0.1:18080
a875d25fbb3491f5cf7d2249fc1bcb6ac37320bb
[ "Markdown", "Shell" ]
2
Markdown
niusmallnan/cloudx5-gate-demo
d51714b1c2960a3ece4d9898c32d101b55aedd08
a144203334ac4e9e98deb9d3e60e503308fa5b95
refs/heads/master
<file_sep>import os, os.path path, dirs, files = next(os.walk('TSE')) for d in dirs: caminho = os.path.join(path, d) tam = 0 for arq in os.listdir(caminho): tam = tam + os.path.getsize(os.path.join(caminho, arq)) print('Tamanho de {} = {} Mbytes'.format(caminho, tam))
dfb1611918ddb17a655e803b6658a98a442369f4
[ "Python" ]
1
Python
ecalasans/notebooksPython
872b47eed7d5b12298bfaad110dc16f1493227a6
78fb482b1b271d8980979ae8a8de21ed1979bcd6
refs/heads/master
<file_sep>/* 题目描述 第一行输入一个数,为n,第二行输入n个数,这n个数中,如果偶数比奇数多,输出NO,否则输出YES。 输入 输入有多组数据。 每组输入n,然后输入n个整数(1<=n<=1000)。 输出 如果偶数比奇数多,输出NO,否则输出YES。 样例输入 1 67 7 0 69 24 78 58 62 64 样例输出 YES NO */ #include<cstdio> int main() { int n,a; while ( scanf("%d", &n) != EOF ) { int _0 = 0, _1 = 0; for ( int i = 0; i < n; i++ ) { scanf("%d", &a); if ( a % 2 == 0 ) { _0 ++; } else { _1 ++; } } if ( _0 > _1 ) { printf("NO\n"); } else { printf("YES\n"); } } return 0; } <file_sep>#include<cstdio> #include<cstring> using namespace std; int main() { char a[20],b[20]; char s[11]; while ( scanf("%s", a) != EOF && scanf("%s", b) != EOF ) { char *post = NULL; while ( (post = strrchr(a,',')) != NULL ) { *post = '\0'; strcpy(s, post+1); strcat(a, s); } while ( (post = strrchr(b,',')) != NULL ) { *post = '\0'; strcpy(s, post+1); strcat(b, s); } // int a1,b1; sscanf(a, "%d", &a1); sscanf(b, "%d", &b1); printf("%d\n", a1+b1); } return 0; } <file_sep>#include<cstdio> #include<cstring> #include<algorithm> using namespace std; struct Student{ char id[15]; int score; //分数 int locationNum; //考场号 int localRank; //考场排名 }stu[30010]; bool cmp(Student a, Student b) { if ( a.score != b.score ) { return a.score > b.score; } else { return strcmp(a.id,b.id) < 0; } } int main() { int n,k,num = 0; scanf("%d", &n); //读入考场数 for ( int i = 0; i < n; i++ ) { scanf("%d", &k); //读入考生人数 for ( int j = 0; j < k; j++ ) { scanf("%s %d", stu[num].id,&stu[num].score); stu[num].locationNum = i + 1; num++; } sort(stu + num - k,stu + num,cmp); stu[num - k].localRank = 1; for ( int j = 1; j < k; j++ ) { //比较成绩给出考场内排名 if ( stu[num - k + j].score < stu[num - k + j - 1].score ) { stu[num - k + j].localRank = j + 1; } else { stu[num - k + j].localRank = stu[num - k + j - 1].localRank; } } } //printf("%d", num-1); sort(stu,stu + num,cmp); printf("%d\n",num); int r = 1; for ( int i = 0; i < num; i++ ) { if ( i > 0 && stu[i].score != stu[i-1].score ) { r = i + 1 ; } printf("%s ", stu[i].id); printf("%d %d %d\n", r, stu[i].locationNum, stu[i].localRank); } return 0; } <file_sep>#include<cstdio> #include<cstring> int main() { int day, year,k; char name[10]; struct name2Num { int Num; char Name[10]; } month[12] = { { 1, "January"}, { 2, "February"}, { 3, "March"}, { 4, "April"}, { 5, "May"}, { 6, "June"}, { 7, "July"}, { 8, "August"}, { 9, "September"}, { 10, "October"}, { 11, "November"}, { 12, "December"} }; name2Num week[7] = { { 0, "Sunday"}, { 1, "Monday"}, { 2, "Tuesday"}, { 3, "Wednesday"}, { 4, "Thursday"}, { 5, "Friday"}, { 6, "Saturday"} }; while ( scanf("%d %s %d", &day, &name, &year) != EOF ) { for ( int i = 0; i < 12; i++ ) { if ( strcmp(name, month[i].Name) == 0 ) { k = month[i].Num; break; } } if ( k <= 2 ) { k += 12; year--; } int w = ( day + 2 * k + 3 * ( k + 1 ) / 5 + year + \ year / 4 - year / 100 + year / 400 + 1 ) % 7; printf("%s\n", week[w].Name); } return 0; } <file_sep>/* 题目描述 写个算法,对2个小于1000000000的输入,求结果。特殊乘法举例:123 * 45 = 1*4 +1*5 +2*4 +2*5 +3*4+3*5 输入 两个小于1000000000的数 输出 输入可能有多组数据,对于每一组数据,输出Input中的两个数按照题目要求的方法进行运算后得到的结果。 样例输入 24 65 42 66666 3 67 样例输出 66 180 39 */ #include<cstdio> #include<cstring> using namespace std; int main() { int a, b, sum; char A[20] = {0}, B[20] = {0}; while ( scanf("%d %d", &a, &b) != EOF ) { sum = 0; sprintf(A, "%d", a); sprintf(B, "%d", b); for ( int i = 0; i < strlen(A); i++ ) { for ( int l = 0; l < strlen(B); l++ ) { sum += (A[i] - 48)*(B[l] - 48); } } printf("%d\n", sum); } return 0; } <file_sep>#include<cstdio> #include<cstring> #include<ctype.h> #include<iostream> using namespace std; int main() { char str1[101]; while ( fgets(str1, 101, stdin) != NULL ) { if ( str1[0] <= 'z' && str1[0] >= 'a' ) { str1[0] -= 32; } for ( int i = 1; i < (signed int )strlen(str1); i++ ) { if ( isspace(str1[i]) ) { if ( str1[i+1] <= 'z' && str1[i+1] >= 'a' && (i + 1) < (signed int)strlen(str1) ) { str1[i+1] -= 32; } } } printf("%s", str1); } return 0; } <file_sep>/* 题目描述 The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits. 输入 Each input file contains one test case. For each case, the first line contains an integer N (in [3, 105]), followed by N integer distances D1 D2 ... DN, where Di is the distance between the i-th and the (i+1)-st exits, and DN is between the N-th and the 1st exits. All the numbers in a line are separated by a space. The second line gives a positive integer M (<=104), with M lines follow, each contains a pair of exit numbers, provided that the exits are numbered from 1 to N. It is guaranteed that the total round trip distance is no more than 107. 输出 For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits. 样例输入 5 1 2 4 14 9 3 1 3 2 5 4 1 样例输出 3 10 7 */ #include<cstdio> void swap(int &a, int &b) { if ( a > b) { int temp = b; b = a; a = temp; } } int lowbit(int x) //利用树状数组快速求和 { return x&(-x); } void change(int x, int p, int n, int t[]) { while ( x <= n ) { t[x] += p; x += lowbit(x); } } int sum(int k, int t[]) { int ans = 0; while ( k > 0 ) { ans += t[k]; k -= lowbit(k); } return ans; } int main() { int N,M,sumD; while ( scanf("%d", &N) != EOF ) { int D[N+1] = {0},t[N+1] = {0}; sumD = 0; for ( int i= 1; i < N+1; i++ ) { scanf("%d", &D[i]); change(i, D[i], N+1, t); sumD += D[i]; } scanf("%d", &M); for ( int i = 0; i < M; i++ ) { int a, b; scanf("%d %d", &a, &b); swap(a, b); int ans = sum(b-1,t) - sum(a-1, t); int _ans = sumD - ans; swap(ans, _ans); printf("%d\n", ans); } } return 0; }
bc1b624e3e611eaba69b3df661687c2a94cb32f9
[ "C++" ]
7
C++
xiaoyingza/Algorithm
d87a1fc91d982c77d0f9988afea5777b941dd1ff
4363d34a786d5e0924e3cd697292ad5df857137b
refs/heads/master
<repo_name>berrybab6/Gebeta<file_sep>/display/migrations/0003_auto_20200904_2023.py # Generated by Django 3.1 on 2020-09-04 17:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('display', '0002_auto_20200904_1735'), ] operations = [ migrations.AddField( model_name='food', name='isTraditional', field=models.BooleanField(default=False), ), migrations.AlterField( model_name='chief', name='award_types', field=models.CharField(default=' ', max_length=150, null=True), ), migrations.AlterField( model_name='chief', name='chief_img', field=models.ImageField(upload_to='pics'), ), migrations.AlterField( model_name='food', name='F_img', field=models.ImageField(upload_to='pics'), ), ] <file_sep>/display/migrations/0002_auto_20200904_1735.py # Generated by Django 3.1 on 2020-09-04 14:35 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('display', '0001_initial'), ] operations = [ migrations.RenameField( model_name='chief', old_name='ch_img', new_name='chief_img', ), migrations.RenameField( model_name='chief', old_name='ch_name', new_name='chief_name', ), ] <file_sep>/display/migrations/0001_initial.py # Generated by Django 3.1 on 2020-09-04 14:15 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Chief', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ch_name', models.CharField(max_length=100)), ('description', models.TextField()), ('ch_img', models.ImageField(upload_to='')), ('exprience', models.PositiveIntegerField()), ('role', models.CharField(max_length=200)), ('awards_num', models.PositiveIntegerField(null=True)), ('award_types', models.CharField(max_length=150, null=True)), ], ), migrations.CreateModel( name='Food', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('F_name', models.CharField(max_length=100)), ('F_desc', models.TextField()), ('F_img', models.ImageField(upload_to='')), ], ), ] <file_sep>/display/views.py from django.shortcuts import render from .models import Food,Chief import random # Create your views here. def addchief(request): ch=Chief.objects.all() return render(request,'aboutus.html',{'chief':ch}) def addfood(request): foodP=Food.objects.all().filter(promot=True) lis_prom=list(foodP) ch=Chief.objects.all().order_by('points') lis=list(ch) #ch_Promot=Chief.objects.all().order_by('exprience') #lis_prom=list(ch_Promot) food=Food.objects.all().filter(isTraditional=True) food_trad=random.choice(food) return render(request,'index.html',{'food':food_trad,'chief':lis[-1],'foodProm':lis_prom[-1]}) def promotechief(request): return render(request,'index.html') def myMax(list1): max = list1[0] for x in list1: if x > max : max = x return max<file_sep>/display/migrations/0006_food_price.py # Generated by Django 3.1 on 2020-09-04 20:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('display', '0005_food_promot'), ] operations = [ migrations.AddField( model_name='food', name='price', field=models.FloatField(default=0.0), ), ] <file_sep>/display/models.py from django.db import models # Create your models here. class Food(models.Model): F_name=models.CharField(max_length=100) F_desc=models.TextField() F_img=models.ImageField(upload_to='pics') isTraditional=models.BooleanField(default=False) promot=models.BooleanField(default=False) price=models.FloatField(default=0.0) class Chief(models.Model): chief_name=models.CharField(max_length=100) description=models.TextField() chief_img=models.ImageField(upload_to='pics') exprience=models.PositiveIntegerField() role=models.CharField(max_length=200) awards_num=models.PositiveIntegerField(null=True) award_types=models.CharField(max_length=150,null=True,default=" ") points=models.PositiveIntegerField(default=0) <file_sep>/contact/models.py from django.db import models # Create your models here. class Comment(models.Model): first_name=models.CharField(max_length=100) last_name=models.CharField(max_length=100) tel_number=models.CharField(max_length=16) email=models.EmailField() contact_me=models.BooleanField(default=False) contact_me_by=models.CharField(max_length=100,null=True) feedback=models.TextField() <file_sep>/contact/migrations/0003_auto_20200908_2253.py # Generated by Django 3.1 on 2020-09-08 19:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('contact', '0002_auto_20200908_2243'), ] operations = [ migrations.AlterField( model_name='comment', name='contact_me_by', field=models.CharField(max_length=100, null=True), ), ] <file_sep>/contact/views.py from django.shortcuts import render,redirect from .models import Comment # Create your views here. def contact(request): if request.method=='POST': f_name=request.POST["firstname"] l_name=request.POST["lastname"] tel_number=request.POST["telnum"] areacode=request.POST["areacode"] email=request.POST["email"] feedback=request.POST["feedback"] approve=request.POST["approve"] tel_email=request.POST["Tel_email"] tel_num="+"+ areacode+ " "+tel_number if approve=="approve": if tel_email=="tel": tel_email="tel" else: tel_email="email" approve=True return tel_email,approve else: tel_email=None approve=False comment = Comment(first_name=f_name, last_name=l_name,tel_number=tel_num,email=email,contact_me=approve,contact_me_by=tel_email,feedback=feedback) comment.save() return redirect('/') else: return render(request,"contactus.html")<file_sep>/display/urls.py from django.urls import path from . import views urlpatterns = [ path("aboutus",views.addchief, name="add chief"), path("",views.addfood,name="add food") ] <file_sep>/accounts/urls.py from django.urls import path from . import views urlpatterns = [ path("",views.login, name="login"), path("aboutus",views.aboutus,name= "aboutus") ] <file_sep>/display/migrations/0004_chief_points.py # Generated by Django 3.1 on 2020-09-04 17:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('display', '0003_auto_20200904_2023'), ] operations = [ migrations.AddField( model_name='chief', name='points', field=models.PositiveIntegerField(default=0), ), ] <file_sep>/display/admin.py from django.contrib import admin from .models import Chief,Food # Register your models here. admin.site.register(Food) admin.site.register(Chief)
b2b388b744dabc61b362c5bbc43dff97a14a77fa
[ "Python" ]
13
Python
berrybab6/Gebeta
1a0b9cb88ee23cc0aaebc307fd5c84ff1b785042
835a54ab1b4bef805837d8c99b46a17fcbe0beb6
refs/heads/master
<file_sep>package model; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public interface Worker { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ public void work() ; } <file_sep>#!/bin/bash javac MyClass.java java MyClass rm *.class <file_sep>using System; using System.Diagnostics; namespace ConsoleApplication { public class Program { public static void Main(string[] args) { Console.WriteLine("Hello World!"); Student st = new Student("Ali"); int sum = 1; for (int i = 1; i <= 6; i++) { sum *= i; } Console.WriteLine("Sum = " + sum); ProcessStartInfo startInfo = new ProcessStartInfo() { FileName = "ls", Arguments = "-l", }; ProcessStartInfo startInfo2 = new ProcessStartInfo() { FileName = "grep", Arguments = "'.cs'", }; Process proc = new Process() { StartInfo = startInfo, }; proc.Start(); } } public class Person { public string name; public Person(string n) { name = n; Console.WriteLine("Person Constructor!"); } } public class Student : Person { public Student(string n) : base(n) { Console.WriteLine("Student Constructor!"); } } } <file_sep>package model; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class Person implements Worker { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ private String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ private int age; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Person(){ super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ public void setName(String name) { // TODO implement me } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ public String getName() { // TODO implement me return ""; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ public void setName(int parameter) { // TODO implement me } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ public int getName() { // TODO implement me return 0; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ public void work() { // TODO implement me } } <file_sep>{ let a : number = 5; var aa : any = "str"; } class TEST { constructor() {} doSubmit() { console.log('hello'); } }<file_sep>// میتوان یک عبارت تابعی را به یک شی نسبت داد var sum = function(a, b) { return a + b; } var object = new Object(); object.age = 20; var obj = { age:55, name:"Ali" }; alert(obj.age); function team(name) { var obj = {}; obj.name = name; obj.game = 0; obj.win = 0; obj.lose = 0; obj.draw = 0; obj.ga = 0; obj.gf = 0; obj.points = 0; return obj; } var team01 = new team('Chelsea'); <file_sep>package model; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class Student extends Person { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ public MyClass myClass; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Student(){ super(); } } <file_sep>/** *Holds the data of one cell of matrix. *@author <NAME>, <NAME> *@version 1.0 (May 30, 2003) */ public class cell{ //numbers 1-8 surrounding mines, 9 is mine public int cellStatus; public boolean isClicked, isMarked; /** *Constructor of the cell. Sets class variables to default values. */ cell(){ this.cellStatus = 0; this.isClicked = false; this.isMarked = false; } /** *Returns the cellStatus of the cell. *@return integer value indicating cellStatus. */ public int getCell() { return cellStatus; } /** *Returns boolean value, whether the cell has been clicked. *@return boolean value indicating whether the cell has been clicked. */ public boolean getisClicked() { return isClicked; } /** *Returns boolean value, whether the cell has been marked. *@return boolean value indicating whether the cell has been marked. */ public boolean getisMarked() { return isMarked; } /** *Sets the value of the variable isClicked to a given boolean value. *@param newstatus boolean value. */ public void setisClicked(boolean newstatus){ this.isClicked = newstatus; } /** *Sets the value of the variable isMarked to a given boolean value. *@param mark boolean value. */ public void setisMarked(boolean mark){ this.isMarked = mark; } } <file_sep># MyProject none and this is for test github. ------------- ok this is for tag 2.0 version ------------- Commit by K112 <file_sep>#include <iostream> using namespace std; int main() { int number = 88; int* pNumber; pNumber = &number; cout << pNumber << endl; cout << &number << endl; cout << *pNumber << endl; cout << number << endl; return 0; } <file_sep>using System; namespace myApp { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!" + sum(5, 9)); } static int sum(int x, int y) { return x * y; } } }
7e4a91f04e02769ce9fc24109391c32bd427e1eb
[ "JavaScript", "Markdown", "C#", "Java", "TypeScript", "C++", "Shell" ]
11
Java
K112/MyProject
608c3d3de43868ceb78e4e16431492766a4ab66e
277c3e66c237441c0c708dd037d7efd609cbf5ac
refs/heads/master
<repo_name>ChetanRawat/StocksDemo<file_sep>/app/src/main/java/com/example/rilstocks/MainActivity.java package com.example.rilstocks; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.example.rilstocks.model.MarketUiData; import com.example.rilstocks.model.Record; import com.example.rilstocks.model.StocksData; import com.example.rilstocks.utils.AppUtils; import com.google.gson.Gson; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { TextView tv_market_filter; RecyclerView rv_stocks; private int clickCount = 1; List<MarketUiData> marketData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_market_filter = findViewById(R.id.tv_market_filter); tv_market_filter.setTag(1); rv_stocks = findViewById(R.id.rv_stocks); String jsondata = AppUtils.loadJSONFromAsset("all_stocks.json",this); StocksData stocksData = new Gson().fromJson(jsondata,StocksData.class); marketData = getMarketData(stocksData.getRecords(),1); StockListAdapter adapter = new StockListAdapter(marketData,MainActivity.this); rv_stocks.setHasFixedSize(true); rv_stocks.setLayoutManager(new LinearLayoutManager(MainActivity.this)); rv_stocks.setAdapter(adapter); tv_market_filter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(clickCount == 5){ clickCount = 1; } tv_market_filter.setText(getTextFromCount(clickCount)); List<MarketUiData> refreshData = getMarketData(stocksData.getRecords(),clickCount); marketData.clear(); marketData.addAll(refreshData); rv_stocks.getAdapter().notifyDataSetChanged(); clickCount +=1; } }); } private String getTextFromCount(int clickCount) { String tvName = ""; if(clickCount ==1){ tvName = "Market Price"; }else if(clickCount ==2){ tvName = "52w High"; }else if(clickCount ==3){ tvName = "52w Low"; }else if(clickCount ==4){ tvName = "Market Cap (Cr)"; } return tvName; } private List<MarketUiData> getMarketData(List<Record> records,int filterId) { List<MarketUiData> marketDataList = new ArrayList<>(); for(Record data:records){ MarketUiData marketData = new MarketUiData(); marketData.setCompanyName(data.getCompanyShortName()); if(filterId == 1){ marketData.setDisplayVal1(""+data.getLivePriceDto().getLtp()); marketData.setDisplayVal2(data.getLivePriceDto().getDayChange()); marketData.setPercentageChange(data.getLivePriceDto().getDayChangePerc()); }else if(filterId == 2){ marketData.setDisplayVal1(""+data.getYearlyHighPrice()); }else if(filterId == 3){ marketData.setDisplayVal1(""+data.getYearlyLowPrice()); }else if(filterId == 4){ marketData.setDisplayVal1(""+getCapDataInCr(data.getMarketCap())); } marketDataList.add(marketData); } return marketDataList; } private BigDecimal getCapDataInCr(BigDecimal marketCap) { BigDecimal amt = marketCap.divide(new BigDecimal(1000000000)); return amt.setScale(2, RoundingMode.HALF_UP); } }<file_sep>/app/src/main/java/com/example/rilstocks/model/DailyStocksCandleModel.java package com.example.rilstocks.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class DailyStocksCandleModel { @SerializedName("candles") @Expose private List<List<Float>> candles = null; @SerializedName("changeValue") @Expose private Object changeValue; @SerializedName("changePerc") @Expose private Object changePerc; public List<List<Float>> getCandles() { return candles; } public void setCandles(List<List<Float>> candles) { this.candles = candles; } public Object getChangeValue() { return changeValue; } public void setChangeValue(Object changeValue) { this.changeValue = changeValue; } public Object getChangePerc() { return changePerc; } public void setChangePerc(Object changePerc) { this.changePerc = changePerc; } } <file_sep>/app/src/main/java/com/example/rilstocks/utils/AppUtils.java package com.example.rilstocks.utils; import android.content.Context; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.math.RoundingMode; public class AppUtils { public static String loadJSONFromAsset(String fileName, Context context) { String json = null; try { InputStream is = context.getAssets().open(fileName); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; } public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = BigDecimal.valueOf(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); } }
a004bff44fbf58fc08069f61cd96608021470751
[ "Java" ]
3
Java
ChetanRawat/StocksDemo
c38e0d4970a542bad3e257afff04906cc17ee983
5b4a4e6c234bd3b603bce69eba6289cb43ea1529
refs/heads/master
<repo_name>anthonywocken/Project-6_The-Game-of-Life<file_sep>/LifeModel.java /** * Class Life is the model (data structure) that holds and updates the * status of our cellular automaton game. It provides methods to initialize * the game (done automatically when the game is first created), update one generation * and access the game status, which can be used by client code to display * the game board and the state of the game * * @author <NAME>, based on work by <NAME>. */ public class LifeModel { // public constants /** Number of rows/columns in Life Grid */ public static final int NROWSCOLS = 23; // private instance variables private LifeState[][] board; // game board private LifeState[][] board2; // next generation game board private int generations; // how many generations have happened private int numAdjacentAlive; private int numAdjacentDead; /** Construct and initialize new game board */ public LifeModel() { board = new LifeState[NROWSCOLS][NROWSCOLS]; board2 = new LifeState[NROWSCOLS][NROWSCOLS]; newGame(); } /** initialize new game * */ public void newGame() { for (int row = 0; row < LifeModel.NROWSCOLS; row++) { for (int col = 0; col < LifeModel.NROWSCOLS; col++) { if(row == 10 & col == 15 | row == 14 & col == 4 | row == 6 & col == 9 | row == 18 & col == 5) { board[row][col] = LifeState.ALIVE; } else { board[row][col] = LifeState.DEAD; } } } /***************************************************** * STUDENTS: setup your initial Life environment here *****************************************************/ } /** Returns the number of generations * @return The number of generations that have been run so far. */ public int getGenerationCount() { return generations; } /** Return the current state of game board cell at given row/column * (Squares numbered from 0 to NROWSCOLS-1). * @throws IllegalArgumentException for bad row/col * @param row The row of the deisred cell. * @param col The column of the desired cell. */ public LifeState getCell(int row, int col) { if(board[row][col] == LifeState.ALIVE) { return LifeState.ALIVE; } else if (board[row][col] == LifeState.DEAD){ return LifeState.DEAD; } return LifeState.DEAD; // stub value /*************************************** * STUDENTS: fix this **************************************/ } /** Process one life cycle of the cellular automaton * */ public void oneCycle() { for (int row = 1; row < NROWSCOLS - 1; row++) { for (int col = 1; col < NROWSCOLS - 1; col++) { numAdjacentAlive = 0; numAdjacentDead = 0; for (int rs = row - 1; rs <= row + 1; rs++) { for (int cs = col - 1; cs <= col + 1; cs++) { if (rs != row & cs != col) { if (board[rs][cs] == LifeState.ALIVE) { numAdjacentAlive += 1; } else if (board[rs][cs] == LifeState.DEAD) { numAdjacentDead += 1; } } } } if (board[row][col] == LifeState.DEAD & numAdjacentAlive == 3) { board2[row][col] = LifeState.ALIVE; } else if (board[row][col] == LifeState.DEAD & numAdjacentAlive != 3) { board2[row][col] = LifeState.DEAD; } else if (board[row][col] == LifeState.ALIVE & numAdjacentAlive == 2) { board2[row][col] = LifeState.ALIVE; } else if (board[row][col] == LifeState.ALIVE & numAdjacentAlive == 0 || numAdjacentAlive == 1) { board2[row][col] = LifeState.DEAD; } else if (board[row][col] == LifeState.ALIVE & numAdjacentAlive >= 4) { board2[row][col] = LifeState.DEAD; } } } for (int col = 0; col < NROWSCOLS; col++) { board2[0][col] = LifeState.DEAD; board2[0][NROWSCOLS - 1] = LifeState.DEAD; } for (int row = 0; row < NROWSCOLS; row++) { board2[row][0] = LifeState.DEAD; board2[row][NROWSCOLS - 1] = LifeState.DEAD; } for (int row = 0; row < NROWSCOLS; row++) { for (int col = 0; col < NROWSCOLS; col++) { board[row][col] = board2[row][col]; } } //board = board2; /*************************************** * STUDENTS: implement this **************************************/ } }
539ed9fcdb89887ee58701fa5acf1b8f76c7eeba
[ "Java" ]
1
Java
anthonywocken/Project-6_The-Game-of-Life
ff5573540337caafe62f1e4fe3005bc05782dd2e
7d017d21ef3af793d2ffb12e555f2a35de1a4ab9
refs/heads/master
<file_sep><?php $hour=date("H"); if($hour>=6 && $hour<12){ $img='morning'; } elseif($hour>=12 && $hour<18){ $img='day'; } elseif($hour>=18 && $hour<23){ $img='evening'; } else{ $img='night'; } ?> <DOCTYPE html> <html> <title>me</title> <meta charset="cp1251"/> <head> <style> ul.nav{ margin-left: 120px; margin-top: 50px; padding-left: 0px; list-style: none; display: block; } .nav li { float: left; display: block; overflow: hidden; } ul.nav a { display: block; width: 15em; padding:15px; margin: 0 5px; background-color: #3f3e3e; border: 1px dashed #333; text-decoration: none; color: #A9A9A9; text-align: center; } ul.nav a:hover{ background-color: #333; color: #90EE90; } .content{ display: block; background: rgba(255,255,255,0.6); margin: 15px 125px; height: 550px; width: 1120; float: left; } </style> </head> <body style= "width: 100%; height: 760px; background: url(img/<?php echo $img; ?>.jpg); background-size: cover;"> <ul class="nav"> <li><a href="Disfortune.php">Disfortune</a></li> <li><a href="game.php">Game</a></li> <li><a href="index.php">News</a></li> <li><a href="video.php">Video</a></li> </ul> <ul class="content"> <il><a href="#"> <?php $connection=mysql_connect("localhost","mybd_user","admin123"); $db=mysql_select_db("my_bd"); mysql_query("SET NAMES 'cp1251'"); if(! $connection|| ! $db) { exit(mysql_error()); } $result=mysql_query("SELECT * FROM news"); mysql_close(); while($row=mysql_fetch_array($result)) {?> <h1><?php echo $row['title'] ?></h1> <p> <?php echo $row['text'] ?></p> <p>Date of publication: <?php echo $row['date'] ?>/<?php echo $row['time'] ?></p> <p>Author news: <?php echo $row['author'] ?></p> <hr/> <?php } ?> </a></li> </body> </html>
cc3414620be30efd1cfc0e9c8e1cbcdb85135b99
[ "PHP" ]
1
PHP
disfortune/gameshop
4bb1a0963be7d70428378a3360db91d57fe83313
ce0a1b59aa950bfb870abe64790bff952f5ad1e5
refs/heads/master
<repo_name>NiuLaura/HelloEveryone<file_sep>/Hello.js class Hello{ constructor(Message) { this.Message = Message; } callMe() { return this.Message; } } var h = new Hello('Hello'); console.log(h instanceof Hello);
54917ca063a490611d33d1590eb0d9a663cc4804
[ "JavaScript" ]
1
JavaScript
NiuLaura/HelloEveryone
6c7fb256698c3bbbaca906b01ed57ea281941932
955effce493c842cbbfcd986a9744b540615389d
refs/heads/master
<file_sep>(function (util) { var createApiList = util.createApiList; var canUseApi = util.canUseApi; var getObjectName = util.getObjectName; var apiList = []; try { createApiList(apiList, String, ['fromCharCode'], ['charAt', 'charCodeAt', 'concat', 'indexOf', 'lastIndexOf', 'localeCompare', 'match', 'replace', 'search', 'slice', 'split', 'substr', 'substring', 'toLocaleLowerCase', 'toLocaleUpperCase', 'toLowerCase', 'toUpperCase', 'toString', 'trim', 'valueOf']); createApiList(apiList, Array, ['isArray'], ['concat', 'every', 'filter', 'forEach', 'indexOf', 'join', 'lastIndexOf', 'map', 'pop', 'push', 'reduce', 'reduceRight', 'reverse', 'shift', 'slice', 'some', 'sort', 'splice', 'toLocaleString', 'toString', 'unshift']); createApiList(apiList, Object, ['create', 'defineProperty', 'defineProperties', 'seal', 'freeze', 'preventExtensions', 'isSealed', 'isFrozen', 'isExtensible', 'keys'], ['constructor', 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable']); createApiList(apiList, Function, ['length'], ['constructor', 'toString', 'apply', 'call', 'bind']); createApiList(apiList, Number, ['MAX_VALUE', 'MIN_VALUE', 'NaN', 'NEGATIVE_INFINITY', 'POSITIVE_INFINITY'], ['toString', 'toLocaleString', 'valueOf', 'toFixed', 'toExponential', 'toPrecision']); createApiList(apiList, Math, ['E', 'LN10', 'LN2', 'LOG2E', 'LOG10E', 'PI', 'SQRT1_2', 'SQRT2', 'abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'random', 'round', 'sin', 'sqrt', 'tan'], []); createApiList(apiList, Date, ['parse', 'UTC', 'now'], ['toString', 'toDateString', 'toTimeString', 'toLocaleString', 'toLocaleDateString', 'toLocaleTimeString', 'valueOf', 'getTime', 'getFullYear', 'getUTCFullYear', 'getMonth', 'getUTCMonth', 'getDate', 'getUTCDate', 'getDay', 'getUTCDay', 'getHours', 'getUTCHours', 'getMinutes', 'getUTCMinutes', 'getSeconds', 'getUTCSeconds', 'getMilliseconds', 'getUTCMilliseconds', 'getTimezoneOffset', 'setTime', 'setMilliseconds', 'setUTCMilliseconds', 'setSeconds', 'setUTCSeconds', 'setMinutes', 'setUTCMinutes', 'setHours', 'setUTCHours', 'setDate', 'setUTCDate', 'setMonth', 'setUTCMonth', 'setFullYear', 'setUTCFullYear', 'toUTCString', 'toISOString', 'toJSON']); createApiList(apiList, RegExp, ['$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9', 'input'], ['exec', 'test', 'toString', 'source', 'global', 'ignoreCase', 'multiline', 'lastIndex']); createApiList(apiList, Error, ['name', 'toString'], ['message']); createApiList(apiList, JSON, ['parse', 'stringify'], []); createApiList(apiList, window, ['EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError'], []); } catch(e) { document.write(e.String()); return; } var table = util.createTable(); apiList.forEach(function (api) { var obj = api.object; var objName = getObjectName(obj); var checkRes = []; api.static.forEach(function (method) { if (!canUseApi(obj, method)) { checkRes.push([objName, method, 'static method']); } }); if (api.prototype.length) { var instance = new obj(); api.prototype.forEach(function (method) { if (!canUseApi(instance, method)) { checkRes.push([objName, method, 'instance method']); } }); } if (!checkRes.length) { table.append([objName, 'all right ok!']); } else { checkRes.forEach(function (row) { table.append(row); }); } }); table.render(); })({ // util createApiList: function (arr, object, staticFuncs, prototypeFuncs) { arr.push({ object: object, static: staticFuncs, prototype: prototypeFuncs }); }, canUseApi: function (object, api) { // console.log(object[api]); return api in object; }, createTable: function () { var table = document.createElement('table'); return { append: function (arr) { table.innerHTML += ['<tr>', '<td>', arr.join('</td><td>'), '</td>', '</tr>'].join(''); }, render: function (container) { if (!(container instanceof HTMLElement)) { container = document.body; } container.appendChild(table); } } }, getObjectName: function (obj) { var matchFunc = obj.toString().match(/^function (\w+)\(\)/) if (matchFunc) { return matchFunc[1]; } else { return obj.toString().slice(8, -1); } } });
fe1a02289871bd2a515ce1e1a6ac9700880d5baa
[ "JavaScript" ]
1
JavaScript
Naixor/can-i-use-es5
c371fefe780776c0fb5bc44f3896ed0f2f71644d
ab304b974d85879cf024e23c52a12f091fde0209
refs/heads/master
<repo_name>marina128/Lab_7<file_sep>/Running Button/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Lab_6 { public partial class Form1 : Form { int xRatio; int yRatio; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { this.MouseMove += new MouseEventHandler(OnMouseMove); xRatio = button1.Location.X * 100 / this.Width; yRatio = button1.Location.Y * 100 / this.Height; } private void OnMouseMove(object sender, MouseEventArgs e) { int btnWidth2 = button1.Width / 2; int btnHeight2 = button1.Height / 2; int centerX = button1.Location.X + btnWidth2; int centerY = button1.Location.Y + btnHeight2; if (Math.Abs(centerX - e.X) < 80 && Math.Abs(centerY - e.Y) < 55) { int newX = centerX - (e.X - centerX); int newY = centerY - (e.Y - centerY); if(newX < button1.Width) { newX = this.Width - button1.Width - 20; } if(newX > this.Width - button1.Width - 20) { newX = button1.Width; } if (newY < button1.Height) { newY = this.Height - button1.Height -40; } if (newY > this.Height - button1.Height - 20) { newY = button1.Height; } xRatio = newX * 100 / this.Width; yRatio = newY * 100 / this.Height; button1.Location = new Point(newX - btnWidth2, newY - btnHeight2); } this.Update(); } private void buttonPush_Click(object sender, EventArgs e) { MessageBox.Show("Поздравляем! Вы смогли нажать на кнопку!"); } private void Form1_Resize(object sender, EventArgs e) { button1.Location = new Point(this.Width * xRatio / 100, this.Height * yRatio / 100); } } } <file_sep>/Color Picker/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp2 { public partial class Form1 : Form { ToolTip tip = new ToolTip(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { lblColor.BackColor = Color.FromArgb(trackRed.Value, trackGreen.Value, trackBlue.Value); tip.SetToolTip(lblColor, "#" + trackRed.Value.ToString("X") + trackGreen.Value.ToString("X") + trackBlue.Value.ToString("X")); } private void trackRed_Scroll(object sender, EventArgs e) { lblValRed.Text = trackRed.Value.ToString(); lblColor.BackColor = Color.FromArgb(trackRed.Value, trackGreen.Value, trackBlue.Value); } private void trackGreen_Scroll(object sender, EventArgs e) { lblValGreen.Text = trackGreen.Value.ToString(); lblColor.BackColor = Color.FromArgb(trackRed.Value, trackGreen.Value, trackBlue.Value); } private void trackBlue_Scroll(object sender, EventArgs e) { lblValBlue.Text = trackBlue.Value.ToString(); lblColor.BackColor = Color.FromArgb(trackRed.Value, trackGreen.Value, trackBlue.Value); } private void lblColor_MouseHover(object sender, EventArgs e) { tip.SetToolTip(lblColor, "#" + trackRed.Value.ToString("X") + trackGreen.Value.ToString("X") + trackBlue.Value.ToString("X")); } private void trackRed_MouseUp(object sender, MouseEventArgs e) { Clipboard.SetText("#" + trackRed.Value.ToString("X") + trackGreen.Value.ToString("X") + trackBlue.Value.ToString("X")); } private void trackGreen_MouseUp(object sender, MouseEventArgs e) { Clipboard.SetText("#" + trackRed.Value.ToString("X") + trackGreen.Value.ToString("X") + trackBlue.Value.ToString("X")); } private void trackBlue_MouseUp(object sender, MouseEventArgs e) { Clipboard.SetText("#" + trackRed.Value.ToString("X") + trackGreen.Value.ToString("X") + trackBlue.Value.ToString("X")); } } }
67e23e71b0d814c05878a622d01281cb970900b8
[ "C#" ]
2
C#
marina128/Lab_7
613d0ee259714866e54a8c577ecfe1d188f0ecba
15936444d6a639cb0163f3d440a5b69576032989
refs/heads/main
<file_sep>package org.wso2.custom.handler.previouslogintime.internal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; import org.wso2.carbon.identity.event.handler.AbstractEventHandler; import org.wso2.custom.handler.previouslogintime.PreviousLoginTimeHandler; /** * @scr.component name="org.wso2.custom.handler.previouslogintime" immediate="true" */ public class ServiceComponent { private static Log log = LogFactory.getLog(ServiceComponent.class); protected void activate(ComponentContext context) { try { BundleContext bundleContext = context.getBundleContext(); bundleContext.registerService(AbstractEventHandler.class.getName(), new PreviousLoginTimeHandler(), null); if (log.isDebugEnabled()) { log.debug("PreviousLoginTimeHandler is activated."); } } catch (Exception e) { log.error("Error while activating PreviousLoginTimeHandler component.", e); } } protected void deactivate(ComponentContext context) { if (log.isDebugEnabled()) { log.debug("PreviousLoginTimeHandler is de-activated."); } } } <file_sep>This event handler was developed to track the time when user logged in previously. This is useful for client applications to perform certain tasks when a user logs in after a long time. This is tested with WSO2 IS 5.7.0 and 5.10.0. **Steps to deploy** Build the component using `mvn clean install` Copy the `org.wso2.custom.handler.previouslogintime-1.0.0.jar` file into `<IS_HOME>/repository/components/dropins` For 5.8.0 or older versions; add following two lines into `<IS_HOME>/repository/conf/identity/identity-event.properties` file ``` module.name.13=previousLoginTimeHandler previousLoginTimeHandler.subscription.1=POST_AUTHENTICATION Note: the number 13 has to be changed to `the highest existing number with module.name + 1` ``` For 5.9.0 or newer versions; add following configuration to `deployment.toml` file. ``` [[event_handler]] name= "previousLoginTimeHandler" subscriptions =["POST_AUTHENTICATION"] ``` Create two local claims http://wso2.org/claims/identity/currentLoginTime http://wso2.org/claims/identity/previousLoginTime Since these claims are identity claims (starting with http://wso2.org/claims/identity), they will be stored on the Identity DB and not on the external userstore. If you need to change the claim URIs, it can be done from the PreviousLoginTimeHandler class. Restart WSO2 IS **Troubleshooting** For 5.8.0 or older versions; add following line into `log4j.properties` file and restart WSO2 IS. ``` log4j.logger.org.wso2.custom.handler.previouslogintime=DEBUG ``` For 5.9.0 or newer versions; add following line into `log4j2.properties` file and add the logger `org-wso2-custom-handler.previouslogintime` at the end of the line starting with `loggers =`. ``` logger.org-wso2-custom-handler.previouslogintime.name = org.wso2.custom.handler.previouslogintime logger.org-wso2-custom-handler.previouslogintime.level = DEBUG ``` Following log will be written at server startup. ``` DEBUG {org.wso2.custom.handler.previouslogintime.internal.ServiceComponent} - PreviousLoginTimeHandler is activated. ``` Following lines will be written when a user logs in sucessfully. ``` DEBUG {org.wso2.custom.handler.previouslogintime.PreviousLoginTimeHandler} - Start handling post authentication event. DEBUG {org.wso2.custom.handler.previouslogintime.PreviousLoginTimeHandler} - Retrieved http://wso2.org/claims/identity/currentLoginTime claim value: 1605370394597 DEBUG {org.wso2.custom.handler.previouslogintime.PreviousLoginTimeHandler} - Successfully updated claim values, http://wso2.org/claims/identity/currentLoginTime : 1605370475020, http://wso2.org/claims/identity/previousLoginTime : 1605370394597 ```
86eea035a0824478b7b5a764a50ed2bccf2f26ae
[ "Markdown", "Java" ]
2
Java
rksk/wso2-custom-event-handler
def45da015d10dae8a28faa3c975a5b2f0225cdb
24e784e6408649dc9b142841ce4d6d17842afd08
refs/heads/master
<file_sep>module ::Interferon::HostSources class Optica DIR = 'loaders' end end
fd9795385e8109f3567162a75069b1182d1d7a6f
[ "Ruby" ]
1
Ruby
remh/interferon
827db6f2dc4207df9679a09da94c1e3e229ad4a0
74e28be82bec215bf40c3992fec05f69fa769180
refs/heads/master
<repo_name>CarmelRobotics/petty-kellers<file_sep>/examples/rain.py from __future__ import division import time import Adafruit_WS2801 import Adafruit_GPIO.SPI as SPI PIXEL_COUNT = 159 PIXEL_CLOCK = 18 PIXEL_DOUT = 23 pixels = Adafruit_WS2801.WS2801Pixels(PIXEL_COUNT, clk=PIXEL_CLOCK, do=PIXEL_DOUT) pixels.clear() pixels.show() RED=[0]*159 BLUE=[0]*159 GREEN=[0]*159 while True: rgb = [255,0,0] decColor = 0 for decColor in range(0,3): incColor = 0 if decColor==2 else decColor+1 i = 0 for i in range(0,5): rgb[decColor] -= 50 rgb[incColor] += 50 RED[0] = rgb[0] GREEN[0] = rgb[1] BLUE[0] = rgb[2] pixels.set_pixel_rgb(0,RED[0],GREEN[0],BLUE[0]) pixels.show() time.sleep(0.0001) c = 159 for c in range (159,0): RED[c] = RED[c-1] GREEN[c] = GREEN[c-1] BLUE[c] = BLUE[c-1]
d45b3286581f6c076854a8d427588da6ce02a3fb
[ "Python" ]
1
Python
CarmelRobotics/petty-kellers
a3420e29be90f24b44bd0dfc12ff029fca61d0f0
1ff3cede108af75f2142b30688745aa6e5bdcce0
refs/heads/master
<repo_name>AYCHConsultant/AYCHConsultant.github.io<file_sep>/assets/js/functions.js $(document).ready(function () { // Get started! var scroll = new SmoothScroll('[data-scroll]'); if (navigator.userAgent.match(/Trident\/7\./)) { $('body').on("mousewheel", function () { event.preventDefault(); var wd = event.wheelDelta; var csp = window.pageYOffset; window.scrollTo(0, csp - wd); }); } $(".navbar-nav .nav-link").on("click", function () { $(".navbar-nav").find(".active").removeClass("active"); $(this).addClass("active"); }); });<file_sep>/Dockerfile FROM ubuntu:16.04 RUN mkdir -p /app WORKDIR /app RUN apt-get update \ && apt-get upgrade -y \ && apt-get install -y curl RUN curl -sL https://deb.nodesource.com/setup_8.x | bash - \ && apt-get install -y nodejs \ && npm install -g gulp EXPOSE 3000 VOLUME ["/app"] CMD ["gulp", "serve"]<file_sep>/README.md # AYCH inc "leadwise" - "managewell" is a principle of AYCH Consultant and Developer. A competent and experienced technical/development company in the global leaderlist. The consultants and developers are of competent, experienced, and of exceptional interpersonal communication skills towards global business environment. Main language used is English for international communication. All are selected to deliver the products and services at the best version in terms of technical and soft skills. ## Quick Start ``` git clone https://github.com/aychconsultant/aychconsultant-website.git cd consulting-website npm install gulp serve ``` ## Requirements This project requires you have [nodejs](https://nodejs.org/en/) with [npm](https://www.npmjs.com/get-npm) installed. This project requires you have a global installation of [gulp](http://gulpjs.com/). ``` npm install -g gulp ``` ## Fixing Node Module Errors ``` rm -fr node_modules rm -fr package-lock.json npm cache clean --force npm install ``` ## Docker ``` docker build -t aychinc . docker run --rm -v "$(pwd)":/app aychinc npm install docker run --rm -v "$(pwd)":/app aychinc gulp docker run --rm -p 3000:3000 -v "$(pwd)":/app aychinc ```
2eb868644c0fe1fb254af655e2910efaba3eaffa
[ "JavaScript", "Dockerfile", "Markdown" ]
3
JavaScript
AYCHConsultant/AYCHConsultant.github.io
8c9b41cf6740708e20ec884670e7f5b7daac9d90
5eb7836c8773df3e65e003a40adb16ac72704df8
refs/heads/master
<repo_name>ali-bulut/ruby-on-rails-blog-web-app<file_sep>/app/controllers/portfolios_controller.rb class PortfoliosController < ApplicationController before_action :set_portfolio_item, only:[:edit, :update, :show, :destroy] layout "portfolio" access all: [:show, :index, :angular], user: {except: [:destroy, :new, :create, :edit, :update, :toggle_status, :sort]}, site_admin: :all def index # we can reach angular method from portfolio model. We created a query from there and we can reach from here # without writing any query. # @portfolio_items = Portfolio.angular # @portfolio_items = Portfolio.ruby_on_rails_portfolio_items # @portfolio_items = Portfolio.all # # that means portfolio items will be ordered by position field in database as ascending. # @portfolio_items = Portfolio.order("position ASC") @portfolio_items = Portfolio.by_position end def sort params[:order].each do |key, value| Portfolio.find(value[:id]).update(position: value[:position]) end # by writing this we are telling rails, dont look for view for this controller, here we are just communicating # with database. render nothing: true end def angular @angular_portfolio_items = Portfolio.angular end def show end def new @portfolio_item = Portfolio.new end def create @portfolio_item = Portfolio.new(portfolio_params) respond_to do |format| if @portfolio_item.save format.html { redirect_to portfolios_path, notice: 'Your portfolio item is now live!' } else format.html { render :new } end end end def edit end def update respond_to do |format| if @portfolio_item.update(portfolio_params) format.html { redirect_to portfolios_path, notice: 'Record was successfully updated.' } else format.html { render :edit } end end end def destroy @portfolio_item.destroy respond_to do |format| # we use url here instead of path because destroy method has no any view that means also has no any route or path # so we have to write the whole url for redirecting. format.html { redirect_to portfolios_url, notice: 'Record was successfully removed.' } end end private def portfolio_params # _destroy is special that is coming from cocoon params.require(:portfolio) .permit(:title, :subtitle, :thumb_image, :main_image, :body, techologies_attributes: [:id, :name, :_destroy]) end def set_portfolio_item @portfolio_item = Portfolio.find(params[:id]) end end <file_sep>/app/controllers/concerns/devise_whitelist.rb # module name is really important. if we wrote for filename devise_whitelist, we should write DeviseWhitelist for # module name. If we wrote for filename devise_white_list, we should write DeviseWhiteList! module DeviseWhitelist extend ActiveSupport::Concern # in order to write before_action method we should use included. That is given us by ActiveSupport. included do # it's doing same thing with before_action only difference is that we can choose which controller can reach that. # so here we say if the controller is devise controller lets it reach. before_action :configure_permitted_parameters, if: :devise_controller? end def configure_permitted_parameters # that is special for devise. devise_parameter_sanitizer.permit(:sign_up, keys: [:name]) devise_parameter_sanitizer.permit(:account_update, keys: [:name]) end end<file_sep>/app/controllers/concerns/current_user_concern.rb module CurrentUserConcern extend ActiveSupport::Concern def current_user # by using this we are able to create a new object for User model. Here we are ovveriding the current_user method # which is coming from devise. And down here we are calling super and if there is no user who logged in # it will be false and so OpenStruct will create a new user model for us. We can compare them by using is_a? # if there is a user who logged in it means current_user.class will be User but if there is no any user who logged # in it will be OpenStruct. # that architecture is called as null object pattern. super || guest_user end def guest_user # there is a bug when we use petergate gem. So we use another option down here. #OpenStruct.new(name: "<NAME>", # first_name: "Guest", # last_name: "User", # email: "<EMAIL>" #) guest = GuestUser.new guest.name = "<NAME>" guest.first_name = "Guest" guest.last_name = "User" guest.email = "<EMAIL>" guest end end<file_sep>/app/controllers/concerns/default_page_content.rb module DefaultPageContent extend ActiveSupport::Concern included do before_action :set_page_defaults end def set_page_defaults # we defined default page title and we use this in application.html.erb that is our main layout. Every single # html page is derived from application.html.erb @page_title = "Blog App | <NAME>" end end<file_sep>/app/models/skill.rb class Skill < ApplicationRecord # we created a helper module(called as concern) in concerns folder in order to create images from one place. # so we can reach this module like this. ### include Placeholder validates_presence_of :title, :percent_utilized # after_initialize :set_defaults ### def set_defaults #self.badge ||= Placeholder.image_generator(250,250) ### end end <file_sep>/app/models/portfolio.rb class Portfolio < ApplicationRecord has_many :techologies, dependent: :destroy # we can add that into portfolio by writing => # Portfolio.create!(title="dgsd", body:"sfgs", techologies_attributes: [{name:"Ruby"}, {name:"Rails"}, {name:"React"}]) # after that query, we will have one more portolio, and 3 more technologies. That means if we write bottom code # we can create new techologies inside of the Portfolio query. # that means => do not accept technologies if name attr of technology is empty (this is just a validation.) accepts_nested_attributes_for :techologies, allow_destroy:true, reject_if: lambda { |attrs| attrs["name"].blank? } #include Placeholder validates_presence_of :title, :body mount_uploader :thumb_image, PortfolioUploader mount_uploader :main_image, PortfolioUploader def self.angular where(subtitle: "Angular") end def self.by_position order("position ASC") end # both of them are same. And we can reach from controller in a same way. scope :ruby_on_rails_portfolio_items, -> {where(subtitle: "Ruby on Rails")} # that means => after 'new'(not create!) method in controller works, the portfolio form will be created. # So after form created, this method will run. #after_initialize :set_defaults ### def set_defaults # ||= => self.main_image = "https://via.placeholder.com/600x400" if main_image == nil # ||= => that means if you have already a main_image or thumb_image I dont override them. # but if you use = instead, that means when we have already an main_image or thumb_image, # ruby will not care about that and it will override that. ### self.main_image ||= Placeholder.image_generator(600,400) ### self.thumb_image ||= Placeholder.image_generator(350,200) ### end end<file_sep>/app/models/topic.rb class Topic < ApplicationRecord validates_presence_of :title # by writing this we say ruby that every topic has multiple blogs. # so we can reach a list of blogs inside of first topic by using this => Topic.first.blogs has_many :blogs end <file_sep>/README.md # ruby-on-rails-blog-web-app A blog web app by using ruby on rails <file_sep>/app/models/blog.rb class Blog < ApplicationRecord enum status: {draft: 0, published: 1} extend FriendlyId friendly_id :title, use: :slugged # by writing this we are banning that adding a new blog or editing an existing blog without title and body text. validates_presence_of :title, :body # by writing this we say ruby that every blog has a topic. # so we can reach the topic of the first blog by using this => Blog.first.topic belongs_to :topic, optional: true end <file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::Base include DeviseWhitelist # we defined session data in application_controller because application_controller is the parent. And the others' # coming from here. So if we define anything here, we can access wherever we want in the whole project. # and we should not write the whole code here. We should separate codes into different modules. include SetSource include CurrentUserConcern include DefaultPageContent before_action :set_copyright def set_copyright @copyright = BulutViewTool::Renderer.copyright("<NAME>", "All rights reserved") end end module BulutViewTool class Renderer def self.copyright(name,msg) "&copy; #{Time.now.year} | <b>#{name}</b> #{msg}".html_safe end end end<file_sep>/config/routes.rb Rails.application.routes.draw do # by writing this we are changing the path (we use /login instead of user/sign_in, /register instead of user/sign_up) # if we would write something in path we would reach /something/login devise_for :users, path: '', path_names: {sign_in: 'login', sign_out: 'logout', sign_up: 'register'} # when we use specific route for all of the operations such as delete, patch, post, get..., we should use # resources. But if we have simple pages for only showing (like about or contact pages) we can simply use get. # that means use default routes for portfolios except show route. # we can add custom routes by using do end block. Here we created a new put route which name is sort(we should define # as sort also in controller.) resources :portfolios, except: [:show] do put :sort, on: :collection end # so we can create a custom route for show. as => we can set the prefix(route method) of show route. get 'portfolio/:id', to: 'portfolios#show', as: 'portfolio_show' get 'angular-items', to: 'portfolios#angular' # if we want to reach about page by writing directly (localhost:3000/about instead of localhost:3000/pages/about) #get 'pages/about' # we can use this. We use # instead of / get 'about', to: 'pages#about' # if we want to react contact page by writing localhost:3000/contact-me #get 'pages/contact' # we can use this. So basically we can write anything we want for routing. get 'contact-me', to: 'pages#contact' # we can add custom routes into current routes like this. # and we can reach by writing toggle_status_blog_path/url resources :blogs do member do get :toggle_status end end # we can define root path of app like this. We use # instead of / root to: 'pages#home' end <file_sep>/app/controllers/concerns/set_source.rb module SetSource extend ActiveSupport::Concern included do before_action :set_source end def set_source # we can write anything we want instead of source, not important. We can reach session data # by searching source keyword. session[:source] = params[:q] if params[:q] end end
7ba844dfb28b5dc90a4e23bf4ea871c724f23b68
[ "Markdown", "Ruby" ]
12
Ruby
ali-bulut/ruby-on-rails-blog-web-app
014153652319502f4c445b75f1520469fb89418d
14bdf42b06c77491c98fb8d47ef23696e0b13521
refs/heads/master
<file_sep># OneRing ### The purpose of this app is to show a ring that is programmed by a timer. ### The animation of the ring is aimed at showing the user the time intervals ### used in regular breathing patterns. <file_sep>// // ViewController.swift // OneRing // // Created by <NAME> on 6/8/16. // Copyright © 2016 Carrera. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var RingView: MKRingProgressView! @IBAction func Breathe(_ sender: AnyObject) { var x = 0.0 repeat{ delay(x){ self.breathin() } x = x + 5 delay(x){ self.breathout() } x = x + 5 }while (x<=20) } func breathin(){ super.viewDidLoad() CATransaction.begin() CATransaction.setAnimationDuration(5) RingView.progress = 1 CATransaction.commit() } func breathout(){ super.viewDidLoad() CATransaction.begin() CATransaction.setAnimationDuration(5) RingView.progress = 0 CATransaction.commit() } override func viewDidLoad() { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } func delay(_ delay: Double, closure: @escaping ()->()) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure ) } func breatheloop(_ inhale: Double, firstPause: Double, exhale: Double, secondPause: Double){ } <file_sep>// // breath.swift // OneRing // // Created by <NAME> on 6/8/16. // Copyright © 2016 Carrera. All rights reserved. // import Foundation class breath { fileprivate var _timer = 5.0 fileprivate var _capacity = 1.0 var timer: Double { get{ return _timer } } var capacity: Double{ get{ return _capacity } } init(startingTimer: Double, startingCapacity: Double){ self._timer = startingTimer self._capacity = startingCapacity } }
37344bace620b405af6480619be254c34c6f239e
[ "Markdown", "Swift" ]
3
Markdown
acarrera94/OneRing
173d084bed842b39ffd60d5745e087b38e21d101
7fb550276169e54674d9bc626f5c164d7b99e58d
refs/heads/main
<repo_name>Juka-Chance/XKickUI<file_sep>/src/JukaChance/XKickUI/XKickUILoader.php <?php namespace JukaChance\XKickUI; use JukaChance\XKickUI\cmds\KickUICMD; use pocketmine\event\Listener; use pocketmine\Player; use pocketmine\plugin\PluginBase; class XKickUILoader extends PluginBase implements Listener { public static $instance; public function onEnable() { $this->getServer()->getPluginManager()->registerEvents($this, $this); $this->getServer()->getCommandMap()->registerAll("XKickUILoader", [ new KickUICMD("kickui") ]); self::$instance = $this; } public static function getInstance(): self { return self::$instance; } public function kickui(Player $sender, $selected) { $api = $this->getServer()->getPluginManager()->getPlugin("FormAPI"); $form = $api->createCustomForm(function (Player $sender, array $data = null) { $result = $data; if ($result === null) { return true; } $reason = $data[1]; $this->kick($sender, $reason); }); $form->setTitle("§l§7Kick§2UI"); $form->setContent("Here you can kick a player!"); $form->addInput("Reason"); $form->sendToPlayer($sender); return $form; } public function kick(Player $sender, $reason) { $selected = KickUICMD::getMgr()->selected; $selected->kick("You was kicked by" . $sender->getName() . "!\nReason:" . $reason, false); $sender->sendMessage("The player " . $selected->getName() . "was kicked by you! Reason" . $reason); } }<file_sep>/README.md # XKickUI Kick a Player ### Commands + Permissions `/xkickui <playername> | XKickUI.xkickui.cmd` ### Credits Owner: JukaChance main developer: supercrafter333 authors: JukaChance, supercrafter333<file_sep>/src/JukaChance/XKickUI/cmds/KickUICMD.php <?php namespace JukaChance\XKickUI\cmds; use JukaChance\XKickUI\XKickUILoader; use pocketmine\command\Command; use pocketmine\command\CommandSender; use pocketmine\Player; class KickUICMD extends Command { public $selected; public function __construct(string $name, string $description = "", string $usageMessage = null, array $aliases = []) { parent::__construct("xkickui", "Kick a player!", "/xkickui <playername>", $aliases); } public function execute(CommandSender $sender, string $commandLabel, array $args) { if (!count($args) >= 1) { $sender->sendMessage("§4Usage: /xkickui <playername>"); } if (!$sender->hasPermission("XKickUI.xkickui.cmd")) { $sender->sendMessage("Yo don't have permissions to use this command!"); } if (!$sender instanceof Player) { $sender->sendMessage("You can use this commmand only In-Game!"); } $selected = XKickUILoader::getInstance()->getServer()->getPlayer($args[0]); if ($selected == null) { $sender->sendMessage("§4Please select a online player!"); } $this->selected = $selected; XKickUILoader::getInstance()->kickui($sender, $selected); } public static function getMgr() { return new KickUICMD(); } public function getSelected() { return $this->selected; } }
36cbbc9121e79bcd9ab91331a1316b552eb78a6d
[ "Markdown", "PHP" ]
3
PHP
Juka-Chance/XKickUI
56869c44429f4f1f199be2a40bc5bcb3f4f12b86
17b83e760b183a51d9be9d996f1fb12e63e78e96
refs/heads/master
<file_sep># PictureEditor Using Python, edit pictures using menu of options <file_sep>import random import tkinter from PIL import ImageTk, Image import time from simpleimage import SimpleImage DEFAULT_FILE = 'images/fam.jpg' CANVAS_WIDTH = 700 CANVAS_HEIGHT = 600 def main(): keep_going = True filename = get_file() image = SimpleImage(filename) canvas = make_canvas(CANVAS_WIDTH, CANVAS_HEIGHT, 'Final Project: Editing Fun!') pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) while keep_going: keep_going = show_menu(image, canvas) image = SimpleImage(filename) def get_file(): # Read image file path from user, or use the default file filename = input('Enter image file (or press enter for default): ') if filename == '': filename = DEFAULT_FILE return filename def show_menu(image, canvas): time.sleep(1/2) print('Choose how to edit the image:') print(' 1. Make more red') print(' 2. Make more blue') print(' 3. Make more green') print(' 4. Make more yellow') print(' 5. Play with color') print(' 6. Random color change') print(' 7. Flip image horizontally') print(' 8. Flip the image vertically') print(' 9. Gradual color change (yellow to blue)') print(' 10. Gradual color change (yellow-pink)') print(' 99. Move Image ') print(' 0. Stop editing the image and end') selection = int(input('Which is your choice: ')) if (selection == 0): keep_going = False else: keep_going = True edit_picture(selection, image, canvas) return keep_going def edit_picture(selection, image, canvas): if (selection == 1): more_red(image, canvas) #image.show() if (selection == 2): more_blue(image, canvas) #image.show() if (selection == 3): more_green(image, canvas) #image.show() if (selection == 4): more_yellow(image, canvas) #image.show() if (selection == 5): custom_color(image, canvas) #image.show() if (selection == 6): random_color(image, canvas) #image.show() if (selection == 7): mirror = flip_horizontal(image, canvas) #mirror.show() if (selection == 8): image = flip_vertical(image, canvas) #image.show() if (selection == 9): gradual_change(image, canvas) if (selection == 10): gradual_change2(image, canvas) if (selection == 99): move_pic(image, canvas) def gradual_change(image,canvas): for i in range(40): for pixel in image: blue_value = (20 - i) red_value = i pixel.red = pixel.red-(red_value*2) pixel.green = pixel.green pixel.blue = pixel.blue-(blue_value*2) pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image = pimg, anchor=tkinter.NW) canvas.update() #canvas.create_image(10, 20, image = pimg, anchor=tkinter.NW) #input('Hit Enter to continue') def gradual_change2(image,canvas): #img = Image.open('filename.png') for i in range(37): for pixel in image: blue_value = (20 - i) red_value = i # pixel.red = pixel.red pixel.red = pixel.red pixel.green = pixel.green-(red_value*1.5) pixel.blue = pixel.blue-(blue_value*1.5) pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image = pimg, anchor=tkinter.NW) canvas.update() def make_canvas(width, height, title): """ Creates and returns a drawing canvas of the given int size with a blue border, ready for drawing. """ top = tkinter.Tk() top.minsize(width=width, height=height) top.title(title) canvas = tkinter.Canvas(top, width=width + 1, height=height + 1) canvas.pack() return canvas def custom_color(image, canvas): red_value = int(input('Pick a number between 0 and 20 for the red: ')) blue_value = int(input('Pick a number between 0 and 20 for the blue: ')) green_value = int(input('Pick a number between 0 and 20 for the green: ')) for pixel in image: pixel.red = pixel.red*(red_value/10) pixel.green = pixel.green*(green_value/10) pixel.blue = pixel.blue*(blue_value/10) pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) canvas.update() time.sleep(1) def random_color(image, canvas): red_value = random.randint(1,20) blue_value = random.randint(1,20) green_value = random.randint(1,20) for pixel in image: pixel.red = pixel.red * (red_value / 10) pixel.green = pixel.green * (green_value / 10) pixel.blue = pixel.blue * (blue_value / 10) pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) canvas.update() time.sleep(1) def more_blue(image, canvas): for pixel in image: pixel.red = pixel.red*0.4 pixel.green = pixel.green*0.4 pixel.blue = pixel.blue*1.7 pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) canvas.update() return canvas def more_red(image, canvas): for pixel in image: pixel.red = pixel.red*1.2 pixel.green = pixel.green*0.5 pixel.blue = pixel.blue*0.5 pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) canvas.update() return canvas def more_green(image, canvas): for pixel in image: pixel.red = pixel.red*0.4 pixel.green = pixel.green*1.6 pixel.blue = pixel.blue*0.4 pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) canvas.update() return canvas def more_yellow(image, canvas): for pixel in image: pixel.red = pixel.red*1.6 pixel.green = pixel.green*1.6 pixel.blue = pixel.blue*0.1 pimg = ImageTk.PhotoImage(image.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) canvas.update() return canvas def flip_vertical(image, canvas): width = image.width height = image.height #Create new image to contain the new reflected image mirror = SimpleImage.blank(width, height) for y in range(height): for x in range(width): pixel = image.get_pixel(x,y) mirror.set_pixel(x,height - (y+1),pixel) pimg = ImageTk.PhotoImage(mirror.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) canvas.update() time.sleep(1) return mirror def flip_horizontal(image, canvas): width = image.width height = image.height #Create new image to contain the new reflected image mirror = SimpleImage.blank(width, height) for y in range(height): for x in range(width): pixel = image.get_pixel(x,y) mirror.set_pixel(width - (x+1),y,pixel) pimg = ImageTk.PhotoImage(mirror.pil_image) canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) canvas.update() time.sleep(1) return mirror def move_pic(image, canvas): #canvas = make_canvas(700, 600, 'Final Project: Morphing Picture') pimg = ImageTk.PhotoImage(image.pil_image) img_tk = canvas.create_image(10, 20, image=pimg, anchor=tkinter.NW) change_x=3 change_y =7 count = 0 while (count < 7): #update world canvas.move(img_tk, change_x,change_y) if (hit_bottom(canvas, img_tk, pimg)): change_y = change_y*-1 count = count + 1 if (hit_side(canvas, img_tk, pimg)): change_x *= -1 count = count + 1 if (hit_top(canvas, img_tk, pimg)): change_y *= -1 count = count + 1 if (hit_other_side(canvas, img_tk, pimg)): change_x *= -1 count += 1 canvas.update() #pause time.sleep(1/70.) #canvas.update() #canvas.mainloop() def hit_bottom(canvas, object, pimg): return canvas.coords(object)[1] > CANVAS_HEIGHT - pimg.height() def hit_side(canvas, object, pimg): return canvas.coords(object)[0]>CANVAS_WIDTH - pimg.width() def hit_top(canvas, object, pimg): return canvas.coords(object)[1] <= 0 def hit_other_side(canvas, object, pimg): return canvas.coords(object)[0] <= 0 if __name__ == '__main__': main()
f4d60177f33abb4cdfc85bd341b01a16a8da0f09
[ "Markdown", "Python" ]
2
Markdown
a-zabala/PictureEditor
3a61789bea3c77b61a140f7c93c83ea243fd1745
8758c7c2c8f288e64d45d36ff14600ba0f981699
refs/heads/master
<file_sep>'use strict'; angular.module('chatterbox.version', [ 'chatterbox.version.interpolate-filter', 'chatterbox.version.version-directive' ]) .value('version', '0.1'); <file_sep>Chatterbox ==================== Chatterbox is a simple web app built on the MEAN stack for talking and sharing notes in class! Just sign up, fnd your course and get involved! Special thanks to Angular seed, which was the basis of this project Setup ---------- First, cp your config_sample.js to config.js and edit the mongoURL to match your mongo setup. Then, run: ``` npm install node server.js ``` That's it! TODO: ---------- Coming soon!
d86fc7645b3afb1a0682b333a5c3f9d7ad4f6c86
[ "JavaScript", "Markdown" ]
2
JavaScript
Joeento/chatterbox
b6f538bf229d62543ff508a332c57eaeef43623f
6b8befccc310735b4688e2d1089b34b04a7d0fb8
refs/heads/master
<file_sep>({ doinit : function(c) { const actions = [ { label: 'Record Details', name: 'record_details'} ]; let recId = c.get("v.recordId"); console.log(recId); let returnSame = c.get("c.returnSameAnimals"); c.set('v.mycolumns', [ { type: 'action',typeAttributes: {rowActions: actions, menuAlignment: 'auto'}}, {label: 'Animal name', fieldName: 'Name', type: 'text'}, {label: 'Description', fieldName: 'Description__c', type: 'text'}, {label: 'Eats', fieldName: 'Eats__c', type: 'text'}, {label: 'Says', fieldName: 'Says__c', type: 'text '} ]); returnSame.setParams({ extId: recId }); returnSame.setCallback(this, function (response) { console.log('Animals: ',response.getReturnValue()); c.set("v.animals", response.getReturnValue()); }); $A.enqueueAction(returnSame); }, clickSearch : function(cmp) { const actions = [ { label: 'Record Details', name: 'record_details'} ]; let searchKey = cmp.get("v.searchKey"); let returnSearch = cmp.get("c.searchAnimal"); cmp.set('v.mycolumns', [ {type: 'action',typeAttributes: {rowActions: actions, menuAlignment: 'auto'}}, {label: 'Animal name', fieldName: 'Name', type: 'text'}, {label: 'Description', fieldName: 'Description__c', type: 'text'}, {label: 'Eats', fieldName: 'Eats__c', type: 'text'}, {label: 'Says', fieldName: 'Says__c', type: 'text '} ]); returnSearch.setParams({ keyWord: searchKey }); returnSearch.setCallback(this, function (response) { console.log('Animals: ',response.getReturnValue()); cmp.set("v.animals", response.getReturnValue()); }); $A.enqueueAction(returnSearch); }, handleRowAction : function(cmp,event,helper){ var action = event.getParam('action'); var row = event.getParam('row'); // navigate to sObject detail page var navEvt = $A.get("e.force:navigateToSObject"); navEvt.setParams({ "recordId": row.Id, "slideDevName": "detail" }); navEvt.fire(); }, }) <file_sep>import { LightningElement, track } from 'lwc'; import getAnimals from '@salesforce/apex/AnimalSearchController.animalSearch'; const columns=[ {label:"Heroku Id", fieldName:"Heroku_Id__c", type:"integer"}, {label: 'Description', fieldName: 'Description__c', type: 'text'}, {label: 'Eats', fieldName: 'Eats__c', type: 'text'}, {label: 'Says', fieldName: 'Says__c', type: 'text '} ]; export default class AnimalSearch extends LightningElement { @track searchItems; @track errorMsg; @track idsInputList = []; animals=[]; columns = columns; handleItemChange(e){ this.searchItems = e.target.value; } searchClick() { this.idsInputList = this.searchItems.split(','); getAnimals({herokuIdList: this.idsInputList}) .then(result =>{ this.animals = result; }) .catch(error =>{ this.errorMsg = error; }) } }
f1c00637a8d34fce548a813e8e620d5260b25d41
[ "JavaScript" ]
2
JavaScript
Anderkor/SyneboDevCoursesHT
2835111ca1eb062e159f9a5b7f6af9735e691895
29e3f267b56e8f89073e7b4c926c548ad3c34969
refs/heads/master
<repo_name>jasperbarcelona/wtg<file_sep>/main/models.py import flask from flask import request from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy.ext.orderinglist import ordering_list from sqlalchemy import Boolean from db_conn import db, app import json class Serializer(object): __public__ = None def to_serializable_dict(self): dict = {} for public_key in self.__public__: value = getattr(self, public_key) if value: dict[public_key] = value return dict class SWEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Serializer): return obj.to_serializable_dict() if isinstance(obj, (datetime)): return obj.isoformat() return json.JSONEncoder.default(self, obj) def SWJsonify(*args, **kwargs): return app.response_class(json.dumps(dict(*args, **kwargs), cls=SWEncoder, indent=None if request.is_xhr else 2), mimetype='application/json') # from https://github.com/mitsuhiko/flask/blob/master/flask/helpers.py class User(db.Model): id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(100)) email = db.Column(db.String(100)) msisdn = db.Column(db.String(20)) password = db.Column(db.Text()) status = db.Column(db.String(20),default='inactive') active_sort = db.Column(db.String(30),default='top_rated') img = db.Column(db.Text()) class AdminUser(db.Model): id = db.Column(db.Integer,primary_key=True) email = db.Column(db.String(60)) password = db.Column(db.Text()) temp_pw = db.Column(db.Text()) name = db.Column(db.String(100)) role = db.Column(db.String(30)) active_sort = db.Column(db.String(30)) added_by_id = db.Column(db.Integer) added_by_name = db.Column(db.String(100)) join_date = db.Column(db.String(50)) created_at = db.Column(db.String(50)) class SVC(db.Model): id = db.Column(db.Integer,primary_key=True) user_id = db.Column(db.Integer()) token = db.Column(db.String(10)) created_at = db.Column(db.String(50)) class Destination(db.Model): id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(100)) description = db.Column(db.Text()) address = db.Column(db.Text()) city = db.Column(db.String(100)) map_link = db.Column(db.Text()) rating_avg = db.Column(db.String(10)) rating_count = db.Column(db.Integer()) review_count = db.Column(db.Integer()) added_by_id = db.Column(db.Integer()) added_date = db.Column(db.String(50)) added_time = db.Column(db.String(50)) added_by_name = db.Column(db.String(100)) upcoming_events = db.Column(db.Text(),default='') img = db.Column(db.Text()) created_at = db.Column(db.String(50)) class Rating(db.Model): id = db.Column(db.Integer,primary_key=True) destination_id = db.Column(db.Integer()) user_id = db.Column(db.Integer()) rating = db.Column(db.Integer()) created_at = db.Column(db.String(50)) class Review(db.Model): id = db.Column(db.Integer,primary_key=True) destination_id = db.Column(db.Integer()) user_id = db.Column(db.Integer()) review = db.Column(db.Text()) created_at = db.Column(db.String(50))<file_sep>/main/static/js/animations.js $(document).ready(function(){ $('.destination').height($('.destination').width()+130); $(window).resize(function(){ $('.destination').height($('.destination').width()+130); }); $(window).load(function(){ setTimeout(function() { $('#mainPreloader').fadeOut(); }, 3000); }); $('.form-control.floatlabel').floatlabel({ labelEndTop:'-2px' }); $(".datepicker").datepicker({ dateFormat: "MM dd, yy" }); $('.clockpicker').clockpicker({ twelvehour: true, donetext: 'Done', autoclose: false }); $('.tooltip').tooltipster({ animation: 'grow', delay: 200, theme: 'tooltipster-shadow', trigger: 'hover' }); $('#menuToggleBtn').on('click', function () { if ($('#navigation').hasClass('open')) { $('#navigation').animate({'left':'-70%'},500); $('#navigation').removeClass('open'); } else { $('#navigation').animate({'left':0},500); $('#navigation').addClass('open'); } }); $('#addDestinationInfoModal .form-control').on('keyup', function () { name = $('#addDestinationName').val(); address = $('#addDestinationAddress').val(); city = $('#addDestinationCity').val(); map_link = $('#addDestinationLink').val(); if ((name != '') && (address != '') && (city != '') && (map_link != '')) { $('#saveDestinationInfoBtn').attr('disabled', false); } else { $('#saveDestinationInfoBtn').attr('disabled', true); } }); $('#addDestinationInfoModal').on('hidden.bs.modal', function () { $(this).find('.form-control').val(''); $('#saveDestinationInfoBtn').attr('disabled', true); }); var ctx = document.getElementById("topDestinationChart").getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["Destination 1", "Destination 2", "Destination 3", "Destination 4", "Destination 5", "Destination 6", "Destination 7", "Destination 8", "Destination 9", "Destination 10"], datasets: [{ label: 'Rating', data: [5,5,4.7,4.6,4.2,4,4,3.9,3.7,3.5], backgroundColor: [ 'rgba(0,187,149, 0.8)', 'rgba(0,187,149, 0.8)', 'rgba(0,187,149, 0.8)', 'rgba(0,187,149, 0.8)', 'rgba(0,187,149, 0.8)', 'rgba(0,187,149, 0.8)', 'rgba(0,187,149, 0.8)', 'rgba(0,187,149, 0.8)', 'rgba(0,187,149, 0.8)', 'rgba(0,187,149, 0.8)', ], borderColor: [ 'rgba(0,187,149, 1)', 'rgba(0,187,149, 1)', 'rgba(0,187,149, 1)', 'rgba(0,187,149, 1)', 'rgba(0,187,149, 1)', 'rgba(0,187,149, 1)', 'rgba(0,187,149, 1)', 'rgba(0,187,149, 1)', 'rgba(0,187,149, 1)', 'rgba(0,187,149, 1)', ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); });<file_sep>/main/static/js/functions.js function show_destinations() { $('#contentLoader').removeClass('hidden'); $('.nav-item').removeClass('active'); $('#navDestinations').addClass('active'); $.get('/adminpanel/destinations', function(data){ $('.admin-content').html(data); $('#contentLoader').addClass('hidden'); }); } function save_destination_info() { $('#saveDestinationInfoBtn').button('loading'); name = $('#addDestinationName').val(); desc = $('#addDestinationDesc').val(); address = $('#addDestinationAddress').val(); city = $('#addDestinationCity').val(); link = $('#addDestinationLink').val(); $.post('/adminpanel/destination/save', { name:name, desc:desc, address:address, city:city, link:link }, function(data){ $('.admin-content').html(data['template']); $('#addDestinationInfoModal').modal('hide'); $('#saveDestinationInfoBtn').button('complete'); setTimeout(function() { $('#saveDestinationInfoBtn').attr('disabled', true); }, 200); }); } function show_destination(destination_id) { $.post('/adminpanel/destination/info', { destination_id:destination_id }, function(data){ $('.admin-content').html(data['template']); }); }<file_sep>/main/wtg.py from flask import url_for, request, session, redirect, jsonify, Response, make_response, current_app from jinja2 import environment, FileSystemLoader from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy.ext.orderinglist import ordering_list from sqlalchemy import Boolean from sqlalchemy import or_ from flask.ext import admin from flask.ext.admin.contrib import sqla from flask.ext.admin.contrib.sqla import ModelView from flask.ext.admin import Admin, BaseView, expose from dateutil.parser import parse as parse_date from flask import render_template, request from flask import session, redirect from datetime import timedelta from datetime import datetime from functools import wraps, update_wrapper import threading from threading import Timer from multiprocessing.pool import ThreadPool import calendar from calendar import Calendar from time import sleep import requests import datetime from datetime import date import time import json import uuid import random import string import smtplib from email.mime.text import MIMEText as text import os import schedule from werkzeug.utils import secure_filename import db_conn from db_conn import db, app from werkzeug.security import generate_password_hash, check_password_hash from models import * IPP_URL = 'https://devapi.globelabs.com.ph/smsmessaging/v1/outbound/%s/requests' APP_ID='EGXMuB5eEgCMLTKxExieqkCGeGeGuBon' APP_SECRET='f3e1ab30e23ea7a58105f058318785ae236378d1d9ebac58fe8b42e1e239e1c3' PASSPHRASE='<PASSWORD>' SHORTCODE='21588479' UPLOAD_FOLDER = 'static/receipts' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER class BubbleAdmin(sqla.ModelView): column_display_pk = True admin = Admin(app, name='Where2Go') admin.add_view(BubbleAdmin(User, db.session)) admin.add_view(BubbleAdmin(SVC, db.session)) admin.add_view(BubbleAdmin(Destination, db.session)) admin.add_view(BubbleAdmin(Rating, db.session)) admin.add_view(BubbleAdmin(Review, db.session)) # admin.add_view(BubbleAdmin(Service, db.session)) def nocache(view): @wraps(view) def no_cache(*args, **kwargs): response = make_response(view(*args, **kwargs)) response.headers['Last-Modified'] = datetime.datetime.now() response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0' response.headers['Pragma'] = 'no-cache' response.headers['Expires'] = '-1' return response return update_wrapper(no_cache, view) def generate_svc(): unique = False while unique == False: new_token = str(uuid.uuid4().fields[-1])[:6] existing = SVC.query.filter_by(token=new_token).first() if not existing or existing == None: unique = True return new_token @app.route('/',methods=['GET','POST']) @nocache def index(): if not session or 'user_id' not in session: return redirect('/login') user = User.query.filter_by(id=session['user_id']).first() destinations = Destination.query.order_by(Destination.name) return flask.render_template( 'index.html', user=user, destinations=destinations ) @app.route('/adminpanel',methods=['GET','POST']) @nocache def admin_page(): if not session or 'admin_id' not in session: return redirect('/adminpanel/login') admin = AdminUser.query.filter_by(id=session['admin_id']).first() destinations = Destination.query.order_by(Destination.name) user_count = User.query.count() destination_count = Destination.query.count() admin_count = AdminUser.query.count() return flask.render_template( 'admin.html', admin=admin, destinations=destinations, user_count=user_count, destination_count=destination_count, admin_count=admin_count ) @app.route('/adminpanel/destinations',methods=['GET','POST']) def admin_page_destinations(): admin = AdminUser.query.filter_by(id=session['admin_id']).first() destinations = Destination.query.order_by(Destination.name) destination_count = Destination.query.count() return flask.render_template( 'admin_destinations.html', admin=admin, destinations=destinations, destination_count=destination_count, ) @app.route('/adminpanel/destination/info',methods=['GET','POST']) def destination(): destination_id = flask.request.form.get('destination_id') destination = Destination.query.filter_by(id=destination_id).first() return jsonify( template=flask.render_template( 'destination_info.html', destination=destination ) ) @app.route('/adminpanel/destination/save',methods=['GET','POST']) def save_destination(): data = flask.request.form.to_dict() destination = Destination( name = data['name'], description = data['desc'], address = data['address'], city = data['city'], map_link = data['link'], added_by_id = session['admin_id'], added_by_name = session['admin_name'], added_date = datetime.datetime.now().strftime('%B %d, %Y'), added_time = time.strftime("%I:%M%p"), created_at=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f') ) db.session.add(destination) db.session.commit() session['open_destination'] = destination.id return jsonify( template = flask.render_template( 'destination_info.html', destination=destination ) ) @app.route('/login',methods=['GET','POST']) @nocache def user_login(): if session and 'user_id' in session: return redirect('/') return flask.render_template('login.html') @app.route('/adminpanel/login',methods=['GET','POST']) @nocache def admin_login(): if session and 'admin_id' in session: return redirect('/admin') return flask.render_template('admin_login.html') @app.route('/signup',methods=['GET','POST']) @nocache def user_signup_page(): return flask.render_template('signup.html') @app.route('/login/template',methods=['GET','POST']) @nocache def login_page(): return flask.render_template('login_template.html') @app.route('/logout', methods=['GET', 'POST']) def logout(): session.clear() return redirect('/login') @app.route('/user/signup', methods=['GET', 'POST']) def signup(): data = flask.request.form.to_dict() new_user = User( name=data['name'].title(), email=data['email'], msisdn=data['msisdn'], password=<PASSWORD>(data['<PASSWORD>']) ) db.session.add(new_user) db.session.commit() svc = SVC( user_id=new_user.id, token=generate_svc(), created_at=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f') ) db.session.add(svc) db.session.commit() session['svc_verification_email'] = data['email'] message_options = { 'app_id': APP_ID, 'app_secret': APP_SECRET, 'message': 'Verification number: %s' % svc.token, 'address': new_user.msisdn, 'passphrase': <PASSWORD>, } r = requests.post(IPP_URL%SHORTCODE,message_options) return flask.render_template('svc.html',msisdn=data['msisdn']) @app.route('/svc/verify', methods=['GET', 'POST']) def verify_svc(): token = flask.request.form.get('svc') user = User.query.filter_by(email=session['svc_verification_email']).first() existing = SVC.query.filter_by(token=token, user_id=user.id).first() if not existing or existing == None: return jsonify(status='failed') user.status = 'active' db.session.delete(existing) db.session.commit() session['user_name'] = user.name session['user_id'] = user.id return jsonify(status='success') @app.route('/user/authenticate',methods=['GET','POST']) def authenticate_user(): data = flask.request.form.to_dict() user = User.query.filter_by(email=data['user_email']).first() if not user or user == None: return jsonify(status='failed', error='Invalid username.') if check_password_hash(user.password, data['user_password']) == False: return jsonify(status='failed', error='Invalid password.') session['user_name'] = user.name session['user_id'] = user.id return jsonify(status='success', error=''),200 @app.route('/user/admin/authenticate',methods=['GET','POST']) def authenticate_admin(): data = flask.request.form.to_dict() admin = AdminUser.query.filter_by(email=data['user_email']).first() if not admin or admin == None: return jsonify(status='failed', error='Invalid username.') if check_password_hash(admin.password, data['user_password']) == False: return jsonify(status='failed', error='Invalid password.') session['admin_name'] = admin.name session['admin_id'] = admin.id return jsonify(status='success', error=''),200 @app.route('/db/rebuild',methods=['GET','POST']) def rebuild_database(): db.drop_all() db.create_all() user = User( name='<NAME>', email='<EMAIL>', msisdn='<PASSWORD>', password=generate_password_hash('<PASSWORD>'), status='active', img='../static/images/users/default.png', active_sort='top', ) admin = AdminUser( email='<EMAIL>', password=generate_password_hash('<PASSWORD>'), temp_pw=generate_password_hash('<PASSWORD>'), name='<NAME>', role='Administrator', active_sort='Alphabetical', added_by_id=1, added_by_name='Super User', join_date=datetime.datetime.now().strftime('%B %d, %Y'), created_at=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f') ) destination = Destination( name='Kuwebang Lampas', description='Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', address='This is a sample address.', city='Pagbilao', map_link='Sample map link', rating_avg='4.0', rating_count=100, review_count=32, added_by_id=1, added_by_name='Super Admin', img='../static/images/destinations/kuwebang_lampas.jpg', created_at=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f') ) destination1 = Destination( name='<NAME>', description='Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', address='This is a sample address.', city='Lucban', map_link='Sample map link', rating_avg='4.2', rating_count=140, review_count=194, added_by_id=1, added_by_name='Super Admin', img='../static/images/destinations/kamay_ni_hesus.jpg', created_at=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f') ) destination2 = Destination( name='<NAME>', description='Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', address='This is a sample address.', city='Pagbilao', map_link='Sample map link', rating_avg='3.5', rating_count=130, review_count=42, added_by_id=1, added_by_name='Super Admin', img='../static/images/destinations/puting_buhangin.jpg', created_at=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f') ) db.session.add(user) db.session.add(destination) db.session.add(destination1) db.session.add(destination2) db.session.add(admin) db.session.commit() return jsonify( status='success', message='Database rebuilt successfully' ),201 if __name__ == '__main__': app.run(port=5000,debug=True,host='0.0.0.0') # port=int(os.environ['PORT']), host='0.0.0.0'
b886383f506c6dc1854a0352ff1ab1eda2221a93
[ "JavaScript", "Python" ]
4
Python
jasperbarcelona/wtg
7e963d0027a1672fb3772300c64eede250f95813
ccfe65705915316b03712922a6ca7b6e3b4bcf05
refs/heads/master
<file_sep>import React, {useEffect, useState} from 'react' import styles from './PickCountry.module.css' import { FormControl } from '@material-ui/core'; import { NativeSelect } from '@material-ui/core'; // import InputLabel from '@material-ui/core/InputLabel'; // import MenuItem from '@material-ui/core/MenuItem'; // import Select from '@material-ui/core/Select'; import axios from 'axios' const PickCountry = ({handleCountryChange}) => { const [countries,setCountries] = useState([]) //countries = untuk menyimpan data //setCountries = untuk memanipulasi data yang ada pada countries useEffect(() => { getCountry(); },[]) function getCountry() { axios.get("https://covid19.mathdro.id/api/countries").then((res) => { setCountries(res.data.countries) }).catch((err) => { console.log(err) }) } return ( <FormControl className={styles.formControl}> <NativeSelect onChange={(event)=>handleCountryChange(event)}> <option value="">Global</option> {countries.map((item, index) => ( <option key={index} value={item.name}>{item.name}</option> ))} </NativeSelect> {/* <InputLabel id="select-label">Select Country</InputLabel> */} {/* <Select labelId="demo-simple-select-label" id="demo-simple-select" value={countries} onChange={(event)=>handleCountryChange(event)}> {countries.map((item, index) => ( <MenuItem key={index} value={item.name}>{item.name}</MenuItem> ))} </Select> */} </FormControl> ) } export default PickCountry<file_sep>import React from 'react' import styles from './Cards.module.css' import Grid from '@material-ui/core/Grid'; import CardComponent from './Card/Card' const Cards = ({ data: { confirmed, recovered, deaths } }) => { if (!confirmed) { return "Loading ..." } return ( <div className={styles.container}> <Grid container spacing={3} justify="center"> <CardComponent cardTitle="Kasus" cardSubtitle="Jumlah angka kasus COVID-19" value={confirmed.value} className={styles.confirmed} shadow={ styles.shadow}/> <CardComponent cardTitle="Sembuh" cardSubtitle="Jumlah angka sembuh COVID-19" value={recovered.value} className={styles.recovered} shadow={ styles.shadow}/> <CardComponent cardTitle="Meninggal" cardSubtitle="Jumlah angka meninggal COVID-19" value={deaths.value} className={styles.deaths} shadow={ styles.shadow}/> </Grid> </div> ) } export default Cards<file_sep>import React from 'react' // import styles from './Card.module.css' import {Grid, Card, CardContent, Typography} from '@material-ui/core'; import Countup from 'react-countup' import cn from 'classnames' import styles from './Card.module.css' const CardComponent = ({cardTitle, cardSubtitle,value,className,shadow}) => { return ( <Grid item xs={12} md={3} component={Card} className={cn(styles.card, className,shadow)}> {/* <Card> */} <CardContent> <Typography color="textSecondary"> {cardTitle} </Typography> <Typography variant="h4"> <Countup start={0} end={value} duration={3} separator=","/> </Typography> <Typography color="textSecondary"> Orang </Typography> <Typography variant="body2" component="p"> {cardSubtitle} </Typography> </CardContent> {/* </Card> */} </Grid> ) } export default CardComponent
6df33059802fcbf6d0d81818bf69bffc2d7088c2
[ "JavaScript" ]
3
JavaScript
FirmanAzharR/Covid-19-Track-ReactJs
4e47b0533a971c34ec8e631c836019d3b184e2bb
fa036fc13cc13cd833e5120a5529ba62987a05b8
refs/heads/master
<file_sep>using System; using System.Data.Entity; using System.IO; using System.Threading.Tasks; using Databas; using File = Databas.Models.File; using FileInfo = Kzta.Domain.Files.Models.FileInfo; namespace Kzta.Domain.Files { /// <summary> /// Класс для файлов /// </summary> public class FileService { private readonly DatabaseContext _context; private readonly FileOptions _fileOptions; public FileService(DatabaseContext context, FileOptions fileOptions) { _context = context; _fileOptions = fileOptions; } /// <summary> /// Загрузить файл /// </summary> /// <returns></returns> public async Task<Guid> UploadFile(FileInfo fileModel) { var fileEnt = new File("", fileModel.FileName); var path = GetPath(fileEnt.Name.ToString()); fileEnt.Path = path; using (var file = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite)) { fileModel.Content.Seek(0, SeekOrigin.Begin); fileModel.Content.CopyTo(file); } _context.Files.Add(fileEnt); await _context.SaveChangesAsync(); return fileEnt.FileGuid; } public async Task<string> GetPath(Guid fileGuid) { var file = await _context.Files.SingleOrDefaultAsync(x => x.FileGuid == fileGuid); return Path.Combine(_fileOptions.BaseRoot, file.Path); } private string GetPath(string fileName) { var path = Path.Combine(_fileOptions.BaseRoot, fileName); if (!Directory.Exists(_fileOptions.BaseRoot)) Directory.CreateDirectory(_fileOptions.BaseRoot); var count = 1; while (System.IO.File.Exists(path)) { path = Path.Combine(_fileOptions.BaseRoot, $"{count}){fileName}"); count++; } return path; } } } <file_sep>using System.Collections.ObjectModel; using System.ComponentModel; using System.Data.Entity; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Windows; using Databas; using Databas.Models; using Kzta.Annotations; using Kzta.Commands; using Kzta.Domain.Details; using Kzta.Domain.Products; using Kzta.Domain.PropertyTypes; using Kzta.Extensions; using Kzta.ViewModels.Details; using Kzta.ViewModels.PropertyTypes; using Kzta.Views; using Kzta.VIews; using Unity; namespace Kzta.ViewModels { /// <summary> /// Основной ViewModel /// </summary> public class MainViewModel : INotifyPropertyChanged { //Collections /// <summary> /// Тип детали /// </summary> public ObservableCollection<PropertyType> PropertyTypes { get; set; } /// <summary> /// Детали /// </summary> public ObservableCollection<Detail> Details { get => _details; set { _details = value; OnPropertyChanged(); } } /// <summary> /// Изделия /// </summary> public ObservableCollection<Product> Products { get => _products; set { _products = value; OnPropertyChanged(); } } //Services private readonly IUnityContainer _containers; private ProductService _productService; private DetailService _detailService; //SelectedItems public PropertyType SelectPropertyType { get; set; } public Product SelectedProduct { get; set; } public Detail SelectedDetail { get; set; } //Db private DatabaseContext _context; private ObservableCollection<Product> _products; private ObservableCollection<Detail> _details; //Commands public Command CreateProductCommand { get; set; } public Command DeleteProductCommand { get; set; } public Command ViewProductCommand { get; set; } public Command CreatePropertyTypeCommand { get; set; } //Commands/Details public Command CreateDetailCommand { get; set; } public Command ViewDetailCommand { get; set; } public Command DeleteDetailCommand { get; set; } //Fiels public PropertyTypeInfo PropertyType { get; set; } public MainViewModel(ProductService productService, DetailService detailService) { _productService = productService; _detailService = detailService; } public MainViewModel( DatabaseContext context, IUnityContainer containrs, ProductService productService, DetailService detailService) { _context = context; _containers = containrs; _productService = productService; _detailService = detailService; InitializeData().Wait(); } private async Task InitializeData() { PropertyType = new PropertyTypeInfo(); PropertyTypes = new ObservableCollection<PropertyType>(await _context.PropertyTypes.ToListAsync()); Details = new ObservableCollection<Detail>(await _context.Details.ToListAsync()); Products = new ObservableCollection<Product>(await _productService.Get()); CreateProductCommand = new Command(async () => await CreateProduct(), () => true); DeleteProductCommand = new Command(async () => await DeleteProduct(), () => true); ViewProductCommand = new Command(async () => { await ViewProduct(); }, () => true); CreatePropertyTypeCommand = new Command(async () => await CreatePropertyType(), () => true); CreateDetailCommand = new Command(async () => await CreateDetail(), () => true); ViewDetailCommand = new Command(async () => await ViewDetail(), () => true); DeleteDetailCommand = new Command(async () => await DeleteDetail(), () => true); } public async Task CreateProduct() { var context = _containers.Resolve<ProductViewModel>(); var window = _containers.Resolve<CreateProductView>(); context.InitializeClose(() => window.Close()); context.IsCreateWindow = true; window.DataContext = context; window.ShowDialog(); Products = new ObservableCollection<Product>(await _productService.Get()); } public async Task DeleteProduct() { await _productService.Delete(SelectedProduct.ProductGuid); Products.Remove(SelectedProduct); } public async Task ViewProduct() { var context = _containers.Resolve<ProductViewModel>(); var window = _containers.Resolve<ProductView>(); context.InitializeProduct(SelectedProduct); context.InitializeClose(() => window.Close()); window.DataContext = context; window.ShowDialog(); Products = new ObservableCollection<Product>(await _productService.Get()); Details = new ObservableCollection<Detail>(await _detailService.Get().ToListAsync()); } private async Task CreatePropertyType() { var context = _containers.Resolve<PropertyTypeViewModel>(); var window = _containers.Resolve<PropertyTypeView>(); context.InitializeClose(() => window.Close()); window.DataContext = context; window.ShowDialog(); } private async Task CreateDetail() { var context = _containers.Resolve<DetailViewModel>(); var window = _containers.Resolve<DetailView>(); context.InitializeClose(() => window.Close()); window.DataContext = context; window.ShowDialog(); Details = new ObservableCollection<Detail>(await _detailService.Get().ToListAsync()); } private async Task ViewDetail() { var context = _containers.Resolve<DetailViewModel>(); var window = _containers.Resolve<DetailView>(); context.InitializeClose(() => window.Close()); context.InitializeDetail(SelectedDetail); window.DataContext = context; window.ShowDialog(); Details = new ObservableCollection<Detail>(await _detailService.Get().ToListAsync()); } public async Task DeleteDetail() { await _detailService.Delete(SelectedDetail.DetailtGuid); Details.Remove(SelectedDetail); } public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }<file_sep>using System; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Databas; using Databas.Models; namespace Kzta.Domain.Details { /// <summary/> public class DetailService { private readonly DatabaseContext _context; /// <summary/> public DetailService(DatabaseContext context) { _context = context; } /// <inheritdoc /> public async Task<Guid> Create(DetailInfo model) { var detail = Mapper.Map<Detail>(model); detail.DetailtGuid = Guid.NewGuid(); _context.Details.Add(detail); await _context.SaveChangesAsync(); return detail.DetailtGuid; } /// <inheritdoc /> public async Task Update(Guid detailGuid, DetailInfo model) { var detail = await _context.Details.SingleOrDefaultAsync(x => x.DetailtGuid == detailGuid); if (detail == null) return; Mapper.Map(model, detail); await _context.SaveChangesAsync(); } /// <inheritdoc /> public async Task Delete(Guid detailGuid) { var detail = await _context.Details .SingleOrDefaultAsync(x => x.DetailtGuid == detailGuid); if (detail == null) return; _context.Details.Remove(detail); _context.SaveChanges(); } public IQueryable<Detail> Get() { return _context.Details.AsNoTracking().OrderBy(x => x.Name); } /// <summary> /// Устанавливает картинку /// </summary> /// <param name="detailGuid"></param> /// <param name="imageGuid"></param> /// <returns></returns> public async Task SetImage(Guid detailGuid, Guid imageGuid) { var detail = await _context.Details.SingleOrDefaultAsync(x => x.DetailtGuid == detailGuid); var image = await _context.Files.SingleOrDefaultAsync(x => x.FileGuid == imageGuid); if (detail == null || image == null) return; detail.ImageGuid = image.FileGuid; await _context.SaveChangesAsync(); } public async Task<Detail> GetSingle(Guid detailGuid) { return _context.Details.SingleOrDefault(x => x.DetailtGuid == detailGuid); } } }<file_sep>namespace Astral.PD.Workflow.Domain.PropertyTypes.Models { /// <summary> /// Модель для создания типа имущества /// </summary> public class PropertyTypeInfo { /// <summary> /// Hазвание типа имущества /// </summary> public string Name { get; set; } /// <summary> /// Описание /// </summary> public string Description { get; set; } } } <file_sep>using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Windows.Media.Imaging; using AutoMapper; using Databas; using Databas.Models; using Kzta.Annotations; using Kzta.Commands; using Kzta.Domain.Details; using Kzta.Domain.Files; using Kzta.Domain.Files.Models; using Kzta.Domain.Products; using Kzta.Extensions; using Kzta.ViewModels.Details; using Kzta.ViewModels.Products; using Kzta.Views; using Kzta.Views.ValidatorViews; using Microsoft.Win32; using Unity; using File = System.IO.File; namespace Kzta.ViewModels { /// <summary> /// VM для продуктов /// </summary> public class ProductViewModel : INotifyPropertyChanged { //Serivces private readonly DatabaseContext _context; private readonly FileService _fileService; private readonly ProductService _productService; private readonly IUnityContainer _containers; private readonly DetailService _detailService; //Details public ObservableCollection<DetailWithCount> Details { get => _details; set { _details = value; OnPropertyChanged(); } } public DetailWithCount SelectedDetail { get; set; } //Продукты public ProductInfo ProductInfo { get; set; } //Картинка private BitmapSource _displayedImagePath; private ObservableCollection<DetailWithCount> _details; public BitmapSource DisplayedImagePath { get => _displayedImagePath; set { _displayedImagePath = value; OnPropertyChanged(); } } //Commands public Command UploadImageCommand { get; set; } public Command SaveDataCommand { get; set; } public Command AddDetailToProductCommand { get; set; } public Command ViewDetailCommand { get; set; } public bool IsCreateWindow { get; set; } public ProductViewModel(DatabaseContext context, FileService fileService, ProductService productService, IUnityContainer containers, DetailService detailService) { _context = context; _fileService = fileService; _productService = productService; this._containers = containers; _detailService = detailService; ProductInfo = new ProductInfo(); InitializeData().Wait(); } private async Task InitializeData() { IsCreateWindow = false; Details = new ObservableCollection<DetailWithCount>(); UploadImageCommand = new Command( async () => { await UploadImage(); }, () => true); SaveDataCommand = new Command(async () => await SaveDate(), () => true); AddDetailToProductCommand = new Command(async () => { await AddDetail(); }, () => true); ViewDetailCommand = new Command(async () => await ViewDetail(), () => true); } private async Task UploadImage() { var res = UploadFileFromFileDialog().Result; if (res == Guid.Empty) return; await _productService.SetImage(ProductInfo.ProductGuid, res); ProductInfo.FileGuid = res; var path = _fileService.GetPath(res).Result; SetImagePath(path); } private async Task SaveDate() { if (Validate()) return; if (IsCreateWindow) await _productService.Create(ProductInfo); else await _productService.Edit(ProductInfo.ProductGuid, ProductInfo); new SaveResultView() .ShowDialog(); Close?.Invoke(); } public Action Close { get; set; } public void InitializeClose(Action close) { Close = close; } /// <summary> /// Иницилизирует объект продукта /// </summary> /// <param name="product"></param> public void InitializeProduct(Product product) { ProductInfo = Mapper.Map<ProductInfo>(product); UpdateDetails().Wait(); SetImagePath(product.File?.Path); } public event PropertyChangedEventHandler PropertyChanged; private void SetImagePath(string path) { if (path == null) { DisplayedImagePath = new BitmapImage(); return; } var uri = new Uri(path); DisplayedImagePath = new BitmapImage(uri); } private async Task<Guid> UploadFileFromFileDialog() { var fileDialog = new OpenFileDialog(); fileDialog.Filter = "Image files (*.png;*.jpeg;*jpg;)|*.png;*.jpeg;*.jpg;|All files (*.*)|*.*"; if (fileDialog.ShowDialog() == true) { var file = new FileInfo { Path = fileDialog.FileName, FileName = fileDialog.SafeFileName, Content = File.OpenRead(fileDialog.FileName) }; return await _fileService.UploadFile(file); } return Guid.Empty; } public async Task AddDetail() { var context = _containers.Resolve<DetailToProductViewModel>(); var window = _containers.Resolve<DetailToProductView>(); context.InitializeProduct(ProductInfo); window.DataContext = context; window.ShowDialog(); await UpdateDetails(); } public async Task UpdateDetails() { Details = new ObservableCollection<DetailWithCount>(await _productService .GetDetailWithProduct(ProductInfo.ProductGuid)); } private async Task ViewDetail() { var context = _containers.Resolve<DetailViewModel>(); var window = _containers.Resolve<DetailView>(); context.InitializeClose(() => window.Close()); var detail = await _detailService.GetSingle(SelectedDetail.DetailtGuid); context.InitializeDetail(detail); window.DataContext = context; window.ShowDialog(); await UpdateDetails(); } private bool Validate() { var validator = Validator.Create(); return validator .IsNull(() => ProductInfo) .IsNullOrEmpty(() => ProductInfo.Name) .RaiseError(); } [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } <file_sep>using System; using Astral.PD.Workflow.Domain.Entities; namespace Astral.PD.Workflow.Domain.PropertyTypes.Models { /// <summary> /// Модель для отображения типа имущества /// </summary> public class PropertyTypeModel { /// <summary> /// Id типа имущества /// </summary> public Guid PropertyTypeGuid { get; set; } /// <summary> /// Hазвание типа имущества /// </summary> public string Name { get; set; } /// <summary> /// Описание /// </summary> public string Description { get; set; } /// <inheritdoc /> public PropertyTypeModel() { } /// <inheritdoc /> public PropertyTypeModel(PropertyType propertyType) { PropertyTypeGuid = propertyType.PropertyTypeGuid; Name = propertyType.Name; Description = propertyType.Description; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using Kzta.Views.ValidatorViews; namespace Kzta.Extensions { /// <summary> /// Простой валидатор /// </summary> public class Validator { /// <summary> /// Список ошибок /// </summary> private List<string> Errors { get; set; } private Validator() { Errors = new List<string>(); } public static Validator Create() { return new Validator(); } /// <summary> /// Проверяет, является ли модель null /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <returns></returns> public Validator IsNull<T>(Expression<Func<T>> source) { var result = source.Compile().Invoke(); var member = source.Body as MemberExpression; if (result == null) //Errors.Add($"Модель {member?.Member.Name} равняется null."); AddError($"Модель {member?.Member.Name} равняется null."); return this; } /// <summary> /// Добавляет ошибку в список /// </summary> /// <param name="errorMessage"></param> /// <returns></returns> public Validator AddError(string errorMessage) { Errors.Add($"{Errors.Count + 1}.{errorMessage}"); return this; } /// <summary> /// Отображает ошибки /// </summary> /// <returns></returns> public bool RaiseError() { if (!Errors.Any()) return false; var view = new ValidatorView(); view.ErrorMessage.Text = GetErrorMessage(); view.ShowDialog(); return true; } private string GetErrorMessage() { var strBuilder = new StringBuilder(); foreach (var item in Errors) { strBuilder = strBuilder.AppendLine(item); } return strBuilder.ToString(); } } } <file_sep>namespace Kzta.Domain.Files { public class FileOptions { /// <summary> /// Базовый путь /// </summary> public string BaseRoot { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Kzta.Extensions { public static class Extension { public static int ParseToInt(this string text) { if (int.TryParse(text, out var result)) { return result; } return 0; } } } <file_sep>using System; using System.Windows.Input; namespace Kzta.Commands { public class Command : ICommand { private Action _executeMethod; private Func<bool> _canExecuteMethod; public Command(Action p_execute, Func<bool> p_canExexute = null) { _executeMethod = p_execute; _canExecuteMethod = p_canExexute; } public bool CanExecute(object parameter) { return _canExecuteMethod?.Invoke() ?? false; } public event EventHandler CanExecuteChanged { add => CommandManager.RequerySuggested += value; remove => CommandManager.RequerySuggested -= value; } public void Execute(object parameter) { if (_canExecuteMethod != null) { _executeMethod(); } } } } <file_sep>using System.IO; namespace Kzta.Domain.Files.Models { /// <summary> /// Входная модель для файлов /// </summary> public class FileInfo { public Stream Content { get; set; } public string FileName { get; set; } public string Path { get; set; } public FileInfo() { Content = new MemoryStream(); } } } <file_sep>namespace Databas.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddProduct : DbMigration { public override void Up() { CreateTable( "dbo.DetailInProducts", c => new { DetailGuid = c.Guid(nullable: false), ProductGuid = c.Guid(nullable: false), Count = c.Int(nullable: false), }) .PrimaryKey(t => new { t.DetailGuid, t.ProductGuid }) .ForeignKey("dbo.Details", t => t.DetailGuid, cascadeDelete: true) .ForeignKey("dbo.Products", t => t.ProductGuid, cascadeDelete: true) .Index(t => t.DetailGuid) .Index(t => t.ProductGuid); CreateTable( "dbo.Products", c => new { ProductGuid = c.Guid(nullable: false), FileGuid = c.Guid(), Name = c.String(nullable: false, maxLength: 200), Description = c.String(maxLength: 1000), }) .PrimaryKey(t => t.ProductGuid) .ForeignKey("dbo.Files", t => t.FileGuid) .Index(t => t.FileGuid); AddColumn("dbo.Details", "Material", c => c.String(maxLength: 100)); AddColumn("dbo.Details", "Size", c => c.String(maxLength: 100)); } public override void Down() { DropForeignKey("dbo.DetailInProducts", "ProductGuid", "dbo.Products"); DropForeignKey("dbo.Products", "FileGuid", "dbo.Files"); DropForeignKey("dbo.DetailInProducts", "DetailGuid", "dbo.Details"); DropIndex("dbo.Products", new[] { "FileGuid" }); DropIndex("dbo.DetailInProducts", new[] { "ProductGuid" }); DropIndex("dbo.DetailInProducts", new[] { "DetailGuid" }); DropColumn("dbo.Details", "Size"); DropColumn("dbo.Details", "Material"); DropTable("dbo.Products"); DropTable("dbo.DetailInProducts"); } } } <file_sep>using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Data.Entity; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Windows.Media.Imaging; using AutoMapper; using Databas.Models; using Kzta.Annotations; using Kzta.Commands; using Kzta.Domain.Details; using Kzta.Domain.Files; using Kzta.Domain.Files.Models; using Kzta.Domain.PropertyTypes; using Kzta.Extensions; using Kzta.Views.ValidatorViews; using Microsoft.Win32; using Unity; using File = System.IO.File; namespace Kzta.ViewModels.Details { public class DetailViewModel : INotifyPropertyChanged { //Serivces private readonly FileService _fileService; private readonly DetailService _detailService; private readonly PropertyTypeService _propertyTypeService; private readonly IUnityContainer _containers; //Property Type private ObservableCollection<PropertyType> _propertyTypes; public ObservableCollection<PropertyType> PropertyTypes { get => _propertyTypes; set { _propertyTypes = value; OnPropertyChanged(); } } public PropertyType SelectedPropertyType { get; set; } //Картинка private BitmapSource _displayedImagePath; public BitmapSource DisplayedImagePath { get => _displayedImagePath; set { _displayedImagePath = value; OnPropertyChanged(); } } //Commands public Command UploadImageCommand { get; set; } public Command SaveDataCommand { get; set; } public DetailInfo Detail { get; set; } public bool IsCreateWindow { get; set; } public DetailViewModel(FileService fileService, DetailService detailService, IUnityContainer containers, PropertyTypeService propertyTypeService) { _fileService = fileService; _detailService = detailService; this._containers = containers; _propertyTypeService = propertyTypeService; Detail = new DetailInfo(); InitializeData().Wait(); } private async Task InitializeData() { IsCreateWindow = true; PropertyTypes = new ObservableCollection<PropertyType>(); UploadImageCommand = new Command(async () => { await UploadImage(); }, () => true); SaveDataCommand = new Command(async () => await SaveDate(), () => true); PropertyTypes = new ObservableCollection<PropertyType>(await _propertyTypeService.Get().ToListAsync()); SelectedPropertyType = PropertyTypes.FirstOrDefault(); } private async Task UploadImage() { var res = UploadFileFromFileDialog().Result; if (res == Guid.Empty) return; await _detailService.SetImage(Detail.DetailtGuid, res); Detail.ImageGuid = res; var path = _fileService.GetPath(res).Result; SetImagePath(path); } private async Task SaveDate() { if (Validate()) return; Detail.PropertyTypeGuid = SelectedPropertyType.PropertyTypeGuid; if (IsCreateWindow) await _detailService.Create(Detail); else await _detailService.Update(Detail.DetailtGuid, Detail); new SaveResultView() .ShowDialog(); Close?.Invoke(); } public Action Close { get; set; } public void InitializeClose(Action close) { Close = close; } /// <summary> /// Иницилизирует объект продукта /// </summary> /// <param name="product"></param> public void InitializeDetail(Detail detail) { Detail = Mapper.Map<DetailInfo>(detail); IsCreateWindow = false; SelectedPropertyType = PropertyTypes.FirstOrDefault(x => x.PropertyTypeGuid == detail.PropertyTypeGuid); SetImagePath(detail.Image?.Path); } public event PropertyChangedEventHandler PropertyChanged; private void SetImagePath(string path) { if (path == null) { DisplayedImagePath = new BitmapImage(); return; } var uri = new Uri(path); DisplayedImagePath = new BitmapImage(uri); } private async Task<Guid> UploadFileFromFileDialog() { var fileDialog = new OpenFileDialog(); fileDialog.Filter = "Image files (*.png;*.jpeg;*jpg;)|*.png;*.jpeg;*.jpg;|All files (*.*)|*.*"; if (fileDialog.ShowDialog() == true) { var file = new FileInfo { Path = fileDialog.FileName, FileName = fileDialog.SafeFileName, Content = File.OpenRead(fileDialog.FileName) }; return await _fileService.UploadFile(file); } return Guid.Empty; } private bool Validate() { var validator = Validator.Create(); validator = validator.IsNull(() => Detail) .IsNullOrEmpty(() => Detail.Name); if (SelectedPropertyType == null) validator.AddError("Выберите тип дитали."); return validator.RaiseError(); } [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }<file_sep>using System.Data.Entity; using Databas.Models; namespace Databas { public class DatabaseContext : DbContext { public DatabaseContext():base("Context") { } /// <summary> /// Таблица деталий /// </summary> public DbSet<Detail> Details { get; set; } /// <summary> /// Таблица файлов /// </summary> public DbSet<File> Files { get; set; } /// <summary> /// Таблица типа имущества /// </summary> public DbSet<PropertyType> PropertyTypes { get; set; } /// <summary> /// Таблица продуктов(изделий) /// </summary> public DbSet<Product> Products { get; set; } /// <summary> /// Связывающая таблица для продукта и детали /// </summary> public DbSet<DetailInProduct> DetailsInProducts { get; set; } /// <inheritdoc /> protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<DetailInProduct>() .HasKey(x => new {x.DetailGuid, x.ProductGuid}); base.OnModelCreating(modelBuilder); } } } <file_sep>using System; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Databas; using Databas.Models; namespace Kzta.Domain.PropertyTypes { /// <summary/> public class PropertyTypeService { private readonly DatabaseContext _context; /// <summary/> public PropertyTypeService(DatabaseContext context) { _context = context; } /// <inheritdoc /> public async Task<Guid> Create(PropertyTypeInfo model) { var propertyType = new PropertyType(model.Name, model.Description); _context.PropertyTypes.Add(propertyType); _context.SaveChanges(); return propertyType.PropertyTypeGuid; } /// <inheritdoc /> public async Task Update(Guid propertyTypeId, PropertyTypeInfo model) { var propertyType = await _context.PropertyTypes.SingleOrDefaultAsync(x => x.PropertyTypeGuid == propertyTypeId); if (propertyType == null) { return; } if (!String.Equals(propertyType.Name, model.Name, StringComparison.CurrentCultureIgnoreCase) && await _context.PropertyTypes.AnyAsync(x => x.Name.ToLower().Equals(model.Name.ToLower()))) { } propertyType.Name = model.Name; propertyType.Description = model.Description; await _context.SaveChangesAsync(); } /// <inheritdoc /> public async Task Delete(Guid propertyTypeGuid) { var propertyType = await _context.PropertyTypes .Include(x => x.Details) .SingleOrDefaultAsync(x => x.PropertyTypeGuid == propertyTypeGuid); if (propertyType.Details.Any()) return; _context.PropertyTypes.Remove(propertyType); _context.SaveChanges(); } public IQueryable<PropertyType> Get() { return _context.PropertyTypes.AsNoTracking().OrderBy(x => x.Name); } public async Task<PropertyType> GetSingle(Guid propertyTypeGuid) { return _context.PropertyTypes.SingleOrDefault(x => x.PropertyTypeGuid == propertyTypeGuid); } } }<file_sep>using System; using Kzta.Commands; namespace Kzta.ViewModels { public class BaseViewModel { public Command OkayCommand { get; set; } public Command CancelCommand { get; set; } public BaseViewModel() { } /// <inheritdoc /> public BaseViewModel(Action ok, Action cancel) { OkayCommand = new Command(ok, () => true); CancelCommand = new Command(cancel, () => true); } /// <inheritdoc /> public BaseViewModel(Action ok, Action cancel, Func<bool> canExecuteOk, Func<bool> canExecuteCancel) { OkayCommand = new Command(ok, canExecuteOk); CancelCommand = new Command(cancel, canExecuteCancel); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Databas.Models { /// <summary> /// Продукт(изделие) /// </summary> public class Product { /// <summary> /// Id /// </summary> [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public Guid ProductGuid { get; set; } /// <summary> /// Внешний ключ на файл(картинку) /// </summary> [ForeignKey(nameof(File))] public Guid? FileGuid { get; set; } /// <summary> /// Название /// </summary> [Required] [MaxLength(200)] public string Name { get; set; } /// <summary> /// Описание /// </summary> [MaxLength(1000)] public string Description { get; set; } /// <summary> /// S/N /// </summary> [MaxLength(1000)] public string SerialNumber { get; set; } /// <summary> /// Картинка(да да, сори за название) /// </summary> public virtual File File { get; set; } /// <summary> /// /// </summary> public virtual ICollection<DetailInProduct> DetailInProducts { get; set; } public Product() { ProductGuid = Guid.NewGuid(); } /// <inheritdoc /> public Product(Guid productGuid, Guid? fileGuid, string name, string description) { ProductGuid = productGuid; FileGuid = fileGuid; Name = name; Description = description; } } }<file_sep>using System; using System.ComponentModel; namespace Kzta.Domain.Products { public class DetailToProductInfo { /// <summary> /// ВК на деталь /// </summary> [Description("Деталь")] public Guid DetailtGuid { get; set; } /// <summary> /// ВК на продукт /// </summary> [Description("Продукт")] public Guid ProductGuid { get; set; } /// <summary> /// Количество в продукте /// </summary> [Description("Количество")] public int Count { get; set; } public DetailToProductInfo() { } } } <file_sep>using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace Kzta.Views { /// <summary> /// Логика взаимодействия для DetailToProductView.xaml /// </summary> public partial class DetailToProductView : Window { public DetailToProductView() { InitializeComponent(); } private void CloseWindow(object sender, RoutedEventArgs e) { this.Close(); } private void UIElement_OnPreviewTextInput(object sender, TextCompositionEventArgs e) { var textBox = sender as TextBox; e.Handled = Regex.IsMatch(e.Text, "[^0-9]+"); } } } <file_sep>using System; using System.ComponentModel.DataAnnotations.Schema; namespace Databas.Models { /// <summary> /// Связь для бд (продукт-деталь) /// </summary> public class DetailInProduct { /// <summary> /// ВК на деталь /// </summary> [ForeignKey(nameof(Detail))] public Guid DetailGuid { get; set; } /// <summary> /// ВК на продукт /// </summary> [ForeignKey(nameof(Product))] public Guid ProductGuid { get; set; } /// <summary> /// Количество в продукте /// </summary> public int Count { get; set; } public virtual Detail Detail { get; set; } public virtual Product Product { get; set; } public DetailInProduct() { } /// <inheritdoc /> public DetailInProduct(Guid detailGuid, Guid productGuid, int count) { DetailGuid = detailGuid; ProductGuid = productGuid; Count = count; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Databas.Models { /// <summary> /// Техника /// </summary> public class Detail { /// <summary> /// Id /// </summary> [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public Guid DetailtGuid { get; set; } /// <summary> /// Внешний ключ на тип имущества /// </summary> [ForeignKey(nameof(PropertyType))] public Guid PropertyTypeGuid { get; set; } /// <summary> /// Внешний ключ на файл изображения /// </summary> [ForeignKey(nameof(Image))] public Guid? ImageGuid { get; set; } /// <summary> /// Название /// </summary> [Required] [MaxLength(100)] public string Name { get; set; } /// <summary> /// Инвентарный номер /// </summary> [MaxLength(100)] public string InventoryNumber { get; set; } /// <summary> /// Описание /// </summary> [MaxLength(1000)] public string Description { get; set; } /// <summary> /// Материал /// </summary> [MaxLength(100)] public string Material { get; set; } /// <summary> /// Размеры /// </summary> [MaxLength(100)] public string Size { get; set; } /// <summary> /// Тип имущества /// </summary> public virtual PropertyType PropertyType{ get; set; } /// <summary> /// Файл изображения /// </summary> public virtual File Image { get; set; } /// <summary> /// /// </summary> public virtual ICollection<DetailInProduct> DetailInProducts { get; set; } /// <summary> /// Конструктор техники /// </summary> public Detail() { DetailtGuid = Guid.NewGuid(); } /// <summary> /// Конструктор техники /// </summary> /// <param name="name"></param> /// <param name="inventoryNumber"></param> /// <param name="description"></param> /// <param name="propertyTypeGuid"></param> /// <param name="imageGuid"></param> public Detail(string name, string inventoryNumber, string description, Guid propertyTypeGuid, Guid? imageGuid) { DetailtGuid = Guid.NewGuid(); Name = name; InventoryNumber = inventoryNumber; Description = description; PropertyTypeGuid = propertyTypeGuid; ImageGuid = imageGuid; } } } <file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using AutoMapper; using AutoMapper.QueryableExtensions; using Databas; using Databas.Models; namespace Kzta.Domain.Products { /// <summary> /// API для изделий /// </summary> public class ProductService { private readonly DatabaseContext _context; public ProductService(DatabaseContext context) { _context = context; } /// <summary> /// Создание изделия /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task<Guid> Create(ProductInfo model) { var result = Mapper.Map<Product>(model); result.ProductGuid = Guid.NewGuid(); _context.Products.Add(result); await _context.SaveChangesAsync(); return result.ProductGuid; } /// <summary> /// Удаляет продукт /// </summary> /// <param name="productGuid"></param> /// <returns></returns> public async Task Delete(Guid productGuid) { var result = await _context.Products.SingleOrDefaultAsync(x => x.ProductGuid == productGuid); if (result == null) return; _context.Products.Remove(result); await _context.SaveChangesAsync(); } /// <summary> /// Изменяет продукт /// </summary> /// <param name="productGuid"></param> /// <param name="model"></param> /// <returns></returns> public async Task Edit(Guid productGuid, ProductInfo model) { var result = await _context.Products.SingleOrDefaultAsync(x => x.ProductGuid == productGuid); if (result == null) return; Mapper.Map(model, result); await _context.SaveChangesAsync(); } /// <summary> /// Устанавливает картинку /// </summary> /// <param name="productGuid"></param> /// <param name="imageGuid"></param> /// <returns></returns> public async Task SetImage(Guid productGuid, Guid imageGuid) { var product = await _context.Products.SingleOrDefaultAsync(x => x.ProductGuid == productGuid); var image = await _context.Files.SingleOrDefaultAsync(x => x.FileGuid == imageGuid); if (product == null || image==null) return; product.FileGuid = image.FileGuid; await _context.SaveChangesAsync(); } /// <summary> /// Возвращает все продукты /// </summary> /// <returns></returns> public async Task<List<Product>> Get() { return await _context.Products .OrderBy(x => x.Name) .AsNoTracking() .ToListAsync(); } public async Task AddDetailToProduct(DetailToProductInfo model) { if (model == null) return; var product = await _context.Products.SingleOrDefaultAsync(x => x.ProductGuid == model.ProductGuid); var detail = await _context.Details.SingleOrDefaultAsync(x => x.DetailtGuid == model.DetailtGuid); if (product == null || detail == null) return; if (await _context.DetailsInProducts.AnyAsync(x => x.ProductGuid == model.ProductGuid && x.DetailGuid == model.DetailtGuid)) { var detailInProduct = await _context.DetailsInProducts.SingleAsync(x => x.ProductGuid == model.ProductGuid && x.DetailGuid == model.DetailtGuid); detailInProduct.Count += model.Count; await _context.SaveChangesAsync(); return; } var result = Mapper.Map<DetailInProduct>(model); _context.DetailsInProducts.Add(result); await _context.SaveChangesAsync(); } /// <summary> /// Возвращает детали с кол-во для данного продукта /// </summary> /// <param name="productGuid"></param> /// <returns></returns> public async Task<List<DetailWithCount>> GetDetailWithProduct(Guid productGuid) { return await _context.DetailsInProducts .Where(x => x.ProductGuid == productGuid) .AsNoTracking() .ProjectTo<DetailWithCount>() .ToListAsync(); } } } <file_sep>using System; namespace Kzta.Domain.Products { public class DetailWithCount { /// <summary> /// Id /// </summary> public Guid DetailtGuid { get; set; } /// <summary> /// Внешний ключ на тип имущества /// </summary> public Guid PropertyTypeGuid { get; set; } /// <summary> /// Внешний ключ на файл изображения /// </summary> public Guid? ImageGuid { get; set; } /// <summary> /// Название /// </summary> public string Name { get; set; } /// <summary> /// Инвентарный номер /// </summary> public string InventoryNumber { get; set; } /// <summary> /// Описание /// </summary> public string Description { get; set; } /// <summary> /// Материал /// </summary> public string Material { get; set; } /// <summary> /// Размеры /// </summary> public string Size { get; set; } public int Count { get; set; } } } <file_sep>namespace Databas.Migrations { using System; using System.Data.Entity.Migrations; public partial class CreateDb : DbMigration { public override void Up() { CreateTable( "dbo.Details", c => new { DetailtGuid = c.Guid(nullable: false), PropertyTypeGuid = c.Guid(nullable: false), ImageGuid = c.Guid(), Name = c.String(nullable: false, maxLength: 100), InventoryNumber = c.String(maxLength: 100), Description = c.String(maxLength: 1000), }) .PrimaryKey(t => t.DetailtGuid) .ForeignKey("dbo.Files", t => t.ImageGuid) .ForeignKey("dbo.PropertyTypes", t => t.PropertyTypeGuid, cascadeDelete: true) .Index(t => t.PropertyTypeGuid) .Index(t => t.ImageGuid); CreateTable( "dbo.Files", c => new { FileGuid = c.Guid(nullable: false), Extension = c.String(maxLength: 100), Name = c.String(nullable: false, maxLength: 100), }) .PrimaryKey(t => t.FileGuid); CreateTable( "dbo.PropertyTypes", c => new { PropertyTypeGuid = c.Guid(nullable: false), Name = c.String(nullable: false, maxLength: 100), Description = c.String(maxLength: 500), }) .PrimaryKey(t => t.PropertyTypeGuid); } public override void Down() { DropForeignKey("dbo.Details", "PropertyTypeGuid", "dbo.PropertyTypes"); DropForeignKey("dbo.Details", "ImageGuid", "dbo.Files"); DropIndex("dbo.Details", new[] { "ImageGuid" }); DropIndex("dbo.Details", new[] { "PropertyTypeGuid" }); DropTable("dbo.PropertyTypes"); DropTable("dbo.Files"); DropTable("dbo.Details"); } } } <file_sep>using System.Collections.ObjectModel; using System.Linq; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Databas; using Databas.Models; namespace Kzta { /// <summary> /// Логика взаимодействия для MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Windows; namespace Kzta.Views.ValidatorViews { /// <summary> /// Логика взаимодействия для SaveResultView.xaml /// </summary> public partial class SaveResultView : Window { public SaveResultView() { InitializeComponent(); } private void CloseWindow(object sender, RoutedEventArgs e) { Close(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.CompilerServices; namespace Databas.Models { /// <summary> /// Тип имущества /// </summary> public class PropertyType : INotifyPropertyChanged { private string _description; private string _name; private Guid _propertyTypeGuid; /// <summary> /// Id типа имущества /// </summary> [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public Guid PropertyTypeGuid { get => _propertyTypeGuid; set { _propertyTypeGuid = value; OnPropertyChanged(); } } /// <summary> /// Название типа имущества /// </summary> [Required] [MaxLength(100)] public string Name { get => _name; set { _name = value; OnPropertyChanged("Name"); } } /// <summary> /// Описание /// </summary> [MaxLength(500)] public string Description { get => _description; set { _description = value; OnPropertyChanged("Description"); } } /// <summary> /// Имущество данного типа /// </summary> public virtual ICollection<Detail> Details { get; set; } /// <inheritdoc /> public PropertyType() { PropertyTypeGuid = Guid.NewGuid(); } /// <inheritdoc /> public PropertyType(string name, string description) { PropertyTypeGuid = Guid.NewGuid(); Name = name; Description = description; } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName] string prop = "") { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(prop)); } } }<file_sep>using System; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; namespace Kzta.Extensions { public static class ValidatorExtensions { public static Validator IsNullOrEmpty(this Validator validator, Expression<Func<string>> source) { var test = source.Compile(); var result = source.Compile().Invoke(); var member = source.Body as MemberExpression; if (string.IsNullOrEmpty(result) || string.IsNullOrWhiteSpace(result)) { var message = GetDescription(member); if (message == null) message = member?.Member.Name; validator.AddError($"Поле '{message}' является пустым."); } return validator; } public static Validator IsZeroOrLow(this Validator validator, Expression<Func<int>> source) { var result = source.Compile().Invoke(); var member = source.Body as MemberExpression; if (result <= 0) { var message = GetDescription(member); if (message == null) message = member?.Member.Name; validator.AddError($"В поле '{message}' число меньше или равно 0."); } return validator; } private static string GetDescription(MemberExpression member) { var colelction = member?.Member?.CustomAttributes; if (colelction == null) return null; var item = colelction.FirstOrDefault(x => x.AttributeType == typeof(DescriptionAttribute)); if (item == null) return null; var res = item.ConstructorArguments.FirstOrDefault(); if (res == null) return null; return res.Value.ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using AutoMapper; using Databas.Models; using Kzta.Commands; using Kzta.Domain.Details; using Kzta.Domain.Products; using Kzta.Extensions; namespace Kzta.ViewModels.Products { public class DetailToProductViewModel { private readonly DetailService _detailService; private readonly ProductService _productService; public ObservableCollection<Detail> Details { get; set; } public Detail SelectedDetail { get; set; } [Description("Кол-во")] public string Count { get; set; } private Product _product; public Command AddDetailToProductCommand { get; set; } public DetailToProductViewModel(DetailService detailService, ProductService productService) { _detailService = detailService; _productService = productService; Details = new ObservableCollection<Detail>(_detailService.Get().ToList()); SelectedDetail = Details.FirstOrDefault(); AddDetailToProductCommand = new Command(async () => await AddDetails(), () => SelectedDetail != null); } public void InitializeProduct(ProductInfo product) { _product = Mapper.Map<Product>(product); } public async Task AddDetails() { var validator = Validator.Create(); var count = Count.ParseToInt(); if (count <= 0) validator.AddError("Введите кол-во (больше 0).") .RaiseError(); var model = new DetailToProductInfo { Count = count, ProductGuid = _product.ProductGuid, DetailtGuid = SelectedDetail.DetailtGuid }; await _productService.AddDetailToProduct(model); } } } <file_sep>using System.IO; using AutoMapper; using AutoMapper.Configuration; using Databas; using Databas.Models; using Kzta.Domain.Details; using Kzta.Domain.Files; using Kzta.Domain.Products; using Kzta.Domain.PropertyTypes; using Kzta.ViewModels; using Kzta.ViewModels.Details; using Kzta.ViewModels.Products; using Kzta.ViewModels.PropertyTypes; using Kzta.Views; using Unity; using Unity.Lifetime; using FileOptions = Kzta.Domain.Files.FileOptions; namespace Kzta.Extensions { /// <summary> /// Расширение для Di /// </summary> public static class UnityExtensions { public static IUnityContainer AddServices(this IUnityContainer containers) { containers.RegisterType<DatabaseContext>(new ContainerControlledTransientManager()); containers.RegisterType<DetailToProductViewModel>(); containers.RegisterType<DetailService>(); containers.RegisterType<DetailViewModel>(); containers.RegisterType<FileService>(); containers.RegisterType<ProductView>(); containers.RegisterType<ProductService>(); containers.RegisterType<CreateProductView>(); containers.RegisterType<PropertyTypeService>(); containers.RegisterType<PropertyTypeViewModel>(); var rootPath = Directory.GetCurrentDirectory(); var opt = new FileOptions {BaseRoot = rootPath +"/Images"}; //var opt = new FileOptions {BaseRoot = rootPath + "~/../../Images" }; containers.RegisterInstance(typeof(FileOptions), opt); Mapper.Initialize(new ConfigMapper()); return containers; } } public class ConfigMapper : MapperConfigurationExpression { public ConfigMapper() { CreateMap<PropertyTypeInfo, PropertyType>(); CreateMap<DetailInfo, Detail>(); CreateMap<Detail, DetailInfo>(); CreateMap<DetailWithCount, Detail>(); CreateMap<ProductInfo, Product>(); CreateMap<Product, ProductInfo>(); CreateMap<DetailToProductInfo, DetailInProduct>(); CreateMap<DetailInProduct, DetailWithCount>() .ForMember(dest => dest.Description, opt => opt.MapFrom(src => src.Detail.Description)) .ForMember(dest => dest.DetailtGuid, opt => opt.MapFrom(src => src.Detail.DetailtGuid)) .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Detail.Name)) .ForMember(dest => dest.Size, opt => opt.MapFrom(src => src.Detail.Size)) .ForMember(dest => dest.InventoryNumber, opt => opt.MapFrom(src => src.Detail.InventoryNumber)) .ForMember(dest => dest.Material, opt => opt.MapFrom(src => src.Detail.Material)) .ForMember(dest => dest.ImageGuid, opt => opt.MapFrom(src => src.Detail.ImageGuid)) .ForMember(dest => dest.PropertyTypeGuid, opt => opt.MapFrom(src => src.Detail.PropertyTypeGuid)) .ForMember(dest => dest.Count, opt => opt.MapFrom(src => src.Count)); } } } <file_sep>using Astral.Extensions.Data; using Astral.PD.Workflow.Domain.Entities; namespace Astral.PD.Workflow.Domain.PropertyTypes.Extensions { /// <summary> /// Расширения для типа имущества /// </summary> public static class PropertyTypeExtensions { /// <summary> /// Сортирует тип имущества /// </summary> /// <param name="collection"></param> /// <param name="sortField"></param> /// <param name="sortOrder"></param> /// <returns></returns> public static CollectionReference<PropertyType> Sort(this CollectionReference<PropertyType> collection, PropertyTypeSortField sortField, SortOrder sortOrder) { switch (sortField) { case PropertyTypeSortField.Name: collection = collection.OrderBy(x => x.Name, sortOrder); break; case PropertyTypeSortField.Description: collection = collection.OrderBy(x => x.Description, sortOrder); break; default: collection = collection.OrderBy(x => x.Name, sortOrder); break; } return collection; } } } <file_sep>using System; using System.Threading.Tasks; using Astral.Extensions.Data; using Astral.PD.Workflow.Domain.Entities; using Astral.PD.Workflow.Domain.PropertyTypes.Models; namespace Astral.PD.Workflow.Domain.PropertyTypes { /// <summary> /// Сервис для работы с типом имущества /// </summary> public interface IPropertyTypeService { /// <summary> /// Создаёт тип имущества /// </summary> /// <param name="model"></param> /// <returns></returns> Task<Guid> Create(PropertyTypeInfo model); /// <summary> /// Обновляет тип имущества /// </summary> /// <param name="propertyTypeGuid"></param> /// <param name="model"></param> /// <returns></returns> Task Update(Guid propertyTypeGuid, PropertyTypeInfo model); /// <summary> /// Удаляет тип имущества /// </summary> /// <param name="propertyTypeGuid"></param> /// <returns></returns> Task Delete(Guid propertyTypeGuid); /// <summary> /// Фильтрует тип имущества /// </summary> /// <param name="search"></param> /// <returns></returns> CollectionReference<PropertyType> Search(string search); } } <file_sep>using System.Windows; using Databas; using Kzta.Domain.PropertyTypes; using Kzta.Extensions; using Kzta.ViewModels; using Kzta.ViewModels.Details; using Unity; namespace Kzta { /// <summary> /// Логика взаимодействия для App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { IUnityContainer container = new UnityContainer(); container.AddServices(); InitializeDb(container); var mainModel = container.Resolve<MainViewModel>(); Resources.Add("MainViewModel", mainModel); MainWindow mainWindow = container.Resolve<MainWindow>(); mainWindow.Show(); } private void InitializeDb(IUnityContainer containers) { var context = containers.Resolve<DatabaseContext>(); context.Database.CreateIfNotExists(); } } } <file_sep>using System; using System.ComponentModel; namespace Kzta.Domain.Details { /// <summary> /// Модель для создания типа имущества /// </summary> public class DetailInfo { /// <summary> /// /// </summary> public Guid DetailtGuid { get; set; } /// <summary> /// Внешний ключ на тип имущества /// </summary> public Guid PropertyTypeGuid { get; set; } /// <summary> /// Внешний ключ на файл изображения /// </summary> public Guid? ImageGuid { get; set; } /// <summary> /// Название /// </summary> [Description("Название")] public string Name { get; set; } /// <summary> /// Инвентарный номер /// </summary> [Description("Инвентарный номер")] public string InventoryNumber { get; set; } /// <summary> /// Описание /// </summary> [Description("ОПисание")] public string Description { get; set; } /// <summary> /// Материал /// </summary> [Description("Материал")] public string Material { get; set; } /// <summary> /// Размеры /// </summary> [Description("Размеры")] public string Size { get; set; } } } <file_sep>using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Databas.Models { /// <summary> /// Класс, предоставляющий файл /// </summary> public class File { /// <summary> /// Id файла, под ним файл храниться в хранилище /// </summary> [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public Guid FileGuid { get; set; } /// <summary> /// Тип файла /// </summary> [Required] [MaxLength(200)] public string Path { get; set; } /// <summary> /// Имя файла /// </summary> [Required] [MaxLength(100)] public string Name { get; set; } /// <summary/> public File() { } /// <summary/> public File(string path, string name) { FileGuid = Guid.NewGuid(); Path = path; Name = name; } } } <file_sep>using System; using System.ComponentModel; using Databas.Models; namespace Kzta.Domain.Products { /// <summary> /// Модель для продукта(добейте меня, пишу в ласт день в 10 вечера) /// </summary> public class ProductInfo { /// <summary> /// Id /// </summary> public Guid ProductGuid { get; set; } /// <summary> /// Внешний ключ на файл(картинку) /// </summary> public Guid? FileGuid { get; set; } /// <summary> /// Название /// </summary> [Description("Название")] public string Name { get; set; } /// <summary> /// Описание /// </summary> [Description("Описание")] public string Description { get; set; } /// <summary> /// S/N /// </summary> [Description("Серийный номер")] public string SerialNumber { get; set; } public ProductInfo() { } /// <inheritdoc /> public override bool Equals(object obj) { if (!(obj is Product product)) return false; if (product.Name == Name && product.ProductGuid == ProductGuid && product.Description == Description && product.SerialNumber == SerialNumber && product.FileGuid == FileGuid) return true; return false; } } } <file_sep>using System.ComponentModel; namespace Kzta.Domain.PropertyTypes { /// <summary> /// Модель для создания типа имущества /// </summary> public class PropertyTypeInfo { /// <summary> /// Hазвание типа имущества /// </summary> [Description("Название")] public string Name { get; set; } /// <summary> /// Описание /// </summary> [Description("Описание")] public string Description { get; set; } } } <file_sep>namespace Astral.PD.Workflow.Domain.PropertyTypes.Extensions { /// <summary> /// Поля для сортировки типа имущества /// </summary> public enum PropertyTypeSortField { /// <summary> /// Название /// </summary> Name = 0, /// <summary> /// Описание /// </summary> Description = 1 } }
015d1421d465fb0ebd8343d7fa4e67f77bd1b2a2
[ "C#" ]
38
C#
sanchezzz41/Kzta
731cb9195ae523ecb5b0dd8cca042464d498e237
e3be968c73c21832b89cefb605ab05f2ea936289
refs/heads/master
<file_sep>import styled from "styled-components" const ContainerList = styled.ul` background-color: black; display: flex; justify-content: space-around; align-items: center; color: white; list-style: none; text-transform: uppercase; font-weight: bold; height: 10vh; ` const BoxList = styled.li` cursor: pointer; color: rgb(88,88,88); transition: 0.5s; &:hover{ color: white; } ` const imgAlistar = styled.img` width: 10rem; ` export default function Footer(){ return( <div> <ContainerList> <BoxList>server status</BoxList> <BoxList> help us improve</BoxList> <BoxList>Suport</BoxList> <BoxList>espots pro site</BoxList> </ContainerList> </div> ) }<file_sep>import styled from "styled-components" import Back from '../img/lol.gif' import Logo from '../img/pngegg.png' import League from '../img/league.png' const Container = styled.div` background-image: url(${Back}); height: 100vh; background-size: cover; background-position: left; ` const BoxList = styled.ul` list-style: none; display: flex; justify-content: space-evenly; height: 5rem; align-items: center; background-color: black; position: fixed; width: 100vw; color: white; text-transform: uppercase; ` const List = styled.li` display: flex; justify-content: center; align-items: center; cursor: pointer; font-weight: bold; height: 5rem; border-bottom: solid black; &:hover{ border-bottom: solid rgb(11,196,226); transition: 0.5s; } ` const LogoImg = styled.img` width: 40px; ` const BoxLeague = styled.div` display: flex; justify-content: center; align-items: center; height: 100vh; ` export default function Header() { return ( <Container> <BoxList> <LogoImg src={Logo} alt='logo' /> <List>Game</List> <List>Champions</List> <List>Suport</List> <List>Downoad</List> </BoxList> <BoxLeague> <img src={ League } alt='league of legends' /> </BoxLeague> </Container> ) }
cabd9c7aed7b8e2171bc5cf5fb06ac6efad186b5
[ "JavaScript" ]
2
JavaScript
renananiceto/-desafio-10-Componentizando
0a4a14a95b7a415503008b2f48dd63534cc98289
4bb5acf41ca9a9fb7be2932866dadb0b28daf0b7
refs/heads/master
<file_sep>using System; using ScrollsModLoader.Interfaces; using Mono.Cecil; using System.Reflection; using System.Collections; using System.Collections.Generic; namespace CardFilterOrOperatorMod { public class CardFilterOrOperatorMod : BaseMod { Type filterType; public CardFilterOrOperatorMod () { filterType = typeof(DeckBuilder2).Assembly.GetType ("CardFilter+Filter"); } public static MethodDefinition[] GetHooks(TypeDefinitionCollection scrollsTypes, int version) { MethodDefinition cardFilterConstructor = scrollsTypes ["CardFilter"].Constructors.GetConstructor(false, new Type[] { "".GetType() }); return new MethodDefinition[] {cardFilterConstructor}; } public static string GetName() { return "CardFilterOr"; } public static int GetVersion() { return 1; } public override void BeforeInvoke (InvocationInfo info) { } private char[] splitChars = new char[] { '|', ';' }; FieldInfo filtersField = typeof(CardFilter).GetField ("filters", BindingFlags.NonPublic | BindingFlags.Instance); public override void AfterInvoke (InvocationInfo info, ref object returnValue) { string arg = (string)info.arguments [0]; if (arg.IndexOfAny(splitChars) >= 0) { IList filters = (IList)filtersField.GetValue (info.target); string[] f =arg.Trim().Split (splitChars, StringSplitOptions.RemoveEmptyEntries); List<CardFilter> cardFilters = new List<CardFilter> (); foreach (string filter in f) { cardFilters.Add (new CardFilter (filter)); } MyFilter orFilter = (Card c) => ( cardFilters.Exists( (CardFilter cardFilter) => (cardFilter.isIncluded(c)) ) ); filters.Clear (); filters.Add(Cast(orFilter, filterType)); } } //Method to cast a delegate - from http://code.logos.com/blog/2008/07/casting_delegates.html public static Delegate Cast(Delegate source, Type type) { if (source == null) return null; Delegate[] delegates = source.GetInvocationList(); if (delegates.Length == 1) return Delegate.CreateDelegate(type, delegates[0].Target, delegates[0].Method); Delegate[] delegatesDest = new Delegate[delegates.Length]; for (int nDelegate = 0; nDelegate < delegates.Length; nDelegate++) delegatesDest[nDelegate] = Delegate.CreateDelegate(type, delegates[nDelegate].Target, delegates[nDelegate].Method); return Delegate.Combine(delegatesDest); } private delegate bool MyFilter(Card c); } }
d68e9e2cda192aecdda12ff128f86141e0bdc4c2
[ "C#" ]
1
C#
MaPePeR/ScrollsMod-CardFilterOrOperator
089d1afbf984d3cee95d368e77df0fa05388489e
c8ed3524e61fc5d07f4bdf0979bcce1740494c5e
refs/heads/master
<file_sep>#!/usr/bin/python3 import requests import re from fractions import Fraction import json import sys from PyQt5 import QtWidgets, QtWidgets, QtCore import time from datetime import date import webbrowser class BoxEntry: def __init__(self): self.length=0 self.width=0 self.depth=0 self.product_id='' class BoxFinder(QtWidgets.QWidget): def __init__(self): super(BoxFinder,self).__init__() self.initUI() self.box_db=dict() #load box database try: self.LoadDatabase() except: self.setWindowTitle('Box Finder - Box Database Not Present') def initUI(self): self.setGeometry(300, 300, 1120, 600) self.setWindowTitle('Box Finder') #layout self.layout = QtWidgets.QVBoxLayout(self) #buttons self.scrape_button=QtWidgets.QPushButton("Scrape Inventory") self.find_button=QtWidgets.QPushButton("Locate Boxes") #input self.input_length=QtWidgets.QLineEdit() self.input_width=QtWidgets.QLineEdit() self.input_depth=QtWidgets.QLineEdit() #labels self.length_label=QtWidgets.QLabel('Desired Length:') self.width_label=QtWidgets.QLabel('Desired Width:') self.depth_label=QtWidgets.QLabel('Desired Depth:') self.unit_label=QtWidgets.QLabel('All units are assumed inches with decimals, i.e. 4.5') self.stock_label=QtWidgets.QLabel('Stock Boxes:') self.over_label=QtWidgets.QLabel('Overrun Boxes:') #outputs self.stock_output=QtWidgets.QTableWidget() self.over_output=QtWidgets.QTableWidget() #output specification self.box_count=QtWidgets.QLineEdit() self.cut_down_yes=QtWidgets.QRadioButton('Assume Cut Down') self.cut_down_yes.setChecked(True) self.cut_down_no=QtWidgets.QRadioButton('No Cut Down') self.count_label=QtWidgets.QLabel('Number of Boxed to Find:') self.box_count.setText('10') #arrange elements self.input_row=QtWidgets.QHBoxLayout() self.input_row.addWidget(self.length_label) self.input_row.addWidget(self.input_length) self.input_row.addWidget(self.width_label) self.input_row.addWidget(self.input_width) self.input_row.addWidget(self.depth_label) self.input_row.addWidget(self.input_depth) self.button_row=QtWidgets.QHBoxLayout() self.button_row.addWidget(self.scrape_button) self.button_row.addWidget(self.find_button) self.options_row=QtWidgets.QHBoxLayout() self.options_row.addWidget(self.cut_down_yes) self.options_row.addWidget(self.cut_down_no) self.options_row.addWidget(self.count_label) self.options_row.addWidget(self.box_count) self.layout.addWidget(self.unit_label) self.layout.addLayout(self.input_row) self.layout.addLayout(self.options_row) self.layout.addLayout(self.button_row) self.layout.addWidget(self.stock_label) self.layout.addWidget(self.stock_output) self.layout.addWidget(self.over_label) self.layout.addWidget(self.over_output) #connections self.scrape_button.clicked.connect(self.ScrapeInventory) self.find_button.clicked.connect(self.FindBoxes) self.stock_output.itemClicked.connect(self.OpenPage) self.over_output.itemClicked.connect(self.OpenPage) self.show() def LoadDatabase(self): self.box_db=dict() self.box_db['stock']=list() self.box_db['over']=list() #load box db infile=open('box_db.json','r') serial_box=json.loads(infile.read()) infile.close() try: for key in serial_box['stock'].keys(): this_box=BoxEntry() this_box.length=serial_box['stock'][key]['l'] this_box.width=serial_box['stock'][key]['w'] this_box.depth=serial_box['stock'][key]['d'] this_box.product_id=key self.box_db['stock'].append(this_box) self.box_db['date']=serial_box['date'] for key in serial_box['over'].keys(): this_box=BoxEntry() this_box.length=serial_box['over'][key]['l'] this_box.width=serial_box['over'][key]['w'] this_box.depth=serial_box['over'][key]['d'] this_box.product_id=key self.box_db['over'].append(this_box) self.setWindowTitle('Box Finder Database Date: '+self.box_db['date']) except: print('Load of database failed') return def ScrapeInventory(self): #scrape the webpage to get the links to the two box types page = requests.get('http://www.serviceboxandtape.com/').text #make thing flexible in case the stock/overrun page id's change stock_str_end='">Boxes - Stock</a></li>' stock_str_start='<li><a href="' over_str_end='">Boxes - Overrun</a></li>' over_str_start='<li><a href="' stock_url_index_end=page.find(stock_str_end) stock_str=page[:stock_url_index_end] stock_url_index_start=stock_str.rfind(stock_str_start) stock_url=stock_str[stock_url_index_start+len(stock_str_start):] over_url_index_end=page.find(over_str_end) over_str=page[:over_url_index_end] over_url_index_start=over_str.rfind(over_str_start) over_url=over_str[over_url_index_start+len(over_str_start):] # now have the stock and overrun pages. each is a page with a bunch of links to listings #get each product from stock stock_page=str(requests.get(stock_url).text) #stock listings pages stock_list_pages=list() stock_type='(http://www.serviceboxandtape.com/pc_product_detail.asp\?key=[0-9A-F]+)"></a>' matches=re.finditer(stock_type,stock_page) #check each for match in matches: stock_list_pages.append(match.group(1)) #manually add moving boxes- it doesn't fit the regex stock_list_pages.append('http://www.serviceboxandtape.com/moving-supplies/MovingBoxes.asp') #page 2 of stock stock_page=str(requests.get(stock_url).text+'&page=2') matches=re.finditer(stock_type,stock_page) #check each for match in matches: stock_list_pages.append(match.group(1)) #overrun over_page=str(requests.get(over_url).text) #overrun listing pages over_list_pages=list() over_type='(http://www.serviceboxandtape.com/pc_product_detail.asp\?key=[0-9A-F]+)"></a>' matches=re.finditer(over_type,over_page) #check each for match in matches: over_list_pages.append(match.group(1)) #build box database #set date self.box_db['date']=date.today().strftime("%d %B %Y") self.box_db['stock']=list() self.box_db['over']=list() for page in stock_list_pages: try: print('fetching product page: '+str(page)) page_text=requests.get(page).text self.box_db['stock'].extend(self.GetBoxes(page_text)) except: print('issue with url: '+str(page)) for page in over_list_pages: try: print('fetching product page: '+str(page)) page_text=requests.get(page).text self.box_db['over'].extend(self.GetBoxes(page_text)) except: print('issue with url: '+str(page)) print(str(len(self.box_db['stock']))+' '+str(len(self.box_db['over']))) #self.setWindowTitle('Box Finder Database Date: '+self.box_db['date']) self.SaveBoxes() self.LoadDatabase() def GetBoxes(self,page_text): box_type='(http://www.serviceboxandtape.com/pc_product_detail.asp\?key=)([0-9A-F]+)">([0-9]+[ ]*[0-9/]*[ ]*x[ ]*[0-9]+[ ]*[0-9/]*[ ]*x[ ]*[0-9]+[ ]*[0-9/]*)' matches=re.finditer(box_type,page_text) match_list=[n for n in matches] box_list=list() for item in match_list: this_box=BoxEntry() #get just the hex this_box.product_id=item.group(2).encode("utf8") dims=item.group(3).split('x') #fix fractions this_box.length=float(sum(Fraction(s) for s in dims[0].split())) this_box.width=float(sum(Fraction(s) for s in dims[1].split())) this_box.depth=float(sum(Fraction(s) for s in dims[2].split())) box_list.append(this_box) print(str(len(box_list))) return box_list def SaveBoxes(self): serial_box=dict() serial_box['date']=self.box_db['date'] serial_box['stock']=dict() for box in self.box_db['stock']: serial_box['stock'][str(box.product_id)]=dict() serial_box['stock'][str(box.product_id)]['l']=box.length serial_box['stock'][str(box.product_id)]['w']=box.width serial_box['stock'][str(box.product_id)]['d']=box.depth serial_box['over']=dict() for box in self.box_db['over']: serial_box['over'][str(box.product_id)]=dict() serial_box['over'][str(box.product_id)]['l']=box.length serial_box['over'][str(box.product_id)]['w']=box.width serial_box['over'][str(box.product_id)]['d']=box.depth #save json save_string=json.dumps(serial_box) #open file try: outfile=open('box_db.json','w') outfile.write(save_string) outfile.close() except: print('save failed') def ProcessType(self,type_key,output,obj_dim,box_count): #search stock boxes fit_list=dict() for box in self.box_db[type_key]: #does this box fit? #arrange dimensions in order box_dim=[box.length,box.width,box.depth] box_dim.sort() box_size=box.length*box.width #check each dimension if box_dim[0]>=obj_dim[0]: if box_dim[1]>=obj_dim[1]: if box_dim[2]>=obj_dim[2]: fit_list[box.product_id]=dict() fit_list[box.product_id]['size']=box_size fit_list[box.product_id]['l']=box.length fit_list[box.product_id]['w']=box.width fit_list[box.product_id]['d']=box.depth print(str(len(fit_list.keys()))+' boxes will contain the object.') #ok, there is a 'pythonic' way to do this with lambda and some list comprehension- but I need this to be understandable by future me. #make dummy list of just id's and sizes small_list=dict() for key in fit_list: small_list[key]=fit_list[key]['size'] #for product_id in sorted(small_list, key=small_list.__getitem__)[0:10]: # box_url='http://www.serviceboxandtape.com/pc_product_detail.asp?key='+product_id #set up table output.setColumnCount(4) output.setSortingEnabled(True) table_rows=list() for product_id in sorted(small_list, key=small_list.__getitem__): dims=str(fit_list[product_id]['l'])+' x '+str(fit_list[product_id]['w'])+' x '+str(fit_list[product_id]['d']) vol=fit_list[product_id]['d']*fit_list[product_id]['w']*fit_list[product_id]['l'] table_rows.append([QtWidgets.QTableWidgetItem(str(product_id)),QtWidgets.QTableWidgetItem(dims),FloatTableWidgetItem(fit_list[product_id]['size']),FloatTableWidgetItem(vol)]) output.setRowCount(min(box_count,len(table_rows))) output.setHorizontalHeaderLabels("Product ID;Dimensions;Opening Area;Volume".split(';')) for ii in range(min(box_count,len(table_rows))): output.setItem(ii,0,table_rows[ii][0]) output.setItem(ii,1,table_rows[ii][1]) output.setItem(ii,2,table_rows[ii][2]) output.setItem(ii,3,table_rows[ii][3]) #make it fill the width output.horizontalHeader().setSectionResizeMode(0,QtWidgets.QHeaderView.Stretch) output.horizontalHeader().setSectionResizeMode(1,QtWidgets.QHeaderView.Stretch) def FindBoxes(self): print('finding boxes that fit') box_count=int(str(self.box_count.text())) obj_dim=list() obj_dim.append(float(str(self.input_length.text()))) obj_dim.append(float(str(self.input_width.text()))) obj_dim.append(float(str(self.input_depth.text()))) obj_dim.sort() self.ProcessType('stock',self.stock_output,obj_dim,box_count) self.ProcessType('over',self.over_output,obj_dim,box_count) #webbrowser.open('https://google.com/') def OpenPage(self,item): print(str(item.text())) webbrowser.open('http://www.serviceboxandtape.com/pc_product_detail.asp?key='+str(item.text())) #dummy class that allows costs to sort the way I want class FloatTableWidgetItem(QtWidgets.QTableWidgetItem): def __init__(self, number): QtWidgets.QTableWidgetItem.__init__(self,str(number),QtWidgets.QTableWidgetItem.UserType) self.sort_key=number def __lt__(self,other): try: return float(self.sort_key)<float(other.sort_key) except: return self.sort_key<other.sort_key def main(): app=QtWidgets.QApplication(sys.argv) ex=BoxFinder() sys.exit(app.exec_()) if __name__=='__main__': main()
fd7d82d8c3c68eba98468755f27bd11098fd5bcc
[ "Python" ]
1
Python
eanow/box_finder
ad59cd8d54368b1816d782e4a11217415aa9dee9
1b1816abc4195d63c4cbf300dd5e06607a21ae2f
refs/heads/master
<repo_name>sodiyaj/2043MAPA<file_sep>/Web Application - Group/webapp/register.php <?php require("config.php"); if(!empty($_POST)) { // Ensure that the user fills out fields if(empty($_POST['username'])) { die("Please enter a username."); } if(empty($_POST['password'])) { die("Please enter a password."); } if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { die("Invalid E-Mail Address"); } // Check if the username is already taken $query = "CALL selectUser(?)"; try { $stmt = $db->prepare($query); $stmt->bindParam(1, $_POST['username'] , PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); $result = $stmt->execute(); } catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); } $row = $stmt->fetch(); if($row){ die("This username is already in use"); } $query = "CALL selectEmail(?)"; try { $stmt = $db->prepare($query); $stmt->bindParam(1, $_POST['email'] , PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); $result = $stmt->execute(); } catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage());} $row = $stmt->fetch(); if($row){ die("This email address is already registered"); } // Add row to database $query = "CALL insertUser(?,?,?,?)"; // Security measures $salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647)); $password = hash('<PASSWORD>', $_POST['password'] . $salt); for($round = 0; $round < 65536; $round++){ $password = hash('<PASSWORD>', $password . $salt); } try { $stmt = $db->prepare($query); $stmt->bindParam(1, $_POST['username'] , PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); $stmt->bindParam(2, $password , PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); $stmt->bindParam(3, $salt , PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); $stmt->bindParam(4, $_POST['email'] , PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); $result = $stmt->execute(); } catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); } header("Location: index.php"); die("Redirecting to index.php"); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Higher Thoughts</title> <!-- Bootstrap core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'> <!-- Plugin CSS --> <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="css/creative.min.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> </head> <body id="page-top"> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="#page-top">Higher Thoughts</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="index.php">Home</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="register.php">Register</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="about.php">About Us</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="secret.php">Our Tv Show</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="debates.php">Debates</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="logout.php">Log out</a> </li> </ul> </div> </div> </nav> <header class="masthead text-center text-white d-flex"> <div class="container my-auto"> <div class="row"> <div class="col-lg-10 mx-auto"> <h1 class="text-uppercase"> <strong>Higher thoughts- Is it really that simple?</strong> </h1> <hr> </div> <div class="col-lg-8 mx-auto"> <p class="text-faded mb-5">Register here to gain access to our exclusive debate show.</p> <a class="btn btn-primary btn-xl js-scroll-trigger" href="#about">Find Out More</a> </div> </div> </div> </header> <section class="bg-light text-black"> <div class="container text-center"> <form action="register.php" method="post"> <label>Username:</label> <input type="text" name="username" value="" /> <label>Email: <strong style="color:darkred;">*</strong></label> <input type="text" name="email" value="" /> <label>Password:</label> <input type="<PASSWORD>" name="password" value="" /> <br /><br /> <p style="color:darkred;">* You may enter a false email address if desired. This demo database does not store addresses for purposes outside of this tutorial.</p><br /> <input type="submit" class="btn btn-info" value="Register" /> </form> </div> </section> <section id="contact"> <section id="contact"> <div class="container"> <div class="row"> <div class="col-lg-8 mx-auto text-center"> <h2 class="section-heading">Let's Get In Touch!</h2> <hr class="my-4"> <p class="mb-5">If you want to join our team, or participate in any of our debates, get in touch</p> </div> </div> <div class="row"> <div class="col-lg-4 ml-auto text-center"> <i class="fa fa-phone fa-3x mb-3 sr-contact"></i> <p>07704577876</p> </div> <div class="col-lg-4 mr-auto text-center"> <i class="fa fa-envelope-o fa-3x mb-3 sr-contact"></i> <p> <a href="mailto:<EMAIL>"><EMAIL></a> </p> </div> </div> </div> </section> </section> <!-- Bootstrap core JavaScript --> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Plugin JavaScript --> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> <script src="vendor/scrollreveal/scrollreveal.min.js"></script> <script src="vendor/magnific-popup/jquery.magnific-popup.min.js"></script> <!-- Custom scripts for this template --> <script src="js/creative.min.js"></script> </body> </html> <file_sep>/Web Application - Basic/register.php <?php require("config.php"); if(!empty($_POST)) { // Ensure that the user fills out fields if(empty($_POST['username'])) { die("Please enter a username."); } if(empty($_POST['password'])) { die("Please enter a password."); } if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { die("Invalid E-Mail Address"); } // Check if the username is already taken $query = "CALL selectUser(?)"; try { $stmt = $db->prepare($query); $stmt->bindParam(1, $_POST['username'] , PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); $result = $stmt->execute(); } catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); } $row = $stmt->fetch(); if($row){ die("This username is already in use"); } $query = "CALL selectEmail(?)"; try { $stmt = $db->prepare($query); $stmt->bindParam(1, $_POST['email'] , PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); $result = $stmt->execute(); } catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage());} $row = $stmt->fetch(); if($row){ die("This email address is already registered"); } // Add row to database $query = "CALL insertUser(?,?,?,?)"; // Security measures $salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647)); $password = hash('<PASSWORD>', $_POST['password'] . $salt); for($round = 0; $round < 65536; $round++){ $password = hash('<PASSWORD>', $password . $salt); } try { $stmt = $db->prepare($query); $stmt->bindParam(1, $_POST['username'] , PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); $stmt->bindParam(2, $password , PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); $stmt->bindParam(3, $salt , PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); $stmt->bindParam(4, $_POST['email'] , PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); $result = $stmt->execute(); } catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); } header("Location: index.php"); die("Redirecting to index.php"); } ?> <form action="register.php" method="post"> <label>Username:</label> <input type="text" name="username" value="" /> <label>Email: <strong style="color:darkred;">*</strong></label> <input type="text" name="email" value="" /> <label>Password:</label> <input type="<PASSWORD>" name="password" value="" /> <br /><br /> <p style="color:darkred;">* You may enter a false email address if desired. This demo database does not store addresses for purposes outside of this tutorial.</p><br /> <input type="submit" class="btn btn-info" value="Register" /> </form> <file_sep>/Web Application - Basic/index.php <?php require("config.php"); $submitted_username = ''; if(!empty($_POST)){ $query = "CALL selectUser(?)"; try{ $stmt = $db->prepare($query); $stmt->bindParam(1, $_POST['username'] , PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); $result = $stmt->execute(); } catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); } $login_ok = false; $row = $stmt->fetch(); if($row){ $check_password = hash('<PASSWORD>', $_POST['password'] . $row['salt']); for($round = 0; $round < 65536; $round++){ $check_password = hash('<PASSWORD>', $check_password . $row['salt']); } if($check_password === $row['password']){ $login_ok = true; } } if($login_ok){ unset($row['salt']); unset($row['password']); $_SESSION['user'] = $row; header("Location: secret.php"); die("Redirecting to: secret.php"); } else{ print("Login Failed."); $submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8'); } } ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href=""> <title>Haven</title> <!-- Bootstrap core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="css/style.css" rel="stylesheet"> </head> <body> <div class="container"> <form class="form-signin" action="index.php" method="post"> <h2 class="form-signin-heading">Please sign in</h2> <input type="text" id="inputUsername" placeholder="Username" name="username" class="form-control" value="<?php echo $submitted_username;?>"/> <input type="password" id="inPassword" placeholder="<PASSWORD>" name="password" value="" class="form-control"> <input type="submit" class="btn btn-lg btn-primary btn-block" value="Login" /> </form> <p><a href="register.php">Click Here to register</a></p> </div> <!-- /container --> </body> </html><file_sep>/Web Application - Group/webapp/debates.php <?php require("config.php"); if(empty($_SESSION['user'])) { header("Location: index.php"); die("Redirecting to index.php"); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Higher Thoughts</title> <!-- Bootstrap core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'> <!-- Plugin CSS --> <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="css/creative.min.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> </head> <body id="page-top"> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="#page-top">Higher Thoughts</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="index.php">Home</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="register.php">Register</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="about.php">About Us</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="secret.php">Our Tv Show</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="debates.php">Debates</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="logout.php">Log out</a> </li> </ul> </div> </div> </nav> <header class="masthead text-center text-white d-flex"> <div class="container my-auto"> <div class="row"> <div class="col-lg-10 mx-auto"> <h1 class="text-uppercase"> <strong>Welcome <?php echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8'); ?>,</strong> </h1> <hr> </div> <div class="col-lg-8 mx-auto"> <p class="text-faded mb-5">What keeps you up at night? Have you ever questioned your existance?Are you the only one, with unanswered questions? Well join us in our debate show, where others like you will be debating societies issues.</p> </div> </div> </div> </header> <section id="Debates"> <div class="jumbotron"> <h1 align="center">Our Debate</h1> <p class="Our-Product">Over the past couple of weeks, the production team have designed a viable and more interactive method of voicing our opinions. Our tv show, covers the following debates on the show, we aim to do an episode once a week, a live intellectual talk between people in our community.</p> </div> <div class="box"> <div class="col-lg-12"> <hr> <h2 class="intro-text text-center">Knife Crime </h2> <p>Knife crime is on the ride over the last decade. With it risen by 10% across England and wales. More people are feeling the need to carry knives as a form of protection. However there, is a correlation between knife crime and a rise in violent crime, and murder rates of over 18%. With knife crime on the rise, we want to know your thoughts on ideas, on why people might carry knives, and do you think in our day of age we may need to carry knives as a form of defence.</p> <div class="row"> <div class="col-md-12"> <img class="img-center" width="80%" height="365" src="img/knife-933312_640.jpg" alt="Knife"> </div> <hr> </div> <hr> </div> </div> <div class="jumbotron"> <h1 align="center">Fair Use</h1> <p class="Fair Use">Fair use Fair use, is the use of copyrighted material done for “transformative purposes, that can be used to critique, or for parody purposes. When using copyrighted material, one must ask the following: has the material you have taken from the original work been transformed by adding new expression or meaning? Was value added to the original by creating new information, new aesthetics, new insights, and understandings? Why the topic has become ever so hot, is through the existence of YouTube. YouTube is a videoing app, and many people use it, to platform their videos. In their videos, they may use existent art work or background music that is owned by existing artist. This work could not be copyrighted or stolen without the user’s authority. </p> <div class="row"> <div class="col-md-12"> <img class="img-center" width="50%" height="365" src="img/copyright-40632_640.png" alt="copyright"> </div> <hr> </div> </div> <div class="box"> <div class="col-lg-12"> <hr> <h2 class="intro-text text-center">Feminism </h2> <p>We want to know your thoughts! Do you think feminism is alive and well in this society? Do you believe that feminism is a big issue that females still have to deal with in 2017 or are you the opposite and view feminism as something that is pro-actively making a difference today? With our debate today this is the perfect opportunity to get your views across and with the results we would be able to understand the opinions of our youths today. </p> <div class="row"> <div class="col-md-12"> <img class="img-center" width="50%" height="365" src="img/emancipation-156066_640.png" alt="3dmodel"> </div> <hr> </div> <hr> </div> </div> <div class="jumbotron"> <h1 align="center">Peace and War</h1> <p class="Peace"> Does peace truly exist? People are always fighting, with wars around the world seeming to pop up every now and then. Wars between borders, politics, religion and gender equality. We need to find a way in which we can build peace, resolve conflicts and be able to find justice and human rights. We will look at both sides of the argument and then choose to agree and disagree. </p> <div class="row"> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src="img/safi1.mp4"></iframe> </div> <hr> </div> </div> <div class="box"> <div class="col-lg-12"> <hr> <h2 class="intro-text text-center">LGBT </h2> <p>The LGBT community is still a taboo subject in today’s society.</p> <p>Agree The general public today feel uncomfortable talking about the subject as they will often have no experience in speaking openly about such matters. As a result of this the topic is not getting enough movement. In America it seemed like they were moving forward with the LGBT community as Barack Obama legalized gay marriage however now Trump is in office and his views are very different. Society has closed its mind to things that it doesn’t understand but with time, society’s views will change and the LGBTQ+ society will be more widely accepted. </p> <p>Disagree There are countless opportunities in society for people to speak about LGBTQ+ and many do. With large news outlets covering LGBTQ+ related issues and governments across the world decriminalising gay marriage, the work of the LGBTQ+ community has clearly impacted the way that society sees them. If there is a taboo, it’s on a time limit. Get Involved LGBT is a hot topic at this moment in time and we want you to get involved. We hope you have been following our debate and want to share your opinion with us. If you want to engage with us in this debate, it’s easy all you need to do is tap Agree or Disagree at the bottom of your screen. </p> <div class="row"> <div class="col-md-12"> <img class="img-center" width="50%" height="365" src="img/lgbt-1792757_640.jpg" alt="lgbt"> </div> <hr> </div> <hr> </div> </div> </section> <section id="contact"> <div class="container"> <div class="row"> <div class="col-lg-8 mx-auto text-center"> <h2 class="section-heading">Let's Get In Touch!</h2> <hr class="my-4"> <p class="mb-5">If you want to join our team, or participate in any of our debates, get in touch</p> </div> </div> <div class="row"> <div class="col-lg-4 ml-auto text-center"> <i class="fa fa-phone fa-3x mb-3 sr-contact"></i> <p>07704577876</p> </div> <div class="col-lg-4 mr-auto text-center"> <i class="fa fa-envelope-o fa-3x mb-3 sr-contact"></i> <p> <a href="mailto:<EMAIL>"><EMAIL></a> </p> </div> </div> </div> </section> <!-- Bootstrap core JavaScript --> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Plugin JavaScript --> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> <script src="vendor/scrollreveal/scrollreveal.min.js"></script> <script src="vendor/magnific-popup/jquery.magnific-popup.min.js"></script> <!-- Custom scripts for this template --> <script src="js/creative.min.js"></script> </body> </html> <file_sep>/Mobile Application/feminism.html <!-- We don't need full layout here, because this page will be parsed with Ajax--> <!-- Top Navbar--> <div class="navbar"> <div class="navbar-inner"> <div class="left"><a href="#" class="back link"> <i class="icon icon-back"></i><span>Back</span></a></div> <div class="center sliding">Feminism</div> <div class="right"> <!-- Right link contains only icon - additional "icon-only" class--><a href="#" class="link icon-only open-panel"> <i class="icon icon-bars"></i></a> </div> </div> </div> <div class="pages"> <!-- Page, data-page contains page name--> <div data-page="about" class="page"> <!-- Scrollable page content--> <div class="page-content"> <div class="content-block"> <div class="content-block-inner"> <p><b>We want to know your thoughts!</b></p> <p><b>Do you think feminism is alive and well in this society?</b></p> <p> Do you believe that feminism is a big issue that females still have to deal with in 2017 or are you the opposite and view feminism as something that is pro-actively making a difference today? With our debate today this is the perfect opportunity to get your views across and with the results we would be able to understand the opinions of our youths today.</p> <p><b>Agree</b></p> <p> Feminism has come a long way from women not being able to vote, but is it enough? Currently there are still issues that woman still have to deal with today such as the gender pay gap. A famous example of this would be how actors and actresses are still dealing with a pay cut on big budget films compared to their male co-hosts due to their contracts from the film companies. </p> <p><b>Disagree</b></p> <p>On the other hand, feminism has improved immensely and woman can now gain the same opportunities as men. Woman now have the same rights as men. </p> <img src="images/feminism.jpg" width="350" height="280"> <p><b>Get Involved</b></p> <p>Feminism is a hot topic at this moment in time and we want you to get involved. We hope you have been following our debate and want to share your opinion with us. If you want to engage with us in this debate, it’s easy all you need to do is tap Agree or Disagree at the bottom of your screen. </p> <div class="content-block"> <div class="row"> <div class="col-50"><a href="#" class="button button-big button-fill color-green">Agree</a></div> <div class="col-50"> <input type="submit" value="Disagree" class="button button-big button-fill color-red"/> </div> </div> </div> </div> </div> </div> </div> </div><file_sep>/Web Application - Group/webapp/about.php <?php require("config.php"); if(empty($_SESSION['user'])) { header("Location: index.php"); die("Redirecting to index.php"); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Higher Thoughts</title> <!-- Bootstrap core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'> <!-- Plugin CSS --> <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="css/creative.min.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> </head> <body id="page-top"> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="#page-top">Higher Thoughts</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="index.php">Home</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="register.php">Register</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="about.php">About Us</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="secret.php">Our Tv Show</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="debates.php">Debates</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="logout.php">Log out</a> </li> </ul> </div> </div> </nav> <header class="masthead text-center text-white d-flex"> <div class="container my-auto"> <div class="row"> <div class="col-lg-10 mx-auto"> <h1 class="text-uppercase"> <strong>Welcome! <?php echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8'); ?>,</strong> </h1> <hr> </div> <div class="col-lg-8 mx-auto"> <p class="text-faded mb-5">Learn More about our team.</p> </div> </div> </div> </header> <section class="bg-light text-black"> <div class="row"> <div class="box"> <div class="col-lg-12"> <hr> <h2 class="intro-text text-center">Our <strong>Team</strong> </h2> <hr> </div> <div class="row"> <div class="col-sm-4" style="padding:10px;text-align:left;"> <img class="img-responsive" src="img/safi.jpg" width="350" height="350" alt="safi"> <h3><NAME> <small>Team assistant</small> </h3> <p> Gandhi said that “whatever you do in life will be insignificant, but it's very important that you do it because nobody else will”.  I think to a certain extent Ghandi was right. Were all doing things because we need to survive, pass time, and go through the motions in life. How many of us, want to make an impact on someone else life, hence our show, wants to aware you, help you make a difference to somebody else life.</p> </div> <div class="col-sm-4" style="padding:10px;"> <img class="img-responsive" src="img/justin.jpg" width="350" height="350" alt="Justin" > <h3><NAME> <small>Team assistant</small> </h3> <p> My whole life I’ve been thoroughly invested in the social justice of others. With a keen eye on creative media, it’s always been my dream to create a collaborative piece of media that incorporates debating in depth about social justice issues and eastern philosophy. Having been raised in London by two South African parents, I’ve been made aware of the differences in culture in a country such as ours and have been desensitised to the inequality that many members of society face. This has spurred my interest and motivated me to speak out about what can so easily be swept under the rug. Wake up England! </p> </div> <div class="col-sm-4" style="padding:10px;"> <img class="img-responsive" src="img/fb.jpg" width="350" height="350" alt="callum"> <h3><NAME> <small>Team assistant</small> </h3> <p> Me and the team are all Digital Media students at Coventry University and we are using this opportunity to spread awareness for everyone and get the best project yet for social issues today. The social issues that are addressed are relevant to everyone and we want to make sure everyone can get a new understanding of certain social issues as well as enjoy the show!</p> </div> </div> <div class="row"> <div class="col-sm-4" style="padding:10px;text-align:left;"> <img class="img-responsive" src="img/ellie.JPG" width="350" height="350" alt="ellie"> <h3><NAME> <small>Team assistant</small> </h3> <p> I'm Ellie, I'm a 19-year-old Digital Media student studying at Coventry University in my second year. I am so pleased that we are addressing the social issues that are tackled in everyday life, the idea of having a debate show about it meant that we were able to review different views and opinions.</p> </div> <div class="col-sm-4" style="padding:10px;"> <img class="img-responsive" src="img/jimmy.jpg" width="350" height="350" alt="Jim"> <h3><NAME> <small>Team Leader</small> </h3> <p> My whole life I’ve been thoroughly invested in the social justice of others. With a keen eye on creative media, it’s always been my dream to create a collaborative piece of media that incorporates debating in depth about social justice issues and eastern philosophy. Having been raised in London by two South African parents, I’ve been made aware of the differences in culture in a country such as ours and have been desensitised to the inequality that many members of society face. This has spurred my interest and motivated me to speak out about what can so easily be swept under the rug. Wake up England! </p> </div> <div class="col-sm-4" style="padding:10px;"> <img class="img-responsive" src="img/lucky.JPG" width="350" height="350"alt="lucky"> <h3>Lucky <small>Team assistant</small> </h3> <p> Hello my name is Luxsaan. Am currently studying at Coventry University, doing my second year of Digital Media, plus I run a photography business in my spare time. Doing a debate show was a great idea, as this enabled us to have different views and opinions on the social issues we all face in our everyday life. </p> </div> </div> </div> </div> </section> <section id="contact"> <div class="container"> <div class="row"> <div class="col-lg-8 mx-auto text-center"> <h2 class="section-heading">Let's Get In Touch!</h2> <hr class="my-4"> <p class="mb-5">If you want to join our team, or participate in any of our debates, get in touch</p> </div> </div> <div class="row"> <div class="col-lg-4 ml-auto text-center"> <i class="fa fa-phone fa-3x mb-3 sr-contact"></i> <p>07704577876</p> </div> <div class="col-lg-4 mr-auto text-center"> <i class="fa fa-envelope-o fa-3x mb-3 sr-contact"></i> <p> <a href="mailto:<EMAIL>"><EMAIL></a> </p> </div> </div> </div> </section> <!-- Bootstrap core JavaScript --> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Plugin JavaScript --> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> <script src="vendor/scrollreveal/scrollreveal.min.js"></script> <script src="vendor/magnific-popup/jquery.magnific-popup.min.js"></script> <!-- Custom scripts for this template --> <script src="js/creative.min.js"></script> </body> </html> <file_sep>/Web Application - Group/webapp/secret.php <?php require("config.php"); if(empty($_SESSION['user'])) { header("Location: index.php"); die("Redirecting to index.php"); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Higher Thoughts</title> <!-- Bootstrap core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'> <!-- Plugin CSS --> <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="css/creative.min.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> </head> <body id="page-top"> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="#page-top">Higher Thoughts</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="index.php">Home</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="register.php">Register</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="about.php">About Us</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="secret.php">Our Tv Show</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="debates.php">Debates</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="logout.php">Log out</a> </li> </ul> </div> </div> </nav> <header class="masthead text-center text-white d-flex"> <div class="container my-auto"> <div class="row"> <div class="col-lg-10 mx-auto"> <h1 class="text-uppercase"> <strong>Welcome <?php echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8'); ?>,</strong> </h1> <hr> </div> <div class="col-lg-8 mx-auto"> <p class="text-faded mb-5">What keeps you up at night? Have you ever questioned your existance?Are you the only one, with unanswered questions? Well join us in our debate show, where others like you will be debating societies issues.</p> <a class="btn btn-primary btn-xl js-scroll-trigger" href="#about">Find Out More</a> </div> </div> </div> </header> <section class="bg-light text-black"> <div> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src="img/LiveDebate.mp4"></iframe> </div> <hr> </div> </section> <section id="contact"> <div class="container"> <div class="row"> <div class="col-lg-8 mx-auto text-center"> <h2 class="section-heading">Let's Get In Touch!</h2> <hr class="my-4"> <p class="mb-5">Ready to start your next project with us? That's great! Give us a call or send us an email and we will get back to you as soon as possible!</p> </div> </div> <div class="row"> <div class="col-lg-4 ml-auto text-center"> <i class="fa fa-phone fa-3x mb-3 sr-contact"></i> <p>123-456-6789</p> </div> <div class="col-lg-4 mr-auto text-center"> <i class="fa fa-envelope-o fa-3x mb-3 sr-contact"></i> <p> <a href="mailto:<EMAIL>"><EMAIL></a> </p> </div> </div> </div> </section> <!-- Bootstrap core JavaScript --> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Plugin JavaScript --> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> <script src="vendor/scrollreveal/scrollreveal.min.js"></script> <script src="vendor/magnific-popup/jquery.magnific-popup.min.js"></script> <!-- Custom scripts for this template --> <script src="js/creative.min.js"></script> </body> </html> <file_sep>/Web Application - Group/webapp/index.php <?php require("config.php"); $submitted_username = ''; if(!empty($_POST)){ $query = "CALL selectUser(?)"; try{ $stmt = $db->prepare($query); $stmt->bindParam(1, $_POST['username'] , PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); $result = $stmt->execute(); } catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); } $login_ok = false; $row = $stmt->fetch(); if($row){ $check_password = hash('<PASSWORD>', $_POST['password'] . $row['salt']); for($round = 0; $round < 65536; $round++){ $check_password = hash('<PASSWORD>', $check_password . $row['salt']); } if($check_password === $row['password']){ $login_ok = true; } } if($login_ok){ unset($row['salt']); unset($row['password']); $_SESSION['user'] = $row; header("Location: secret.php"); die("Redirecting to: secret.php"); } else{ print("Login Failed."); $submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8'); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Higher Thoughts</title> <!-- Bootstrap core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'> <!-- Plugin CSS --> <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="css/creative.min.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> </head> <body id="page-top"> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="#page-top">Higher Thoughts</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="index.php">Home</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="register.php">Register</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="about.php">About Us</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="secret.php">Our Tv Show</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="debates.php">Debates</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="logout.php">Log out</a> </li> </ul> </div> </div> </nav> <header class="masthead text-center text-white d-flex"> <div class="container my-auto"> <div class="row"> <div class="col-lg-10 mx-auto"> <h1 class="text-uppercase"> <strong>Higher thoughts- Is it really that simple?</strong> </h1> <hr> </div> <div class="col-lg-8 mx-auto"> <p class="text-faded mb-5">What keeps you up at night? Have you ever questioned your existance?Are you the only one, with unanswered questions? Well join us in our debate show, where others like you will be debating societies issues.</p> <a class="btn btn-primary btn-xl js-scroll-trigger" href="#about">Find Out More</a> </div> </div> </div> </header> <section class="bg-primary" id="about"> <div class="container"> <div class="row"> <div class="col-lg-8 mx-auto text-center"> <h2 class="section-heading text-white">Login</h2> <hr class="light my-4"> <form class="navbar-form navbar-right" action="index.php" method="post"> <div class="form-group"> <input type="text" placeholder="Username" name="username" class="form-control" value="<?php echo $submitted_username; ?>"/> </div> <div class="form-group"> <input type="password" placeholder="<PASSWORD>" name="<PASSWORD>" value="" class="form-control"> </div> <input type="submit" class="btn btn-success" value="Login" /> </form> </div> </div> </div> </section> <section id="services"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">Our TV Show</h2> <hr class="my-4"> </div> </div> </div> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src="img/htvid.mp4"></iframe> </div> </section> <section class="p-0"> <div class="container-fluid p-0"> <div class="row no-gutters popup-gallery"> <div class="col-lg-4 col-sm-6"> <a class="portfolio-box" href="img/portfolio/fullsize/1.jpg"> <img class="img-fluid" src="img/portfolio/thumbnails/1.jpg" alt=""> <div class="portfolio-box-caption"> <div class="portfolio-box-caption-content"> <div class="project-category text-faded"> Category </div> <div class="project-name"> Copyright </div> </div> </div> </a> </div> <div class="col-lg-4 col-sm-6"> <a class="portfolio-box" href="debates.php"> <img class="img-fluid" src="img/portfolio/thumbnails/2.jpg" alt=""> <div class="portfolio-box-caption"> <div class="portfolio-box-caption-content"> <div class="project-category text-faded"> Category </div> <div class="project-name"> Feminisim </div> </div> </div> </a> </div> <div class="col-lg-4 col-sm-6"> <a class="portfolio-box" href="debates.php"> <img class="img-fluid" src="img/portfolio/thumbnails/3.jpg" alt=""> <div class="portfolio-box-caption"> <div class="portfolio-box-caption-content"> <div class="project-category text-faded"> Category </div> <div class="project-name"> Knife Crime </div> </div> </div> </a> </div> <div class="col-lg-4 col-sm-6"> <a class="portfolio-box" href="debates.php"> <img class="img-fluid" src="img/portfolio/thumbnails/4.jpg" alt=""> <div class="portfolio-box-caption"> <div class="portfolio-box-caption-content"> <div class="project-category text-faded"> Category </div> <div class="project-name"> LGBT </div> </div> </div> </a> </div> <div class="col-lg-4 col-sm-6"> <a class="portfolio-box" href="debates.php"> <img class="img-fluid" src="img/portfolio/thumbnails/5.jpg" alt=""> <div class="portfolio-box-caption"> <div class="portfolio-box-caption-content"> <div class="project-category text-faded"> Category </div> <div class="project-name"> Peace and War </div> </div> </div> </a> </div> <div class="col-lg-4 col-sm-6"> <a class="portfolio-box" href="debates.php"> <img class="img-fluid" src="img/portfolio/thumbnails/6.jpg" alt=""> <div class="portfolio-box-caption"> <div class="portfolio-box-caption-content"> <div class="project-category text-faded"> Category </div> <div class="project-name"> Balance of Power </div> </div> </div> </a> </div> </div> </div> </section> <section id="contact"> <div class="container"> <div class="row"> <div class="col-lg-8 mx-auto text-center"> <h2 class="section-heading">Let's Get In Touch!</h2> <hr class="my-4"> <p class="mb-5">If you want to join our team, or participate in any of our debates, get in touch</p> </div> </div> <div class="row"> <div class="col-lg-4 ml-auto text-center"> <i class="fa fa-phone fa-3x mb-3 sr-contact"></i> <p>07704577876</p> </div> <div class="col-lg-4 mr-auto text-center"> <i class="fa fa-envelope-o fa-3x mb-3 sr-contact"></i> <p> <a href="mailto:<EMAIL>"><EMAIL></a> </p> </div> </div> </div> </section> <!-- Bootstrap core JavaScript --> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Plugin JavaScript --> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> <script src="vendor/scrollreveal/scrollreveal.min.js"></script> <!--<script src="vendor/magnific-popup/jquery.magnific-popup.min.js"></script>--> <!-- Custom scripts for this template --> <script src="js/creative.min.js"></script> </body> </html>
929b279bf35d62207db2924a67dc331c9855d5c2
[ "HTML", "PHP" ]
8
PHP
sodiyaj/2043MAPA
0606d0f7d8425472d1017bc16d11a30bedf86d4e
9d4cbe8e0f8a686e896e58f8c4adff6eeb0c6bee
refs/heads/master
<repo_name>MinnuMariyaJoy/luminarpythoncode<file_sep>/Advanced/Test/Test 1/q8.py #finally block will be always working along with try block a=int(input("enter your first no")) b=int(input("enter your second no")) try: c=a/b print("sum = ",c1) except: print("Error") finally: print("process completed")<file_sep>/Advanced/two string method/college two string.py class College: collegename="LT" def __init__(self,name,roll): self.name=name self.roll=roll def print(self): print("college name: ",College.collegename) print("NAme of student :",self.name) print("Roll no: ",self.roll) def __str__(self): return self.name+str(self.roll) obj=College("Minnu",36) print(obj)<file_sep>/Advanced/Test/Test 1/q4.py #4. Create an Animal class using constructor and build a child class for Dog? class Animal: def __init__(self,animaltype,food): self.animaltype=animaltype self.food=food def printvalue(self): print("Animal type :", self.animaltype) print("Food: ", self.food) class Dog: animalname="dog" def m1(self): print("Animal Name: ", Dog.animalname) obj2=Dog() obj2.m1() obj1=Animal("carnovoras","meat") obj1.printvalue() <file_sep>/List/Binary search.py # lst=[2,10,4,5,1,15,7,9] # num=int(input("eneter your number")) # lst.sort() # # low=0 # upper=len(lst)-1 # # mid=(low+upper)//2 # # if(num>lst[mid]): # low=mid+1 # found() # elif(num<lst[mid]): # upper=mid-1 # found() # else: # print("element found") # # def found(): # flag=0 # for i in range(low,upper): # if (num == i): # flag = 1 # break # else: # pass # if (flag > 0): # print("number found") # else: # print("number not found") # lst=[3,4,2,11,15,34,45,15] # lst.sort() # print(lst) # upp=len(lst)-1 # element=int(input("enter eleemnt")) # flag=0 # while(low<=upp): # mid=(lower+upp)//2 # # if(element>lst[mid]): # low=mid+1 # elif(element<lst[mid]): # upp=mid-1 # elif(elemet==lst[mid]): <file_sep>/Functions/calculator.py print("press 1 for addition") print("press 2 for sub") print("press 3 for mul") print("press 4 for dividion") option=int(input("enter your option")) num1=int(input("enter no 1")) num2=int(input("enter no 2")) def add(): result1=num1+num2 print(result1) def sub(): result2=num1-num2 print(rsult2) def mul(): result3=num1*num2 print(result3) def division(): result4=num1/num2 print(result4) if(option==1): add() elif(option==2): sub() elif(option==3): mul() elif(option==4): division() else: print("error") # def add(num1,num2): # return num1+num2 # def sub(num1,num2): # return num1-num2 # def mul(num1,num2): # return num1*num2 # def div(num1,num2): # retunr num1/num2 # # print("select operations\n" # "1.add\n" # "2.sub\n" # "3.mul\n" # "4.div") # select=int(input("select operation")) # num1=int(input("eneter first number")) # num2=int(input("enter second number")) # if select==1 # print(num1,"+",num2,"=",add())<file_sep>/nested for loop/Nested 03.py #1 #1 2 #1 2 3 #1 2 3 4 #for i in range(1,6): # for j in range(1,i): # print(j,end=" ") # print(" ") for i in range(1,6): for j in range(1,(i+1)): print(j,end=" ") print(" ") <file_sep>/Functions/Factorial of a number.py #5!=5*4*3*2*1 # def factorial(): # num=int(input("enter your number")) # fact=1 # for i in range(1,(num+1)): # fact=fact*i # print(fact) # factorial() # def factorial(num1): # fact=1 # for i in range(1,(num1+1)): # fact=fact*i # print(fact) # factorial(3) def factorial(num): fact=1 for i in range (1,(num+1)): fact=fact*i return(fact) data=factorial(5) print(data)<file_sep>/Functions/cube of a number.py #create a function to find out cube of a number. # def cube(): # num=int(input("enter the number")) # temp=1 # for i in range(1,4): #num**3 # temp=temp*num # print(temp) # cube() def cube(num) t<file_sep>/ductionary/word count program.py line="hai hello hai hello hai" #hai 3 times #hello - 2 times #split function - for splitting a line in to word by word #print(line) #for splitting word=line.split(" ") print(word) dic={} for i in word: if (i not in dic): dic[i] = 1 else: dic[i]+=1 print(dic) <file_sep>/for loop/prime btwn lower to upper.py lower=int(input("enter lower limit ")) #5 upper=int(inout("enter upper limit")) #10 for i in range(2,lower): #i=2 if(lower%i==0): #not prime #5 break else: flage=0 #prime if(flag>0): print("not prime") else: print("prime")<file_sep>/q.py age=int(input("enter your age")) if(age>50): salary=int(input("enter your salary")) bonus= .05*salary newsalary=salary+bonus print("your new net salary is ",newsalary) else: print("no change in salary") <file_sep>/Looping/1 to upper limit.py limit=int(input("enter your upper limit")) i=1 while(i<=limit): print(i) i=i+1<file_sep>/ductionary/intro.py #dictionary dic={} #print(type(dic)) #Key -value pairs #roll:1098 #name:arun #age:25 #key:rolls,name,age #value:1098,arun,25 # student={"roll":1089,"name":"arun","age":25} # print(student) # #heterogenous values are allowed student1={"rolls":1089,"name":"arun","age":25,"age":30,"cpp":25} ##print(student1) #will not support duplicated key #Dupliacted values will be supported ##for fectching a particular value use key #print(student1["age"]) #roll:1089 #name #age for i in student1: print(i,",",student1[i]) #print(i) #print(student1[i]) #for upadating name student1["name"]="arjun" student1["age"]=30 student1["cpp"]+=10 print(student1) #for deleting a key and its corresponding value #del student1["cpp"] #print(student1) #for adding a new key and a value #total 150 #for checking a key in dictionary # print("total" in student1) #very imported..for checking a key in the dictonary # print("cpp" in student1) #for adding elemnt print(student1) student1["total"]=158 print(student1) <file_sep>/Collections/Interview..total.py #collection #define #hetero #insertion #duplicate #mutable #list [] yes yes yes yes #tuples () yes yes yes no #set {} yes no no yes #dic {} yes yes value yes<file_sep>/Advanced/Regular Expression/register no/reg.py import re f2=open("validreg",'w') x='([L][U][M]\d{2}[P][Y]\d{3}$)' #LUM12PY678 f=open("reg no", "r") #if file doesnot exist use append, for existing files use w for num in f: number=num.rstrip("\n") matcher= re.fullmatch(x,number) if matcher is not None: f2.write(number) f2.write('\n') <file_sep>/Functions/sum of n numbers.py # sum of even numbers # even function #prime def sum(): num=int(input("enter your number")) sum=0 i=0 while(i<=num): sum=sum+i i=i+1 print(sum) sum()<file_sep>/ductionary/data.py Google News is a news aggregator service developed by Google. It presents a continuous flow of links to articles organized from thousands of publishers and magazines.<file_sep>/Advanced/Test/Test 1/demo.py #6. Create objects of the following file and print the details of student with maximum mark? # anu,1,bca,200 rahul,2,bba,177 vinod,3,bba,187 ajay,4,bca,198 maya,5, bba,195 class Students: def __init__(self,name,roll,course,marks): self.name=name self.roll=roll self.course=course self.marks=marks def printvalue(self): print("Name :",self.name) print("Roll no: ",self.roll) print("Course : ",self.course) print("Mark: ",self.marks) f=open("max mark","r") for line in f : data=line.split(",") name=data[0] roll=data[1] course=data[2] marks=int([data[3]]) print(marks) max=0 for i in marks: if (i>max): max=i else: pass obj = Students(name, roll, course, marks) obj.printvalue() <file_sep>/Looping/lower to upper limit.py lower=int(input("enter your lower limit")) upper=int(input("enter your upper limit")) while(lower<=upper): print(lower) lower=lower+1<file_sep>/Advanced/object oreinted/2 persons.py class Person: def setVal(self,name,age): #passing attributes self.age=age #slef.age will accept as attribute within class self.name=name def printValue(self): print("name",self.name) print("age",self.age) obj=Person() obj.setVal("ram",23) obj.printValue() <file_sep>/Looping/demo 01.py #while #for #syntax:initialization, condition,increment or decrement #while loop i=1 while(i<=10): print("hello") i=i+1 <file_sep>/tuples intro.py # #tuples #Define # tp=() # print(type(tp)) # # #function tuples tp=(10,10.5,"sabir",True,True) print(tp) #support heterogenous data #supports deplicates value tp=(1,2,3,3,6,5,4,3,10,9) print(tp) #it preserve insertion order #Immutable, index will not work #Difference btwn list and tuples,tuples will not allow mutation <file_sep>/Advanced/exception handling/exception 02.py lst=[18,4,5] try: i=int(input("enter the number")) print("the number is ",number) except: print("please enter a int value")<file_sep>/django/functional programmong/list comprehension.py # lst=[1,2,3,4] # lst2=[10,20] # output=[] # for i in lst: # for j in lst2: # output.append((i,j)) # print(output) lst=[1,2,3,4] square=[num**2 for num in lst] even=[num for num in lst if num%2==0] print(even) print(square)<file_sep>/Identifier/demo 01.py #print("hello minnu") cname = "luminar techno lab" location = "kakkanad" #print(cname) #print(location) #print(cname,location) #print(cname," is located in ",location) <file_sep>/for loop/prime number.py #num1=int(input("enter the number ")) #for i in range(2,num1): # if(num1%i==0): # num="prime no" # else: # num="not a prime" #print(num) num=int(input("enter the number ")) for i in range(2,num): if(num%i==0): #not prime flag=1 break else: flage=0 #prime if(flag>0): print("not prime") else: print("prime") <file_sep>/Advanced/object oreinted/bank.py #account creation #deposit #withdrawal class Bank(): bname="sbi" def accountcreat(self,acno,name): self.name=name self.acno=acno self.minimumbal=5000 self.balances=self.minimumbal def deposit(self,amnt): self.balances+=amnt print("your",Bank.bname," account has been credited with ",amnt) print("your account balance is ",self.balances) def withdraw(self,amnt): if amnt>self.balances: print("insuffeint balance") else: print("account debited with ",amnt) self.balances -= amnt print("available balance is, ",self.balances) obj=Bank() obj.accountcreat(1234,"Minnu") obj.deposit(10000) obj.withdraw(2000) #instance variables.....using self, related to objects #static variables <file_sep>/Advanced/Test/Test 1/q6.py #6. Create objects of the following file and print the details of student with maximum mark? # anu,1,bca,200 rahul,2,bba,177 vinod,3,bba,187 ajay,4,bca,198 maya,5, bba,195 class Students: def __init__(self,name,roll,course,marks): self.name=name self.roll=roll self.course=course self.marks=marks def printvalue(self): print("Name :",self.name) print("Roll no: ",self.roll) print("Course : ",self.course) print("Mark: ",self.marks) f=open("max mark","r") for line in f : data=line.split(",") name=data[0] roll=data[1] course=data[2] marks=data[3] #print(max(marks)) obj = Students(name, roll, course, marks) obj.printvalue() <file_sep>/Advanced/inheritence/intro inheritence.py #Single inheritance class Parent: parent_name='arun' def m1(self,age): #parent class, base class,super class self.age=age print("my name is ",Parent.parent_name) print(self.age) class Child(Parent): #derived class or child class def m2(self): print("parent name is ",Parent.parent_name) print(self.age) c=Child() c.m1(20) c.m2() <file_sep>/Identifier/demo 03.py num1 = 20 num2 = 35 #for swapping temp = num1 num1 = num2 num2 = temp print(num1) print(num2) num1 = num1 + num2 num2= num1-num1 print("num2 is ",num2)<file_sep>/Identifier/demo 02.py name = "minnu" age = 25 color = "red" print(name," of ",age," likes ",color) <file_sep>/Advanced/exception handling/division.py a=int(input("enter a")) b=int(input("enter b")) try: res=a/b print(res) except: print("error") <file_sep>/Advanced/Test/Test 1/q10.py import re x='[a]b$' r = "aaab abc aaaa cgab" matcher=re.finditer(x,r) for match in matcher: print(match.start()) print(match.group())<file_sep>/file/odd or even.py f=open("numbers","r") lst=[] even=[] odd=[] for num in f: lst.append(int(num.rstrip("\n"))) for number in lst: if(number%2==0): even.append(number) else: odd.append(number) print(sum(odd)) print(sum(even)) <file_sep>/Functions/substarct.py def substarct(): num1=int(input("enter number1")) num2=int(input("enter number2")) result=num1-num2 print(result) substarct() <file_sep>/Looping/demo 02.py i=10 while (i>=0): print(i) i=i-1 <file_sep>/django/functional programmong/student.py class Student: def __init__(self,rollno,name,course,total): self.roolno=rollno self.name=name self.course=course self.total=total def __str__(self): return self.name s1=Student(12,"anna","BBA",120) s2=Student(14,"anee","BBA",10) s3=Student(12,"athul","BBA",130) print(s1) studentlist=[] studentlist.append(s1) studentlist.append(s2) studentlist.append(s3) studenttotal=list(map(lambda stud:stud.total,studentlist)) print(studenttotal)<file_sep>/file/intro file.py #file #file operations #1.read - for reading data from file r #2. write - file write w #3. append - a #.......... #file references - for any functions there should be a file refernce f=open("filepath","mode of operation") f=open("filepath","r") f=open("filepath","w") f=open("filepath","a") <file_sep>/python database connection/createnew table.py import mysql.connector db=mysql.connector.connect( host="localhost", user="root", password="<PASSWORD>", database="pythonfeb", auth_plugin='mysql_native_password' ) cursor=db.cursor() # sql="create table demo(eid int, ename varchar(50),desig varchar(30),salary int)" # cursor.execute(sql) # db.close() sql="insert into demo(eid,ename,desig,salary) values(1009,'amal','hr',25000)" try: cursor.execute(sql) db.commit() except Exception as e: print(e.args) db.rollback() finally: db.close() <file_sep>/Q on if else/Q3.py age=int(input("enter your age ")) sex=str(input("enter your sex ")) Maritual=input("enter your maritual status") if sex(sex=f): print("you will work in urban areas") elif sex: if(age<=40)&(age>=20): print("you may work in anywhere") if(age>40)&(age<=60): print("you will work in urban areas only") else: print("error") <file_sep>/Advanced/object oreinted/object intro.py #class:design pattern Eg:plan for a house, tv #object:real number eg : sumsung, lg #references :name that refers to memory location of an object (remote) class Person: #class #cap should be given to the first letter def walk(self): #self appeard becase it is a method inside class print("Person is walking") def run(self): #methods print("person is running") def jumping(self): print("person is jumping") obj=Person() #this is the reference, use this refernce for calling methods obj.walk() obj.run() obj.jumping() ab=Person() #another object, we can create any number of object ab.walk() <file_sep>/Advanced/Test/Test 1/q9.py #9. Write a Python program to find the sequences of one upper case letter followed by lower case letters? import re x='[A-Z][a-z]' r = "azDAxada ADADac aA BGFa" matcher=re.finditer(x,r) for match in matcher: print(match.start()) print(match.group())<file_sep>/for loop/sum of even and odd within olimts.py lower=int(input('enter the lower limit')) upper=int(input("enter the upper limit")) sume=0 sumo=0 for i in range(lower,(upper+1)): if(i%2==0): sume=sume+i if(i%2==1): sumo=sumo+i print("sum of even is ",sume) print("sum of odd is ",sumo)<file_sep>/Collections/intro.py #collections #for collecting heterogenous data, without any limit #list #tuples #set #dictionary <file_sep>/Functions/import.py import Functions.demo sum=Functions.demo.add(10,20) print(sum) <file_sep>/for loop/even no btwn lower to upper.py lower=int(input('enter the lower limit')) upper=int(input("enter the upper limit")) for i in range(lower,(upper+1)): if(i%2==0): print(i) <file_sep>/Functions/with argument and wo return.py #def add(num1,num2): # sum=num1+num2 # print(sum) #add(20,30) def sub(numm1,numm2): result=numm1-numm2 print(result) sub(5,3)<file_sep>/Collections/properties.py #How to define? #Check whether it support heterogenous data #Dupicated valued allowed or not #Insertion order preserved or not #Mutable or imutable lst=[10,"minnu",10.5,"bigdata",True] print(lst) #10 int #sabir string #true boolean #each individual entity is treated as single entity <file_sep>/ductionary/employee.py #employee #keys - id, emlpoyyee name,designation, salary #1. print employee name only #2. check whther compony key in employee #3. add compony and luminar #4.upadte salry =15k #print all key value pairs employee={"id":1890,"name":"Minnu","designation":"Tutor","Salary":15000} print(employee) print(employee["name"]) print("company" in employee) employee["company"]="luminar" print(employee) employee["Salary"]+=15000 print(employee) for i in employee: print(i, ",", employee[i]) <file_sep>/django/functional programmong/decorators/div.py def div_decorator(func): def inner(n1,n2): if n1<n2: (n1,n2)=(n2,n1) return (func(n1,n2)) return inner @div_decorator def div(num1,num2): return num1/num2 res=div(2,10) print(res) <file_sep>/List/sum.py lst=[10,15,20,30,40,50,50] # sum=0 # for i in lst: # sum=sum+i # print(sum) #list has some inbult functions #sum print(sum(lst)) #max function print(max(lst)) #minimum print(min(lst)) #length function print(len(lst)) <file_sep>/List/50 to 200.py lst=[] for i in range(0,51): lst.append(i) print(lst) <file_sep>/List/iterate.py lst=[10,20,21,22,23,24] print(lst) #10 #20 #21 #22 #23 for i in lst: print(i) <file_sep>/break cntu and pass/pass.py num=int(input("enter your number")) if(num%==0): print("even") else: pass<file_sep>/nested for loop/nested for loop 01.py for i in range(1,4): for j in range(1,4): if(j==1): print(i,i,i) <file_sep>/Functions/interview q.py #1) for num in range(-2,-5,-1): # print(num,end=",") # # #what is tha output #2) a,b=12,5 # if a+b: # print("true") # else: # print("false") #what will be the out put #for non zero return will be true and for zero it will be false #3) for l in 'john': # if l=='o': # pass # print(l,end=",") # #j,h,n # #j,h,o,n #4) x=0 # a=0 # b=-5 # if a>0: # if b<0: # x=x+5 # elif a>5: # x=x+4 # else: # x=x+2 # for l in 'john': # if l=='o': # pass # x=0 # a=5 # b=5 # if a>0: # if b<0: # x=x+5 # elif a>5: # x=x+4 # else: # x=x+3 # else: # x=x+2 #b <file_sep>/django/functional programmong/employee.py class Employee: def __init__(this,eid,ename,desig,salary): this.eid=eid this.ename=ename this.desig=desig this.salary=salary def print_emp(this): print(this.ename) e1=Employee(1089,"Minnu","developer",290000) e2=Employee(1010,"arun","developer",250000) e3=Employee(1025,"vivek","qa",280000) e4=Employee(1011,"athul","marketing",270000) employees=[] employees.append(e1) employees.append(e2) employees.append(e3) employees.append(e4) # Sal=[] # for emp in employees: # sal.append.(emp.salary) # print(sal) salary=list(map(lambda emp:emp.salary,employees)) max_salary=max(list(map(lambda emp:emp.salary,employees))) print(salary) print(max_salary) <file_sep>/django/functional programmong/operator overloading/oprator overloading intro.py #07/04/2021 # class Book: # def __init__(self,pages): # self.pages=pages # # def __add__(self, other): # return self.pages+other.pages # # b1=Book(100) # b2=Book(200) # print(b1+b2) #one more book object class Book: def __init__(self, pages): self.pages = pages def __add__(self, other): return Book(self.pages + other.pages) #object will get printed def __sub__(self, other): return "overloading substraction" def __str__(self): #for coverting object printing return(str(self.pages)) b1 = Book(100) b2 = Book(200) b3=Book(100) print(b1-b2) print(b1 + b2 +b3)<file_sep>/Functions/demo.py def add(num1,num2): result=num1+num2 return result def sub(num1,num2): result=num1-num2 return result def mul(num1,num2): result=num1*num2 return result def div(num1,num2): result=num1/num2 return result #module #.py files are modules #package #collection of modules are packages <file_sep>/Advanced/Regular Expression/intro.py #Pattern matching #re---package for pattern matching import re count=0 matcher=re.finditer('ab','abaabbbabab') #finditter for itretion for match in matcher: count+=1 print("count = ",count) <file_sep>/Advanced/inehritance nd constructor/person.py class Person: def __init__(self,name,age): self.name=name self.age=age def printvalue(self): print("name: ",self.name) print("age : ",self.age) class Student(Person): def __init__(self,roll,marks,name,age): super().__init__(name,age) self.roll=roll self.marks=marks def print(self): print(self.roll) print(self.marks) cr=Student(36,100,"Minnu",25) cr.printvalue() cr.print() <file_sep>/Looping/marks.py maths=int(input("enter your marks for maths ")) social=int(input("enter your marks for social ")) mala=int(input("enter your makrs for mala ")) eng = int(input('enter your marks for eng ')) total=maths+social+mala+eng pg=total/200*100 print("your percentage is ",pg) if(pg>=90): print("you scored A + ") elif(pg>=80)&(pg<90): print("you scored A") elif(pg>=70)&(pg<80): print("you scored B+") elif(pg>=60)&(pg<70): print("you scored B") elif(pg>=50)&(pg<60): print("you scored C+") elif(pg>=40)&(pg<50): print("you scored C") else: print("you have failed") <file_sep>/for loop/forloop01.py #initialization, condition , increment or decremnt #for i in range(0,10): #for loop will print form lower limit to upper limit-1 # print(i) for i in range(0,11,2): #2 is the increment print(i) <file_sep>/django/functional programmong/operator overloading/variable gears.py # def add(*args): #tuple format # sum=0 # for num in args: # sum+=num # return sum # res=add(20,20,30) # print(res) # def print_person_details(*args): # print(args) # print_person_details("ajay","coder",26) # # def print_person_details(**kwargs): # print(kwargs) # print_person_details(name="ajay",job="coder",age=26) # *args - tuples # **kwargs - dictionary(key value pair) # lst=[10,34,20,76,4,30,5] # lst=sorted(lst,reverse=False) # print(lst) # employees={ # 1000:{"name":"Minnu","design":"trainer","exp":3}, # 1001:{"name":"arun","design":"trainer","exp":2}, # 1002:{"name":"neha","design":"trainer","exp":3} # } # # eid=int(input("enter the employee id ")) # if eid in employees: # print("eid exist") # print(employees[eid]["name"]) # else: # print("edi dosent exist") #crwate a function employees={ 1000:{"name":"Minnu","design":"trainer","exp":3}, 1001:{"name":"arun","design":"trainer","exp":2}, 1002:{"name":"neha","design":"trainer","exp":3} } id=int(input("enter id")) #emp_details(eid=1000) #sanjay def emp_details(**kwargs): #kwargs={eid:1000} id=kwargs["eid"] if id in employees: print(employees[id]["name"]) else: print("desnt exist") <file_sep>/Advanced/exception handling/value error.py #a=int(input("enter your no")) try: a=int(input("enter the no")) print(a) except: print("error")<file_sep>/Advanced/Regular Expression/a position count.py #when we will get 3 a...at what postion import re x="a{3}" r = "aaa abc aaaa cga" matcher=re.finditer(x,r) for match in matcher: print(match.start()) print(match.group())<file_sep>/Advanced/Test/Test 1/q7.py import re lst=[] f=open("phone no","r") x='[+][9][1]\d{10}' for lines in f: match = re.fullmatch(x,lines.rstrip("\n")) if match is not None: lst.append(lines.rstrip("\n")) print(lst) <file_sep>/set intro.py #set # set1={1,2,3,4} # print(type(set)) # #if only curly braces it will ber ead as dictionary # #for creating empty set use futnion set # set1=set() # set={1,2,3,12.5,"minnu",2} # print(set) # #support heterogenous value # #duplicate value not supported set1={10,2,12,8,15} print(set1) #insertion order not precerved #it is mutable <file_sep>/Functions/function 01.py #num1=int(input("enter first number")) #num2=int(input("enter second number")) #sum=num1+num2 #print(sum) #print() #input() #type #Syntax #def funtionname(arguments): # funtion definition #function call #using fn name #methods #1)Funtion without an argument and no return type #2)Function with argument and no return type #3)Function with arguments and return type #1.Funcrion without arguments and return type def add(): num1=int(input("enter number1")) num2=int(input("enter number2")) sum=num1+num2 print(sum) add() <file_sep>/Looping/lower to upper even.py lower=int(input("enter your lower limit")) upper=int(input("enter your upper limit")) while(lower<=upper): if(lower%2==0): print(lower) lower=lower+1 <file_sep>/set/set operations.py #operations #union #intersection #difference set1={1,2,3,4,5,6} set2={5,6,7,8,9,10} set3=set1.union(set2) #union set4=set1.intersection(set2) #intersection set5=set1.difference(set2) #difference print(set3) print(set4) print(set5) <file_sep>/Advanced/Regular Expression/56kg.py #for chechikng whether the word is 6 letter word import re n="56kg" x='\d{2}[a-z]{2}' match=re.fullmatch(x,n) if match is not None: print("valid") else: print("Invalid")<file_sep>/nested for loop/nested loop 06.py #1 1 1 1 1 #2 2 2 2 #3 3 3 #4 4 #5 for i in range(1,6): for j in range(i,6): #for i in range((6-i),0,-1): print(i,end=" ") print( )<file_sep>/Identifier/demo.py #identifier #variables #class name #class name #variable name = vale name = "minnu" # use either underscore or letter for declaring # error - space/number for first letter of name # variable is case sensitive # dont use reserved key words # no limit for variable length # always give a name <file_sep>/django/functional programmong/Duck typing/programmer.py class Pycharch: def open(self): print("pycharm open") def run(self): print("pycharm run") def debug(self): print("pycharm debug") class Vs: def open(self): print("vs open") def run(self): print("vs run") def debug(self): print("vs debug") class Programmer: def coding(self,ide): ide.open() ide.run() ide.debug() py=Pycharch() visual=Vs() pg=Programmer() pg.coding(visual) <file_sep>/file/sample 1.py f=open("C:\Users\minnu\PycharmProjects\python_01\file\Sample","r") for lines in f: print(lines) <file_sep>/Advanced/Test/Test 1/q5.py #5. What is method overriding give an example using Books class? #Over riding is when the child class obeject over ride parent class object. class Book1: def fav(self,peom): self.peom=peom print("favorite book is ",self.peom) class Book2: def fav(self,novels): self.novels=novels print("favorite book is ",self.novels) obj=Book2() obj.fav("Revolution 2020") <file_sep>/Functions/even numbers.py def even(): num=int(input("enter your num")) if(num%2==0): print("even") even()<file_sep>/Looping/reverse.py #3457 #7543 num=int(input("eneter your number")) res=0 while(num!=0): digit=num%10 res=(res*10)+digit num=num//10 print(res) <file_sep>/django/Django.py #29/03/2021 #django - frame work #set of rules #front end technologies - just for a user interface # HTML, # css(casceding stle sheet) # ,javascript, # bootstrap, # ajax nd jquerry(while choosing country page will not get refresh) #Back end # fuctions -1)data store - data bases can be used for storing dara (data base eg:mongodb,mysql,postgress) # 2)processig (python,php,nodejs,java,c# #language and its framework python --->django,flask php--->wordpress Nodejs--->express java-->spring c#--->asp.net #django is used for creating web applications #web applications are the prgrm which run on web server #frame work #frame work is a collection of predefined classes and fuctions #frame work should be followed by following certain set of rules #What is library? re is library not frame work..but wyyy??? #Python #dynamically typed #identifeirs #flow controls(descision making,looping,jumping statemnts) Functions collections # list # tuples - unmutable aanu # set-insertion oreder is not preserved, duplicated values cannot be stored # Dictionary # # file i/o # oop # class(design pattern) # object(real world entity) # refrence () # # inheritance # polymorphism #operator #duck typing - any bird than walk and make sound lyk duck is considered as duck # Argument- the value massed to method # Parameter- <file_sep>/Advanced/Regular Expression/vehicle registration/vehicle regisrtration.py import re lst=[] f=open("vehicle","r") x='\w{2}\d{2}\w{2}\d{4}' #"[Kk][Ll]\d{2}[a-zA-Z]{2}\d{4} for num in f: number=num.rstrip("\n") matcher = re.fullmatch(x,number) if matcher is not None: lst.append(number) print(lst)<file_sep>/Advanced/oop/marks.py class Student: def __init__(self,name,roll,course,marks): self.name=name self.roll=roll self.course=course self.marks=marks def printvalue(self): print("Name: ",self.name) print("Roll no : ",self.roll) print("Course : ",self.course) print("Marks : ",self.marks) f=open("mark","r") for line in f : data=line.split(",") name=data[0] roll=data[1] course=data[2] marks=int(data[3]) obj=Student(name,roll,course,marks) if(marks>190): obj.printvalue() <file_sep>/Advanced/exception handling/finally.py lst=[18,4,5] index=int(input("enter the index")) try: print(lst[index]) except: print("exception") finally: print("inside finally") #finally block will be always working along with try block<file_sep>/Advanced/Test/Test 1/q1.py class Vehicle: def m1(self,registration,cost,mileage): self.registration=registration self.cost=cost self.mileage=mileage def m2(self): print("Registration: ",self.registration) print("Cost: ",self.cost) print("mileage: ",self.mileage) class Bus(Vehicle): bname='Bus' def m3(self): print("Vehicle name : ", Bus.bname) obj=Bus() obj.m3() obj.m1("KL AE 0890",1000000,"50km/ltr") obj.m2()<file_sep>/Advanced/object oreinted/add.py class Add(): def add(self,a,b): self.a=a self.b=b print("the sum is ",self.a+self.b) op=Add() op.add(2,6) <file_sep>/List/Binary Search intro.py #Binary Search #Algorithm of Binary search #1.Sorting lst=[7,4,1,2,3] lst.sort #for sorting #2. low=0 #upper=len(lst)-1 #3 Caculate mid #mid=(low+upper)//2 #(0+4)//2=2lst(2) #3 Conditions #4 #if(element>lst[mid]) #4>3 #low=midd+1 #2 #if(element<lst[mid]) 2<3 #upp=mid-1 #Search elemt ==lst[mid] #element found <file_sep>/Advanced/object oreinted/employee.py class Employee(): companyname="luminar" def setVal(self,id,name,salary): self.id=id self.name=name self.salary=salary def printValue(self): print("id",self.id) print("name",self.name) print("salary",self.salary) print("company name :",Employee.companyname) obj = Employee() obj.setVal(1089,"ram",23000) obj.printValue() employe2=Employee() employe2.setVal(1900,"anil",25000) employe2.printValue()<file_sep>/set/add element to set.py #how to add elemt set1={1,2,3} #add function set1.add(4) #append in list set1.add("luminar") set1.update([13,"minnu"]) #extend in list print(set1) #for adding multiple values #update set1={1,2,3,4,16,9,10} print(sum(set1)) print(max(set1)) print(len(set1)) <file_sep>/Identifier/q2.py held = int(input("number of classes held")) attenteded = int(input("number of classes attended")) temp=(attenteded/held)*100 #print(temp) if(temp>75): print("you are eligible") else: print("you are not eligible")<file_sep>/Advanced/inheritence/single inheritance.py class School: schoolname="choice" def m1(self,place): self.place=place print("School name ",School.schoolname) print(self.place) class Student(School): def m2(self,student_name): self.student_name=student_name print(self.student_name,"is student at ",School.schoolname,"at ",self.place) obj=Student() obj.m1('trpntra') obj.m2('minnu') <file_sep>/Advanced/Regular Expression/irule.py #for chechikng whether the word is 6 letter word import re n="hellooo" x='\w{6}' match=re.fullmatch(x,n) if match is not None: print("valid") else: print("Invalid")<file_sep>/List/add element.py lst=[1] #append lst.append(10) lst.append("Minnu") lst.append("luminar") lst.extend([10,11,15,"Mariya"]) print(lst) #at a time can pass only 1 value <file_sep>/django/functional programmong/employee filter.py class Employee: def __init__(this,eid,ename,desig,salary): this.eid=eid this.ename=ename this.desig=desig this.salary=salary def print_emp(this): print(this.ename) e1=Employee(1089,"Minnu","developer",290000) e2=Employee(1010,"arun","developer",250000) e3=Employee(1025,"vivek","qa",280000) e4=Employee(1011,"athul","marketing",270000) employees=[] employees.append(e1) employees.append(e2) employees.append(e3) employees.append(e4) developers=list(filter(lambda emp: emp.desig=="developer",employees)) for dev in developers: print(dev) <file_sep>/Advanced/Test/Test 1/q02.py class Person: def m1(self,name): self.name=name class Address(Person): def m2(self,adrs): self.adrs=adrs print("Name: ",self.name) print("Address : ",self.adrs) class Mobile(Address): def m3(self,mob): self.mob=mob print("Mobile: ",self.mob) class Age: def m4(self,ageof): self.ageof=ageof class Weight: def m5(self,wght): self.wght=wght class Health(Age,Weight): def m6(self): print("Weght: ", self.wght) print("Age: ", self.ageof) print("End") obj=Mobile() obj.m1("Minnu") obj.m2("xyzzzzzzzzzzzz") obj.m3(9548754674) obj2=Health() obj2.m4(25) obj2.m5(50) obj2.m6()<file_sep>/List/element found.py lst=[10,2,33,35,4,6,8,10] num=int(input("enter your number")) flag=0 for i in lst: if(num==i): flag=1 break else: pass if(flag>0): print("number found") else: print("number not found") #linear Search- Each tym we have to pick one by one and check #complicity will be more #Binary Search <file_sep>/Advanced/two string method/enployee.py class Employee: companyname="luminar" def setvalue(self,id,name,age,salry): self.id=id self.name=name self.age=age self.salry=salry def printvalue(self): print("id = ",self.id) print("name= ",self.name) print("age= ",self.age) def __str__(self): return str(self.id) empl1=Employee() empl1.setvalue(1089,"rahul",26,20000) print(empl1) empl2=Employee() empl2.setvalue(1190,"Arun",28,25000) print(empl2) <file_sep>/django/functional programmong/intro.py # #add numbers() # #snake notation add_twonumbers # #camelnotation addTwo # # # add=lambda num1,num2:num1+num2 # print(add(200,300)) # # # # def cube(num): # # return num**3 # # # cube=lambda num:num**3 # print(cube(3)) #map() #filter() #reduce() # lst=[10,20,30,21,22] # squ=[] # for num in lst: # res=num**2 # squ.append(res) # print(squ) # #map - if we waant to perform a function on each object # two arguemnts should be there, enthu ftn aanu...eethu fnt nu aanu apply cheyyan ponathu # lst=[10,20,30,21,22] # def squ(no): # return no**2 # squres = list(map(squ,lst)) # print(squres) lst=[10,20,30,21,22] squres=list(map(lambda no:no**2,lst)) print(squres) #2 argument #1)fuction? #2)iterables lst=[10,20,2,3,45] cubes=list(map(lambda no:no**3,lst)) print(cubes) <file_sep>/Advanced/Polymophism/intro poly.py #ploymophism #poly - many #mophosm - forms #over loading - in inhertence if parent cls and child cls method name are same there will be confusion #over riding <file_sep>/Functions/w arguments and return.py # def add(num1,num2): # sum=num1+num2 # return sum # data=add(3,5) # print(data) # def sub(num1,num2): # result=num1-num2 # return result # data=sub(5,10) # print(data) def mul(num1,num2): result=num1*num2 return result data=mul(2,5) print(data)<file_sep>/List/even.py lst=[2,4,3,6,7,8,10,11,11,20,25] for i in lst: if(i%2==0): print(i) <file_sep>/set removal of duplicate.py lst=[18,2,45,23,18,2,1,2,34,35] #duplicate elements lst1=set(lst) print(lst1) <file_sep>/python database connection/pythontomsql.py #mysql- connector #step 1 -import mysql module import mysql.connector #step 2 - establish connection db=mysql.connector.connect( host="localhost", user="root", password="<PASSWORD>", auth_plugin='mysql_native_password' ) #step 3 - create curser object (for transporting data from and to ) cursor=db.cursor() #step 4- execute sql quries sql="select version()" cursor.execute(sql) data=cursor.fetchone() print(data) db.close() #step 5 - close database connection <file_sep>/Advanced/Polymophism/over loading.py class Person: def show(self,num1): self.num1=num1 print(self.num1) class Student(Person): def show(self,num2,num3): self.num2=num2 self.num3=num3 print(self.num2,self.num3) obj=Student() obj.show(2) #If given only one argument person show mwthod will work and 2 argument student show mwthod will work. This is overloading #overloading is not supported , so no output <file_sep>/django/functional programmong/reduce.py from functools import reduce lst=[10,20,30,50,80] total=reduce(lambda no1,no2:no1+no2,lst) max=reduce(lambda no1,no2:no1 if no1>no2 else no2,lst) min=reduce(lambda no1,no2:no1 if no1<no2 else no2,lst) print(total) print(max) print(min) # if (no<0): # return -ve # else: # return +ve # n1 if n1>n2 else no2<file_sep>/django/functional programmong/isl data.py isldata=[ {"team":"mumbai","mp":20,"won":12,"drawn":4,"los":4,"pts":40}, {"team":"atk","mp":20,"won":12,"drawn":4,"los":4,"pts":40}, {"team":"ne","mp":20,"won":8,"drawn":9,"los":3,"pts":33}, {"team":"tcg","mp":20,"won":7,"drawn":10,"los":3,"pts":31}, {"team":"hybd","mp":20,"won":6,"drawn":11,"los":3,"pts":29} ] #highest point points=max(list(map(lambda data:data["pts"],isldata))) hpt=list(filter(lambda team:team["pts"]==points,isldata)) print(max) print(hpt) fakr api<file_sep>/Advanced/Polymophism/over riding.py class Parent: def properties(self): print("10 l , 2 cars") def marry(self): print("with ram") class Child(Parent): def marry(self): print("with arun ") c=Child() c.marry() #child class method will over ride parent class #this is not averloading since there is no arguments<file_sep>/List/Nested list.py employee=[[1001,"arun",15000], [1002,"arjun",20000], [1003,"binu",13000]] #print(employee) #nested list - list inside list # #for getting each element # for i in employee: # print(i) # # #for collecting only names # for i in employee: # print(i[1]) # #print employee name whose salary greter than 17000 # for i in employee: # if(i[2]>17000): # print(i[1]) # #calculate total salary total=0 for i in employee: total=total+i[2] print(total) <file_sep>/django/functional programmong/listmap.py lst=[4,2,1,6,7,8] #output [3,1,0,7,8,9] otputlist=[] for i in lst: if(i>5): i+=1 otputlist.append(i) else: i -= 1 otputlist.append(i) print(otputlist)<file_sep>/List/intro.py #list #define # lst=[] #sqaure bracets are used to define,this is empty # st=list() #here list is a function # print(type(lst)) # print(type(st)) # #heterogenous or not # list=[10,10.5,"Minnu",True] # print(list) # #it support heterogenous data #Duplication or not # lst=[10,10,10.5,10.5] # print(lst) #it allow duplication #Insertion order preserved or not # lst=[10,10.5,"Minnu",0,1] # print(lst) # Insertion order is preserved # #Mutable or not # lst=[10,8,8,9,0,1,2] # #list have index starting from 0 to n-1. it is used to collect elements # #index value of 10 is 0 # print(lst[3]) # lst[1]=50 # print(lst) # #list is mutableand is done using the index vale <file_sep>/django/functional programmong/decorators/intro.py #in all cases smaller no should be substarcted from larger def decorator_fun(fun): # sub(10,20) #parameter should be a ftn def wrapper(n1,n2): #wrapper will be called on retuen wrapper if n1<n2: (n1,n2)=(n2,n1) return fun(n1,n2) return wrapper @decorator_fun def sub(num1,num2): return num1-num2 res=sub(10,20) print(res)<file_sep>/List/even and odd append.py lst=[] odd=[] even=[] for i in range(0,51): lst.append(i) print(lst) for i in lst: if(i%2==0): even.append(i) else: odd.append(i) print(even) print(odd)<file_sep>/Advanced/Test/Test 1/q3.py #3. Create a Book class with instance Library_name, book_name, author, pages? class Book: def __init__(self,library_name,book_name,author,pages): self.library_name=library_name self.book_name=book_name self.author=author self.pages=pages def printvalue(self): print("Library name: ",self.library_name) print("Book Name: ","self.book_name") print("Author :",self.author) print("Pages: ",self.pages) obj=Book("LMK","Promise","Nikitha ",150) obj.printvalue()<file_sep>/Looping/multiplication table.py #input a numb # 1 to 10 #1*6 #2*6 #3*6 number=int(input("eneter the number")) i=1 while(i<=10): result=i*number print(i,"*",number,"=",result) i=i+1 <file_sep>/Advanced/Constructor/intro.py # constructor: to initialise instance variables # it autimatically invoke when creating object class Employee(): companyname = "luminar" def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary def printValue(self): print("id", self.id) print("name", self.name) print("salary", self.salary) print("company name :", Employee.companyname) obj = Employee(1089, "ram", 2300) obj.printValue() <file_sep>/file/write.py f=open("demo01","w") f.write("hello")<file_sep>/Looping/sum of n numbers.py number=int(input("enter your number")) i=1 sum=0 while(i<=number): sum=sum+i i=i+1 print(sum)<file_sep>/django/functional programmong/filer intro.py # #filter(function ,iteration) # lst=[2,3,45,20,10] # even=list(filter(lambda no:no%2==0,lst)) # print(even) lst=["akhil","aravind","akshay","varun","vipin","ram"] aname=list(filter(lambda name:name[0]=="a",lst)) print(aname)<file_sep>/List/slicing.py lst=[5,41,51,25,50,18,25,85] print(lst[2]) print(lst[1:4]) print(lst[3;7]) print(lst[2;5]) print(lst[2:]) #2 to entire limit print(lst[:5]) #starting to fifth elemt,excluding lst[5] print(lst[-1]) #85 - negative indexing <file_sep>/Advanced/exception handling/index value.py a=[1,2,3,4,5] index=int(input("enter index value")) try: print(a[index]) except: print("error") <file_sep>/List/power.py lst=[10,20,21,22,23,24] # 10**1 #20**2 #21**3 l=len(lst) for i in range(0,l):
42ddde3ae707ea25329f360dea331f8ca5d4b0d8
[ "Python" ]
120
Python
MinnuMariyaJoy/luminarpythoncode
121a4e85ddb6a69f56b0c0d7830a360a9e427c0c
326b4a387b2599ef15d3138a2e1d214682c648f8
refs/heads/main
<repo_name>mdsayedarif84/git-upload-e-commerce<file_sep>/README.md #laravel-E-commerce <file_sep>/ecommerce/routes/web.php <?php use Illuminate\Support\Facades\Route; //front-end rout// Route::get('/',[ 'uses'=>'App\Http\Controllers\MyShopController@index', 'as' =>'/' ]); Route::get('/category-product',[ 'uses'=>'App\Http\Controllers\MyShopController@categoryProduct', 'as' =>'category-product' ]); Route::get('/mail-us',[ 'uses'=>'App\Http\Controllers\MyShopController@mailUs', 'as' =>'mail-us' ]); Route::get('/register',[ 'uses'=>'App\Http\Controllers\MyShopController@register', 'as' =>'register' ]); Route::get('/product-details',[ 'uses'=>'App\Http\Controllers\MyShopController@productDetails', 'as' =>'product-details' ]); Route::get('/shopping-cart',[ 'uses'=>'App\Http\Controllers\MyShopController@shoppingCart', 'as' =>'shopping-cart' ]); Route::get('/checkout',[ 'uses'=>'App\Http\Controllers\MyShopController@checkout', 'as' =>'checkout' ]); //Authentication file Auth::routes(); Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home'); <file_sep>/ecommerce/app/Http/Controllers/MyShopController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class MyShopController extends Controller{ public function index(){ return view('front-end.home.home'); } public function categoryProduct(){ return view('front-end.category.category-product'); } public function mailUs(){ return view('front-end.mail.mail-us'); } public function register(){ return view('front-end.register.register'); } public function productDetails(){ return view('front-end.product-details.product-details'); } public function shoppingCart(){ return view('front-end.cart.shopping-cart'); } public function checkout(){ return view('front-end.checkout.checkout'); } }
f11b030a46e1974d10f598e179a48cc225c8238f
[ "Markdown", "PHP" ]
3
Markdown
mdsayedarif84/git-upload-e-commerce
276c322d29011e837f81c6541fc77382560183a9
f1fa3e8290faf96b27fa10c6a4e84cad3a5d47e6
refs/heads/master
<file_sep>//navbar scroll behavior window.onscroll = function() {scrollFunction()}; function scrollFunction() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { document.getElementById("navbar").style.backgroundColor = "yellow"; document.getElementById("navbar").style.borderBottom = "1px solid gray"; } else { document.getElementById("navbar").style.backgroundColor= "transparent"; document.getElementById("navbar").style.borderBottom = "none"; } }
0740b071eb9511294f8ee66052670a6c3f929687
[ "JavaScript" ]
1
JavaScript
thea-fan/thea-fan.github.io
7e4f93294a53f3c39c0a4ca7d19ded95da019617
f03ed6900f5fefe2949782204c7f51f23dbc1520
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """ Created on Sat Aug 11 16:44:13 2018 @author: <NAME> """ import cv2 ''' img=cv2.imread(' ') img=cv2.imread(' ') print(img) imgr=cv2.resize(img,(600,600)) cv2.imshow('open',img) ''' cap=cv2.VideoCapture(0) face_recog=cv2.CascadeClassifier('C:\\New folder\\Lib\\site-packages\\cv2\\data\\haarcascade_frontalface_alt2.xml') while(True): ret,frame=cap.read() if ret: gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) faces=face_recog.detectMultiScale(gray,1.3,5) for x,y,w,h in faces: cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2) cv2.imshow("Finding faces...",frame) if cv2.waitkey(1)==27: break else: print("Camera not available") break cv2.destroyAllWindows()<file_sep>"# Python-opencv-projects"
8ee19c6a352621cda8654f1eba17c580e9aca67f
[ "Markdown", "Python" ]
2
Python
Shubham92166/Python-opencv-projects
77828fea05b3ada605776b63e7c4851ec5f9f8d4
a4f1e774493f41d48b25741f70eaf437e2449804
refs/heads/master
<repo_name>In2itive/WebBanking<file_sep>/Mobile Banking/scripts/config.js define([], function () { var domain = "www.kendouimusicstore.com", serverUrl = "http://" + domain, serviceUrl = serverUrl + "/Services/MusicStore.svc", staticUrl = "./scripts/app/data"; return { domain: domain, serverUrl: serverUrl, serviceUrl: serviceUrl, staticURL: staticUrl, homeUrl: staticUrl + "/homeData.json", branchesUrl: staticUrl + "/branches.json", accountsUrl: staticUrl + "/accountData.json", genresUrl: serviceUrl + "/Genres", artistsUrl: serviceUrl + "/Artists", albumsUrl: serviceUrl + "/Albums", loginUrl: serverUrl + "/Api/AccountApi", cartSubmitUrl: serverUrl + "/Api/CheckoutApi", orderHistoryUrl: serverUrl + "/OrderHistory" }; });<file_sep>/Mobile Banking/scripts/appData.js var AppData = function() { var _endpoints, _initialCards, _announcements, _private; _endpoints = { starbucksLocs: {path:"http://www.starbucks.com/api/location.ashx?&features=&lat={LAT}&long={LONG}&limit={MAX}", verb:"GET"}, starbucksTest: {path:"scripts/testData/starbucksTest.json", verb:"GET"}, branchData: {path:"scripts/branches.json", verb:"GET"} }; _initialCards = [ { "cardNumber":"461253932", "amount":20, "bonusPoints":60, "expireDate":"2013/12/06" },{ "cardNumber":"723128745", "amount":76, "bonusPoints":22, "expireDate":"2014/10/16" },{ "cardNumber":"912472185", "amount":104, "bonusPoints":56, "expireDate":"2014/11/24" } ]; _announcements = [ { title: "*NEW* BCU Mobile", description: "Enjoy the ease and convinence of mobile banking.", url: "images/mobile.png" }, { title: "Mobile Security", description: "The mobile app uses the same security creidetals as Web and Phone Banking. If you dont have access, Sign-up now.", url: "images/rewards.png" }, { title: "Locate Branches", description: "Use your current location to find the nerest BCU branch.", url: "images/cheers.png" }, { title: "More services", description: "Contact or visit a branch to utilise all the services BCU has to offer.", url: "images/hot-drink.png" } ]; _private = { load: function(route, options) { var path = route.path, verb = route.verb, dfd = new $.Deferred(); console.log("GETTING", path, verb, options); //Return cached data if available (and fresh) if (verb === "GET" && _private.checkCache(path) === true) { //Return cached data dfd.resolve(_private.getCache(path)); } else { //Get fresh data $.ajax({ type: verb, url: path, data: options, dataType: "json" }).success(function (data, code, xhr) { _private.setCache(path, { data: data, expires: new Date(new Date().getTime() + (15 * 60000)) //+15min }); dfd.resolve(data, code, xhr); }).error(function (e, r, m) { console.log("ERROR", e, r, m); dfd.reject(m); }); } return dfd.promise(); }, checkCache: function(path) { var data, path = JSON.stringify(path); try { data = JSON.parse(localStorage.getItem(path)); if (data === null || data.expires <= new Date().getTime()) { console.log("CACHE EMPTY", path); return false; } } catch (err) { console.log("CACHE CHECK ERROR", err); return false; } console.log("CACHE CHECK", true, path); return true; }, setCache: function(path, data, expires) { var cache = { data: data, expires: expires }, path = JSON.stringify(path); //TODO: Serialize JSON object to string localStorage.setItem(path, JSON.stringify(cache)); console.log("CACHE SET", cache, new Date(expires), path); }, getCache: function(path) { var path = JSON.stringify(path), cache = JSON.parse(localStorage.getItem(path)); console.log("LOADING FROM CACHE", cache, path); //TODO: Deserialize JSON string return cache.data.data; } }; return { getStarbucksLocations: function(lat, lng, max) { var route = $.extend({}, _endpoints.branchData); //route.path = route.path.replace(/{LAT}/g, lat); //route.path = route.path.replace(/{LONG}/g, lng); //route.path = route.path.replace(/{MAX}/g, max || 10); return _private.load(route, {}); }, getInitialCards: function() { return JSON.stringify(_initialCards); }, getAnnouncements: function() { return _announcements; } }; }<file_sep>/Mobile Banking/scripts/app/views/home-view.js define(["kendo", "app/data/data"], function (kendo, data) { return { viewModel: kendo.observable({ homeList: data.homeList }) }; });<file_sep>/Mobile Banking/scripts/app/views/accounts-view.js define(["kendo", "app/data/data"], function (kendo, data) { return { viewModel: kendo.observable({ accountsList: data.accountsList }), initAccounts: function() { } }; });
9f5cc8b3c716b9b50cd13bf1a12782b794ca19c2
[ "JavaScript" ]
4
JavaScript
In2itive/WebBanking
b7e8c131331e8e9eb0621640d171c8aab96cd658
5b4f587e7886b35ba4dfb946a638ba2cd9b9acbc
refs/heads/master
<file_sep>#!/bin/bash export PATH=/Library/Frameworks/Mono.framework/Commands:$PATH alias xbuild="/Library/Frameworks/Mono.framework/Commands/xbuild" alias XBuild="/Library/Frameworks/Mono.framework/Commands/xbuild" <file_sep>#load "./common.cake" /* mono \ ~/bin/tools/Cake/Cake.exe \ -verbosity=diagnostic Docs: https://github.com/cake-build/cake http://cakebuild.net/ http://cakebuild.net/docs/tutorials/getting-started http://redth.codes/would-you-like-some-csharp-in-your-cake/ http://patriksvensson.se/2014/07/its-not-a-party-without-cake/ http://cakebuild.net/addins?path= */ //################################################################################### // Externals setup // external files archives needed to build artifacts string folder_externals_extensive = System.IO.Path.Combine(".", "external", "binaries-xtensive"); string folder_externals_minimal = System.IO.Path.Combine(".", "external", "binaries-minimal"); Dictionary<string, string> files_external = new Dictionary<string, string>(); Task ("externals-download-holisticware") .Does ( () => { string fd = null; string fo = null; fd = System.IO.Path.Combine(folder_externals_extensive, "*.zip"); //DeleteFiles(fd); fd = System.IO.Path.Combine(folder_externals_extensive, "*.tar.*"); //DeleteFiles(fd); foreach(KeyValuePair<string, string> kvp in files_external) { fo = kvp.Value; fd = System.IO.Path.Combine(folder_externals_extensive, kvp.Key); Information (" fo = " + fo); Information (" fd = " + fd); if (fo.EndsWith(".git")) { Information (" fo = cloning" ); StartProcess ( "git", " clone --recursive " + kvp.Value + " " + fd ); } else { if (!FileExists(fd)) { DownloadFile (kvp.Value, fd); } } } } ); Task ("externals-unzip-holisticware") .IsDependentOn("externals-download-holisticware") .Does ( () => { } ); //################################################################################### // Library setup List<string> library_projectnames = new List<string>(); List<string> library_project_outputfiles = new List<string>(); List<OutputFileCopy> library_output_files_to_copy = new List<OutputFileCopy>(); <file_sep>#addin "Cake.Json" var TARGET = Argument ("target", Argument ("t", Argument ("Target", "build"))); var BUILD_INFO = DeserializeJsonFromFile<BuildInfo> ("./output/buildinfo.json"); var BUILD_GROUPS = BUILD_INFO.BuiltGroups; var BUILD_NAMES = Argument ("names", Argument ("name", Argument ("n", ""))) .Split (new [] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries); var BUILD_TARGETS = Argument ("targets", Argument ("build-targets", Argument ("build-targets", Argument ("build", "")))) .Split (new [] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries); // Print out environment variables to console var ENV_VARS = EnvironmentVariables (); Information ("Environment Variables: {0}", ""); foreach (var ev in ENV_VARS) Information ("\t{0} = {1}", ev.Key, ev.Value); public class BuildInfo { public List<BuildGroup> ManifestGroups { get; set; } public List<BuildGroup> BuiltGroups { get; set; } } public class BuildGroup { public BuildGroup () { Name = string.Empty; TriggerPaths = new List<string> (); TriggerFiles = new List<string> (); BuildTargets = new List<string> { "libs" }; } public string Name { get; set; } public FilePath BuildScript { get; set; } public List<string> TriggerPaths { get; set; } public List<string> TriggerFiles { get; set; } public List<string> BuildTargets { get; set; } } var NUGET_API_KEY = Argument ("nuget-api-key", ""); var NUGET_SOURCE = Argument ("nuget-publish-source", "https://www.nuget.com/api/v2/"); Task ("publish-nuget").Does (() => { var packages = new List<FilePath> (); // If a filter was specified use it if (BUILD_NAMES != null && BUILD_NAMES.Any ()) { var groupsToPublish = BUILD_GROUPS.Where (bg => BUILD_NAMES.Any (n => n.ToLower () == bg.Name.ToLower ())).ToList (); foreach (var buildGroup in groupsToPublish) { var buildScriptFilePath = new FilePath (buildGroup.BuildScript); packages.AddRange (GetFiles (MakeAbsolute (buildScriptFilePath.GetDirectory ()).FullPath.TrimEnd ('/') + "/**/*.nupkg")); } } else { // No name filters specified, so add all the nupkgs we can find packages.AddRange (GetFiles ("./**/*.nupkg")); } foreach (var pkg in packages) StartProcess ("nuget", string.Format ("push {0} -Source {1} -ApiKey {2}", MakeAbsolute (pkg).FullPath, NUGET_SOURCE, NUGET_API_KEY)); }); RunTarget (TARGET);<file_sep>//################################################################################### // Externals setup // external files archives needed to build artifacts string folder_externals_extensive = System.IO.Path.Combine(".", "external", "binaries-xtensive"); string folder_externals_minimal = System.IO.Path.Combine(".", "external", "binaries-minimal"); Dictionary<string, string> files_external = new Dictionary<string, string>(); Task("Setup-Externals-HolisticWare") .Does ( () => { foreach (KeyValuePair<string, string> kvp in files_external) { Information(kvp.Key + " = " + kvp.Value); //DownloadFile(kvp.Value, kvp.Key); } } ); //################################################################################### // Library setup // project names needed to build library (normal or bindings) List<string> library_projectnames = new List<string>(); List<string> library_project_outputfiles = new List<string>(); List<OutputFileCopy> library_output_files_to_copy = new List<OutputFileCopy>(); Task("SetupLibraryHolisticWare") .IsDependentOn("Setup-Externals-HolisticWare") .Does ( () => { foreach (string s in library_projectnames) { Information("output_file = " + output_file); string output_file = System.IO.Path.Combine(".", "source", "bin" ,"Release", s + ".dll"); OutputFileCopy ofc = new OutputFileCopy() { FromFile = output_file }; library_output_files_to_copy.Add(ofc); } } ) ; //################################################################################### // injecting setup steps - personal Task("Default").IsDependentOn("SetupLibraryHolisticWare"); <file_sep># Components.CI.WorkingInProgress Components.CI.WorkingInProgress
e9970ab4f059ead1fcf899fdade00ec8abc878fe
[ "Markdown", "C#", "Shell" ]
5
Shell
moljac/Components.CI.Published-Done
52bc4d0f84a562dc3e578889385dd2fe0002efb2
a6957bd508b1d379dd21268777100dcf580e625c
refs/heads/master
<repo_name>lgxbslgx/core_java_volume_one<file_sep>/src/chapter_3/TypeChange.java package chapter_3; /** * p44 * 强制类型转换 */ public class TypeChange { public static void main(String[] args) { double x = 9.997; int nx = (int)x;//直接截断小数部分 System.out.println(x); System.out.println(nx); nx = (int)Math.round(x);//四舍五入,Math.round的返回值是long型,所以要转换成int型 System.out.println(nx); } } <file_sep>/src/chapter_12/PairTest.java package chapter_12; /** * p530 * 使用泛型类Pair * 使用类ArrayAlg */ public class PairTest { public static void main(String[] args) { String[] words = {"Mary", "had", "a", "little", "lamb"}; Pair<String> pair = ArrayAlg.minmax(words); System.out.println("min = " + pair.getFirst()); System.out.println("max = " + pair.getSecond()); } } <file_sep>/src/chapter_14/threadPool/ThreadPoolTest.java package chapter_14.threadPool; import java.io.File; import java.util.concurrent.*; /** * p681 * 线程池 */ public class ThreadPoolTest { public static void main(String[] args) { String directory = "E:\\note"; String keyword = "java"; ExecutorService pool = Executors.newCachedThreadPool(); MatchCounter counter = new MatchCounter(new File(directory), keyword, pool); Future<Integer> result = pool.submit(counter); try { System.out.println(result.get() + " matching files."); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } pool.shutdown(); int largestPoolSize = ((ThreadPoolExecutor) pool).getLargestPoolSize(); System.out.println("largest pool size=" + largestPoolSize); } } <file_sep>/src/chapter_13/HashMapTest.java package chapter_13; import java.util.HashMap; import java.util.Map; /** * p589 * HashMap映射表 */ public class HashMapTest { public static void main(String[] args) { Map<String, String> staff = new HashMap<>(); staff.put("144-25-5464", "Amy"); staff.put("567-24-2546", "Harry"); staff.put("157-62-7935", "Gary"); staff.put("456-62-5527", "Francesca"); System.out.println(staff); staff.remove("567-24-2546"); staff.put("456-62-5527", "Fran"); System.out.println(staff.get("157-62-7935")); for (Map.Entry<String, String> entry : staff.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); System.out.println("key=" + key + ", value=" + value); } } } <file_sep>/src/chapter_13/TreeSetTest.java package chapter_13; import java.util.Comparator; import java.util.SortedSet; import java.util.TreeSet; /** * p582 * 比较,树集 */ public class TreeSetTest { public static void main(String[] args){ SortedSet<Item> parts = new TreeSet<>(); parts.add(new Item("Amy", 1234)); parts.add(new Item("widget", 4562)); parts.add(new Item("other", 9912)); System.out.println(parts); SortedSet<Item> sortByDesc = new TreeSet<>(new Comparator<Item>(){ @Override public int compare(Item o1, Item o2) { String desc_a = o1.getDescription(); String desc_b = o2.getDescription(); return desc_a.compareTo(desc_b); } }); sortByDesc.addAll(parts); System.out.println(sortByDesc); } } <file_sep>/src/chapter_3/StringNull.java package chapter_3; /** * p48 * 空串、Null串 */ public class StringNull { public static void main(String[] args) { String str = null; System.out.println(str); // System.out.println(str.length());//str为null,没有length } } <file_sep>/src/chapter_13/LinkedListTest.java package chapter_13; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * p569 * 链表LinkedList */ public class LinkedListTest { public static void main(String[] args) { List<String> staff = new LinkedList<>(); staff.add("Amy"); staff.add("Bob"); staff.add("Carl"); Iterator iterator = staff.iterator(); for(String elem : staff){ System.out.println(elem); } String first = (String)iterator.next(); String second = (String)iterator.next(); iterator.remove(); for(String elem : staff){ System.out.println(elem); } } } <file_sep>/src/chapter_14/synch/Bank.java package chapter_14.synch; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * p49 */ public class Bank { private final double[] accounts; private Lock bankLock; private Condition sufficientFunds; public Bank(int n, double init) { accounts = new double[n]; for (int i = 0; i < accounts.length; i++) { accounts[i] = init; } bankLock = new ReentrantLock(); sufficientFunds = bankLock.newCondition(); } public double getTotalBalance() { bankLock.lock(); try { double sum = 0; for (double a : accounts) { sum += a; } return sum; } finally { bankLock.unlock(); } } public int size() { return accounts.length; } } <file_sep>/src/chapter_13/HashSetTest.java package chapter_13; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * p578 * 散列集 */ public class HashSetTest { public static void main(String[] args) { Set<String> words = new HashSet<>(); long totalTime = 0; String[] str = {"Amy", "test", "mark", "size", "alice", "list", "fast", "host", "next"}; for (String s : str) { long callTime = System.currentTimeMillis(); words.add(s); callTime = System.currentTimeMillis() - callTime; totalTime += callTime; } Iterator<String> iterator = words.iterator(); for (int i = 1; i <= 20 && iterator.hasNext(); i++) { System.out.println(iterator.next()); } System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds."); } } <file_sep>/src/chapter_5/PersonTest.java package chapter_5; /** * p166 * 测试Person类 */ public class PersonTest { public static void main(String[] args) { Person[] people = new Person[2]; people[0] = new Employee("Amy", 50000, 1989, 10, 1); people[1] = new Student("mark", "computer science"); for (Person p : people) { System.out.println(p); System.out.println(); } } } <file_sep>/src/chapter_5/MaxTest.java package chapter_5; /** * p190 * 计算最大值 * 参数个数可变的方法 */ public class MaxTest { public static double max(double... values) { double largest = Double.MIN_VALUE; for (double value : values) { if (value > largest) { largest = value; } } return largest; } public static void main(String[] args) { double m = max(2.12, 212, 212212, 323.32, 312312.3211); System.out.println(m); } } <file_sep>/src/chapter_13/TreeSetTest2.java package chapter_13; import java.util.SortedSet; import java.util.TreeSet; /** * p579 * 树集 */ public class TreeSetTest2 { public static void main(String[] args) { SortedSet<String> sortedSet = new TreeSet<>(); sortedSet.add("Bob"); sortedSet.add("Amy"); sortedSet.add("Carl"); for (String s : sortedSet) { System.out.println(s); } } } <file_sep>/README.md 学习《java核心技术》卷一 原书第9版 中文版 写的代码<file_sep>/src/chapter_3/InputTest.java package chapter_3; import java.util.Scanner; /** * p55 * 输入、输出 * Scanner */ public class InputTest { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("What is your name?"); String name = scanner.nextLine(); System.out.println("How old are you?"); int age = scanner.nextInt(); System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1)); } } <file_sep>/src/chapter_3/BigIntegerTest.java package chapter_3; import java.math.BigInteger; import java.util.Scanner; /** * p77 * 计算中奖概率 * 大数值 */ public class BigIntegerTest { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the number: "); int num = scanner.nextInt();//中奖的数字个数 System.out.println("Enter the largest number: "); int largestNum = scanner.nextInt();//数字个数 BigInteger lotteryOdds = BigInteger.valueOf(1); for (int i = 1; i <= num; i++) { lotteryOdds = lotteryOdds.multiply(BigInteger.valueOf(largestNum - i + 1)).divide(BigInteger.valueOf(i)); } System.out.println("Your odds are 1 in " + lotteryOdds + ". Good luck!"); } } <file_sep>/src/chapter_3/VariableTest.java package chapter_3; /** * p37-p38 * 使用变量 * 变量声明后要初始化才能使用 */ public class VariableTest { public static void main(String[] args) { double salary = 65000.0; int vacationDays; System.out.println(salary); // System.out.println(vacationDays);//未初始化,出错 vacationDays = 12; System.out.println(vacationDays); } } <file_sep>/src/chapter_6/clone/CloneTest.java package chapter_6.clone; /** * p227 * 使用clone */ public class CloneTest { public static void main(String[] args) { try { Employee original = new Employee("Amy", 5000); original.setHireDay(1989, 12, 1); Employee copy = original.clone(); copy.raiseSalary(10); copy.setHireDay(2002, 1, 21); System.out.println("original = " + original); System.out.println("copy = " + copy); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } } <file_sep>/src/chapter_5/Manager.java package chapter_5; import chapter_4.Employee; /** * p156 * 管理员,继承普通员工 */ public class Manager extends Employee { private double bonus; /** * 构造函数 * * @param n 名字 * @param s 工作 * @param year 年 * @param month 月 * @param day 日 */ public Manager(String n, double s, int year, int month, int day) { super(n, s, year, month, day); bonus = 0; } public double getSalary() { double baseSalary = super.getSalary(); return baseSalary + bonus; } public void setBonus(double b) { bonus = b; } @Override public String toString() { return "name = " + getName() + "\nsalary = " + getSalary() + "\nhireDay = " + getHireDay() + "\n"; } } <file_sep>/problem.md ## 问题 ## - 3.6.6 代码点与代码单元 - p89 LotteryArray.java 没写 - p117 setOut、本地方法 不懂 - p140 类路径 - p178-p180 代码没写 - p193 5.7反射 没看 - p247 6.5代理 没看 - 第7、8、9、10章没看 - 第11章看得很快,特别是11.5日志这节 - p538-p559 12.6、12.7、12.8没看 - p637 14.4.3未捕获异常处理器 不懂 - 第14章“多线程”不是很懂 - 14.9.4 Fork-Join框架 不懂 - 14.10 同步器 14.11 线程与swing 没看
920b041340c1b809a7a0c8afd7be980e387c1ea0
[ "Markdown", "Java" ]
19
Java
lgxbslgx/core_java_volume_one
23be79527a198a7fd2201b05384c9d8eef1179e2
6ba55222141350b35a41fff08187c6707787090c
refs/heads/master
<repo_name>johnstonskj/pkgdep<file_sep>/src/main/java/org/johnstonshome/maven/pkgdep/goal/ListRepositoryGoal.java /* * Licensed Materials - Property of <NAME> (<EMAIL>) * (c) Copyright <NAME> 2009-2010. All rights reserved. * * For full license details, see the file LICENSE inncluded in the * distribution of this code. */ package org.johnstonshome.maven.pkgdep.goal; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.johnstonshome.maven.pkgdep.model.Repository; import org.johnstonshome.maven.pkgdep.model.RepositoryWalker; import org.johnstonshome.maven.pkgdep.model.VersionNumber; /** * This goal will list, in a hierarchical form, the contents of the local * package repository. The repository maps package/version pairs to one or more * artifact/version pairs. * * @goal list-repository * * @author simonjo (<EMAIL>) * */ public class ListRepositoryGoal extends AbstractMojo { private static final String PADDING = " "; //$NON-NLS-1$ private static final String HEADER_TEXT = Messages.getString("ListRepositoryGoal.headerText"); //$NON-NLS-1$ private static final String HEADER_UNDER = Messages.getString("ListRepositoryGoal.headerUnderline"); //$NON-NLS-1$ private static final String REPO_ROOT = Messages.getString("ListRepositoryGoal.repositoryRoot"); //$NON-NLS-1$ /* * Used to walk and print out the contents of the repository. */ class RepositoryWalkerImpl implements RepositoryWalker { public void startRepository(String name) { getLog().info(String.format(REPO_ROOT, name)); } public void endRepository() { } public void startPackage(String name) { getLog().info(name); } public void endPackage(String name) { } public void startPackageVersion(VersionNumber version) { getLog().info(PADDING + version.toString()); } public void endPackageVersion(VersionNumber version) { } public void artifact(String groupId, String artifactId, VersionNumber version) { getLog().info(PADDING + PADDING + groupId + ":" + artifactId); getLog().info(PADDING + PADDING + PADDING + version.toString()); } } /** * {@inheritDoc} */ public void execute() throws MojoExecutionException { getLog().info(HEADER_TEXT); getLog().info(HEADER_UNDER); final Repository repository = new Repository(); repository.setLog(this.getLog()); repository.walkRepository(new RepositoryWalkerImpl()); } } <file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.johnstonshome.maven</groupId> <artifactId>pkgdep-maven-plugin</artifactId> <packaging>maven-plugin</packaging> <name>Package Dependency Maven plugin</name> <version>0.0.1-SNAPSHOT</version> <url>http://code.google.com/p/pkgdep/</url> <scm> <connection>https://code.google.com/p/pkgdep</connection> </scm> <dependencies> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-plugin-api</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-project</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.1</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.0.2</version> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.5.1</version> <configuration> <instrumentation> <excludes> <exclude>org.johnstonshome.maven.pkgdep.goal.*</exclude> </excludes> </instrumentation> <check> <branchRate>0</branchRate> <lineRate>0</lineRate> <totalBranchRate>0</totalBranchRate> <totalLineRate>0</totalLineRate> </check> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.0-beta-2</version> <configuration> <reportPlugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.7</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jxr-plugin</artifactId> <version>2.1</version> <configuration> <aggregate>true</aggregate> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-report-plugin</artifactId> <version>2.6</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.4</version> <configuration> <formats> <format>xml</format> <format>html</format> </formats> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.6</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>findbugs-maven-plugin</artifactId> <version>2.3</version> <configuration> <findbugsXmlOutput>true</findbugsXmlOutput> <findbugsXmlWithMessages>true</findbugsXmlWithMessages> <threshold>Low</threshold> <effort>Max</effort> <xmlOutput>true</xmlOutput> </configuration> </plugin> </reportPlugins> </configuration> </plugin> </plugins> </build> </project> <file_sep>/src/main/java/org/johnstonshome/maven/pkgdep/goal/ExportGoal.java /* * Licensed Materials - Property of <NAME> (<EMAIL>) * (c) Copyright <NAME> 2009-2010. All rights reserved. * * For full license details, see the file LICENSE inncluded in the * distribution of this code. * */ package org.johnstonshome.maven.pkgdep.goal; import java.io.File; import java.io.FilenameFilter; import java.util.LinkedList; import java.util.List; import org.apache.maven.model.Resource; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.johnstonshome.maven.pkgdep.model.Artifact; import org.johnstonshome.maven.pkgdep.model.Package; import org.johnstonshome.maven.pkgdep.model.Repository; import org.johnstonshome.maven.pkgdep.model.VersionNumber; import org.johnstonshome.maven.pkgdep.parse.ImportExportParser; /** * This goal scans certain known locations for exported packages from this * project. * * @phase initialize * @goal export * * @author simonjo (<EMAIL>) * */ public class ExportGoal extends AbstractMojo { private static final String MANIFEST_FILE = "MANIFEST.MF"; //$NON-NLS-1$ /** * {@inheritDoc} */ public void execute() throws MojoExecutionException { /* * The list of all discovered packages. */ final List<Package> packages = new LinkedList<Package>(); /* * Copy of the Maven local POM */ final MavenProject project = (MavenProject) this.getPluginContext() .get("project"); /* * The default target for any discovered package. */ final Artifact thisBundle = new Artifact(project.getGroupId(), project.getArtifactId(), new VersionNumber(project.getVersion())); /* * The parser for Export-Package decalarations. */ final ImportExportParser parser = new ImportExportParser(); /* * Find any static MANIFEST.MF file(s) */ getLog().info(String.format("Processing %s files...", MANIFEST_FILE)); if (project.getBuild().getResources() != null) { for (final Object resource : project.getBuild().getResources()) { final File resourceDir = new File( ((Resource) resource).getDirectory()); final File[] manifests = resourceDir .listFiles(new FilenameFilter() { public boolean accept(final File dir, final String name) { return name.equals(MANIFEST_FILE); } }); for (final File manifest : manifests) { getLog().info(manifest.getPath()); packages.addAll(parser .parseManifestExports(manifest, project.getBuild() .getSourceDirectory(), thisBundle)); } } } /* * Look for the felix bundle plugin */ getLog().info( String.format("Processing %s content...", ImportExportParser.PLUGIN_ARTIFACT)); packages.addAll(parser.parsePomExports(project, thisBundle)); final Repository repository = new Repository(); for (final Package found : packages) { getLog().info(found.getName() + ":" + found.getVersions()); final Package local = repository.readPackage(found.getName()); if (local != null) { local.merge(found); repository.writePackage(local); } else { repository.writePackage(found); } } } } <file_sep>/src/main/java/org/johnstonshome/maven/pkgdep/model/Package.java /* * Licensed Materials - Property of <NAME> (<EMAIL>) * (c) Copyright <NAME> 2009-2010. All rights reserved. * * For full license details, see the file LICENSE inncluded in the * distribution of this code. * */ package org.johnstonshome.maven.pkgdep.model; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * This class models a Java package in the repository, each package has 0..n * identified versions and each version then has 0..n artifacts identified that * provide that package/version. The key methods here are those that * <i>resolve</i> a package a version(s) to zero or more implementing artifacts. * * @author simonjo (<EMAIL>) * */ public class Package { private static final String COLON = ":"; //$NON-NLS-1$ private static final String COMMA = ","; //$NON-NLS-1$ private static final int FIELD_GROUP = 0; private static final int FIELD_ARTIFACT = 1; private static final int FIELD_VERSION = 2; private static final int FIELDS = 3; /* * The fully-qualified name of a Java package. */ private final String name; /* * The internal map holding implementing artifacts. */ private final Map<VersionNumber, Set<Artifact>> artifacts = new HashMap<VersionNumber, Set<Artifact>>(); /** * Construct an empty package. * * @param name * the name of the package in its canonical Java form. */ public Package(final String name) { if (name == null) { throw new IllegalArgumentException( "Invalid package name, may not be null"); } this.name = name; } /** * Construct a Package instance from a standard Java properties file, that * is a set of identifiers of the form: * * <pre> * version=group:artifact:version * </pre> * * @param name * the name of the package in its canonical Java form. * @param properties * a property object to extract versions and artifacts from. */ public Package(final String name, final Properties properties) { this(name); if (properties == null) { throw new IllegalArgumentException( "Invalid properties, may not be null"); } for (final Object key : properties.keySet()) { final VersionNumber version = new VersionNumber((String) key); if (!artifacts.containsKey(version)) { artifacts.put(version, new HashSet<Artifact>()); } /* * Read comma-separated list. */ final String[] contents = ((String) properties.get(key)) .split(COMMA); for (final String artifact : contents) { final String[] parts = artifact.split(COLON); if (parts.length != FIELDS) { throw new IllegalArgumentException(); } artifacts.get(version).add( new Artifact( parts[FIELD_GROUP], parts[FIELD_ARTIFACT], new VersionNumber(parts[FIELD_VERSION]))); } } } /** * Return the fully qualified name of the Java package represented by this * model object. * * @return the Java package name. */ public String getName() { return this.name; } /** * Return the set of all versions known for this package, note that by * returning this as a sorted set you can enumerate the versions in order * from first to last. * * @return a {@link SortedSet} instance holding all versions of this * package. */ public SortedSet<VersionNumber> getVersions() { return new TreeSet<VersionNumber>(this.artifacts.keySet()); } /** * Return the latest version of this package in the repository. * * @return the latest version of this package. */ public VersionNumber getLatestVersion() { return new TreeSet<VersionNumber>(this.artifacts.keySet()).last(); } /** * Resolve a version number, that is return the set of all artifacts that * implement this package <b>at exactly this</b> version. * * @param version * the version to resolve * @return the set of all artifacts implementing the specified version. */ public Set<Artifact> resolve(final VersionNumber version) { if (version == null) { throw new IllegalArgumentException( "Invalid version, may not be null"); } return this.artifacts.get(version); } /** * Resolve all packages that implement this package with a version number * <b>greater than, or equal to</b> (depending on * <code>startInclusive</code>) the version <code>start</code>. * * @param start * the lower bound version to compare to * @param startInclusive * whether or not this is an inclusive search, for example if * this is <code>true</code> then the test is effectively * <i>greater or equal</i>, whereas if this is <code>false</code> * then the test is effectively <i>greater than</i> only. * @return the set of all artifacts implementing the specified version. */ public Set<Artifact> resolve(final VersionNumber start, final boolean startInclusive) { if (start == null) { throw new IllegalArgumentException( "Invalid start version, may not be null"); } Set<Artifact> results = new HashSet<Artifact>(); for (final VersionNumber version : this.artifacts.keySet()) { final int startComp = version.compareTo(start); if (startComp > 0 || (startInclusive && startComp == 0)) { results.addAll(this.artifacts.get(version)); } } return results; } /** * Resolve all packages that implement this package with a version number * <b>greater than, or equal to</b> (depending on * <code>startInclusive</code>) the version <code>start</code> <b>and</b> * also <b>less thatm or equal to</b> (depending on * <code>endInclusive</code>) the version <code>end</code>. * * @param start * the lower bound version to compare to * @param startInclusive * whether or not this is an inclusive search, for example if * this is <code>true</code> then the test is effectively * <i>greater than or equal</i>, whereas if this is * <code>false</code> then the test is effectively <i>greater * than</i> only. * @param end * the upper bound version to compare to * @param endInclusive * whether or not this is an inclusive search, for example if * this is <code>true</code> then the test is effectively <i>less * than or equal</i>, whereas if this is <code>false</code> then * the test is effectively <i>less than</i> only. * @return the set of all artifacts implementing the specified version. */ public Set<Artifact> resolve(final VersionNumber start, final boolean startInclusive, final VersionNumber end, final boolean endInclusive) { if (start == null) { throw new IllegalArgumentException( "Invalid start version, may not be null"); } if (end == null) { throw new IllegalArgumentException( "Invalid end version, may not be null"); } Set<Artifact> results = new HashSet<Artifact>(); for (final VersionNumber version : this.artifacts.keySet()) { final int startComp = version.compareTo(start); final int endComp = version.compareTo(end); if ((startComp > 0 || (startInclusive && startComp == 0)) && (endComp < 0 || (endInclusive && endComp == 0))) { results.addAll(this.artifacts.get(version)); } } return results; } /** * Add an artifact that implements a specified version of this package. * * @param packageVersion * the version of the package * @param artifact * the implementation artifact. */ public void addArtifact(final VersionNumber packageVersion, final Artifact artifact) { if (packageVersion == null) { throw new IllegalArgumentException( "Invalid package version, may not be null"); } if (artifact == null) { throw new IllegalArgumentException( "Invalid artifact, may not be null"); } if (!this.artifacts.containsKey(packageVersion)) { this.artifacts.put(packageVersion, new HashSet<Artifact>()); } this.artifacts.get(packageVersion).add(artifact); } /** * Merge another package's contents into this package. * * @param other * the package to merge from, into <code>this</code>. */ public void merge(final Package other) { if (other == null) { throw new IllegalArgumentException( "Invalid package, may not be null"); } if (!this.name.equals(other.name)) { throw new IllegalArgumentException( "Invalid package name, must be same"); } for (final VersionNumber version : other.getVersions()) { if (!this.artifacts.containsKey(version)) { this.artifacts.put(version, new HashSet<Artifact>()); } for (final Artifact artifact : other.resolve(version)) { this.artifacts.get(version).add(artifact); } } } /** * Return this package instance serialized into a Java {@link Properties} * instance. This is the reverse of the constructor * {@link #Package(String, Properties)}. * * @return the content of this package serialized. */ public Properties toProperties() { final Properties properties = new Properties(); for (final VersionNumber version : getVersions()) { final StringBuilder value = new StringBuilder(); /* * Make comma-separated list */ final Iterator<Artifact> iterator = resolve(version).iterator(); while (iterator.hasNext()) { value.append(iterator.next().toString()); if (iterator.hasNext()) { value.append(COMMA); } } properties.put(version.toString(), value.toString()); } return properties; } } <file_sep>/src/main/java/org/johnstonshome/maven/pkgdep/goal/messages.properties ListRepositoryGoal.headerText=Listing local package repository ListRepositoryGoal.headerUnderline================================= ListRepositoryGoal.repositoryRoot=Repository root: %s <file_sep>/src/main/java/org/johnstonshome/maven/pkgdep/goal/Messages.java /* * Licensed Materials - Property of <NAME> (<EMAIL>) * (c) Copyright <NAME> 2009-2010. All rights reserved. * * For full license details, see the file LICENSE inncluded in the * distribution of this code. * */ package org.johnstonshome.maven.pkgdep.goal; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * This is a static resource used to wrap access to a message bundle for all * externalized (and potentially localized) strings. * * @author simonjo (<EMAIL>) * */ final class Messages { private static final String BUNDLE_NAME = "org.johnstonshome.maven.pkgdep.goal.messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); private Messages() { } /** * Return a string from the message bundle. * * @param key * the key for the externalized string. * @return value of the externalized string, or <code>"!{key}!"</code> if * the key was not found in the message bundle. */ public static String getString(final String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } } <file_sep>/src/test/java/org/johnstonshome/maven/pkgdep/model/VersionNumberTest.java /* * Licensed Materials - Property of <NAME> (<EMAIL>) * (c) Copyright <NAME> 2009-2010. All rights reserved. * * For full license details, see the file LICENSE inncluded in the * distribution of this code. * */ package org.johnstonshome.maven.pkgdep.model; import junit.framework.Assert; import org.junit.Test; /** * Test cases for {@link VersionNumber}. * * @author simonjo (<EMAIL>) * */ public class VersionNumberTest { @Test public void testConstructNulls() { try { @SuppressWarnings("unused") VersionNumber test = new VersionNumber((String) null); Assert.fail("Should not allow null"); } catch (IllegalArgumentException ex) { // ignore, success } try { @SuppressWarnings("unused") VersionNumber test = new VersionNumber((Integer) null); Assert.fail("Should not allow null"); } catch (IllegalArgumentException ex) { // ignore, success } try { @SuppressWarnings("unused") VersionNumber test = new VersionNumber(1, (Integer) null); Assert.fail("Should not allow null"); } catch (IllegalArgumentException ex) { // ignore, success } try { @SuppressWarnings("unused") VersionNumber test = new VersionNumber(1, 2, (Integer) null); Assert.fail("Should not allow null"); } catch (IllegalArgumentException ex) { // ignore, success } try { @SuppressWarnings("unused") VersionNumber test = new VersionNumber(1, 2, 3, (Integer) null); Assert.fail("Should not allow null"); } catch (IllegalArgumentException ex) { // ignore, success } try { @SuppressWarnings("unused") VersionNumber test = new VersionNumber(1, 2, 3, (String) null); Assert.fail("Should not allow null"); } catch (IllegalArgumentException ex) { // ignore, success } } @Test public void testParseString() { VersionNumber test = new VersionNumber("1"); Assert.assertEquals("1.0.0", test.toCanonicalString()); test = new VersionNumber("1.2"); Assert.assertEquals("1.2.0", test.toCanonicalString()); test = new VersionNumber("1.2.3"); Assert.assertEquals("1.2.3", test.toCanonicalString()); test = new VersionNumber("1.2.3.99"); Assert.assertEquals("1.2.3.99", test.toCanonicalString()); test = new VersionNumber("1.2.3-TEST"); Assert.assertEquals("1.2.3-TEST", test.toCanonicalString()); } @Test public void testParseBadStrings() { testBadString("BAD"); testBadString("A.1.1.99"); testBadString("1.A.1.99"); testBadString("1.1.A.99"); testBadString("1.1.1.AA"); testBadString("1.1.1-"); testBadString("1.1.1-SOME QUALIFIER"); testBadString("1.1.1-SOME QUALIFIER"); // preserve TAB in string } @Test public void testToString() { VersionNumber test = new VersionNumber(1); Assert.assertEquals("1", test.toString()); test = new VersionNumber(1, 0); Assert.assertEquals("1.0", test.toString()); test = new VersionNumber(1, 0, 2); Assert.assertEquals("1.0.2", test.toString()); test = new VersionNumber(1, 0, 2, 99); Assert.assertEquals("1.0.2.99", test.toString()); test = new VersionNumber(1, 0, 2, "TEST"); Assert.assertEquals("1.0.2-TEST", test.toString()); } @Test public void testToCanonicalString() { VersionNumber test = new VersionNumber(1); Assert.assertEquals("1.0.0", test.toCanonicalString()); test = new VersionNumber(1, 0); Assert.assertEquals("1.0.0", test.toCanonicalString()); test = new VersionNumber(1, 0, 2); Assert.assertEquals("1.0.2", test.toCanonicalString()); test = new VersionNumber(1, 0, 2, 99); Assert.assertEquals("1.0.2.99", test.toCanonicalString()); test = new VersionNumber(1, 0, 2, "TEST"); Assert.assertEquals("1.0.2-TEST", test.toCanonicalString()); } @Test public void testEquals() { final VersionNumber test = new VersionNumber("1.2.3-TEST"); Assert.assertTrue(test.equals(test)); Assert.assertFalse(test.equals(null)); Assert.assertTrue(equals("1", "1")); Assert.assertTrue(equals("1", "1.0")); Assert.assertTrue(equals("1", "1.0.0")); Assert.assertTrue(equals("1.0", "1.0")); Assert.assertTrue(equals("1.0.0", "1.0.0")); Assert.assertTrue(equals("1.0.0.99", "1.0.0.99")); Assert.assertTrue(equals("1-TEST", "1.0.0-TEST")); Assert.assertTrue(equals("1.0-TEST", "1.0.0-TEST")); Assert.assertTrue(equals("1.0.0-TEST", "1.0.0-TEST")); Assert.assertFalse(equals("2", "1")); Assert.assertFalse(equals("2", "1.0")); Assert.assertFalse(equals("2", "1.0.0")); Assert.assertFalse(equals("2.0", "1.0")); Assert.assertFalse(equals("2.0.0", "1.0.0")); Assert.assertFalse(equals("2.0.0.99", "1.0.0.99")); Assert.assertFalse(equals("2-TEST", "1.0.0-TEST")); Assert.assertFalse(equals("2.0-TEST", "1.0.0-TEST")); Assert.assertFalse(equals("2.0.0-TEST", "1.0.0-TEST")); Assert.assertFalse(equals("1", "1.0.0.0")); Assert.assertFalse(equals("1", "1.0.0-TEST")); } @Test public void testCompareTo() { // LHS == RHS Assert.assertEquals(0, compare("1", "1")); Assert.assertEquals(0, compare("1", "1.0")); Assert.assertEquals(0, compare("1", "1.0.0")); Assert.assertEquals(0, compare("1.0", "1")); Assert.assertEquals(0, compare("1.0.0", "1")); Assert.assertEquals(0, compare("1.0", "1.0")); Assert.assertEquals(0, compare("1.0.0", "1.0.0")); Assert.assertEquals(0, compare("1.0.0.99", "1.0.0.99")); Assert.assertEquals(0, compare("1.0.0-TEST", "1.0.0-TEST")); // LHS < RHS Assert.assertEquals(-1, compare("1", "2")); Assert.assertEquals(-1, compare("1", "2.0")); Assert.assertEquals(-1, compare("1", "2.0.0")); Assert.assertEquals(-1, compare("1", "1.1")); Assert.assertEquals(-1, compare("1", "1.1.1")); Assert.assertEquals(-1, compare("1", "1.0.1")); Assert.assertEquals(-1, compare("1.0", "2")); Assert.assertEquals(-1, compare("1.0.0", "2")); Assert.assertEquals(-1, compare("1.0", "2.0")); Assert.assertEquals(-1, compare("1.0.0", "2.0.0")); Assert.assertEquals(-1, compare("1.0.0.99", "2.0.0.99")); Assert.assertEquals(-1, compare("1.0.0.98", "1.0.0.99")); Assert.assertEquals(-1, compare("1.0.0-TEST", "2.0.0-TEST")); // LHS > RHS Assert.assertEquals(1, compare("2", "1")); Assert.assertEquals(1, compare("2", "1.0")); Assert.assertEquals(1, compare("2", "1.0.0")); Assert.assertEquals(1, compare("2.0", "1")); Assert.assertEquals(1, compare("2.0.0", "1")); Assert.assertEquals(1, compare("2.0", "1.0")); Assert.assertEquals(1, compare("2.0.0", "1.0.0")); Assert.assertEquals(1, compare("2.0.0.99", "1.0.0.99")); Assert.assertEquals(1, compare("2.0.0-TEST", "1.0.0-TEST")); } private boolean equals(final String lhs, final String rhs) { return new VersionNumber(lhs).equals(new VersionNumber(rhs)); } private int compare(final String lhs, final String rhs) { return new VersionNumber(lhs).compareTo(new VersionNumber(rhs)); } private void testBadString(final String versionString) { try { @SuppressWarnings("unused") final VersionNumber number = new VersionNumber(versionString); Assert.fail(String.format( "Version string '%s' should have thrown an exception.", versionString)); } catch (IllegalArgumentException ex) { // ignore, this is success } } } <file_sep>/src/test/java/org/johnstonshome/maven/pkgdep/parse/ImportExportParseTest.java /* * Licensed Materials - Property of <NAME> (<EMAIL>) (c) * Copyright <NAME> 2009-2010. All rights reserved. For full license * details, see the file LICENSE inncluded in the distribution of this code. */ package org.johnstonshome.maven.pkgdep.parse; import java.io.File; import java.util.List; import junit.framework.Assert; import org.johnstonshome.maven.pkgdep.model.Artifact; import org.johnstonshome.maven.pkgdep.model.Package; import org.johnstonshome.maven.pkgdep.model.VersionNumber; import org.junit.Test; /** * Test the ImportExportParser class * * @author simonjo * */ public class ImportExportParseTest { private final String srcDir = "src/test/resources/root"; private final Artifact defaultArtifact = new Artifact("example", "test", new VersionNumber("1.0.1")); @Test public void testExportPackageStringOne() { final ImportExportParser parser = new ImportExportParser(); final String test = "com.example.api"; final List<Package> packages = parser.parseExport(test, srcDir, defaultArtifact); Assert.assertEquals(1, packages.size()); Assert.assertEquals("com.example.api", packages.get(0).getName()); Assert.assertEquals(1, packages.get(0).getVersions().size()); Assert.assertEquals("1.0.1", packages.get(0).getVersions().first() .toString()); } @Test public void testExportPackageStringTwo() { final ImportExportParser parser = new ImportExportParser(); final String test = "com.example.api, com.example.model"; final List<Package> packages = parser.parseExport(test, srcDir, defaultArtifact); Assert.assertEquals(2, packages.size()); Assert.assertEquals("com.example.api", packages.get(0).getName()); Assert.assertEquals("com.example.model", packages.get(1).getName()); Assert.assertEquals(1, packages.get(0).getVersions().size()); Assert.assertEquals("1.0.1", packages.get(0).getVersions().first() .toString()); Assert.assertEquals(1, packages.get(1).getVersions().size()); Assert.assertEquals("1.0.1", packages.get(1).getVersions().first() .toString()); } @Test public void testExportPackageStringVersioned() { final ImportExportParser parser = new ImportExportParser(); final String test = "com.example.api; version=1.5, com.example.model"; final List<Package> packages = parser.parseExport(test, srcDir, defaultArtifact); Assert.assertEquals(2, packages.size()); Assert.assertEquals("com.example.api", packages.get(0).getName()); Assert.assertEquals("com.example.model", packages.get(1).getName()); Assert.assertEquals(1, packages.get(0).getVersions().size()); Assert.assertEquals("1.5", packages.get(0).getVersions().first() .toString()); Assert.assertEquals(1, packages.get(1).getVersions().size()); Assert.assertEquals("1.0.1", packages.get(1).getVersions().first() .toString()); } @Test public void testExportPackageStringWild() { final ImportExportParser parser = new ImportExportParser(); final String test = "com.example.*"; final List<Package> packages = parser.parseExport(test, srcDir, defaultArtifact); Assert.assertEquals(4, packages.size()); } @Test public void testExportPackageStringWildExclude() { final ImportExportParser parser = new ImportExportParser(); final String test = "!com.example.impl, com.example.*"; final List<Package> packages = parser.parseExport(test, srcDir, defaultArtifact); Assert.assertEquals(3, packages.size()); } @Test public void testManifestExports() { final ImportExportParser parser = new ImportExportParser(); final List<Package> packages = parser.parseManifestExports(new File( "src/test/resources/TEST_MANIFEST.MF"), "src/test/resources", defaultArtifact); Assert.assertEquals(3, packages.size()); Assert.assertEquals("org.wikipedia.helloworld", packages.get(0) .getName()); Assert.assertEquals(1, packages.get(0).getVersions().size()); Assert.assertEquals("1.0.0", packages.get(0).getVersions().first() .toString()); Assert.assertEquals("org.wikipedia.test", packages.get(1).getName()); Assert.assertEquals(1, packages.get(1).getVersions().size()); Assert.assertEquals("1.5.0", packages.get(1).getVersions().first() .toString()); } } <file_sep>/src/main/java/org/johnstonshome/maven/pkgdep/model/Artifact.java /* * Licensed Materials - Property of <NAME> (<EMAIL>) * (c) Copyright <NAME> 2009-2010. All rights reserved. * * For full license details, see the file LICENSE inncluded in the * distribution of this code. * */ package org.johnstonshome.maven.pkgdep.model; /** * An artifact here represents a specific tuple (groupId, artifactId, version) * that uniquely identifies a version of an artifact in Maven. Such an artifact * is assumed to be either a jar file or OSGi bundle that provides a package * that is registered in the local package dependency repository. * * Note that this is an immutable object once constructed, there are no mutators * and all fields are final. * * @author simonjo (<EMAIL>) * */ public final class Artifact { private final String groupId; private final String artifactId; private final VersionNumber version; private final int hash; /** * Construct a new artifact based on the standard Maven identifiers. * * @param groupId * the Maven group ID * @param artifactId * the Maven artifact ID * @param version * the version of this artifact */ public Artifact(final String groupId, final String artifactId, final VersionNumber version) { if (groupId == null) { throw new IllegalArgumentException( "Invalid group ID, may not be null"); } if (artifactId == null) { throw new IllegalArgumentException( "Invalid artifact ID, may not be null"); } if (version == null) { throw new IllegalArgumentException( "Invalid version, may not be null"); } this.groupId = groupId; this.artifactId = artifactId; this.version = version; /* * Pre-calculate as these are used in sets and maps that use hashCode a * lot. The following is null-safe as both this and other are immutable * and do not allow nulls in their constructors. */ int hash = 0; hash = 31 * hash + this.groupId.hashCode(); hash = 31 * hash + this.artifactId.hashCode(); hash = 31 * hash + this.version.hashCode(); this.hash = hash; } /** * The Maven group ID of this artifact. * * @return the Maven group ID */ public String getGroupId() { return this.groupId; } /** * The Maven artifact ID of this artifact. * * @return the Maven artifact ID */ public String getArtifactId() { return this.artifactId; } /** * The Maven version of this artifact. * * @return the Maven version */ public VersionNumber getVersion() { return this.version; } /** * {@inheritDoc} */ @Override public int hashCode() { return hash; } /** * {@inheritDoc} */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if ((obj == null) || (obj.getClass() != this.getClass())) { return false; } final Artifact other = (Artifact) obj; /* * The following is null-safe as both this and other are immutable and * do not allow nulls in their constructors. */ return (this.groupId == other.groupId || this.groupId .equals(other.groupId)) && (this.artifactId == other.artifactId || this.artifactId .equals(other.artifactId)) && (this.version == other.version || this.version .equals(other.version)); } /** * {@inheritDoc} */ @Override public String toString() { return String.format("%s:%s:%s", this.groupId, this.artifactId, this.version); } } <file_sep>/README.md Maven plugin to resolve dependencies by package, not artifact. The goal is to provide a build model that parallels the runtime model provided by OSGi. [http://www.theserverside.com/feature/Successful-modularity-depends-on-your-dependency-model Successful modularity depends on your dependency model]
49353f524ec70bcbff17b662efb4f0f38694263a
[ "Markdown", "Java", "Maven POM", "INI" ]
10
Java
johnstonskj/pkgdep
e9ef5bdd11cc11d3c229adb2acaf8d134f3b2bbc
7c41058a1109c368fbdbca9a8dff5d45e95a6928
refs/heads/master
<repo_name>shota-co/cebutern<file_sep>/page-intern.php <?php get_header();?> <div class="container_12" id="article_main"> <div class="grid_12" > <?php if(have_posts()): while(have_posts()): the_post(); ?> <h1><?php the_title();?></h1> <?php endwhile; endif; ?> </div> </div><!--end main--> <div class="grid_12" id="f_sns_action"> <h3>記事をシェアする</h3> <a href="https://twitter.com/share" class="twitter-share-button" data-via="cebutern">Tweet</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> </div> <?php get_footer();?><file_sep>/contact_theme.php <?php /* Template Name: contact_theme */ ?> <?php if(is_mobile()) { ?> <?php get_header("mb");?> <?php } else { ?> <?php get_header();?> <?php } ?> <!--パソコン--> <div class="mb_hidden"> <h1>お問い合わせフォーム</h1> <p>留学・インターンシップのご相談・ご質問はこのお問い合わせフォームからお気軽にご連絡ください。こちらのフォームよりお問い合わせいただきますと原則翌営業日以内にご返信させていただきます。</p> <span style="text-decoration: underline;"><span style="font-size: 16pt;">※既に選考を申し込みたい企業様が決まっている方は<a href="http://intern-college.com/apply/">お申込みフォーム</a>よりお申込みいただければスムーズに選考のご案内をすることが可能です。</span></span> <p style="text-align: right;"><span style="font-size: 16pt;">&gt;&gt;<a href="http://intern-college.com/apply/">お申込みフォーム</a></span></p> <div id="article_main"> &nbsp; <span class="resizeimg">[trust-form id=1707]</span> &nbsp; <p>不具合でフォームをご利用できない場合、お手数ですが<EMAIL>まで直接ご連絡ください。</p> <p> もし送信後2日以上経過してメールが届かない場合は、迷惑メールやごみ箱を点検し、それでもメールが届いてない場合には、お手数をお掛けしますが、再度お問い合わせください。</> </div> </div> <!--パソコンここまで--> <!--スマホ--> <div class="pc_hidden"> <h1>お問い合わせフォーム</h1> <p>留学・インターンシップのご相談・ご質問はこのお問い合わせフォームからお気軽にご連絡ください。こちらのフォームよりお問い合わせいただきますと原則翌営業日以内にご返信させていただきます。</p> <span style="text-decoration: underline;"><span style="font-size: 16pt;">※既に選考を申し込みたい企業様が決まっている方は<a href="http://intern-college.com/apply/">お申込みフォーム</a>よりお申込みいただければスムーズに選考のご案内をすることが可能です。</span></span> <p style="text-align: right;"><span style="font-size: 16pt;">&gt;&gt;<a href="http://intern-college.com/apply/">お申込みフォーム</a></span></p> <div> &nbsp; <span class="resize"><?php get_template_part( 'trustform', '1707' ); ?></span> &nbsp; <p>不具合でフォームをご利用できない場合、お手数ですが<EMAIL>まで直接ご連絡ください。</p> <p> もし送信後2日以上経過してメールが届かない場合は、迷惑メールやごみ箱を点検し、それでもメールが届いてない場合には、お手数をお掛けしますが、再度お問い合わせください。</> </div> </div> <!--スマホここまで--> <?php if(is_mobile()):?> <!--モバイルのヘッダー読み込み--> <?php get_footer("mb");?> <?php else: ?> <?php get_footer();?> <?php endif;?> <file_sep>/front-page.php <?php if (is_mobile()) :?> <?php get_header("mb");?> <?php else: ?> <?php get_header();?> <?php endif; ?> <div class="container_12" id="main"> <title>フィリピンセブ島No.1の海外インターンシップ求人サイト|セブターン</title> <div class="grid_12 alpha" id="front_intern_title"> <h1 class="content_title" id="start">新着インターンシップ情報</h1> </div> <!--記事の取得--> <?php $args = array( 'numberposts' => 6, //表示(取得)する記事の数 'post_type' => 'intern' //投稿タイプの指定 ); $customPosts = get_posts($args); if($customPosts) : foreach($customPosts as $post) : setup_postdata( $post ); ?> <!--ここまで--> <!--記事表示部分PC用--> <section class="grid_4 omega alpha f_article mb_hidden"> <figure class="label inside bottom f_thum" data-label="<?php the_title(); ?>"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a></figure> <div class="f_article_labels"> <ul> <li><a href="<?php the_permalink(); ?>">期間:<?php echo esc_html($post->cf_min_day); ?>〜</a></li> <li><a href="<?php the_permalink(); ?>">授業数:<?php echo esc_html($post->cf_tuition); ?></a></li> <li><a href="<?php the_permalink(); ?>">勤務地:<?php echo esc_html($post->area); ?></a></li> <ul> </div> <div class="f_article_tags"> <a href="<?php the_permalink(); ?>">企業 No.<?php echo esc_html(get_post_meta($post->ID, 'cf_no', true)); ?></a> <a id="f_business" href="<?php the_permalink(); ?>"><?php echo esc_html($post->cf_business); ?></a> <div class="clear"></div> <div class="primary_btn_wrapper"><a class="primary_btn" href="<?php the_permalink(); ?>" >インタビュー記事を見る</a></div> </div> </section> <!--スマホ用レイアウト--> <div class="container-fluid"> <section class="pc_hidden row article_wrap"> <a class="col-xs-4" href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a> <div class="mb_top_article_detail col-xs-8"> <a class="col-xs-8 mb_front_article_title" href="<?php the_permalink(); ?>"><p class="mb_front_no">No.<?php echo esc_html($post->cf_no); ?></p><?php the_title(); ?></a> <div class="clearfix"></div> <ul class="intern_tags"> <li class="tag_a"><a href="<?php the_permalink(); ?>"><?php echo esc_html($post->cf_min_day); ?>〜</a></li> <li class="tag_b"><a href="<?php the_permalink(); ?>"><?php echo esc_html($post->area); ?></a></li> <li class="tag_c"><a href="<?php the_permalink(); ?>">授業数:<?php echo esc_html($post->cf_tuition); ?></a></li> </ul> </div> </section> </div> <!--記事が取得できなかった場合--> <?php endforeach; ?> <?php else : //記事が無い場合 ?> <li><p>記事はまだありません。</p></li> <?php endif; wp_reset_postdata(); //クエリのリセット ?> <!--ここまで--> <div class="clear"></div> <div class="grid_12 mb_hidden" id="top_archive_btn"> <a class="" href="http://intern-college.com/search_intern/">インターン先一覧を見る</a> </div> <div class="container-fluid"> <div class="row"> <a class=" btn_blue large_btn col-xs-12 pc_hidden"href="http://intern-college.com/search_intern/">インターン先一覧を見る</a> </div> </div> <!-- ブログ記事 --> <div class="container_12 container-fluid" id="blog_wrapper"> <div class="row"> <h1 class="col-xs-12 secondary_content_title">新着ブログ・コラム</h1> </div> <div class="clear"></div> <div class="grid_12"> <!--記事の取得--> <?php $args = array( 'numberposts' => 5, //表示(取得)する記事の数 'post_type' => 'blog' //投稿タイプの指定 ); $customPosts = get_posts($args); if($customPosts) : foreach($customPosts as $post) : setup_postdata( $post ); ?> <!--ここまで--> <!--記事表示部分--> <div class="grid_12 alpha top_blog_article mb_hidden"> <div class="grid_3 omega"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a></div> <div class="grid_8 push_1"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></div> <div class="grid_7 push_1"><?php the_excerpt(); ?></div> </div><!--f_wrapper end--> <!--モバイル--> <section class="article_wrap pc_hidden row"> <a class="col-xs-4" href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a> <a class="col-xs-8 mb_front_article_title mb_front_blog_title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </section> <!--ここまで--> <!--記事が取得できなかった場合--> <?php endforeach; ?> <?php else : //記事が無い場合 ?> <li><p>記事はまだありません。</p></li> <?php endif; wp_reset_postdata(); //クエリのリセット ?> <div class="clear"></div> <div class="grid_12"id="top_archive_btn"> <a class="mb_hidden" href="http://intern-college.com/column-blog/">ブログ・コラム一覧を見る</a> </div> <div class="container-fluid pc_hidden"> <div class="row"> <a class="btn_orange large_btn col-xs-12" href="http://intern-college.com/column-blog/">ブログ・コラム一覧を見る</a> </div> </div> </div><!--row end--> </div><!--blog_wrapper end--> <!--新着情報の表示--> <div class="container-fluid container_12" id="news_wrapper"> <div class="grid_12 alpha row" id="front_news_theme"> <h1 class="col-xs-12 third_content_title grid_12 ">新着情報</h1> </div><!--front_news_theme end--> <?php $newslist = get_posts( array( 'field' => 'news', 'posts_per_page' => 5 //取得記事件数 )); foreach( $newslist as $post ): setup_postdata( $post ); ?> <p><?php the_time('Y年n月j日'); ?></p> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?></a> <?php endforeach; wp_reset_postdata(); ?> </div> </div> <?php if(is_mobile()):?> <!--モバイルのヘッダー読み込み--> <?php get_footer("mb");?> <?php else: ?> <?php get_footer();?> <?php endif;?> <file_sep>/conditions.php <?php /* Template Name: tag-intern */ ?> <?php get_header(); ?> <div class="container_12"> <div id="main" class="grid_12 tag_btn"> <h1>条件で検索</h1> <ul> <li> <?php wp_tag_cloud( array( 'taxonomy'=>'intern-tag', // 最小フォント指定 'smallest'=>'12', // 最大フォント指定 'largest'=>'12' ) ); ?> </li> </ul> </div> </div> <?php get_footer(); ?> <file_sep>/single.php <?php get_header();?> <div class="container_12" id="main"> <div class="grid_12" id="article_main"> <?php if(have_posts()): while(have_posts()): the_post(); ?> <h1 class="article_title"><?php the_title();?></h1> <div class="grid_12 post_thum"> <?php the_post_thumbnail(); ?> </div> <?php the_content();?> <?php endwhile; endif; ?> </div> </div><!--end main--> <?php get_footer();?><file_sep>/table-numbers.php <div> <tr> <th>企業No.</th> <td><?php echo esc_html($post->cf_no); ?></td> </tr> </div><file_sep>/student_member_theme.php <?php /* Template Name: recruit_member_theme */ ?> <?php get_header();?> <div class="container_12 recruit_member_wrapper"> <div class="grid_12 article_main"> <h1>セブターンを共に拡大していく運営メンバーを募集中!</h1> <img class="eye_catch" id="member_logo" src="<?php bloginfo('template_url');?>/images/logo.png"/> <div class="clear"></div> <p>セブターンは「海外に挑戦したい若者に良質な情報を提供し、グローバル化対応への成長機会を提供する」をビジョンに掲げるフィリピン・セブ島No.1の海外インターンシップ求人サイトです。</p> <br /> <p>2015年10月にはHPを全面リニューアルし、海外インターンシップや留学に関して日々お問い合わせ・お申し込みをいただいております。</p> <br /> <p>そしてこの度、より大きな飛躍を目指して共に良質なサービスを提供していく同志を求め、今回の募集に至りました。</p> <br /> <ul> <li>・何か今までにやったことがないような面白い経験がしたい!</li> <li>・フィリピン留学や海外インターンの経験を活かしたい!</li> <li>・海外を舞台にしたwebサービス創りをしてみたい!</li> </ul> </br> <p>そんなあなたと一緒にセブターンを創っていきたいです!</p> </div> <div class="grid_12 article_main"> <h2>こんなことをやってもらいたい</h2> <h3>カスタマーサポート</h3> <img class="grid_6" src="<?php bloginfo('template_url');?>/images/theme_img/article_member4.jpg"/> <p>お客様の要望に合ったインターン先や留学先を提案し、カウンセリングや渡航までの準備を全面サポートします。 フィリピン留学や海外インターンの経験を最も活かすことができます。</p></br> <ul>【得られるもの】 <li>コミュニケーション能力</li> <li>ヒアリング力</li> <li>提案力</li> </ul> </div> <div class="grid_12 article_main"> <h3>Webエンジニア</h3> <img class="grid_6" src="<?php bloginfo('template_url');?>/images/theme_img/article_member5.jpg"/> <p>HTML、CSS、PHP、Javascript、JQueryなどを使用してHPの構築、サービス開発をします。 上記の言語を勉強中でスキルを向上させたい方も大歓迎です。</p></br> <ul>【得られるもの】 <li>プログラミングスキル</li> <li>サービス開発経験</li> <li>論理的思考力</li> </ul> </div> <div class="grid_12 article_main"> <h3>Webデザイナー</h3> <img class="grid_6" src="<?php bloginfo('template_url');?>/images/theme_img/article_member6.png"/> <p>マーケティングの数値分析と連携して改善を重ね、HPをUI/UXの観点からwebデザインを構築します。 グラフィックやLP作成などもどんどんお任せしたいと思っています。</p></br> <ul>【得られるもの】 <li>webデザインスキル</li> <li>サービス開発経験</li> <li>課題解決力</li> </ul> </div> <div class="grid_12 article_main"> <h3>Webマーケティング</h3> <img class="grid_6" src="<?php bloginfo('template_url');?>/images/theme_img/article_member7.jpg"/> <p>ユーザーの行動分析、トラフィックの観点は勿論、SNSの運用など幅広く関わります。 アナリティクス等の分析ツールを使っての戦略策定から実行まで全て見ることができます。</p></br> <ul>【得られるもの】 <li>webマーケティングスキル</li> <li>戦略立案・実行経験</li> <li>課題発見力</li> </ul> </div> <div class="grid_12 article_main"> <h3>Webライター</h3> <img class="grid_6" src="<?php bloginfo('template_url');?>/images/theme_img/article_member8.jpg"/> <p>海外インターンやフィリピン留学に関する有益な記事をwordpress上で書いてもらいます。 ご自身の経験、フィリピンやセブ島に関する情報を求めている人に素敵な情報を届けましょう!</p></br> <ul>【得られるもの】 <li>webライティングスキル</li> <li>情報収集・発信力</li> <li>マーケティング視点</li> </ul> </div> <div class="grid_12 article_main"> <h2>こんな人たちと一緒に運営したい</h2> <img id="member_logo" src="<?php bloginfo('template_url');?>/images/theme_img/article_member_1.jpg"/> <div class="clear"></div> <h3>海外に興味がある、フィリピンやセブ島が好き!</h3> <p>海外、特にフィリピンやセブ島に対して共通の興味関心を持つ方と一緒に運営していきたいと考えています。 好きなこと、興味があることにはとことん本気になれる、そんな方と一緒に運営していきたいです。</p> <h3>誰かに何かを与えることが好き!</h3> <p>セブターンは海外に挑戦したい人をサポートすることを目的としています。 自己満足で終わることなく、常にユーザー目線で考えられる方と一緒に運営したいと思っています。</p> <h3>自ら積極的に考え、動ける!</h3> <p>セブターンはまだまだ発展の途上です。やることもたくさんありますが、その分やれることもたくさんあります。 各自が頭をひねって積極的に提案し、どんどん実行していく風土を作りたいと思っています。</p> </div> <div class="grid_12 article_main"> <h2>運営メンバー特典</h2> <img id="member_logo" src="<?php bloginfo('template_url');?>/images/theme_img/article_member9.jpg"/> <div class="clear"></div> <h3>①プログラム参加料が無料 ※webライター以外</h3> <p>運営メンバーの方はセブターンの<p class="article_attention">プログラム参加料が無料<p>になります。</p> <p>海外インターンの参加を全面バックアップしますので、是非挑戦してみてください!</p> <h3>②キャッシュバックあり ※webライターのみ</h3> <p>ライターの方には<p class="article_attention">10記事更新に付き5000円</p>(フィリピンならビールが50本分)をキャッシュバックします。</p> <p>ご自身のスキル向上のための目標にも役立ててもらえればと思います。</p> </div> <div class="grid_12 contact_form article_main"> <h2>運営メンバーに興味のある方はこちら</h2> <?php echo do_shortcode('[trust-form id=2630]'); ?> </div> <div class="grid_12 article_main recruit_text"> <p>ご応募頂いた方から順にお話させていただきたいと思っています。(※遠方の方はSkypeでお話しましょう!)</p> <p>現在のスキルよりもやる気やサービスへの共感を重視しますので、未経験、スキルに自信がない方にもご安心を。</p> <p>「海外に挑戦したい若者に良質な情報を提供し、グローバル化対応への成長機会を提供したい」</p> <p>という方のご応募お待ちしております!</p> </div> </div><!--wrapper end--> <?php get_footer();?><file_sep>/table-intern.php <table> <tr> <th>企業No.</th> <td><?php echo esc_html($post->cf_no); ?></td> </tr> <tr> <th>業種</th> <td><?php echo esc_html($post->cf_business); ?></td> </tr> <tr> <th>受け入れ期間</th> <td><?php echo esc_html($post->cf_min_day); ?>&#xFF5E;<?php echo esc_html($post->cf_max_day); ?></td> </tr> <tr> <th>勤務地</th> <td> <?php echo esc_html($post->area); ?> </td> </tr> <tr> <th>勤務日数・勤務時間</th> <td><?php echo esc_html($post->cf_work_day); ?>&#xFF5E;<?php echo esc_html($post->cf_work_time); ?></td> </tr> <tr> <th>無料英語授業数</th> <td><?php echo esc_html(get_post_meta($post->ID, 'cf_tuition', true)); ?></td> </tr> <tr> <th>食事補助</th> <td><?php echo esc_html($post->cf_meal); ?></td> </tr> <tr> <th>住宅補助</th> <td><?php echo esc_html($post->cf_lifeline); ?></td> </tr> <tr> <th>VISA補助</th> <td><?php echo esc_html($post->cf_visa); ?></td> </tr> <tr> <th>業務内容</th> <td><?php echo esc_html($post->cf_business_content); ?></td> </tr> <tr> <th>求める英語力</th> <td><?php echo esc_html($post->cf_english_skill); ?></td> </tr> <tr> <th>補足備考</th> <td><?php echo esc_html($post->cf_remarks); ?></td> </tr> </table> <file_sep>/pager.php <div class="pager container_12 col-xs-12 col-md-12"> <!--▼ページ送り▼--> <?php $prevpost = get_adjacent_post(false, '', true); //前の記事 $nextpost = get_adjacent_post(false, '', false); //次の記事 if( $prevpost or $nextpost ){ //前の記事、次の記事いずれか存在しているとき ?> <?php if ( $prevpost ) { //前の記事が存在しているとき echo '<div class="col-xs-6 col-md-6 grid_6"> <p>前の記事</p> <a href="' . get_permalink($prevpost->ID) . '"> <span class="grid_3">' . get_the_post_thumbnail($prevpost->ID, '') . '</span> <span class="pager_title">' . get_the_title($prevpost->ID) . '</span> </a> <p class="pager_author">' . get_the_author($prevpost->ID) . '</p> </div>'; } else { //前の記事が存在しないとき echo '<div class="alignleft nopost"> <a class="grid_5 col-xs-6 pager_start_btn" href="#start">TOPへ戻る</a> </div>'; } if ( $nextpost ) { //次の記事が存在しているとき echo '<div class="col-xs-6 col-md-6 grid_6"> <p>次の記事</p> <a href="' . get_permalink($nextpost->ID) . '"> <span class="grid_3">' . get_the_post_thumbnail($nextpost->ID, '') . '</span> <span class="pager_title">' . get_the_title($nextpost->ID) . '</span> </a> <p class="pager_author">' . get_the_author($prevpost->ID) . '</p> </div>'; } else { //次の記事が存在しないとき echo '<div class="alignright nopost"> <a class="grid_5 col-xs-6 pager_start_btn" href="#start">TOPへ戻る</a> </div>'; } ?> <?php } ?> <!--▲ページ送り▲--> </div><file_sep>/table-internTop.php <table> <tr> <th>業種</th> <td><?php echo esc_html($post->cf_business); ?></td> </tr> <tr> <th>受け入れ期間</th> <td><?php echo esc_html($post->cf_min_day); ?>&#xFF5E;<?php echo esc_html($post->cf_max_day); ?></td> </tr> <tr> <th>英語授業数</th> <td><?php echo esc_html(get_post_meta($post->ID, 'cf_tuition', true)); ?></td> </tr> <tr> <th>勤務地</th> <td><?php echo esc_html($post->area); ?></td> </tr> </table><file_sep>/footer-mb.php </div><!--wrap end--> <!-- フッターここから --> <footer class="container-fluid footer_wrap"> <img class="footer_img" src="<?php bloginfo('stylesheet_directory');?>/images/footer_bg.png" alt=""> <div class="row footer"> <a class="col-xs-12" href="">運営メンバー</a> <a class="col-xs-12" href="">運営メンバー募集</a> <a class="col-xs-12" href="">掲載企業様へ</a> <a class="col-xs-12" href="">個人情報の取り扱いについて</a> </div> </footer> <!-- フッターここまで --> <!--ハンバーガーjavascripit--> <script src="//cdnjs.cloudflare.com/ajax/libs/headroom/0.7.0/headroom.min.js"></script> <script> // enabling to open the overflow menu as the pure css link // would toggle a scroll and therefore hide the menu document.getElementById("paradeiser-dropdown").addEventListener("click", function(event){ // stopping the scroll event.preventDefault(); // toggling the class document.getElementById("paradeiser-more").classList.toggle("open"); }); // hide the menu on click onto greybox document.getElementById("greybox").addEventListener("click", function(event){ // stopping the scroll event.preventDefault(); // toggling the class document.getElementById("paradeiser-more").classList.remove("open"); }); // enabling headroom var myElement = document.querySelector(".paradeiser"); var headroom = new Headroom(myElement, { tolerance : 5, onUnpin : function() { document.getElementById("paradeiser-more").classList.remove("open"); } }); headroom.init(); </script> <!--ここまで--> <!-- facebookのスクリプト --> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/ja_JP/sdk.js#xfbml=1&version=v2.0"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <!-- twitterのスクリプト --> <script> !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https'; if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js'; fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs'); </script> <?php wp_footer();?> </body> </html><file_sep>/page.php <?php if(is_mobile()) { ?> <?php get_header("mb");?> <?php } else { ?> <?php get_header();?> <?php } ?> <div class="container_12" id="main"> <?php if(have_posts()): while(have_posts()): the_post(); ?> <h1 class="grid_12 col-xs-12 content_title content_title_margin"><?php the_title();?></h1> <?php the_content();?> <?php endwhile; endif; ?> </div><!--end main--> <div style="height:100%;"> </div> <?php if(is_mobile()):?> <!--モバイルのヘッダー読み込み--> <?php get_footer("mb");?> <?php else: ?> <?php get_footer();?> <?php endif;?> <file_sep>/question_theme2.php <?php /* Template Name: question_theme2 */ ?> <?php if(is_mobile()) { ?> <?php get_header("mb");?> <?php } else { ?> <?php get_header();?> <?php } ?> <div class="container_12" id="q_a_wrapper"> <div class="grid_12" id="q_a"> <h1 class="grid_12 col-xs-12 content_title content_title_margin">よくある質問</h1> <!--パソコン版--> <div class="grid_12 mb_hidden"> <div class="grid_6 alpha" id="question_nabi"> <ul> <li><a href="#q_cebu"><button class="btn_gray">1.フィリピン・セブ島について</button></a></li> <li><a href="#q_intern"><button class="btn_gray">2.インターンシップについて</button></a></li> <li><a href="#q_request"><button class="btn_gray">3.お問い合わせ・お申込みについて</button></a></li> </ul> </div><!--question_nabi--> <div class="grid_6 omega" id="question_nabi"> <ul> <li><a href="#q_rule"><button class="btn_gray">4.インターンシップ参加契約について</button></a></li> <li><a href="#q_ready"><button class="btn_gray">5.事前準備について</button></a></li> <li><a href="#q_life"><button class="btn_gray">6.現地での生活について</button></a></li> </ul> </div><!--question_nabi--> </div> <!--モバイル版--> <div class="grid_12 pc_hidden m_question_navi"> <div class="grid_6 alpha"> <ul> <li><a href="#mb_q_cebu"><button class="btn_gray">1.フィリピン・セブ島について</button></a></li> <li><a href="#mb_q_intern"><button class="btn_gray">2.インターンシップについて</button></a></li> <li><a href="#mb_q_request"><button class="btn_gray">3.お問い合わせ・お申込みについて</button></a></li> </ul> </div><!--question_nabi--> <div class="grid_6 omega"> <ul> <li><a href="#mb_q_rule"><button class="btn_gray">4.インターンシップ参加契約について</button></a></li> <li><a href="#mb_q_ready"><button class="btn_gray">5.事前準備について</button></a></li> <li><a href="#mb_q_life"><button class="btn_gray">6.現地での生活について</button></a></li> </ul> </div><!--question_nabi--> </div> <!--パソコン用--> <div class="grid_12 alpha omega mb_hidden" id="q_cebu"> <h2>フィリピン・セブ島について</h2> <p id="question">Q.フィリピン人の英語の訛りは強いですか?</p> <p id="answer">A.講師にもよりますが、特に訛りは気になりません。フィリピンでは、英語を公用語として幼少期から教育や日常の中で使用しています。 その影響でフィリピンは世界で3番目に英語を話す人口が多い国です。2012年に行われたGlobal English社(米国)の調査によると、フィリピン人のビジネス英語運用能力はアメリカを抜いて第1位にもなりました。</p> <p id="question"><h3>Q.セブ島の治安はどうですか?</h3></p> <p id="answer">A.セブ島は国際観光都市として有名で、フィリピンの中でも比較的治安のよい場所です。 しかし、もちろん海外なので日本に比べると危険です。例えばスリや置き引き、日本人をターゲットとする詐欺事件もあります。 日本の常識とは違うということ念頭に置いて注意を払い、危険を未然に防ぐ意識が必要です。</p> <p id="question"><h3>Q.セブ島の気候はどうですか?</h3></p> <p id="answer">A.フィリピンは熱帯性気候のため、年間を通じて日本の夏のような気候です。セブ島も年中温暖な気候で過ごしやすいです。季節は2種類しかなく、6月~11月の雨季と12月~5月までの乾季です。</p> <p id="question"><h3>Q.セブ島の物価はいくらくらいですか?</h3></p> <p id="answer">A.フィリピンの物価は日本の3分の1から5分の1と言われています。 フィリピンの通貨はペソで、1ペソ≒2.3円です。(2014年6月現在) 一般的に、セブやマニラでのタクシー初乗り料金は約40ペソ、映画は90ペソ、飲み屋ではビール1本50ペソ前後など、日本と比べるとかなり低価格です。</p> <p id="question"><h3>Q.セブ島の食事や水は安全ですか?</h3></p> <p id="answer">A.必ずしも安全とは言い切ることはできません。寮で提供される食事は衛生的にも安心できますが、屋台などで外食する際には注意が必要です。特に水道水は飲めませんので、各滞在場所に設置されている無料の給水器をご利用ください。不安のある方は日本から腹痛に効くお薬を持っていかれることをお勧めします。</p> </div> <!--パソコン用ここまで--> <!--スマホ用--> <!--1/29 1--> <div id="mb_q_cebu"> <br /> <br /> </div> <div class="grid_12 alpha omega pc_hidden menu_fqa fqa"> <h2>フィリピン・セブ島について</h2> <button class="btn_fqa"><label for="Panel1"><h3>Q.フィリピン人の英語の訛りは強いですか?</h3></label></button> <input type="checkbox" id="Panel1" class="on-off" /> <ul><li><h3>A.講師にもよりますが、特に訛りは気になりません。フィリピンでは、英語を公用語として幼少期から教育や日常の中で使用しています。 その影響でフィリピンは世界で3番目に英語を話す人口が多い国です。2012年に行われたGlobal English社(米国)の調査によると、フィリピン人のビジネス英語運用能力はアメリカを抜いて第1位にもなりました。</h3></li></ul> <button class="btn_fqa"><label for="Panel2"><h3>Q.セブ島の治安はどうですか?</h3> <input type="checkbox" id="Panel2" class="on-off" /><ul><li><h3>A.セブ島は国際観光都市として有名で、フィリピンの中でも比較的治安のよい場所です。 しかし、もちろん海外なので日本に比べると危険です。例えばスリや置き引き、日本人をターゲットとする詐欺事件もあります。 日本の常識とは違うということ念頭に置いて注意を払い、危険を未然に防ぐ意識が必要です。</h3></li></ul> <button class="btn_fqa"><label for="Panel3"><h3>Q.セブ島の気候はどうですか?</h3> <input type="checkbox" id="Panel3" class="on-off" /><ul><li><h3>A.フィリピンは熱帯性気候のため、年間を通じて日本の夏のような気候です。セブ島も年中温暖な気候で過ごしやすいです。季節は2種類しかなく、6月~11月の雨季と12月~5月までの乾季です。</h3></li></ul> <button class="btn_fqa"><label for="Panel4"><h3>Q.セブ島の物価はいくらくらいですか?</h3> <input type="checkbox" id="Panel4" class="on-off" /><ul><li><h3>A.フィリピンの物価は日本の3分の1から5分の1と言われています。 フィリピンの通貨はペソで、1ペソ≒2.3円です。(2014年6月現在) 一般的に、セブやマニラでのタクシー初乗り料金は約40ペソ、映画は90ペソ、飲み屋ではビール1本50ペソ前後など、日本と比べるとかなり低価格です。</h3></li></ul> <button class="btn_fqa"><label for="Panel5"><h3>Q.セブ島の食事や水は安全ですか?</h3> <input type="checkbox" id="Panel5" class="on-off" /><ul><li><h3>A.必ずしも安全とは言い切ることはできません。寮で提供される食事は衛生的にも安心できますが、屋台などで外食する際には注意が必要です。特に水道水は飲めませんので、各滞在場所に設置されている無料の給水器をご利用ください。不安のある方は日本から腹痛に効くお薬を持っていかれることをお勧めします。</h3></li></ul> </div> <!--スマホ用ここまで--> <!--パソコン用--> <div class="grid_12 alpha omega mb_hidden" id="q_intern"> <h2>インターンシップについて</h2> <p id="question"><h3> Q.インターンシップの費用は半年間でいくらくらいですか?</h3></p> <p id="answer">A.受け入れ先企業様によりますが、大体半年間で30万円~40万円といったところです。 受け入れ企業様の多くが1日3食の食費、寮滞在費、1日3時間~4時間の英語マンツーマン授業、(VISA代)を無償で提供してくださります。 つまり、インターン生にご負担して頂くのは往復航空券、保険代、交通費、その他娯楽費になりますので、航空券をセール時に購入したり、旅行や外食を抑えたりすればより費用を抑えることが可能です。 ご質問いただけましたらより詳細は費用についてお話させていただきます。</p> <p id="question"><h3>Q.インターンシップは有給ですか?無給ですか?</h3></p> <p id="answer">A.VISAの関係上、原則として給料の支給はありません。 その代わり、業務の対価として食費、滞在費、英語マンツーマン授業、VISA等を無償で提供してくださります。</p> <p id="question"><h3>Q.短期でのインターンシップも可能ですか?</h3></p> <p id="answer">A.募集は少なくなりますが、可能です。語学学校でのインターンシップの場合、半年間~が一般的ですが、半年未満でも募集している語学学校もございます。企業でのインターンシップの場合、1か月~募集されている企業様もありますので、夏休みや春休み等の長期休暇を利用した短期での応募も歓迎しております。</p> <p id="question"><h3>Q.英語が話せませんが、インターンシップに参加することはできますか?</h3></p> <p id="answer">A.大丈夫です。インターン先によってはそれほど高い英語力を必要とされていない場合もあります。また、ほとんどの企業様が1日3時間~4時間の英語マンツーマン授業を無償で提供してくださりますので、英語を日々学びながら業務をこなすことができます。不安がありましたら受け入れ先企業の社員の方に直接質問してみてください。</p> <p id="question"><h3>Q英語力によって任される仕事は変わりますか?</h3></p> <p id="answer">A. 企業様により異なりますが、多くの場合、多少変わってきます。例えば韓国人やフィリピ ン人スタッフとのミーティングや、講師のマネジメント、英語での来客対応や電話対応等です。事前に英語力を身に着けたいという方はインターンシップ前に留学される方が多いです。インターンシップ前の留学については是非お任せください。</p> </div> <!--パソコン用ここまで--> <!--スマホ用--> <div id="mb_q_intern"> <br /> <br /> </div> <div class="grid_12 alpha omega pc_hidden menu_fqa fqa"> <h2>インターンシップについて</h2> <button class="btn_fqa"><label for="Panel6"><h3> Q.インターンシップの費用は半年間でいくらくらいですか?</h3></label></button> <input type="checkbox" id="Panel6" class="on-off" /><ul><li><h3>A.受け入れ先企業様によりますが、大体半年間で30万円~40万円といったところです。 受け入れ企業様の多くが1日3食の食費、寮滞在費、1日3時間~4時間の英語マンツーマン授業、(VISA代)を無償で提供してくださります。 つまり、インターン生にご負担して頂くのは往復航空券、保険代、交通費、その他娯楽費になりますので、航空券をセール時に購入したり、旅行や外食を抑えたりすればより費用を抑えることが可能です。 ご質問いただけましたらより詳細は費用についてお話させていただきます。</h3></li></ul> <button class="btn_fqa"><label for="Panel7"><h3>Q.インターンシップは有給ですか?無給ですか?</h3></label></button> <input type="checkbox" id="Panel7" class="on-off" /><ul><li><h3>A.VISAの関係上、原則として給料の支給はありません。 その代わり、業務の対価として食費、滞在費、英語マンツーマン授業、VISA等を無償で提供してくださります。</h3></li></ul> <button class="btn_fqa"><label for="Panel8"><h3>Q.短期でのインターンシップも可能ですか?</h3></label></button> <input type="checkbox" id="Panel8" class="on-off" /><ul><li><h3>A.募集は少なくなりますが、可能です。語学学校でのインターンシップの場合、半年間~が一般的ですが、半年未満でも募集している語学学校もございます。企業でのインターンシップの場合、1か月~募集されている企業様もありますので、夏休みや春休み等の長期休暇を利用した短期での応募も歓迎しております。</h3></li></ul> <button class="btn_fqa"><label for="Panel9"><h3>Q.英語が話せませんが、インターンシップに参加することはできますか?</h3></label></button> <input type="checkbox" id="Panel9" class="on-off" /><ul><li><h3>A.大丈夫です。インターン先によってはそれほど高い英語力を必要とされていない場合もあります。また、ほとんどの企業様が1日3時間~4時間の英語マンツーマン授業を無償で提供してくださりますので、英語を日々学びながら業務をこなすことができます。不安がありましたら受け入れ先企業の社員の方に直接質問してみてください。</h3></li></ul> <button class="btn_fqa"><label for="Panel10"><h3>Q英語力によって任される仕事は変わりますか?</h3></label></button> <input type="checkbox" id="Panel10" class="on-off" /><ul><li><h3>A. 企業様により異なりますが、多くの場合、多少変わってきます。例えば韓国人やフィリピ ン人スタッフとのミーティングや、講師のマネジメント、英語での来客対応や電話対応等です。事前に英語力を身に着けたいという方はインターンシップ前に留学される方が多いです。インターンシップ前の留学については是非お任せください。</h3></li></ul> </div> <!--スマホ用ここまで--> <!--パソコン用--> <div class="grid_12 alpha omega mb_hidden" id="q_request"> <h2>お問い合わせ・お申込みについて</h2> <p id="question"><h3>Q.お問い合わせとお申込みの違いは何ですか?</h3></p> <p id="answer">A.お問い合わせは素朴な疑問があったり、興味があって話だけでも聞いてみたいという際に幅広くご利用ください。お申込みは選考を受けたい企業様がある程度決まっており、早めに選考を開始されたいという際にご利用ください。どちらからご連絡いただいてもカウンセリングは実施しております。</p> <p id="question"><h3>Q.カウンセリングについて教えてください。</h3></p> <p id="answer">A.カウンセリングはメール、電話、Skype、個別相談会にてさせていただいております。内容としましてはこちらからインターンシップやセブ島についてお話させていただくことに加え、問い合わせを頂いた方の目的や希望業種・職種、現状の英語力、予算、期間等をお伺いし、最適なインターンシップ先をご提案できるよう努めております。</p> <p id="question"><h3>Q.申し込みから参加決定までどれくらいの期間が必要ですか?</h3></p> <p id="answer">A.2週間~1か月程度を目安にお考えください。過去には1週間で決定した方もいらっしゃれば、2か月程度かかった方もおられました。 ただし、インターン枠の関係上先着順になりますので、なるべく3か月前には申し込まれることをお勧めします。</p> <p id="question"><h3>Q.何社の選考を受けることが出来ますか?</h3></p> <p id="answer">A.基本的には1社ずつです。しかし、やむを得ない理由や強い要望がある場合は最大3社まで一度にお申込みすることが可能ですのでご相談ください。</p> <p id="question"><h3>Q.海外からの問い合わせ・申し込みは可能ですか?</h3></p> <p id="answer">A.大歓迎です。フィリピン留学中の方からはよくお問い合わせをいただきますし、その他の国に滞在している方でもお申込みをいただいております。面接もSkypeで実施しておりますので安心してご連絡ください。</p> </div> <!--パソコン用ここまで--> <!--スマホ用--> <div id="mb_q_request"> <br /> <br /> </div> <div class="grid_12 alpha omega pc_hidden menu_fqa fqa"> <h2>お問い合わせ・お申込みについて</h2> <button class="btn_fqa"><label for="Panel11"><h3>Q.お問い合わせとお申込みの違いは何ですか?</h3></label></button> <input type="checkbox" id="Panel11" class="on-off" /><ul><li><h3>A.お問い合わせは素朴な疑問があったり、興味があって話だけでも聞いてみたいという際に幅広くご利用ください。お申込みは選考を受けたい企業様がある程度決まっており、早めに選考を開始されたいという際にご利用ください。どちらからご連絡いただいてもカウンセリングは実施しております。</h3></li></ul> <button class="btn_fqa"><label for="Panel12"><h3>Q.カウンセリングについて教えてください。</h3></label></button> <input type="checkbox" id="Panel12" class="on-off" /><ul><li><h3>A.カウンセリングはメール、電話、Skype、個別相談会にてさせていただいております。内容としましてはこちらからインターンシップやセブ島についてお話させていただくことに加え、問い合わせを頂いた方の目的や希望業種・職種、現状の英語力、予算、期間等をお伺いし、最適なインターンシップ先をご提案できるよう努めております。</h3></li></ul> <button class="btn_fqa"><label for="Panel13"><h3>Q.申し込みから参加決定までどれくらいの期間が必要ですか?</h3></label></button> <input type="checkbox" id="Panel3" class="on-off" /><ul><li><h3>A.2週間~1か月程度を目安にお考えください。過去には1週間で決定した方もいらっしゃれば、2か月程度かかった方もおられました。 ただし、インターン枠の関係上先着順になりますので、なるべく3か月前には申し込まれることをお勧めします。</h3></li></ul> <button class="btn_fqa"><label for="Panel14"><h3>Q.何社の選考を受けることが出来ますか?</h3></label></button> <input type="checkbox" id="Panel4" class="on-off" /><ul><li><h3>A.基本的には1社ずつです。しかし、やむを得ない理由や強い要望がある場合は最大3社まで一度にお申込みすることが可能ですのでご相談ください。</h3></li></ul> <button class="btn_fqa"><label for="Panel15"><h3>Q.海外からの問い合わせ・申し込みは可能ですか?</h3></label></button> <input type="checkbox" id="Panel5" class="on-off" /><ul><li><h3>A.大歓迎です。フィリピン留学中の方からはよくお問い合わせをいただきますし、その他の国に滞在している方でもお申込みをいただいております。面接もSkypeで実施しておりますので安心してご連絡ください。</h3></li></ul> </div> <!--スマホ用ここまで--> <!--パソコン用--> <div class="grid_12 alpha omega mb_hidden" id="q_rule"> <h2>インターンシップ参加契約について</h2> <p id="question"><h3>Q.参加にあたって必要な書類はありますか?</h3></p> <p id="answer">A.2種類ございます。1つ目がお客様の登録情報をご記入いただく書類、2つ目が申込み規約に関する書類です。こちらからメールにてお送りいたしますので、ご記入後、スキャンして送信、または郵送で送付ください。</p> <p id="question"><h3>Q.インターンシップ参加費用には何が含まれていて、いつ支払うことになりますか?</h3></p> <p id="answer">A.インターンシップ参加費用に関しましてはこちらをご覧ください。</p> <p id="question"><h3>Q.カードでの支払いは可能ですか?</h3></p> <p id="answer">A.申し訳ございませんが、カードでの支払いは対応しておりません。銀行振り込みのみとなりますのでご了承くださいませ。</p> <p id="question"><h3>Q.参加契約後もサポートしていただけますか?</h3></p> <p id="answer">A.はい、もちろん契約後もサポートさせていただいております。航空券や保険などの事前準備や英語の勉強法等でお困りの際はお気軽にご相談ください。</p> <p id="question"><h3>Q.参加契約後にキャンセルは可能ですか?</h3></p> <p id="answer">A.可能です。ただし、キャンセル時期によって返金規定がございますので、詳しくはお問い合わせください。</p> </div> <!--パソコン用ここまで--> <!--スマホ用--> <div id="mb_q_rule"> <br /> <br /> </div> <div class="grid_12 alpha omega pc_hidden menu_fqa fqa"> <h2>インターンシップ参加契約について</h2> <button class="btn_fqa"><label for="Panel16"><h3>Q.参加にあたって必要な書類はありますか?</h3></label></button> <input type="checkbox" id="Panel16" class="on-off" /><ul><li><h3>A.2種類ございます。1つ目がお客様の登録情報をご記入いただく書類、2つ目が申込み規約に関する書類です。こちらからメールにてお送りいたしますので、ご記入後、スキャンして送信、または郵送で送付ください。</h3></li></ul> <button class="btn_fqa"><label for="Panel17"><h3>Q.インターンシップ参加費用には何が含まれていて、いつ支払うことになりますか?</h3></label></button> <input type="checkbox" id="Panel17" class="on-off" /><ul><li><h3>A.インターンシップ参加費用に関しましてはこちらをご覧ください。</h3></li></ul> <button class="btn_fqa"><label for="Panel18"><h3>Q.カードでの支払いは可能ですか?</h3></label></button> <input type="checkbox" id="Panel18" class="on-off" /><ul><li><h3>A.申し訳ございませんが、カードでの支払いは対応しておりません。銀行振り込みのみとなりますのでご了承くださいませ。</h3></li></ul> <button class="btn_fqa"><label for="Panel19"><h3>Q.参加契約後もサポートしていただけますか?</h3></label></button> <input type="checkbox" id="Panel19" class="on-off" /><ul><li><h3>A.はい、もちろん契約後もサポートさせていただいております。航空券や保険などの事前準備や英語の勉強法等でお困りの際はお気軽にご相談ください。</h3></li></ul> <button class="btn_fqa"><label for="Panel20"><h3>Q.参加契約後にキャンセルは可能ですか?</h3></label></button> <input type="checkbox" id="Panel20" class="on-off" /><ul><li><h3>A.可能です。ただし、キャンセル時期によって返金規定がございますので、詳しくはお問い合わせください。</h3></li></ul> </div> <!--スマホ用ここまで--> <!--パソコン用--> <div class="grid_12 alpha omega mb_hidden" id="q_ready"> <h2>事前準備について</h2> <p id="question"><h3>Q.保険には加入しておくべきでしょうか?</h3></p> <p id="answer">A.必ず海外旅行傷害保険(海外留学保険)に加入してください。日本の保険は適用されませんので、現地で病気になったり、怪我をしたり、盗難にあった場合、保証がありません。海外では何が起こるか分かりませんし、保険に未加入のせいで病院に行くのを我慢したり、行動を制限してしまったりしては本末転倒です。備えあれば憂いなしというように、万が一を想定して必ずご加入ください。 保険の入り方、選び方についてもサポートさせていただきますのでご相談ください。</p> <p id="question"><h3>Q.航空券はどこで取るのがおすすめですか?</h3></p> <p id="answer">A.値段の安さが最優先という方はセブパシフィックのセール時に購入されることをお勧めします。セール情報はセブターンのTwitterやFacebookでもお知らせしておりますのでチェックしてみてください。 その他ですとフィリピン航空、大韓航空、アシアナ航空をご利用される方が多いです。スカイスキャナーというアプリを使用すれば最安価格を調べることも可能ですが、ご購入の際は一度ご相談いただければと思います。</p> <p id="question"><h3>Q.VISAは事前に用意しておく必要がありますか?</h3></p> <p id="answer">A.必要ありません。フィリピンの場合、VISAは渡航後に取得できます。取得手続きや、延長手続きも学校・企業側が代行してくださるので特別な知識も不要です。</p> <p id="question"><h3>Q.変圧器は必要ですか?</h3></p> <p id="answer">A.特に必要ありません。パソコンや携帯電話の充電器などはほとんどが対応しているので、そのまま使用できますが、念のためお調べ下さい。ドライヤーは壊れる場合がございますので現地で購入されるか、壊れてもよいものを持っていくことをお勧めします。</p> <p id="question"><h3>Q.渡航前に予防接種は必要ですか?</h3></p> <p id="answer">A.ほとんどの方は予防接種を受けずに渡航されています。必須という訳ではありませんが、ご自身の判断でお受けください。受けるとしたら狂犬病、B型肝炎などになります。</p> </div> <!--パソコン用ここまで--> <!--スマホ用--> <div id="mb_q_ready"> <br /> <br /> </div> <div class="grid_12 alpha omega pc_hidden menu_fqa fqa"> <h2>事前準備について</h2> <button class="btn_fqa"><label for="Panel21"><h3>Q.保険には加入しておくべきでしょうか?</h3></label></button> <input type="checkbox" id="Panel21" class="on-off" /><ul><li><h3>A.必ず海外旅行傷害保険(海外留学保険)に加入してください。日本の保険は適用されませんので、現地で病気になったり、怪我をしたり、盗難にあった場合、保証がありません。海外では何が起こるか分かりませんし、保険に未加入のせいで病院に行くのを我慢したり、行動を制限してしまったりしては本末転倒です。備えあれば憂いなしというように、万が一を想定して必ずご加入ください。 保険の入り方、選び方についてもサポートさせていただきますのでご相談ください。</h3></li></ul> <button class="btn_fqa"><label for="Panel22"><h3>Q.航空券はどこで取るのがおすすめですか?</h3></label></button> <input type="checkbox" id="Panel22" class="on-off" /><ul><li><h3>A.値段の安さが最優先という方はセブパシフィックのセール時に購入されることをお勧めします。セール情報はセブターンのTwitterやFacebookでもお知らせしておりますのでチェックしてみてください。 その他ですとフィリピン航空、大韓航空、アシアナ航空をご利用される方が多いです。スカイスキャナーというアプリを使用すれば最安価格を調べることも可能ですが、ご購入の際は一度ご相談いただければと思います。</h3></li></ul> <button class="btn_fqa"><label for="Panel23"><h3>Q.VISAは事前に用意しておく必要がありますか?</h3></label></button> <input type="checkbox" id="Panel23" class="on-off" /><ul><li><h3>A.必要ありません。フィリピンの場合、VISAは渡航後に取得できます。取得手続きや、延長手続きも学校・企業側が代行してくださるので特別な知識も不要です。</h3></li></ul> <button class="btn_fqa"><label for="Panel24"><h3>Q.変圧器は必要ですか?</h3></label></button> <input type="checkbox" id="Panel24" class="on-off" /><ul><li><h3>A.特に必要ありません。パソコンや携帯電話の充電器などはほとんどが対応しているので、そのまま使用できますが、念のためお調べ下さい。ドライヤーは壊れる場合がございますので現地で購入されるか、壊れてもよいものを持っていくことをお勧めします。</h3></li></ul> <button class="btn_fqa"><label for="Panel25"><h3>Q.渡航前に予防接種は必要ですか?</h3></label></button> <input type="checkbox" id="Panel25" class="on-off" /><ul><li><h3>A.ほとんどの方は予防接種を受けずに渡航されています。必須という訳ではありませんが、ご自身の判断でお受けください。受けるとしたら狂犬病、B型肝炎などになります。</h3></li></ul> </div> <!--スマホ用ここまで--> <!--パソコン用--> <div class="grid_12 alpha omega mb_hidden" id="q_life"> <h2>現地での生活について</h2> <p id="question"><h3>Q.現地でのお金の管理はどうすればいいですか?</p> <p id="answer">A.国際キャッシュカードがおすすめです。 大手都市銀などが発行しております。裏面にPLUSやCirrusなどのマークが付いていれば、手数料がかかりますが、現地ATMで現地通貨の引き落しが可能です。 もしくは現金を持っていき、現地でペソに両替しましょう。</p> <p id="question"><h3>Q.滞在施設について教えてください。</h3></p> <p id="answer">A.滞在場所は多くの場合、語学学校の寮または用意された社宅になります。シャワーやトイレは付属している場合がほとんどですのでご安心ください。部屋の人数等はご希望通りにいかないことはありますが、もし要望がある場合は面接の際に伝えておくと良いでしょう。</p> <p id="question"><h3>Q.インターネット環境はどうですか?</h3></p> <p id="answer">A.ほとんどの企業様、語学学校様でWi-Fi接続でインターネット接続が可能です。日本との連絡も、Wifi環境があればLINEやSkype、Facebook等のメッセンジャーアプリで連絡を取ることが可能です。しかしながら日本の様な回線速度でなかったり、接続が不安定だったりする場合もございます。 仕事等で高速インターネット環境が必要な方は現地でポケットWi-Fi(月々2500円~3000円)を購入されると良いと思います。</p> <p id="question"><h3>Q.現地での交通手段はどのようなものがありますか?</h3></p> <p id="answer">A.基本的にはタクシー(初乗り100円~120円程度)での移動になります。ジプニーやトライシクル(一律20円~30円程度)という現地の乗り物もありますが、大変混雑するため、安全とは言えません。スリなどを未然に防ぐためにもタクシーで移動することをお勧めします。</p> <p id="question"><h3>Q.休日はどのように過ごす方が多いですか?</h3></p> <p id="answer">A.生徒様や同僚と海に行く方や観光スポットへ行かれる方が多いです。長期の方はカフェでのんびり過ごしたり、休日も勉強に励んだりということが多くなるようです。また、ボランティアプログラムが開催されていることが多いので、長期で滞在される方は是非参加してみてください。</p> </div> <!--パソコン用ここまで--> <!--スマホ用--> <div id="mb_q_life"> <br /> </div> <div class="grid_12 alpha omega pc_hidden menu_fqa fqa"> <h2>現地での生活について</h2> <button class="btn_fqa"><label for="Panel26"><h3>Q.現地でのお金の管理はどうすればいいですか?</h3></label></button> <input type="checkbox" id="Panel26" class="on-off" /><ul><li><h3>A.国際キャッシュカードがおすすめです。 大手都市銀などが発行しております。裏面にPLUSやCirrusなどのマークが付いていれば、手数料がかかりますが、現地ATMで現地通貨の引き落しが可能です。 もしくは現金を持っていき、現地でペソに両替しましょう。</h3></li></ul> <button class="btn_fqa"><label for="Panel27"><h3>Q.滞在施設について教えてください。</h3></label></button> <input type="checkbox" id="Panel27" class="on-off" /><ul><li><h3>A.滞在場所は多くの場合、語学学校の寮または用意された社宅になります。シャワーやトイレは付属している場合がほとんどですのでご安心ください。部屋の人数等はご希望通りにいかないことはありますが、もし要望がある場合は面接の際に伝えておくと良いでしょう。</h3></li></ul> <button class="btn_fqa"><label for="Panel28"><h3>Q.インターネット環境はどうですか?</h3></label></button> <input type="checkbox" id="Panel28" class="on-off" /><ul><li><h3>A.ほとんどの企業様、語学学校様でWi-Fi接続でインターネット接続が可能です。日本との連絡も、Wifi環境があればLINEやSkype、Facebook等のメッセンジャーアプリで連絡を取ることが可能です。しかしながら日本の様な回線速度でなかったり、接続が不安定だったりする場合もございます。 仕事等で高速インターネット環境が必要な方は現地でポケットWi-Fi(月々2500円~3000円)を購入されると良いと思います。</h3></li></ul> <button class="btn_fqa"><label for="Panel29"><h3>Q.現地での交通手段はどのようなものがありますか?</h3></label></button> <input type="checkbox" id="Panel29" class="on-off" /><ul><li><h3>A.基本的にはタクシー(初乗り100円~120円程度)での移動になります。ジプニーやトライシクル(一律20円~30円程度)という現地の乗り物もありますが、大変混雑するため、安全とは言えません。スリなどを未然に防ぐためにもタクシーで移動することをお勧めします。</h3></li></ul> <button class="btn_fqa"><label for="Panel30"><h3>Q.休日はどのように過ごす方が多いですか?</h3></label></button> <input type="checkbox" id="Panel30" class="on-off" /><ul><li><h3>A.生徒様や同僚と海に行く方や観光スポットへ行かれる方が多いです。長期の方はカフェでのんびり過ごしたり、休日も勉強に励んだりということが多くなるようです。また、ボランティアプログラムが開催されていることが多いので、長期で滞在される方は是非参加してみてください。</h3></li></ul> </div> <!--スマホ用ここまで--> <!--投稿記事フォーム部分--> <div class="grid_12 inlinebox fqaap" id="contact_form"> <p>上記以外のご質問やご相談がある方は以下のフォームよりお気軽にご質問ください。</p> <a href="http://intern-college.com/contact/"><img class="resizeimg" src="<?php bloginfo('template_url');?>/images/icon/intern_contact.png" id="intern_contact"/></a> </div><!--contact form end--> </div><!--q_a end--> </div><!--end main--> <?php if(is_mobile()):?> <!--モバイルのヘッダー読み込み--> <?php get_footer("mb");?> <?php else: ?> <?php get_footer();?> <?php endif;?> <file_sep>/functions.php <?php // 最上位の固定ページ情報を取得する。 function apt_page_ancestor() { global $post; $anc = array_pop(get_post_ancestors($post)); $obj = new stdClass; if ($anc) { $obj->ID = $anc; $obj->post_title = get_post($anc)->post_title; } else { $obj->ID = $post->ID; $obj->post_title = $post->post_title; } return $obj; } // カテゴリ情報を取得する。 function apt_category_info($tax='category') { global $post; $cat = get_the_terms($post->ID, $tax); $obj = new stdClass; if ($cat) { $cat = array_shift($cat); $obj->name = $cat->name; $obj->slug = $cat->slug; } else { $obj->name = ''; $obj->slug = ''; } return $obj; } //おすすめインターン記事のテーブルを取得? function Include_my_php($params = array()) { extract(shortcode_atts(array( 'file' => 'default' ), $params)); ob_start(); include(get_theme_root() . '/' . get_template() . "/$file.php"); return ob_get_clean(); } add_shortcode('myphp', 'Include_my_php'); //ここまで //カスタム投稿タイプを定義 インターン記事 add_action( 'init', 'register_post_type_and_taxonomy'); function register_post_type_and_taxonomy(){ register_post_type( 'intern', array( 'labels'=>array( 'name' => 'インターン情報', 'add_new_item'=>'新規インターンを追加', 'edit_item'=>'インターン情報を編集', ), 'public'=> true, 'supports'=> array( 'title', 'editor', 'excerpt', 'custom-fields', 'thumbnail', ), ) ); //カスタムタクソノミー 業種 register_taxonomy( 'business', 'intern', array( 'labels'=>array( 'name' => '業種', 'add_new_item' => '業種を追加', 'edit_item' => '業種を編集', ), 'hierarchical'=>true, 'show_admin_column'=>true, ) ); //intern投稿タイプにカテゴリー追加 // register_taxonomy( // 'intern-cat', // 'intern', // array( // 'hierarchical'=>true, // 'update_count_callback'=>'_update_post_term_count', // 'label'=>'留学・インターンのカテゴリー', // 'singular_label'=>'留学・インターンのカテゴリー', // 'public'=>true, // 'show_ui'=>true // ) // ); //intern投稿タイプにタグ追加 register_taxonomy( 'intern-tag', //たくそのミー 'intern', array( 'hierarchical' => false, 'update_count_callback' => '_update_post_term_count', 'label' => '留学・インターンの条件タグ', 'singular_label' => '留学・インターンの条件タグ', 'public' => true, 'show_ui' => true ) ); //テストカスタム投稿タイプ2つめ register_post_type( 'blog', array( 'labels' => array( 'name' => __( 'ブログコラム一覧' ), 'add_new_item' => '新規追加', 'edit_item' => 'ブログを編集', ), 'public' => true, 'supports'=> array( 'title', 'editor', 'author', 'excerpt', 'thumbnail', ), ) ); register_taxonomy( 'column', 'blog', array( 'labels'=>array( 'name' => 'タグ', 'add_new_item' => 'タグ追加', 'edit_item' => 'タグ編集', ), 'hierarchical'=>true, 'show_admin_column'=>true, ) ); // register_taxonomy( // 'blog', // 'blog', // array( // 'labels'=>array( // 'name' => 'ブログ', // 'add_new_item' => 'ブログ追加', // 'edit_item' => 'ブログ編集', // ), // 'hierarchical'=>true, // 'show_admin_column'=>true, // ) // ); register_post_type( 'member', array( 'labels' => array( 'name' => __( '運営メンバー' ), 'add_new_item' => '新規追加', 'edit_item' => 'メンバーを編集', ), 'public' => true, 'supports'=> array( 'title', 'editor', 'custom-fields', 'thumbnail', ), ) ); } //カスタムメニューを表示 register_nav_menus(array( 'navigation'=>'ナビゲーションバー', 'footernav'=>'フッターメインナビ', 'footer_sub_nav'=>'フッターサブナビ' )); //wp_list_pagesのクラス属性を変更する function apt_add_current($output) { global $post; $oid = "page-item-{$post->ID}"; $cid = "$oid current_page_item"; $output = preg_replace("/$oid/", $cid, $output); return $output; } // アイキャッチ画像を利用できるようにします。 add_theme_support('post-thumbnails'); set_post_thumbnail_size(300, 210, true);//ブログ、インターン記事などのアイキャッチのサイズ指定はここ //メニューの機能を追加 add_theme_support('menus'); // メディアのサイズを追加します。 //サブイメージに関してはgrid_3で表示する。 add_image_size('main_image', 370); add_image_size('sub_image1', 220); add_image_size('sub_image2', 220); add_image_size('sub_image3', 220); add_image_size('sub_image4', 220); //wp_nav_menuにslugのクラス属性を追加 function apt_slug_nav($css,$item){ if($item->object=='page'){ $page=get_post($item->object_id); $css[]='menu-item-slug-'.esc_attr($page->post_name); } return $css; } //ループ回数を取得 function loopCountNum(){ global $wp_query; return $wp_query->current_post+1; } //スマホ表示分岐 function is_mobile(){ $useragents = array( 'iPhone', // iPhone 'iPod', // iPod touch 'Android.*Mobile', // 1.5+ Android *** Only mobile 'Windows.*Phone', // *** Windows Phone 'dream', // Pre 1.5 Android 'CUPCAKE', // 1.5+ Android 'blackberry9500', // Storm 'blackberry9530', // Storm 'blackberry9520', // Storm v2 'blackberry9550', // Storm v2 'blackberry9800', // Torch 'webOS', // Palm Pre Experimental 'incognito', // Other iPhone browser 'webmate' // Other iPhone browser ); $pattern = '/'.implode('|', $useragents).'/i'; return preg_match($pattern, $_SERVER['HTTP_USER_AGENT']); } // テーマのタグクラウドのパラメータ変更 function my_tag_cloud_filter($args) { $myargs = array( 'smallest' => 18, // 最小文字サイズを指定する 'largest' => 18, // 最大文字サイズを指定する 'number' => 12, // 一度に表示するタグの数を指定する(上限は45) 'order' => 'RAND', // 表示順はランダムで ); return $myargs; } add_filter('widget_tag_cloud_args', 'my_tag_cloud_filter'); // ユーザー情報編集 function update_profile_fields( $contactmethods ) { //項目の削除 unset($contactmethods['aim']); unset($contactmethods['jabber']); unset($contactmethods['yim']); //項目の追加 $contactmethods['twitter'] = 'Twitter'; $contactmethods['facebook'] = 'Facebook'; return $contactmethods; } add_filter('user_contactmethods','update_profile_fields',10,1); //アクセス数の取得 function get_post_views( $postID ) { $count_key = 'post_views_count'; $count = get_post_meta( $postID, $count_key, true ); if ( $count == '' ) { delete_post_meta( $postID, $count_key ); add_post_meta( $postID, $count_key, '0' ); return "0 views"; } return $count . ''; } //アクセス数の保存 function set_post_views( $postID ) { $count_key = 'post_views_count'; $count = get_post_meta( $postID, $count_key, true ); if ( $count == '' ) { $count = 0; delete_post_meta( $postID, $count_key ); add_post_meta( $postID, $count_key, '0' ); } else { $count ++; update_post_meta( $postID, $count_key, $count ); } } //記事内の自動生成クラス名を削除 add_filter( 'post_thumbnail_html', 'custom_attribute' ); function custom_attribute( $html ){ // class を削除する $html = preg_replace('/class=".*\w+"\s/', '', $html); return $html; }<file_sep>/kyukatsu_theme.php <?php /* Template Name: kyukatsu_theme */ ?> <?php get_header();?> <div class="grid_12" id="k_main_image"> <img src="<?php bloginfo('template_url')?>/images/banner/kyu_katu.jpg"> <br /> <h1 class="grid_12"><?php wp_title();?></h1> </div> <div class="grid_12" id="k_copy"> <p>近年、休学という選択をする学生の数は増加の一途を辿っており、2014年には大学4年生の40人に1人が休学しているというデータも出ました。しかし、休学はまだまだ一般的な選択肢ではなく、悩み や不安を抱えている方も多いと思います。</p> </div> <div class="grid_12" id="k_merit_list"> <ul> <li>休学はしたいけど、特に何かやりたいことがあるわけじゃない…</li> <li>欧米留学や長期語学留学はお金がたくさんかかるから難しい…</li> <li>休学終了後に就職活動で自信を持って話せるエピソードが欲しい…</li> <li>せっかく休学するのなら使える英語力をしっかりと身に着けたい…</li> <li>ワーホリやバックパックなどではなく、「働く」という経験がしたい…</li> </ul> <p>休学するに当たってこのような悩みや想いを持っているあなたのために、セブターンでは「休学×留学×インターン」という形であなたの“休活”をトータルサポートします!</p> </div> <div class="container_12" id="k_merit"> <h1>休活インターン3つのメリット</h1> <div class="grid_6" id="k_merit_box"> <h2>①圧倒的なコストパフォーマンス</h2> <p>セブ島でのインターンシップにかかる費用は航空券や保険も全て込みで半年間30万円前後です。フィリピン留学と組み合わせても欧米留学の1/3~1/5程度の費用で過ごすことができます。</p> </div> <div class="grid_6" id="k_merit_box"> <h2>②良質なアウトプットの機会</h2> <p>留学直後にインターンに挑戦することで、留学で学んだ英語をすぐにアウトプットする機会を得ることができます。英語力の高いフィリピンならではの良質なアウトプットの機会となります。</p> </div> </div> <div class="container_12" id="k_merit"> <h2>③就活で圧倒的に有利になる</h2> <p>留学×インターンで得られる能力を身に着けることで、就活で圧倒的に有利になります。</p> <div class="grid_6" id="k_merit_list2"> <h3>留学で得られる能力</h3> <ul> <li>英語力</li> <li>異文化理解力</li> <li>視野の広さ</li> <li>自制心</li> <li>協調性 etc...</li> </ul> </div> <div class="grid_6" id="k_merit_list2"> <h3>インターンで得られる能力</h3> <ul> <li>問題解決力</li> <li>責任感</li> <li>論理性</li> <li>柔軟性</li> <li>職業観 etc...</li> </ul> </div> <div class="grid_12" id="k_copy"> <p>他にも様々な人との出会や対話の中で磨かれるコミュニケーション能力、海外という土地で育まれる主体性やチャレンジ精神など、海外生活で得られる能力もたくさんあります。これら海外での留学×インターンシップで得られる能力は企業が求める人材に適合しています。</p> <img src=""> <p>企業が求める人材に近づくということは、就活で圧倒的に有利になるということです。</p> <h3>⇒お金の負担が非常に少なく、時間を最大限有効に使えて、就活でも圧倒的に有利になるのが休活インターン!</h3> </div> </div> <div class="grid_12" id="k_discount_button"> <a href="http://intern-college.com/contact/"><img src="<?php bloginfo('template_directory'); ?>/images/icon/intern_contact.png" /></a> </div> <div class="grid_12" id="what_k"> <h1>休活インターンとは?</h1> <div class="grid_8 push_2"> <h3>休学生の方に対し、出国前のカウンセリングから留学、インターン、そして帰国後のキャリアサポートまでをセブターンがトータルサポートする仕組みです。</h3> </div> <img src=""> <div class="grid_12"> <h2>カウンセリング</h2> <p>休学の目的や休学後のなりたい像を明確にするお手伝いをすると共に、フィリピンでの留学とインターンを両方経験したスタッフがあなたに最適な休活プランをご提案します。</p> <h2>フィリピン留学</h2> <p>インターンシップ前に1か月~3か月程度フィリピン留学で基礎英語や日常英会話を徹底的に勉強することで、インターンシップでの成果を最大化することができます。</p> <h2>インターンシップ</h2> <p>留学で身に着けた英語力とこれまでの経験を武器に、長期インターンシップに挑戦しましょう。インターンシップでは業務スキルと実践的な英語力、東南アジアでの長期実務経験という3つを同時に手に入れることができます。</p> <h2>キャリアサポート</h2> <p>ご希望があればキャリアコンサルタントをご紹介したり、休学経験者のコミュニティにご招待します。また、体験談を利用して出国前に立てた目標の確認や、現地での学びを整理することで休学後のキャリアまでをサポートします。</p> </div> </div> <div class="grid_12" id="k_intern_discount"> <h1>休活インターン生限定割引</h1> <h3>インターンシップ参加費用</h3> <h1>通常69,800円→49,800円(税抜)</h1> <div class="grid_12" id="k_discount_button"> <a href="http://intern-college.com/contact/"><img src="<?php bloginfo('template_directory'); ?>/images/icon/intern_contact.png" /></a> </div> </div> <div class="grid_12" id="customer_voice"> </div> <div class="container_12" id="k_q_and_a"> <div class="container_12" id="k_q"> <div class="grid_4 " id="k_q"> <h5>Q.インターンシップでも英語を学べますが、留学する必要はありますか?</h5> </div> <div class="grid_8 " id="k_a"> <p>A.予算とのご相談にはなりますが、留学だとインターンの3倍程度の勉強時間が取れるので、英語力の伸びが全く違います。インターンシップの密度を濃くするためにも、英語力をしっかり身に着けた上で挑戦されることをお勧めします。</p> </div> </div> <div class="container_12" id="k_q"> <div class="grid_4" id="k_q"> <h5>Q.留学先の手配はどのようにすればいいですか?</h5> </div> <div class="grid_8 " id="k_a"> <p>A.お任せください。セブターンは20校以上の語学学校と提携しておりますので、その中からあなたのご要望に沿った語学学校をご提案します。また、インターンの開始時期と調整いたしますのでスムーズにご案内することが可能です。</p> </div> </div> <div class="container_12" id="k_q"> <div class="grid_4" id="k_q"> <h5>Q.既に休学して留学中ですが、割引は適用されますか?</h5> </div> <div class="grid_8" id="k_a"> <p>A.はい、留学中であれば適用されます。留学後だと適用されませんのでご注意ください。</p> </div> </div> <div class="grid_12" id="k_attention"> <h1>注意事項</h1> <ul> <li>休学して留学+インターンシップのお申込みの方に限ります。</li> <li>留学・インターンシップの合計8週間以上お申込みの方に限ります。</li> <li>キャンペーンは事前のお知らせなく終了・変更する可能性がございます。</li> <li>他の割引・キャンペーンとの併用は不可です。</li> </ul> <div class="grid_12" id="k_discount_button"> <a href="http://intern-college.com/contact/"><img src="<?php bloginfo('template_directory'); ?>/images/icon/intern_contact.png" /></a> </div> </div> </div> <?php get_footer();?><file_sep>/company.php <?php /* Template Name: company */ ?> <?php get_header();?> <div class="container_12 article_main" id="company_wraper"> <h1 class="grid_12"><?php wp_title('',true,'');?></h1> <div class="grid_12" id="company"> <h1>運営情報</h1> <table> <tr> <th>名称</th> <td>セブターン</td> </tr> <tr> <th>設立</th> <td>2013年11月</td> </tr> <tr> <th>所在地</th> <td>〒533-0033 大阪具大阪市東淀川区東中島2-8-6 新大阪サムティビル1103号室</td> </tr> <tr> <th>代表者</th> <td><NAME></td> </tr> <tr> <th>連絡先</th> <td><EMAIL></td> </tr> <tr> <th>事業内容</th> <td>フィリピン・セブ島を中心とした海外インターンシップサポート、海外留学サポート</td> </tr> <tr> <th>ビジョン</th> <td>海外に挑戦したい若者に良質な情報を提供し、グローバル化対応への成長機会を提供する</td> </tr> </table> </div><!--運営情報 end--> <div class="grid_12" id="company"> <h1 id="company_h1">沿革・メディア掲載</h1> <table> <tr> <th>2013年11月</th> <td>セブターン設立</td> </tr> <tr> <th>2013年11月</th> <td>ノマド研究所&nbsp;大石哲之様からの<a href="http://www.jcast.com/kaisha/2013/10/24187079.html">インタビュー</a></td> </tr> <tr> <th>2015年4月</th> <td><a href="http://www.gakunavi.info/entry/international/cebutern.html">ガクナビ</a>に掲載</td> </tr> <tr> <th>2015年5月</th> <td><a href="http://kyukatsu.com/">休活ブログ</a>と業務提携</td> </tr> <tr> <th>2015年9月</th> <td>Learnasiaと業務提携、オンライン英会話サービス提供開始</td> </tr> <tr> <th>2015年10月</th> <td>HPリニューアル</td> </tr> <tr> <th>2015年10月</th> <td>フィリピン留学体験談ラジオに代表の<a href="http://ph-radio.travel-book.info/i148/">インタビュー</a>が掲載</td> </tr> </table> </div><!--沿革・メディア掲載 end--> </div><!--wrapper end--> <?php get_footer();?><file_sep>/searchpage.php <?php /* Template Name: Search Page */ ?> <div id="container_12 container-fluid"> <div id="main" class="grid_12 row"> <div class="col-xs-12"> <h1>同じ業種の記事はこちら</h1> <?php $term = array_shift(get_the_terms($post->ID, 'business')); ?> <?php $tax_posts = get_posts('post_type = intern & posts_per_page = 5 &taxonomy = business & term='.esc_html($term->slug)); if($tax_posts): ?> <ul> <?php foreach($tax_posts as $tax_post): ?> <li><a href="<?php echo get_permalink($tax_post->ID); ?>"><?php echo esc_html($tax_post->post_title); ?></a></li> <?php endforeach; ?> </ul> <?php endif; ?> </div> </div> </div> <file_sep>/member_theme.php <?php /* Template Name: member_theme */ ?> <?php get_header();?> <div class="container_12" id="article_main"> <h1 class="grid_12"><?php wp_title('',true,'');?></h1> <?php $args = array( 'numberposts' => 6, //表示(取得)する記事の数 'post_type' => 'member' //投稿タイプの指定 ); $customPosts = get_posts($args); if($customPosts) : foreach($customPosts as $post) : setup_postdata( $post ); ?> <!--記事表示部分--> <div class="grid_4 alpha" id="f_wrapper"> <div class="grid_4" id="f_article"> <a href="<?php the_permalink(); ?>"><?php echo the_title();?></a> </div> </div><!--f_wrapper end--> <!--記事が取得できなかった場合--> <?php endforeach; ?> <?php else : //記事が無い場合 ?> <li><p>記事はまだありません。</p></li> <?php endif; wp_reset_postdata(); //クエリのリセット ?> <!--ここまで--> </div><!--end main--> <?php get_footer();?><file_sep>/page-member.php <?php /* Template Name: member */ ?> <?php get_header();?> <div class="container_12" id="main"> <h1 class="grid_12"><?php wp_title('',true,'');?></h1> <?php $args = array( 'numberposts' => -1, //表示(取得)する記事の数 ここの数字をいじれば何件出すかを変える事ができる 'post_type' => 'member' //投稿タイプの指定 ); $customPosts = get_posts($args); if($customPosts) : foreach($customPosts as $post) : setup_postdata( $post ); ?> <!--記事の表示方法--> <!--変更点 記事表示--> <div class="grid_4" id="f_wrapper"> <div class="grid_4" id="f_article"> <span id="blog_colum_ribon"> <?php //newの表示について $hours = 10; //Newを表示させたい期間の時間 $today = date_i18n('U'); $entry = get_the_time('U'); $kiji = date('U',($today - $entry)) / 3600 ; if( $hours > $kiji ){ echo 'New!'; } ?> </span> <figure class="label inside bottom" data-label="<?php the_title(); ?>"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a></figure> </div> </div> <!--記事表示終了--> <?php endforeach; ?> <?php else : //記事が無い場合 ?> <li><p>記事はまだありません。</p></li> <?php endif; wp_reset_postdata(); //クエリのリセット ?> </div><!-- end main--> <?php get_footer(); ?><file_sep>/about.php <?php /* Template Name: about */ ?> <?php if (is_mobile()) :?> <?php get_header("mb");?> <?php else: ?> <?php get_header();?> <?php endif; ?> <div class="container_12 aboutap" id="about_wrapper"> <img class="grid_6 resizeimg pc_hidden" src="<?php bloginfo('template_url')?>/images/cebutern.png" /> <div class="grid_12 aboutap" id="about"> <h1 class="grid_12 col-xs-12 content_title content_title_margin">セブターンとは</h1> <br /> <h2>海外に挑戦したい若者に良質な情報を提供し、グローバル対応への成長の機会を提供する。</h2> <br /> <h2>セブターンはフィリピン・セブ島での海外インターンシップをサポートする<b>インタビュー型</b>求人サイトです。</h3> <div class="pc_hidden aboutap"align="right"><a href="http://intern-college.com/archives/blog/cebutern-interview/"><p><button class="btn_blue">>>なぜインタビュー形式なのか?</button></p></a></div> <div class="mb_hidden aboutap" align="right"><a href="http://intern-college.com/archives/blog/cebutern-interview/"><p>>>なぜインタビュー形式なのか?</p></a></div> <img class="resizeimg" src="<?php bloginfo('template_url')?>/images/logo_new.png" /> <div class="grid_12 aboutap" id="about_text"> <p>近年語学学校の設立や日系企業の進出が著しいフィリピン・セブ島。</p> <p>英語教育水準の高さ、物価の安さ、温かい気候、そして未来を担う新興都市でのビジネス経験...</p> <p>これらの要素が絡み合うフィリピン・セブ島での海外インターンシップは若者にとって非常に魅力的です。</p> <br/> <p>セブターンはこのような背景から、魅力的な経験を求める若者と、意欲ある人材を求める現地企業を繋ぐことで、</p> <p>若者に海外挑戦の機会を提供していくことを目的としています。</p> </div><!--about_text end--> </div><!--about end--> <div class="grid_12 mb_hidden aboutap"id="Greeting"> <h1>代表挨拶</h1> <div class="grid_5 aboutap" id="greeting_text"> <p>大学4年時に休学して飛び立ったフィリピン。</p> <p>そこで恩師と出会い、人生観が大きく変わりました。</p> <br /> <p>半年間のセブ島でのインターンシップでは、濃密な経験の数々を経てこのようなことを思うようになりました。</p> <h2>「こんなに良いインターン制度があるのに知らない人が多いなんてもったいない」</h2> <p>英語教育水準、費用、地理、新興国での経験、どれをとってもフィリピン・セブ島でのインターンシップは</p> <p>日本の若者にとって魅力的な選択肢だと信じています。</p> <h2>このセブターンというメディアを通して一歩踏み出す大切さを伝えたい、<br />そして海外へ挑戦する若者の背中を押したい。</h2> <p>これが私がセブターンに情熱を注ぐ理由です。</p> <p>セブターンがあなたの人生を変えるきっかけになれば幸いです。</p> </div><!--greeting_text end--> <img class="grid_6 resizeimg" src="<?php bloginfo('template_url')?>/images/about/ceo_new.jpg" /> </div><!--greeting end--> <!-------------------代表挨拶ここまで----------------------> <!-------------------3つのメリット----------------------> <div class="grid_12 merithead aboutap"> <h1 >セブ島インターンシップの3つのメリット</h1> <div class="grid_4 omega mb_merit aboutap" id="about_block"> <h2 class="mb_merit">①圧倒的なコストパフォーマンス</h2> <img class="resizeimg" src="<?php bloginfo('template_url');?>/images/about/merit1_new.jpg"/> <p>インターンの受け入れ先の多くは1日3食の食費、1日3~4時間の英語マンツーマン授業、寮滞在費、VISA代等を無償で提供して下さります。つまり、半年間のセブ島滞在、全て込みで30万あれば十分に挑戦の機会を掴めます。</p> </div> <div class="grid_4 mb_merit aboutap" id="about_block"> <h2>②英語&amp;ビジネスを新興国で学べる環境</h2> <img class="resizeimg" src="<?php bloginfo('template_url');?>/images/about/merit2_new.jpg"/> <p>セブターンなら毎日3~4時間の良質な授業を受け、実際のビジネス現場でアウトプットすることができます。また、東南アジアの新興都市での英語を使った長期実務経験はかけがいのない貴重な経験となるでしょう。</p> </div> <div class="grid_4 alpha mb_merit aboutap" id="about_block"> <h2>③アジア屈指の島でメリハリのある生活</h2> <img class="resizeimg" src="<?php bloginfo('template_url');?>/images/about/merit3_new.jpg"/> <p>温暖で豊かな自然に恵まれたフィリピンの中でもセブ島はアジア屈指のリゾート地として有名な島。インターンで疲れた身体をマッサージで癒し、休日は綺麗なビーチでリフレッシュ。そんな南国ライフを堪能してみませんか?</p> </div> </div> <!--モバイル代表者挨拶--> <div class="grid_12 pc_hidden aboutap"id="Greeting"> <h1>代表挨拶</h1> <div class="grid_5 " id="greeting_text"> <img class="grid_6 resizeimg" src="<?php bloginfo('template_url')?>/images/about/ceo_new.jpg" /> <p>大学4年時に休学して飛び立ったフィリピン。<br> そこで恩師と出会い、人生観が大きく変わりました。<br> 半年間のセブ島でのインターンシップでは、濃密な経験の数々を経てこのようなことを思うようになりました。<br> 「こんなに良いインターン制度があるのに知らない人が多いなんてもったいない」<br> 英語教育水準、費用、地理、新興国での経験、どれをとってもフィリピン・セブ島でのインターンシップは<br> 日本の若者にとって魅力的な選択肢だと信じています。<br> このセブターンというメディアを通して一歩踏み出す大切さを伝えたい、そして海外へ挑戦する若者の背中を押したい。<br> これが私がセブターンに情熱を注ぐ理由です。<br> セブターンがあなたの人生を変えるきっかけになれば幸いです。</p> </div><!--greeting_text end--> </div><!--greeting end--> <div class="pc_hidden aboutap" id="mb_company"> <h1>運営情報</h1> <h3>運営情報</h3> <hr> <table id="mb_company"> <tr> <th>名称</th> <td>セブターン</td> </tr> <tr> <th>設立</th> <td>2013年11月</td> </tr> <tr> <th>所在地</th> <td>〒533-0033 大阪具大阪市東淀川区東中島2-8-6 新大阪サムティビル1103号室</td> </tr> <tr> <th>代表者</th> <td>江浪 啓典</td> </tr> <tr> <th>連絡先</th> <td><EMAIL></td> </tr> <tr> <th>事業内容</th> <td>フィリピン・セブ島を中心とした海外インターンシップサポート、海外留学サポート</td> </tr> <tr> <th>ビジョン</th> <td>海外に挑戦したい若者に良質な情報を提供し、グローバル化対応への成長機会を提供する</td> </tr> </table> </div><!--運営情報 end--> <div class="grid_12 pc_hidden" id="mb_company"> <h3>沿革・メディア掲載</h3> <hr> <table id="mb_company"> <tr> <th>2013年11月</th> <td>セブターン設立</td> </tr> <tr> <th>2013年11月</th> <td>ノマド研究所&nbsp;大石哲之様からの<a href="http://www.jcast.com/kaisha/2013/10/24187079.html">インタビュー</a></td> </tr> <tr> <th>2015年4月</th> <td><a href="http://www.gakunavi.info/entry/international/cebutern.html">ガクナビ</a>に掲載</td> </tr> <tr> <th>2015年5月</th> <td><a href="http://kyukatsu.com/">休活ブログ</a>と業務提携</td> </tr> <tr> <th>2015年9月</th> <td>Learnasiaと業務提携、オンライン英会話サービス提供開始</td> </tr> <tr> <th>2015年10月</th> <td>HPリニューアル</td> </tr> <tr> <th>2015年10月</th> <td>フィリピン留学体験談ラジオに代表の<a href="http://ph-radio.travel-book.info/i148/">インタビュー</a>が掲載</td> </tr> </table> </div><!--沿革・メディア掲載 end--> <!--インターンを探すボタン--> <div class="grid_12" id="about_search_intern"> <center><h4><a href="<?php echo get_permalink(get_page_by_path('search_intern'));?>"><img src="<?php bloginfo('template_url');?>/images/button/btn_search.png" /></a></h4></center> </div> </div> </div><!-- end about--> <?php if(is_mobile()):?> <!--モバイルのヘッダー読み込み--> <?php get_footer("mb");?> <?php else: ?> <?php get_footer();?> <?php endif;?> <file_sep>/sns-actions.php <div class="sns_actions_mb col-xs-12 col-md-12 grid_12"> <!-- facebook --> <section class="facebook col-xs-4 grid_3"> <a href="https://www.facebook.com/sharer/sharer.php?u=http://intern-college.com/"> <img src="<?php bloginfo('template_directory');?>/images/button/facebook.png" width="160" height="40" alt="シェアする" /> </a> <!-- [head]内や、[body]の終了直前などに配置 --> <div id="fb-root"></div> </section> <!-- ここまで --> <!-- twitter --> <a class="twitter col-xs-4 grid_3" href="https://twitter.com/share?url=http://intern-college.com/&text=人で決める海外インターンセブターン"> <img src="<?php bloginfo('template_directory');?>/images/button/tweet.png" width="160" height="40" alt="シェアする" /> </a> <!-- ここまで --> <!-- LINE --> <!-- 画像のURLを指定すること --> <a href="http://line.me/R/msg/text/?{message}" class="col-xs-4 line grid_3"> <img src="<?php bloginfo('template_directory');?>/images/button/linebutton_82x20.png" width="160" height="40" alt="LINEで送る" /> </a> <!-- ここまで --> </div> <file_sep>/archive-master.php <?php /* Template Name: intern_archive_master */ ?> <?php get_header(); ?> <div id="container_12"> <div id="main" class="grid_12"> <h1>アーカイブ</h1> <ul class="grid_6"> <?php $args = array( 'numberposts' => 5, //表示(取得)する記事の数 'post_type' => 'intern' //投稿タイプの指定 ); $customPosts = get_posts($args); if($customPosts) : foreach($customPosts as $post) : setup_postdata( $post ); ?> <!-- 記事の表示方法 --> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <!-- 表示方法ここまで --> <?php endforeach; ?> <?php else : //記事が無い場合 ?> <li><p>記事はまだありません。</p></li> <?php endif; wp_reset_postdata(); //クエリのリセット ?> </ul> </div> <div class="grid_12"> <h1> <?php $taxonomy = $wp_query->get_queried_object(); echo $taxonomy->name; ?>での検索結果</h1> <?php $term = array_shift(get_the_terms($post->ID, 'business')); ?> <?php $tax_posts = get_posts('post_type=intern&posts_per_page=5&taxonomy=business&term='.esc_html($term->slug)); if($tax_posts): ?> <ul> <?php foreach($tax_posts as $tax_post): ?> <li><a href="<?php echo get_permalink($tax_post->ID); ?>"><?php echo esc_html($tax_post->post_title); ?></a></li> <?php endforeach; ?> </ul> <?php endif; ?> </div> </div> <section class="grid_12 archive_intern"> <h3>◆インターンシップ先一覧(45)</h3> <?php $args = array( 'numberposts' => -1, //表示(取得)する記事の数 ここの数字をいじれば何件出すかを変える事ができる(-1で全部) 'post_type' => 'intern' //投稿タイプの指定 ); $customPosts = get_posts($args); if($customPosts) : foreach($customPosts as $post) : setup_postdata( $post ); ?> <!--記事表紙する際、繰り返される処理--> <section class="grid_4 omega alpha f_article"> <figure class="label inside bottom" data-label="<?php the_title(); ?>"><a id="intern_thum" href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a></figure> <div class="f_article_labels"> <ul> <li><a href="<?php the_permalink(); ?>">期間:<?php echo esc_html($post->cf_min_day); ?>〜</a></li> <li><a href="<?php the_permalink(); ?>">授業数:<?php echo esc_html($post->cf_tuition); ?></a></li> <li><a href="<?php the_permalink(); ?>">勤務地:<?php echo esc_html($post->area); ?></a></li> <ul> </div> <div class="f_article_tags"> <a href="<?php the_permalink(); ?>">企業 No.<?php echo esc_html(get_post_meta($post->ID, 'cf_no', true)); ?></a> <a class="f_business" href="<?php the_permalink(); ?>"><?php echo esc_html($post->cf_business); ?></a> <div class="clear"></div> <div class="primary_btn_wrapper"><a class="primary_btn" href="<?php the_permalink(); ?>" >インタビュー記事を見る</a></div> </div> </section> <?php endforeach; ?> <?php else : //記事が無い場合 ?> <li><p>記事はまだありません。</p></li> <?php endif; wp_reset_postdata(); //クエリのリセット ?> <!--記事表示終了--> </section> <?php get_footer(); ?> <file_sep>/archive.php <?php /* Template Name: archive */ ?> <?php get_header(); ?> <div class="container_12" id="article_main"> <h1> <?php $taxonomy = $wp_query->get_queried_object(); echo $taxonomy->name; ?>での検索結果 </h1> <!-- 検索結果記事取得 --> <?php if(have_posts()): ?> <?php while(have_posts()): the_post(); ?> <!--記事表示部分PC用--> <section class="grid_4 omega alpha f_article mb_hidden"> <figure class="label inside bottom f_thum" data-label="<?php the_title(); ?>"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a></figure> <div class="f_article_labels"> <ul> <li><a href="<?php the_permalink(); ?>">期間:<?php echo esc_html($post->cf_min_day); ?>〜</a></li> <li><a href="<?php the_permalink(); ?>">授業数:<?php echo esc_html($post->cf_tuition); ?></a></li> <li><a href="<?php the_permalink(); ?>">勤務地:<?php echo esc_html($post->area); ?></a></li> <ul> </div> <div class="f_article_tags"> <a href="<?php the_permalink(); ?>">企業 No.<?php echo esc_html(get_post_meta($post->ID, 'cf_no', true)); ?></a> <a id="f_business" href="<?php the_permalink(); ?>"><?php echo esc_html($post->cf_business); ?></a> <div class="clear"></div> <div class="primary_btn_wrapper"><a class="primary_btn" href="<?php the_permalink(); ?>" >インタビュー記事を見る</a></div> </div> </section> <!-- ここまで --> <!-- スマホ --> <div class="container-fluid"> <section class="pc_hidden row article_wrap"> <a class="col-xs-4" href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a> <a class="col-xs-8 mb_article_title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <ul class="col-xs-8 intern_tags"> <li class="day_tag"><a href="<?php the_permalink(); ?>">期間:<?php echo esc_html($post->cf_min_day); ?>〜</a></li> <li class="tuition_tag"><a href="<?php the_permalink(); ?>">授業数:<?php echo esc_html($post->cf_tuition); ?></a></li> <li class="area_tag"><a href="<?php the_permalink(); ?>">勤務地:<?php echo esc_html($post->area); ?></a></li> </ul> </section> </div> <?php endwhile; ?> <?php endif; ?> </div> <div class="container_12" id="article_main"> <h4>他の記事を探す</h4> <!-- 業種検索 --> <section class="grid_12 intern_section business_search tag_btn"> <h3>業種から探す</h3> <ul> <li> <?php wp_tag_cloud( array( 'taxonomy'=>'business', // 最小フォント指定 'smallest'=>'12', // 最大フォント指定 'largest'=>'12' ) ); ?> </li> </ul> </section> <!-- ここまで --> <!-- 条件検索 --> <section class="grid_12 intern_section business_search"> <h3>条件から探す</h3> <div class="container_12"> <div id="main" class="grid_12 tag_btn"> <h1>条件で検索</h1> <ul> <li> <?php wp_tag_cloud( array( 'taxonomy'=>'intern-tag', // 最小フォント指定 'smallest'=>'12', // 最大フォント指定 'largest'=>'12' ) ); ?> </li> </ul> </div> </div> </section> <!-- ここまで --> </div> <div class="container_12 to_archive_btn"> <a class="btn_blue grid_12" href="">インターン一覧を見る</a> </div> <section class="container_12" id="article_main"> <h3 class="grid_12">スタッフおすすめ記事</h3> <?php $loop = new WP_Query( array( 'post_type' => 'intern', //カスタム投稿名 'taxonomy' => 'intern-tag', //タクソノミーを指定 'term' => 'recommend', //ターム(タグ) 'posts_per_page' => 6 //表示件数( -1 = 全件 ) )); while ( $loop->have_posts() ) : $loop->the_post(); ?> <!-- 表示方法 --> <div class="grid_4 omega alpha f_article mb_hidden"> <figure class="label inside bottom f_thum" data-label="<?php the_title(); ?>"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a> </figure> <div class="f_article_labels"> <ul> <li><a href="<?php the_permalink(); ?>">期間:<?php echo esc_html($post->cf_min_day); ?>〜</a></li> <li><a href="<?php the_permalink(); ?>">授業数:<?php echo esc_html($post->cf_tuition); ?></a></li> <li><a href="<?php the_permalink(); ?>">勤務地:<?php echo esc_html($post->area); ?></a></li> <ul> </div> <div class="f_article_tags"> <a href="<?php the_permalink(); ?>">企業 No.<?php echo esc_html(get_post_meta($post->ID, 'cf_no', true)); ?></a> <a id="f_business" href="<?php the_permalink(); ?>"><?php echo esc_html($post->cf_business); ?></a> <div class="clear"></div> <div class="primary_btn_wrapper"><a class="primary_btn" href="<?php the_permalink(); ?>" >インタビュー記事を見る</a></div> </div> </div> <!-- ここまで --> <?php endwhile; ?> </section> <?php get_footer(); ?> <file_sep>/content-intern.php <div class="container_12 container-fluid" id="article_main"> <div class="row grid_12 mb_article"> <section class="col-xs-12 col-md-12"> <h1 class="mb_article_title" ><?php the_title();?></h1> <span class="article_thumbnail"><?php the_post_thumbnail();?></span> <?php the_content(); ?> </section> <section class="col-xs-12 col-md-12 intern_table"> <h2 class="intern_text">インターンシップ募集概要</h2> <?php get_template_part('table-intern'); ?> </section> <section class="col-xs-12 col-md-12 article_contact_form"> <h3 class="third_content_title">当インターンシップ先に対するお問い合わせは以下のフォームからご連絡ください。</h3> <?php echo do_shortcode('[trust-form id=2916]');?> </section> <div class="clearfix"></div> </div> <div class="row grid_12"> <section class="col-xs-12 col-md-12"> <h4 class="third_content_title">記事をシェアする</h4> <?php get_template_part('sns-actions');?> </section> <!-- <section class="pager Similar_posts col-xs-12"> <h4 class="third_content_title">あなたにおすすめのインターンシップ*調整中</h4> <!--< ?php get_template_part('related-intern-entries');? >--> </section>--> <a class="btn_blue large_btn prev_all col-xs-12" href="http://intern-college.com/search_intern/">インターン先一覧に戻る</a> </div> </div><file_sep>/header-mb.php <!DOCTYPE html> <html class="no-js" lang="ja"> <head> <title><?php wp_title('',true,'');bloginfo('name');?></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <!--コンテンツのcss--> <link rel="stylesheet" type="text/css" media="all" href="<?php echo get_template_directory_uri(); ?>/mb-style.css"> <!-- <link rel="stylesheet" type="text/css" media="all" href="<?php echo get_template_directory_uri(); ?>/css/front_1707.css"> <link rel="stylesheet" type="text/css" media="all" href="<?php echo get_template_directory_uri(); ?>/css/form_style.css"> <link rel="stylesheet" type="text/css" media="all" href="<?php echo get_template_directory_uri(); ?>/css/front_1709.css">--> <?php wp_enqueue_script('jquery.rwdImageMaps.min', get_bloginfo('template_url').'/js/jquery.rwdImageMaps.min.js'); ?> <?php wp_deregister_script('jquery'); ?><!-- WordPressのjQueryを読み込ませない --> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <?php wp_enqueue_script('jquery.flexslider-min', get_bloginfo('template_directory').'/js/jquery.flexslider-min.js');?><!--スライダースクリプト--> <!--アナリティクス--> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-44795290-1','auto' ); ga('require', 'linkid', 'linkid.js'); ga('send', 'pageview'); </script> <!--ここまで--> <!--flexslider--> <script type="text/javascript" charset="utf-8"> $(window).load(function() { $('.flexslider').flexslider(); }); </script> <!--ここまで--> </head> <body<?php body_class();?>> <div class="liquid_theme contaiter-fluid"> <div class="header_wrapper container_12 row"> <!--ナビゲーション--> <nav class="paradeiser mbnav"> <a href="<?php echo home_url('/'); ?>"> <img class="logo" src="<?php bloginfo('template_url');?>/images/logo_new.png" alt="Logo"> </a> <a class="nav_btn" href="http://intern-college.com/search_intern/"> インターンを探す </a> <a class="nav_btn" href="http://intern-college.com/column-blog/"> ブログ・コラム </a> <!-- paste in as many links as you want --> <!-- and include the dropdown aswell --> <span class="paradeiser_dropdown"> <a href="#paradeiser-more" id="paradeiser-dropdown"> <div class="paradeiser_icon_canvas"> <img src="<?php bloginfo('template_url');?>/images/nav/menu_overflow.svg" alt=""> </div> <span>Menu</span> </a> <ul class="paradeiser_children" id="paradeiser-more"> <li><a href="http://intern-college.com/about/">セブターンとは</a></li> <li><a href="http://intern-college.com/flow/">参加までの流れ・料金</a></li> <li><a href="http://intern-college.com/q_and_a/">よくある質問</a></li> <li><a href="http://intern-college.com/contact/">お問い合わせ</a></li> <li><a href="http://intern-college.com/apply/">お申込み</a></li> </ul> </span> </nav> <div class="clearfix"></div> <!--スライダー--> <div class="container_12 col-xs-12"> <?php if(is_front_page()):?> <div class="flexslider"> <ul class="slides"> <li><a class="slides_link" href="#"><img src="<?php bloginfo('template_url');?>/images/banner/mbtop_banner.jpg"></a></li> <li><a class="slides_link" href="http://intern-college.com/kobetsu-soudankai/"><img src="<?php bloginfo('template_url');?>/images/banner/soudankai_new.jpg"></a></li> <li><a class="slides_link" href="http://intern-college.com/online-english/"><img src="<?php bloginfo('template_url');?>/images/banner/online_banner_new.jpg"></a></li> <li><a class="slides_link" href="http://intern-college.com/about/"><img src="<?php bloginfo('template_url');?>/images/banner/main_banner_new.jpg"></a></li> </ul> </div> <?php else:?> <?php endif;?> </div> </div><!--header end--> <file_sep>/single-intern.php <?php if (is_mobile()) :?> <?php get_header("mb");?> <?php else: ?> <?php get_header();?> <?php endif; ?> <div class="container_12 container-fluid" id="main"> <div class="row" id="start"> <div class="grid_12 col-xs-12 intern_article_main"> <?php if(have_posts()): while(have_posts()): the_post(); ?> <?php get_template_part('content-intern'); ?> <?php endwhile; endif; ?> </div><!--end main_content--> </div> </div><!--end main--> <?php if(is_mobile()):?> <!--モバイルのヘッダー読み込み--> <?php get_footer("mb");?> <?php else: ?> <?php get_footer();?> <?php endif;?> <file_sep>/category-business.php <?php /* Template Name: category-business */ ?> <?php get_header(); ?> <div class="container_12" id="article_main"> <section class="grid_12 main"> <h1>業種で検索</h1> <h3> <?php $taxonomy = $wp_query->get_queried_object(); echo $taxonomy->name; ?>での検索結果</h1> <?php $term = array_shift(get_the_terms($post->ID, 'business')); ?> <?php $tax_posts = get_posts('post_type=intern & posts_per_page=6 & taxonomy=business&term='.esc_html($term->slug)); if($tax_posts): ?> <ul> <?php foreach($tax_posts as $tax_post): ?> <!-- PC記事表示部分 --> <li><a href="<?php echo get_permalink($tax_post->ID); ?>"><?php echo esc_html($tax_post->post_title); ?></a></li> <li><a href="<?php echo get_permalink($tax_post->ID); ?>"><?php echo esc_html($tax_post->post_thumbnail); ?></a></li> <!-- ここまで --> <?php endforeach; ?> </ul> <?php endif; ?> </section> </div> <?php get_footer(); ?> <file_sep>/footer.php <?php get_template_part('toplink');?> </div><!--wrap end--> <div class="footer_wrapper"> <div class="container_12 footer_body"> <div class="grid_3 footer_nav"> <p class="footer_text">Contents</p> <?php wp_nav_menu(array( 'theme_location'=>'footernav', 'depth' => 3, )); ?> </div> <div class="grid_3 footer_nav"> <p class="footer_text">Contact us</p> <?php wp_nav_menu(array( 'theme_location'=>'footer_sub_nav', 'depth' => 1, )); ?> </div> <div class="grid_3 footer_banner"> <p class="footer_text">Recommended</p> <a href="http://intern-college.com/?p=1716"><img src="<?php bloginfo('template_url');?>/images/banner/soudankai_new.jpg"/></a> <a href="http://intern-college.com/online-english/"><img src="<?php bloginfo('template_url');?>/images/banner/online_banner_new.jpg"/></a> </div> <div class="grid_3 official_acount"> <p class="footer_text">Official acount</p> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/ja_JP/sdk.js#xfbml=1&version=v2.5&appId=1508113636173404"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <div class="fb-page" data-href="https://www.facebook.com/Cebuturn" data-width="220" data-height="87" data-small-header="false" data-adapt-container-width="false" data-hide-cover="false" data-show-facepile="false" data-show-posts="false"> <div class="fb-xfbml-parse-ignore"> <blockquote cite="https://www.facebook.com/Cebuturn"><a href="https://www.facebook.com/Cebuturn">セブターン</a></blockquote> </div> </div> <div id="official_acount_twi"> <script> !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https'; if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js'; fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs'); </script> <a href="https://twitter.com/cebutern" class="twitter-follow-button" data-show-count="false" data-size="large">Follow @cebutern</a> </div> </div> <div class="grid_12 omega alpha footer_logo"> <h3>Copyright &copy; セブターン All Rights Reserved.</h3> </div><!--footer_logo end--> </div><!--footer end--> </div><!--footerwrapper end--> <?php wp_footer();?> </body> </html><file_sep>/blog-search-page.php <?php /* Template Name: Blog Search Page */ ?> <div id="container_12"> <div id="main" class="grid_12"> <h1>同じカテゴリの記事はこちら</h1> <?php $term = array_shift(get_the_terms($post->ID, 'blog')); ?> <?php $tax_posts = get_posts('post_type=blog & posts_per_page=3 & taxonomy = blog& term='.esc_html($term->slug)); if($tax_posts): ?> <ul> <?php foreach($tax_posts as $tax_post): ?> <li><a href="<?php echo get_permalink($tax_post->ID); ?>"><?php echo esc_html($tax_post->post_title); ?></a></li> <?php endforeach; ?> </ul> <?php endif; ?> </div> </div> <file_sep>/tag.php <?php /* Template Name: intern_tag_test */ ?> <div class="container_12 container-fluid" id="article_main"> <div id="main" class="grid_12 tag_btn row"> <div class="col-xs-12"> <h3>業種で検索</h3> <ul> <li> <?php wp_tag_cloud( array( 'taxonomy'=>'business', // 最小フォント指定 'smallest'=>'12', // 最大フォント指定 'largest'=>'12' ) ); ?> </li> </ul> </div> </div> </div> <file_sep>/page-intern_search.php <?php /* Template Name: intern-wo-sagasu */ ?> <!--インターンを探すページ本体--> <?php if (is_mobile()):?> <?php get_header("mb");?> <?php else: ?> <?php get_header();?> <?php endif; ?> <div class="container_12 main_container container-fluid article_title" id="article_main"> <section class="grid_12 intern_top_block row" id="start"> <h1 class="grid_12 content_title content_title_margin col-xs-12 "><?php wp_title('',true,'');?></h1> <span class="clearfix mb_hidden"></span> <img class="intern_banner mb_banner grid_12 banner" src="<?php bloginfo('template_url');?>/images/banner/intern-search-banner.jpg"> <div class="mb_article_text col-xs-12"> <p class="intern_article_text">セブターンはインタビュー型のインターンシップ募集記事を掲載しています。</p> <p class="intern_article_text">\あなたの価値観に合う方を探してインターン先を決めましょう!/</p> </div> <div class="article_label_btn col-xs-6 col-xs-offset-6 "> <a class="btn_orange btn_left large_btn" href="http://intern-college.com/archives/blog/cebutern-interview/">>>なぜインタビュー形式なのか?</a> </div> </section><!-- row end --> <!-- 業種検索 --> <div class="row"> <section class="grid_12 intern_section business_search tag_btn col-xs-12"> <h3 class="h2_title">業種から探す</h3> <ul class="intern_tags_cloud"> <li class="col-xs-12"> <?php wp_tag_cloud( array( 'taxonomy'=>'business', // 最小フォント指定 'smallest'=>'12', // 最大フォント指定 'largest'=>'12' ) ); ?> </li> </ul> </section> </div> <!-- ここまで --> <!-- 条件検索 --> <div class="row"> <section class="grid_12 intern_section business_search col-xs-12"> <h3 class="h2_title">条件から探す</h3> <div class="container_12"> <div id="main" class="grid_12 tag_btn"> <ul class="intern_tags_cloud"> <li> <?php wp_tag_cloud( array( 'taxonomy'=>'intern-tag', // 最小フォント指定 'smallest'=>'12', // 最大フォント指定 'largest'=>'12' ) ); ?> </li> </ul> </div> </div> </section> </div> <!-- ここまで --> </div><!-- end main--> <div class="container-fluid"> <div class="row"> <section class="container_12" id="article_main"> <h3 class="grid_12 third_content_title col-xs-12">スタッフおすすめ記事</h3> <div> <?php $args = array( 'posts_per_page' => 6, 'offset' => 0, 'category' => 'recommend', 'orderby' => 'post_date', 'order' => 'DESC', 'include' => '', 'exclude' => '', 'meta_key' => '', 'meta_value' => '', 'post_type' => 'intern', 'post_mime_type' => '', 'post_parent' => '', 'post_status' => 'publish', 'suppress_filters' => true ); ?> <!-- 条件ここまで --> <?php $myposts = get_posts( $args ); ?> <?php foreach ( $myposts as $post ) : setup_postdata( $post ); ?> <!-- 表示方法 --> <section class="grid_4 omega alpha f_article mb_hidden"> <figure class="label inside bottom f_thum" data-label="<?php the_title(); ?>"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a></figure> <div class="f_article_labels"> <ul> <li><a href="<?php the_permalink(); ?>">期間:<?php echo esc_html($post->cf_min_day); ?>〜</a></li> <li><a href="<?php the_permalink(); ?>">授業数:<?php echo esc_html($post->cf_tuition); ?></a></li> <li><a href="<?php the_permalink(); ?>">勤務地:<?php echo esc_html($post->area); ?></a></li> <ul> </div> <div class="f_article_tags"> <a href="<?php the_permalink(); ?>">企業 No.<?php echo esc_html(get_post_meta($post->ID, 'cf_no', true)); ?></a> <a id="f_business" href="<?php the_permalink(); ?>"><?php echo esc_html($post->cf_business); ?></a> <div class="clear"></div> <div class="primary_btn_wrapper"><a class="primary_btn" href="<?php the_permalink(); ?>" >インタビュー記事を見る</a></div> </div> </section> <!--スマホ用レイアウト--> <div class="container-fluid"> <section class="pc_hidden row article_wrap col-xs-12"> <a class="col-xs-4" href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a> <a class="col-xs-8 mb_archive_article_title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <ul class="col-xs-8 intern_tags"> <li class="day_tag"><a href="<?php the_permalink(); ?>">期間:<?php echo esc_html($post->cf_min_day); ?>〜</a></li> <li class="tuition_tag"><a href="<?php the_permalink(); ?>">授業数:<?php echo esc_html($post->cf_tuition); ?></a></li> <li class="area_tag"><a href="<?php the_permalink(); ?>">勤務地:<?php echo esc_html($post->area); ?></a></li> </ul> </section> </div> <!-- ここまで --> <?php endforeach; wp_reset_postdata(); ?> </div> </section> <section class="col-xs-12 container_12"> <h3 class="grid_12 third_content_title col-xs-12">新着記事</h3> <?php $args = array( 'posts_per_page' => 3, 'offset' => 0, 'category' => '', 'orderby' => 'post_date', 'order' => 'DESC', 'include' => '', 'exclude' => '', 'meta_key' => '', 'meta_value' => '', 'post_type' => 'intern', 'post_mime_type' => '', 'post_parent' => '', 'post_status' => 'publish', 'suppress_filters' => true ); ?> <!-- 条件ここまで --> <?php $myposts = get_posts( $args ); ?> <?php foreach ( $myposts as $post ) : setup_postdata( $post ); ?> <!-- 表示方法 --> <section class="grid_4 omega alpha f_article mb_hidden"> <figure class="label inside bottom f_thum" data-label="<?php the_title(); ?>"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a></figure> <div class="f_article_labels"> <ul> <li><a href="<?php the_permalink(); ?>">期間:<?php echo esc_html($post->cf_min_day); ?>〜</a></li> <li><a href="<?php the_permalink(); ?>">授業数:<?php echo esc_html($post->cf_tuition); ?></a></li> <li><a href="<?php the_permalink(); ?>">勤務地:<?php echo esc_html($post->area); ?></a></li> <ul> </div> <div class="f_article_tags"> <a href="<?php the_permalink(); ?>">企業 No.<?php echo esc_html(get_post_meta($post->ID, 'cf_no', true)); ?></a> <a id="f_business" href="<?php the_permalink(); ?>"><?php echo esc_html($post->cf_business); ?></a> <div class="clear"></div> <div class="primary_btn_wrapper"><a class="primary_btn" href="<?php the_permalink(); ?>" >インタビュー記事を見る</a></div> </div> </section> <!--スマホ用レイアウト--> <div class="container-fluid"> <section class="pc_hidden row article_wrap col-xs-12"> <a class="col-xs-4" href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a> <a class="col-xs-8 mb_archive_article_title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <ul class="col-xs-7 intern_tags test_tag"> <li class="business_tag"><a href="<?php the_permalink(); ?>"><?php echo esc_html($post->cf_business); ?></a></li> <li class="com_num_tag business_tag"><a href="<?php the_permalink(); ?>">No.<?php echo esc_html($post->cf_no); ?></a></li> </ul> </section> </div> <!-- ここまで --> <?php endforeach; wp_reset_postdata(); ?> </section> <div class="container_12 to_archive_btn"> <a class="btn_blue grid_12 col-xs-12 mb_primary_btn" href="">インターン一覧を見る</a> </div> <?php get_template_part('toplink');?> </div><!-- row end --> </div> <?php if(is_mobile()):?> <!--モバイルのフッター読み込み--> <?php get_footer("mb");?> <?php else: ?> <?php get_footer();?> <?php endif;?><file_sep>/related-intern-entries.php <?php //タグ情報から関連記事をランダムに呼び出す $tags = wp_get_post_tags($post->ID); $tag_ids = array(); foreach($tags as $tag): array_push( $tag_ids, $tag -> term_id); endforeach ; $args = array( 'post__not_in' => array($post -> ID), 'posts_per_page'=> 10, 'post_type'=>"intern", 'tag__in' => $tag_ids, 'orderby' => 'rand' ); $query = new WP_Query($args); ?> <?php if( $query -> have_posts() && !empty($tag_ids) ): ?> <?php while ($query -> have_posts()) : $query -> the_post(); ?> <!-- 表示処理 --> <div class="similar_posts grid_4 omega alpha col-xs-12"> <figure class="label inside bottom" data-label="<?php the_title(); ?>"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a></figure> </div> <!-- ここまで--> <?php endwhile;?> <?php else:?> <p>記事はありませんでした</p> <?php endif; wp_reset_postdata(); ?> <file_sep>/page-blog_column.php <?php /* Template Name: blog_column */ ?> <?php if (is_mobile()) :?> <?php get_header("mb");?> <?php else: ?> <?php get_header();?> <?php endif; ?> <div class="container_12 container-fluid" id="article_main"> <div class="row blog_wrap"> <section class="col-xs-12" id="start"> <h1 class="grid_12 col-xs-12 content_title content_title_margin"><?php wp_title('',true,'');?></h1> <img class="blog_page_bn mb_banner " src="<?php bloginfo('template_url');?>/images/banner/blog_banner.jpg"> </section> <section class="col-xs-12 col-md-12 blog_wrap"> <h2 class="h2_title col-xs-12 col-md-12">人気記事</h2> <!-- 閲覧数順記事取得 --> <?php $args = array( 'post_type' => 'blog', //投稿タイプ 'numberposts' => 6, //表示数 'meta_key' => 'post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC', ); $posts = get_posts( $args ); if($posts) : ?> <div class="col-xs-12 col-md-12 pc_blog_new"> <ul class="col-xs-6 col-md-6"> <?php foreach( $posts as $post ) : setup_postdata( $post ); ?> <li class="grid_4"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'thumbnail' ); ?></a></li> <li class="grid_8"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <div class="clearfix mb_hidden"></div> <li class="grid_8 pc_blog_author"><?php the_author(); ?></li> <?php endforeach; ?> <?php wp_reset_postdata(); ?> </ul> <?php else : ?> <p class="col-xs-12 col-md-12">アクセスランキング集計中です。</p> <?php endif; ?> </div> </section> <!-- 新着記事 --> <section class="row blog_wrap"> <h2 class="h2_title col-xs-12 col-md-12">新着記事</h2> <?php $goodslist = get_posts( array( 'post_type' => 'blog', //特定のカスタム投稿タイプスラッグを指定 'orderby' => 'day', //何順で並べるか 'posts_per_page' => 3 //取得記事件数 )); foreach( $goodslist as $post ): setup_postdata( $post ); ?> <!-- タグ情報取得 --> <?php $tag = ''; $separator = ''; $before = ''; if( get_post_type() === 'blog' ) { $tag = get_the_term_list( $post->ID, 'column', $before, $separator ); } ?> <!-- 表示部分 --> <div class="col-xs-12 col-md-12 mb_blog_article_archive pc_blog_article_archive grid_12"> <a class="img-responsive col-xs-4 col-md-4 grid_4" href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a> <a class="grid_7 pc_new_blog_title"href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <p class="archive_author grid_7">written by:<?php the_author(); ?></p> <ul class="col-xs-8 col-md-8 grid_7 blog_archive_tag_wrap"> <li class="blog_archive_tag"><?php echo $tag; ?></li> </ul> </div> <?php endforeach; wp_reset_postdata(); ?> </section> <!-- ここまで --> <!-- アーカイブ周り --> <section class="row mb_blog_article_archive_wrap"> <h3 class="third_content_title h3_title">アーカイブ</h3> <?php $goodslist = get_posts( array( 'post_type' => 'blog', //特定のカスタム投稿タイプスラッグを指定 'posts_per_page' => -1 //取得記事件数 )); foreach( $goodslist as $post ): setup_postdata( $post ); ?> <!-- タグ情報取得 --> <?php $tag = ''; $separator = ''; $before = ''; if( get_post_type() === 'blog' ) { $tag = get_the_term_list( $post->ID, 'column', $before, $separator ); } ?> <!-- モバイル表示方法 --> <article class="col-xs-12 col-md-12 pc_hidden mb_blog_article_archive"> <a class="img-responsive col-xs-4 col-md-4" href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a> <div class="col-xs-8 col-md-8"> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <p class="archive_author">written by:<?php the_author(); ?></p> <div class="clearfix"></div> <ul> <li class="blog_archive_tag"><?php echo $tag; ?></li> </ul> </div> </article> <!--記事の表示方法PC--> <div class="grid_4 mb_hidden"> <div class="grid_4 f_article"> <!-- <span id="blog_colum_ribon"> <?php //newの表示について $hours = 10; //Newを表示させたい期間の時間 $today = date_i18n('U'); $entry = get_the_time('U'); $kiji = date('U',($today - $entry)) / 3600 ; if( $hours > $kiji ){ echo 'New!'; } ?> </span> --> <figure class="label test_label inside bottom f_thum" data-label="<?php the_title(); ?>"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a> </figure> </div> </div> <!--記事表示終了--> <?php endforeach; wp_reset_postdata(); ?> </section> <!-- ここまで --> </div><!--row end--> </div><!--container end--> <!-- end main--> <?php if(is_mobile()):?> <!--モバイルのヘッダー読み込み--> <?php get_footer("mb");?> <?php else: ?> <?php get_footer();?> <?php endif;?><file_sep>/single-blog.php <?php if (is_mobile()) :?> <?php get_header("mb");?> <?php else: ?> <?php get_header();?> <?php endif; ?> <div class="container_12 container-fluid" id="main"> <div class="row" id="start"> <div class="grid_12 col-xs-12 intern_article_main" id="article_main"> <!-- 記事の取得 --> <?php if(have_posts()): while(have_posts()): the_post(); ?> <!-- 記事の表示 --> <h1 class="article_title mb_article_title"><?php the_title();?></h1> <!-- <div class="grid_12 post_thum article_thumbnail"> --> <span class="col-xs-12 col-md-12 mb_blog_thum pc_blog_thum"><?php the_post_thumbnail('thumbnail', array('class' => 'img-thumbnail img-thumbnail-overwrite')); ?></span> <p class="col-xs-12 col-md-12 grid_12 mb_article_author pc_article_author">written by:<?php the_author(); ?></p> <!-- </div> --> <section class="col-xs-12 col-md-12 mb_blog_article"> <?php the_content();?> </section> <?php endwhile; endif; ?> </div> <div class="grid_12 col-xs-12 col-md-12"> <p>記事をシェアする</p> <?php get_template_part('sns-actions');?> </div> <div class="pager grid_12 col-xs-12 col-md-12"> <?php get_template_part('pager');?> </div> </div> </div><!--end main--> <?php if(is_mobile()):?> <!--モバイルのヘッダー読み込み--> <?php get_footer("mb");?> <?php else: ?> <?php get_footer();?> <?php endif;?> <file_sep>/flow_theme.php <?php /* Template Name: flow_theme */ ?> <?php if(is_mobile()) { ?> <?php get_header("mb");?> <?php } else { ?> <?php get_header();?> <?php } ?> <div class="container_12" id="main"> <!--パソコン--> <div class="container_12 mb_hidden" id="flow_main_image"> <h1 class="grid_12"><?php wp_title('',true,'');?></h1> <ul> <li><a href="#search"><img src="<?php bloginfo('template_url');?>/images/flowmenu/b_flow_search (1).jpg" /></a></li> <li><a href="#counseling"><img src="<?php bloginfo('template_url');?>/images/flowmenu/b_frow_counseling (1).jpg" /></a></li> <li><a href="#business"><img src="<?php bloginfo('template_url');?>/images/flowmenu/b_flow_business (1).jpg"/></a></li> <li><a href="#text"><img src="<?php bloginfo('template_url');?>/images/flowmenu/b_flow_text (1).jpg"/></a></li> <li><a href="#skype"><img src="<?php bloginfo('template_url');?>/images/flowmenu/b_flow_skype (1).jpg"/></a></li> <li><a href="#money"><img src="<?php bloginfo('template_url');?>/images/flowmenu/b_flow_money (1).jpg"/></a></li> <li><a href="#trip"><img src="<?php bloginfo('template_url');?>/images/flowmenu/b_flow_trip (1).jpg"/></a></li> <li><a href="#alive"><img src="<?php bloginfo('template_url');?>/images/flowmenu/b_flow_alive (1).jpg"/></a></li> </ul> </div><!--image end--> <!--スマホ--> <div class="pc_hidden"> <h1 class="grid_12"><?php wp_title('',true,'');?></h1> <section> <script> $(document).ready(function(e) { $('img[usemap]').rwdImageMaps(); }); </script> <img class="resizeimg" src="<?php bloginfo('template_url');?>/images/flowmenu/flowbtn.jpg" alt="ページ内ナビゲーション" width="100%" height="100%" border="0" usemap="#flowbtnmap"/> <map name="flowbtnmap" width="100%" height="100%"> <area shape=rect coords="0%,0%,25%,50%" href="#search" alt="search" /> <area shape=rect coords="25%,0%,50%,50%" href="#counseling" alt="counseling" /> <area shape=rect coords="50%,0%,75%,50%" href="#business" alt="business" /> <area shape=rect coords="75%,0%,100%,50%" href="#text" alt="text" /> <area shape=rect coords="0%,50%,25%,100%" href="#alive" alt="alive" /> <area shape=rect coords="25%,50%,50%,100%" href="#trip" alt="trip" /> <area shape=rect coords="50%,50%,75%,100%" href="#money" alt="money" /> <area shape=rect coords="75%,50%,100%,100%" href="#skype" alt="skype" /> </map> </section> <!-- <nav class="link1"> <ul> <li class="navSearch"><a href="#search">インターンを探す</a></li> <li class="navCounseling"><a href="#counseling">カウンセリング</a></li> <li class="navBusiness"><a href="#business">申し込み企業の決定</a></li> <li class="navText"><a href="#text">書類選考</a></li> </ul> </nav> <nav id="link2"> <ul> <li class="navAlive"><a href="#alive">渡航</a></li> <li class="navTrip"><a href="#trip">渡航の準備</a></li> <li class="navMoney"><a href="#money">手続き・入金</a></li> <li class="navSkype"><a href="#skype">Skype面接</a></li> </ul> </nav>--> </div><!--image end--> <div class="grid_12 flow_block" id="search"> <img class="resizeimg mb_hidden" src="<?php bloginfo('template_url');?>/images/flowmenu/flow_search (1).png" /> <h1 class="pc_hidden">インターン先を探す</h1> <p>まずはどんな企業様がインターンシップ生を募集しているのかを探しましょう。 インタビュー形式になっておりますので、どんな人がどんな想いを持って海外で働いているのかを知り、自分がそこで働く具体的なイメージを持つことができます。 <br>各ページには募集要項も掲載しておりますので、合わせてご覧ください。</p> <span id="flow_link"><h3><a href="http://intern-college.com/search_intern/">>>インターンを探す</a></h3></span> </div> <div class="grid_12 flow_block" id="counseling"> <img class="resizeimg mb_hidden" src="<?php bloginfo('template_url');?>/images/flowmenu/flow_counseling (1).png" /> <h1 class="pc_hidden">カウンセリング</h1> <p>まずはお気軽にご相談ください。経験豊富なスタッフがお電話またはメールであなたのお悩みにお答えさせていただきます。 開始時期、期間、英語力、身に着けたいスキルなど、お客様の納得のいく選択ができるよう徹底的にサポートさせていただきます。 <a href="http://intern-college.com/archives/1716/" target="_blank">個別無料相談会</a>も毎週末に実施しておりますので是非ご予約ください。</p><br /> <span id="flow_link"><h3><a href="http://intern-college.com/contact/">>>お問い合わせフォーム</a></h3></span> </div> <div class="grid_12 flow_block" id="business"> <img class="resizeimg mb_hidden" src="<?php bloginfo('template_url');?>/images/flowmenu/flow_business (1).png" /> <h1 class="pc_hidden">申し込み企業の決定</h1> <p>インターンシップへの参加を申し込む企業様を決定しましょう。最大で1度に3社までお申込み可能ですので、お悩みの際はご相談ください。</p><br /> <span id="flow_link"><h3><a href="http://intern-college.com/apply/">>>お申込みフォーム</a></h3></span> </div> <div class="grid_12 flow_block" id="text"> <img class="resizeimg mb_hidden" src="<?php bloginfo('template_url');?>/images/flowmenu/flow_text (1).png" /> <h1 class="pc_hidden">書類選考</h1> <p>申込み企業様が決定しましたら履歴書をご記入いただきます。セブターンでは専用の履歴書を用意しておりますのでご活用ください。 履歴書をご記入いただきますと、申込み企業様にお送りし、書類選考となります。 書類 選考の結果は1週間前後でセブターンよりお伝えさせていただきます。</p>  <div class="grid_4 push_4" id="f_file"><?php echo do_shortcode('[wpdm_package id=2918]');?></div> <span id="flow_link"><h3><a href="https://rireki.engawa.jp/app/b4d.do;jsessionid=2991BB2CBC770F5F64A6836B3A47F8A1">>>電子履歴書をダウンロードする</a></h3></span> </div> <div class="grid_12 flow_block" id="skype"> <img class="resizeimg mb_hidden" src="<?php bloginfo('template_url');?>/images/flowmenu/flow_skype (1).png" /> <h1 class="pc_hidden">Skype面接</h1> <p>書類選考に合格されますと、Skypeでの面接なります。お客様、面接担当者、セブターンの3者でSkypeグループを作成致しますので、そちらのメッセージ機能を利用して直接面接日程をご調整ください。        <br>面接の結果は1週間前後でセブターンよりお伝えさせていただきます。</p> </div> <div class="grid_12 flow_block" id="money"> <img class="resizeimg mb_hidden" src="<?php bloginfo('template_url');?>/images/flowmenu/flow_money (1).png" /> <h1 class="pc_hidden">手続き・入金</h1> <p>面接で合格し、インターンシップ参加への意思をお伝えいただきましたら、仮決定となります。 参加に際して必要な書類が2点ございますので、そちらをご記入いただき、料金のお振り込みが確認できた時点で参加が正式決定となります。</p><br /> <span id="flow_link"><h3><a href="">>>プログラム参加料</a></h3></span> </div> <div class="grid_12 flow_block" id="trip"> <img class="resizeimg mb_hidden" src="<?php bloginfo('template_url');?>/images/flowmenu/flow_trip (1).png" /> <h1 class="pc_hidden">渡航の準備</h1> <p>参加が正式決定しましたら、渡航までの準備を進めましょう。 航空券や保険、クレジットカードなどのサポートもさせていただいておりますので、いつでもお気軽にご相談ください。 渡航に際して分からないことがある場合はよくある質問もお読みください。</p><br /> <span id="flow_link"><h3><a href="http://intern-college.com/%E3%82%88%E3%81%8F%E3%81%82%E3%82%8B%E8%B3%AA%E5%95%8F/">>>よくある質問</a></h3></span> </div> <div class="grid_12 flow_block" id="alive"> <img class="resizeimg mb_hidden" src="<?php bloginfo('template_url');?>/images/flowmenu/flow_alive (1).png" /> <h1 class="pc_hidden">渡航</h1> <p>いよいよ出発です。 フィリピン・セブ島でかけがえのない経験を積みましょう。 渡航後も何かお困りのことがございましたらお気軽にご連絡ください。</p> </div> <div class="grid_12 flow_block_2" id=""> <h1>&nbsp;料金</h1> <p>プログラム参加料として<b>69,800円(税抜)</b> を面接に合格し、インターンシップへの参加が正式に決定した時点でお支払いいただきます。</p></br> <a color=“#white”><b>ポイント①</b></a></br><p>何ヶ月滞在しても一律料金で、フィリピン留学1週間分の授業料に相当!</p> <a color=“#white”><b>ポイント②</b></a><p>受け入れ先との密な情報交換と丁寧なコンサルティングにより高確率での内定獲得を支援!</p> <a color=“#white”><b>ポイント③</b></a><p>セブターン専用の無料オンライン英会話サービスでインターンシップ前の不安を解消!</p> <a color=“#white”><b>ポイント④</b></a><p>インターンシップ期間中は無料相談サービス付きで現地生活で困ったときも安心!</p> <a color=“#white”><b>ポイント⑤</b></a><p>留学+インターンでお申し込みの方、すでにフィリピン留学中の方には特別割引サービス実施中!</p> </br><p><h2>【プログラム参加料の中に含まれるもの】</h2> 相談・カウンセリング、受け入れ先のリサーチ、書類選考、受け入れ先のご紹介、受け入れ先との面接の手配、無料オンライン英会話サービス、現地生活情報の提供、空港送迎、インターンシップ期間中のサポート、帰国後のキャリアコンサルタントのご紹介、海外インターンシッププログラム参加申込書の発行、契約書の発行、受け入れ企業への申込み手続き代行、海外送金手数料</p></br> <p><h2>【上記金額に含まれないもの】</h2> 航空券、海外保険、VISA(受け入れ企業側負担・補助の場合あり)、現地生活費(受け入れ企業側の負担・補助の場合あり)、現地交通費(受け入れ企業側負担・補助の場合あり)</p> <span id="flow_link"><h3><a href="">>>特別割引サービスについて</a></h3></span> </div> <a class="intern_contact_form" href="http://intern-college.com/contact/"><img class="resizeimg" src="<?php bloginfo('template_url');?>/images/icon/intern_contact.png" id="intern_contact"/></a> <div class="grid_2" id="page_top_link"> <?php get_template_part('page_top_link'); ?> </div> </div> <!--end main--> <?php if(is_mobile()):?> <!--モバイルのヘッダー読み込み--> <?php get_footer("mb");?> <?php else: ?> <?php get_footer();?> <?php endif;?> <file_sep>/header.php <!DOCTYPE html> <html class="no-js" lang="ja"> <head> <title><?php wp_title('',true,'');bloginfo('name');?></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <!--リセットcss--> <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.18.1/build/cssreset/cssreset-min.css"> <!--コンテンツのcss--> <link rel="stylesheet" type="text/css" media="all" href="<?php echo get_template_directory_uri(); ?>/style.css"> <?php wp_head();?> <?php wp_deregister_script('jquery'); ?><!-- WordPressのjQueryを読み込ませない --> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <?php wp_enqueue_script('jquery.flexslider-min', get_bloginfo('template_directory').'/js/jquery.flexslider-min.js');?><!--スライダースクリプト--> <!--メニューをホバー時に半透明にするエフェクトをかける--> <script type="text/javascript"> jQuery(function(){ jQuery("menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-31 current_page_item menu-item-88").hover(function(){ jQuery(this).stop().animate({"opacity":"0.7"}); },function(){ jQuery(this).stop().animate({"opacity":"1"}); }); }); </script> <!--ここまで--> <!--アナリティクス--> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-44795290-1','auto' ); ga('require', 'linkid', 'linkid.js'); ga('send', 'pageview'); </script> <!--ここまで--> <!--flexslider--> <script type="text/javascript" charset="utf-8"> $(window).load(function() { $('.flexslider').flexslider(); }); </script> <!--ここまで--> <!-- トップリンク --> <script> // グローバル変数 var syncerTimeout = null ; // 一連の処理 $( function(){ // スクロールイベントの設定 $( window ).scroll( function(){ // 1秒ごとに処理 if( syncerTimeout == null ){ // セットタイムアウトを設定 syncerTimeout = setTimeout( function(){ // 対象のエレメント var element = $( '#page-top' ) ; // 現在、表示されているか? var visible = element.is( ':visible' ) ; // 最上部から現在位置までの距離を取得して、変数[now]に格納 var now = $( window ).scrollTop() ; // 最下部から現在位置までの距離を計算して、変数[under]に格納 var under = $( 'body' ).height() - ( now + $(window).height() ) ; // 最上部から現在位置までの距離(now)が1500以上かつ // 最下部から現在位置までの距離(under)が200px以上かつ… if( now > 1500 && 200 < under ){ // 非表示状態だったら if( !visible ){ // [#page-top]をゆっくりフェードインする element.fadeIn( 'slow' ) ; } } // 1500px以下かつ // 表示状態だったら else if( visible ){ // [#page-top]をゆっくりフェードアウトする element.fadeOut( 'slow' ) ; } // フラグを削除 syncerTimeout = null ; } , 1000 ) ; } } ) ; // クリックイベントを設定する $( '#move-page-top' ).click( function(){ // スムーズにスクロールする $( 'html,body' ).animate( {scrollTop:0} , 'slow' ) ; } ) ; } ) ; </script> <!-- ここまで --> </head> <body<?php body_class();?>> <div class="liquid_theme" id="start"> <div class="header_wrapper container_12"> <div class="grid_12 header"> <a href="<?php echo home_url('/'); ?>"><img class="grid_3 alpha"src="<?php bloginfo('template_url');?>/images/logo_new.png"/></a> <p class="grid_5 alpha omega"><?php bloginfo('name')?></p> <a class="grid_4 push_1" id="g_contact" href="http://intern-college.com/contact/"><p>お問い合わせ</p></a> </div> <div class="clearfix"></div> <div class="container_12"> <?php if(is_front_page()):?> <div class="flexslider"> <ul class="slides"> <li><a class="slides_link" href="http://intern-college.com/kobetsu-soudankai/"><img src="<?php bloginfo('template_url');?>/images/banner/soudankai_new.jpg"></a></li> <li><a class="slides_link" href="http://intern-college.com/online-english/"><img src="<?php bloginfo('template_url');?>/images/banner/online_banner_new.jpg"></a></li> <li><a class="slides_link" href="http://intern-college.com/about/"><img src="<?php bloginfo('template_url');?>/images/banner/main_banner_new.jpg"></a></li> </ul> </div> <?php else:?> <?php endif;?> </div> </div><!--header end--> <!--グローバルナビ--> <div class="container_12"> <div class="container_12 gNavi"> <?php wp_nav_menu(array( 'theme_location'=>'navigation', 'depth' => 1, )); ?> </div> <!--バナーここまで--> <div class="grid_12 pankuzu"> <?php if(is_front_page()):?> <?php else:?> <?php if(class_exists('WP_SiteMAnager_bread_crumb')): WP_Sitemanager_bread_crumb::bread_crumb('navi_element=div&elm_id=bread_crumb'); endif; ?> <?php endif;?> </div><!--pankuzu end--> </div> <file_sep>/author.php <?php /* Template Name: author */ ?> <div class="container-fluid"> </div><!--end container--><file_sep>/content-member.php <div class="container_12" id="article_main"> <div id="eye_catch_test"> <div class="grid_12" id="intern_thumbnail"><?php the_post_thumbnail();?></div><!--intern_thumbnail end--> <div class="grid_12" > <h1><?php the_title();?></h1> <div class="member_title grid_4 omega push_9"> <a class="member_sns" href="<?php echo esc_html($post->Twitter); ?>">Twitter</a> <a class="member_sns" href="<?php echo esc_html($post->Facebook); ?>">facebook</a> </div> </div> </div> <div class="grid_12 article_text" > <?php the_content(); ?> </div><!--intern content end--> <div class="grid_12" id="f_sns_action"> <h4>記事をシェアする</h4> <a href="https://twitter.com/share" class="twitter-share-button" data-via="cebutern">Tweet</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> </div> <div class="grid_6 alpha pager"> <?php previous_post_link('<li>&laquo;前の投稿<br />%link</li>'); ?> </div> <div class="grid_6 omega pager"> <?php next_post_link('<li>&raquo;次の投稿<br />%link</li>'); ?> </div> </div><!--article_main container_12 end--> <file_sep>/kobetsu.php <?php /* Template Name: kobetsu */ ?> <?php if(is_mobile()) { ?> <?php get_header("mb");?> <?php } else { ?> <?php get_header();?> <?php } ?> <img class="so-widget-image" style="max-width: 100%; height: auto; width: 100%; display: block;" src="http://intern-college.com/wp-content/uploads/2015/11/0ff308f2bb9fb4f8618e383063ffa351.jpg" alt="" width="940" height="372" /> <h2 style="text-align: center; width: 100%; text-decoration: underline;">フィリピン留学・海外インターン個別相談会を3会場で同時開催中!</h2> <span style="font-size: 14pt;">セブターンでは東京、大阪、セブ島の3会場にそれぞれカウンセリングスタッフが駐在しており、<span style="color: #ff0000;">毎週末</span>お客様のご希望に合わせて直接お話を伺う機会を設けています。</span> &nbsp; <span style="font-size: 14pt;">それがこちらの個別相談会です。参加費用はもちろん<span style="color: #ff0000;">無料</span>(ドリンクサービス付き)で、必ず<span style="color: #ff0000;">1:1</span>でのカウンセリングとなりますので、ご安心してお越しください。</span> &nbsp; <span style="font-size: 14pt;"><strong>・フィリピン留学とインターンって何が違うの?</strong></span> &nbsp; <span style="font-size: 14pt;"><strong>・費用はどれくらいかかるの?</strong></span> &nbsp; <span style="font-size: 14pt;"><strong>・フィリピンって安全なの?</strong></span> &nbsp; <span style="font-size: 14pt;"><strong style="line-height: 1.5;">・全く英語が話せないけど大丈夫?</strong></span> &nbsp; <span style="font-size: 14pt;">海外経験豊富なカウンセリングスタッフがこのような質問・不安に対して的確にアドバイスいたします。</span> &nbsp; <h1 style="text-align: center;">カウンセラー紹介</h1> <img class="so-widget-image" style="max-width: 100%; height: auto; display: block;" src="http://intern-college.com/wp-content/uploads/2016/01/IMG_5902.jpg" alt="" width="1280" height="853" /> <p style="text-align: center; width: 100%;"><span style="font-size: 18pt;"><strong>江浪 啓典(大阪、東京担当)</strong></span></p> &nbsp; <ul> <li><span style="font-size: 14pt;">フィリピン留学期間:1か月半</span></li> <li><span style="font-size: 14pt;">インターンシップ期間:6か月</span></li> </ul> <span style="font-size: 14pt;">セブターン代表。</span><span style="font-size: 14pt;"> 大学4年時に就職留年をしてフィリピン留学へ。1か月半でTOEIC400点UPに成功し、半年間のセブ島インターンに挑戦。100名以上の留学生のサポート経験を生かしてフィリピン留学、インターンシップ情報に精通。就職活動、休学、留学、インターン、何でもご相談ください。</span> <img class="so-widget-image" style="max-width: 100%; height: auto; display: block;" src="http://intern-college.com/wp-content/uploads/2016/01/original.png" alt="" width="956" height="635" /> <p style="text-align: center; max-width: 100%;"><span style="font-size: 18pt;"><strong>久世 惇人(セブ島担当)</strong></span> <span style="font-size: 14pt;"> </span></p> <ul> <li><span style="font-size: 14pt;">フィリピン留学期間:5か月</span></li> <li><span style="font-size: 14pt;">インターンシップ期間:4か月</span></li> </ul> &nbsp; <span style="font-size: 14pt;">セブターン現地担当。</span> <span style="font-size: 14pt;"> セブ島の語学学校を2校経験したのちオーストラリアのワーホリへ。その後再びセブ島に戻り、旅人たちが集まる語学学校でのインターンを経験。現在はセブ島でインタビューをしながら語学学校を駆け回る、休学、旅、留学、語学学校のスペシャリスト。</span><span style="font-size: 14pt;">セブでお会いしましょう</span>! <h1 style="text-align: center;">個別相談会の概要</h1> <img class="so-widget-image" style="max-width: 100%; height: auto; display: block;" src="http://intern-college.com/wp-content/uploads/2016/01/d2626f0eccf2e0449ed15d3174084d36_m.jpg" alt="" width="1920" height="1280" /> <span style="font-size: 14pt;">・1:1の個別で約1時間みっちりカウンセリング</span><span style="font-size: 14pt;"> </span> &nbsp; <span style="font-size: 14pt;">・毎週土・日に3会場(東京・大阪・セブ)から選択可能</span> &nbsp; <span style="font-size: 14pt;">・ドリンク無料サービス</span> &nbsp; <span style="font-size: 14pt;">・各日程先着1名様限定</span> <h1 style="text-align: center;">会場</h1> ・大阪会場 タリーズ阪急ビル店 大阪府大阪市北区角田町8-1 梅田阪急ビルオフィスタワー15F(<a href="https://www.google.co.jp/maps/place/%E6%A2%85%E7%94%B0%E9%98%AA%E6%80%A5%E3%83%93%E3%83%AB+%E3%82%AA%E3%83%95%E3%82%A3%E3%82%B9%E3%82%BF%E3%83%AF%E3%83%BC/@34.6894859,135.4830286,13.23z/data=!4m2!3m1!1s0x6000e692f16755c1:0x30a4d2a97295a0b" target="_blank">地図</a>) &nbsp; ・東京会場 麻布十番マンシーズトウキョウ(<a href="https://www.google.co.jp/maps/place/%E3%80%92106-0045+%E6%9D%B1%E4%BA%AC%E9%83%BD%E6%B8%AF%E5%8C%BA%E9%BA%BB%E5%B8%83%E5%8D%81%E7%95%AA%EF%BC%91%E4%B8%81%E7%9B%AE%EF%BC%93%E2%88%92%EF%BC%99+%EF%BC%B4%EF%BC%A2%EF%BC%A3%E9%BA%BB%E5%B8%83/@35.6568125,139.7335516,17z/data=!3m1!4b1!4m2!3m1!1s0x60188b9f15bfc139:0x860edc4b3e690de1" target="_blank">地図</a>) &nbsp; ・セブ島会場 Ayala Mall Starbucks Coffee Ayala Center Cebu, Cebu Business Park, Cebu City(<a href="https://www.google.co.jp/maps/place/StarBucks+-+Ayala+Center+Cebu+Branch/@10.3184923,123.9025423,17z/data=!3m1!4b1!4m2!3m1!1s0x33a9993efb129017:0xa00e5ed6c687ce59" target="_blank">地図</a>) <img class="so-widget-image" style="max-width: 100%; height: auto; display: block;" src="http://intern-college.com/wp-content/uploads/2015/10/12182000_739541569511425_1312998323_n.jpg" alt="" width="960" height="720" /> <h2 style="text-align: center;">予約フォーム</h2> [trust-form id=1839] <?php if(is_mobile()):?> <!--モバイルのヘッダー読み込み--> <?php get_footer("mb");?> <?php else: ?> <?php get_footer();?> <?php endif;?> <file_sep>/test-pagenetion.php <!--▼ページ送り▼--> <!--<?php $prevpost = get_adjacent_post(false, '', true); //前の記事 $nextpost = get_adjacent_post(false, '', false); //次の記事 if( $prevpost or $nextpost ){ //前の記事、次の記事いずれか存在しているとき ?> <div class="cat_paging grid_12 pager"> <?php if ( $prevpost ) { //前の記事が存在しているとき echo '<div class="grid_6 omega alpha pager"> <h4>前の記事</h4> <a href="' . get_permalink($prevpost->ID) . '"> <p id="thumb">' . get_the_post_thumbnail($prevpost->ID, 'thumbnail') . '</p> <p id="title">' . get_the_title($prevpost->ID) . '</p> </a> </div>'; } else { //前の記事が存在しないとき echo '<div class=""grid_6 omega alpha pager"> <a href="' . network_site_url('/') . '">TOPへ戻る</a> </div>'; } if ( $nextpost ) { //次の記事が存在しているとき echo '<div class=""grid_4 omega alpha pager"> <h4>次の記事</h4> <a href="' . get_permalink($nextpost->ID) . '"> <p class="thumb">' . get_the_post_thumbnail($nextpost->ID, 'thumbnail') . '</p> <p class="title">' . get_the_title($nextpost->ID) . '</p> </a> </div> '; } else { //次の記事が存在しないとき echo '<div class="alignright nopost pager"> <a href="' . network_site_url('/') . '">TOPへ戻る</a> </div>'; } ?> <?php } ?> </div>--><file_sep>/online-english-theme.php <?php /* Template Name: online-english-theme */ ?> <?php get_header();?> <div class="container_12 on_main on_spacing"> <div class="grid_12" id="on-english"><h1><?php echo get_the_title(); ?></h1></div> <div class="grid_12 on_heading"><h1>Learnasia様とセブターンが連携!</h1></div> <div class="grid_12"><img src="http://intern-college.com/wp-content/uploads/2015/12/cebulearnasia.jpg"></div> <div class="grid_10"> <p>この度、セブ島にオンライン英会話の拠点を構えるLearnasia様と提携しまして、<br> 海外インターンシップご参加前にSkypeオンライン英会話をご提供させていただくこととなりました。</p> </div> <div class="clear"></div> <ul class="grid_7" id="on-intro"> <li>これまで海外インターンシップに参加するに当たって、</li> <li>英語でクレームが来たらどうしよう・・・</li> <li>英語で電話を取るのが不安・・・</li> <li>英文メールで失礼な文章を送ってしまわないかな・・・</li> <li>このような不安を抱えておられる方が多数おりました。</li> </ul> <div class="clear"></div> <div class="grid_12"><p>そこで上記のような不安を抱えておられる方のために、 セブターンとLearnasia様で協力して、海外インターンシップで頻繁に起こる場面を想定した特別コースを作成いたしました。</p></div> <!--<div class="grid_12" id="on-course"><img src=""></div> <div class="grid_12" id="oe_body_2">--> <div class="grid_12 on_heading"><h1>セブターン専用インターン準備8コマ完結コース</h1></div> <div class="grid_6"><img class="sizechange"src="http://intern-college.com/wp-content/uploads/2015/12/onimg.jpg"></div> <div class="grid_4 prefix_2 on_spacing"> <ul> <li>1コマ目 挨拶・自己紹介</li> <li>2コマ目 許可・依頼</li> <li>3コマ目 アポイントメント</li> <li>4コマ目 クレーム対応</li> <li>5コマ目 電話対応</li> <li>6コマ目 メール対応</li> <li>7コマ目 来客対応</li> <li>8コマ目 プレゼンテーション</li> </ul> </div> <div class="clear"></div> <div class="grid_12 on_heading"> <h1>実施時間(1コマ50分)</h1></div> <div class="grid_12 on_spacing"> <p>月曜日~金曜日<br>14:00~20:00(レッスン開始時間)</p><br> <p>土曜日、日曜日<br>10:00~17:00(レッスン開始時間)</p> </div> <div class="grid_12 on_heading"><h1>受講方法</h1></div> <div class="grid_12 on_spacing"> <p>インターンシップの参加が正式に決定したのち、IDとパスワードを発行致しますので自身のご都合の良い時間にご予約ください。</p> <p>教材として各授業のレッスンシート(PDFファイル)と予習用の動画をお送りいたします。</p> <p>ファイルを開ける状態にしておくか、印刷してご用意ください。</p> <p>授業はSkypeにて行います。SkypeのIDを取得しておられない方は事前にご取得ください。</p> <p>受講方法の詳細は別途ご案内いたします。</p> </div> <div class="grid_12 on_heading"><h1>注意事項</h1></div> <div class="grid_12"> <ul> <li>提供は2015年10月1日以降にお問い合わせ、お申込みされた方に限ります。</li> <li>こちらのコースは渡航後にも受講いただくことができます。</li> <li>混雑時はご希望の時間に受講できないことが予想されます。</li> <li>料金はプログラム参加料に含まれます。教材を印刷する場合はご自身で負担ください。</li> <li>コースは予告なく変更・終了することがございます。予めご了承ください。</li> <li>年末年始、クリスマス、フィリピンの祝日等はご予約いただくことはできません。</li> </ul> </div> <div class="grid_12" id="on-contact"><p>その他のご質問につきましては下記フォームよりお気軽にお問い合わせください。</p></div> <br> <br> <div class="grid_12" id="contact-form"> <a href="http://intern-college.com/contact/"><img src="<?php bloginfo('template_url');?>/images/icon/intern_contact.png" id="intern_contact"/></a> </div><!--contact form end--> </div><!--end main--> <?php get_footer();?>
65de9841f388a3535b84805616e1267e8b3b4da9
[ "PHP" ]
41
PHP
shota-co/cebutern
bb3b59c21e466eb8e859c6438c67d3cf657b6f19
6f3403e09fa0a5f483a2fd382368fd6db4b7b6a3
refs/heads/master
<file_sep>'use strict'; const express = require('express'); const user_helper = require('../../helpers/user'); const students = require('../../functions/student/student'); const config = require('../../config/config.json'); var router = express.Router(); router.get('/', (req, res) => { const user_id = req.headers['id']; students.getStudent(user_id) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); router.get('/checkout/id/:price', (req, res) => { var price = req.params['price']; price = Number(price).toFixed(2); const user_id = req.headers['id']; students.getCheckoutID(user_id, price) .then(result => { res.status(200).json({ id: result.id }) }) .catch(err => res.status(err.status).json(null)); }); router.post('/checkout/success', (req, res) => { const id = req.headers['id']; const course_number = req.body["course_number"]; const level_number = req.body["level_number"]; const subject_number = req.body["number"]; students.purchaseSuccess(id, course_number, level_number, subject_number) .then(result => res.json(result)) .catch(err => res.status(err.status).json(null)); }); router.get('/checkout/status/:id', (req, res) => { const user_id = req.headers['id']; const checkout_id = req.params['id']; students.getCheckoutStatus(checkout_id) .then(result => res.json(result)) .catch(err => res.status(err.status).json(null)); }); module.exports = router;<file_sep>'use strict' const mongoose = require('mongoose'); const Schema = mongoose.Schema; const studentSchema = mongoose.Schema({ user_id: String, paid_subjects: [{ course_number: Number, level_number: Number, subject_number: Number, date: Date, remain_date: Number }] }); module.exports = mongoose.model('student', studentSchema);<file_sep>'use strict' const mongoose = require('mongoose'); mongoose.Promise = global.Promise; //mongoose.connect('mongodb://localhost:27017/school-db'); const username = 'snowsea'; const password = '<PASSWORD>'; mongoose.connect('mongodb://' + username + ':' + password + '@ds115091-a0.mlab.com:15091,ds115091-a1.mlab.com:15091/heroku_ldk8l55q?replicaSet=rs-ds115091'); <file_sep>'use strict' const mongoose = require('mongoose'); const Schema = mongoose.Schema; const courseSchema = mongoose.Schema({ number: Number, name: String, is_available: Boolean, levels: [{ number: Number, name: String }] }); module.exports = mongoose.model('course', courseSchema);<file_sep>'use strict'; const auth = require('basic-auth'); const jwt = require('jsonwebtoken'); const express = require('express'); const register = require('../../functions/user/register'); const login = require('../../functions/user/login'); const config = require('../../config/config.json'); const helper = require('../../helpers/user'); const user = require('../../functions/user/user'); const password = require('../../functions/user/password'); var router = express.Router(); router.post('/login', (req, res) => { const credentials = auth(req); if (!credentials) { res.status(400).json({ message: 'Invalid Request !' }); } else { login.login(credentials.name, credentials.pass) .then(result => { const token = jwt.sign(result.user.email, config.secret, {}); const user = { email: result.user.email, user_type: result.user.user_info.user_type, first_name: result.user.user_info.first_name, last_name: result.user.user_info.last_name, token: token } res.status(result.status).json({ user: user, token: token }); }) .catch(err => res.status(err.status).json({ message: err.message })); } }); router.post('/register', (req, res) => { const info = { first_name: req.body.first_name, last_name: req.body.last_name, country: req.body.country, phone_number: req.body.phone_number, user_type: req.body.user_type }; if (info.user_type === undefined) { info.user_type = 0; } const email = req.body.email; const password = <PASSWORD>; if (!email || !password || !email.trim() || !password.trim()) { res.status(400).json({ message: 'Invalid Request !' }); } else { register.register(email, password, info) .then(result => { res.setHeader('Location', '/' + email); res.status(result.status).json({ message: result.message, user: result.user }) }) .catch(err => { res.status(err.status).json({ message: err.message }) }); } }); router.get('/:id', (req, res) => { if (helper.checkToken(req)) { profile.getProfile(req.params.id) .then(result => res.json(result)) .catch(err => res.status(err.status).json({ message: err.message })); } else { res.status(401).json({ message: 'Invalid Token !' }); } }); router.get('/users/:type', (req, res) => { if (helper.checkToken(req)) { const type = req.params.type; user.getUsers(type) .then(result => res.json(result)) .catch(err => res.status(err.status).json({ message: err.message })); } else { res.status(401).json({ message: 'Invalid Token !' }); } }); router.get('/delete/:id', (req, res) => { if (helper.checkToken(req)) { const id = req.params.id; user.deleteUser(id) .then(result => res.json(result)) .catch(err => res.status(err.status).json({ message: err.message })); } else { res.status(401).json({ message: 'Invalid Token !' }); } }); router.post('/update', (req, res) => { if (helper.checkToken(req)) { const info = req.body.user_info; user.updateUser(info) .then(result => res.json(result)) .catch(err => res.status(err.status).json({ message: err.message })); } else { res.status(401).json({ message: 'Invalid Token !' }); } }); router.put('/:id', (req, res) => { if (helper.checkToken(req)) { const oldPassword = req.body.password; const newPassword = req.body.newPassword; if (!oldPassword || !newPassword || !oldPassword.trim() || !newPassword.trim()) { res.status(400).json({ message: 'Invalid Request !' }); } else { password.changePassword(req.params.id, oldPassword, newPassword) .then(result => res.status(result.status).json({ message: result.message })) .catch(err => res.status(err.status).json({ message: err.message })); } } else { res.status(401).json({ message: 'Invalid Token !' }); } }); router.post('/:id/password', (req, res) => { const email = req.params.id; const code = req.body.code; const newPassword = <PASSWORD>; if (!code || !newPassword) { password.resetPasswordInit(email) .then(result => res.status(result.status).json({ message: result.message })) .catch(err => res.status(err.status).json({ message: err.message })); } else { password.resetPasswordFinish(email, code, newPassword) .then(result => res.status(result.status).json({ message: result.message })) .catch(err => res.status(err.status).json({ message: err.message })); } }); module.exports = router;<file_sep>'use strict'; const express = require('express'); const user_helper = require('../../helpers/user'); const courses = require('../../functions/course/course'); const subjects = require('../../functions/course/subject'); var router = express.Router(); router.get('/', function (req, res) { courses.getCourses() .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); router.get('/delete/:id', function (req, res) { const id = req.params.id; courses.deleteCourse(id) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); router.post('/add', function (req, res) { const data = req.body.data; courses.addCourse(data) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); router.post('/subjects/update', function (req, res) { const data = req.body.data; subjects.updateSubject(data) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); router.post('/subjects/add', function (req, res) { const data = req.body.data; subjects.addSubject(data) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); router.post('/update', function (req, res) { const data = req.body.data; courses.updateCourse(data) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); router.post('/levels/add', function (req, res) { const data = req.body.data; courses.addLevel(data) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); router.post('/levels/delete', function (req, res) { const data = req.body.data; courses.deleteLevel(data) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); router.post('/levels/update', function (req, res) { const data = req.body.data; courses.updateLevel(data) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); router.get('/:course_number/:level_number/subjects', (req, res) => { const course_number = req.params['course_number']; const level_number = req.params['level_number']; subjects.getSubjects(course_number, level_number) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); router.get('/subjects/delete/:id', (req, res) => { const id = req.params.id; subjects.deleteSubject(id) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); router.post('/chapters/add', function (req, res) { const data = req.body.data; subjects.addChapter(data) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); router.post('/chapters/delete', function (req, res) { const data = req.body.data; subjects.deleteChapter(data) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); router.post('/chapters/update', function (req, res) { const data = req.body.data; subjects.updateChapter(data) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); module.exports = router;<file_sep>'use strict' const mongoose = require('mongoose'); const Schema = mongoose.Schema; const questionSchema = mongoose.Schema({ _id: Schema.ObjectId, course_number: Number, level_number: Number, subject_number: Number, question: { user_id: String, title: String, content: String, created_at: Date }, is_answered: Boolean, answer: { user_id: String, content: String, created_at: Date } }); module.exports = mongoose.model('question', questionSchema);<file_sep>'use strict'; const course = require('../../models/course'); module.exports.getCourses = () => new Promise((resolve, reject) => { course.find().sort({ number: 1 }) .then(courses => resolve(courses)) .catch(err => reject({ status: 500, message: 'Internal Server Error !' })); }); module.exports.deleteCourse = (id) => new Promise((resolve, reject) => { course.find({_id: id}) .then(courses => { if (courses.length == 0) { reject({ status: 404, message: 'Course Not Found !' }); } courses[0].remove(); }) .then(() => resolve({ status: 200, message: 'Operation has done successfully !' })) .catch(err => reject({ status: 500, message: 'Internal Server Error !' })); }); module.exports.deleteLevel = (data) => new Promise((resolve, reject) => { course.find({ _id: data.course_id }) .then(courses => { if (courses.length == 0) { reject({ status: 404, message: 'Course Not Found !' }); } const course = courses[0]; for (var i = 0; i < course.levels.length; i++) { if (course.levels[i].number == data.number) { course.levels.splice(i, 1); break; } } return course.save(); }) .then(() => resolve({ status: 200, message: 'Operation has done successfully !' })) .catch(err => reject({ status: 500, message: 'Internal Server Error !' })); }); module.exports.addCourse = (data) => new Promise((resolve, reject) => { const newCourse = new course({ number: data.number, name: data.name, is_available: data.is_available, levels: [] }); newCourse.isNew = true; newCourse.save() .then((course) => resolve({ status: 200, message: 'Operation has done successfully !', course: course })) .catch(err => reject({ status: 500, message: 'Internal Server Error !' })); }); module.exports.updateCourse = (data) => new Promise((resolve, reject) => { course.find({ _id: data.id }) .then(courses => { if (courses.length == 0) { reject({ status: 404, message: 'Course Not Found !' }); } const course = courses[0]; course.number = data.number; course.name = data.name; course.is_available = data.is_available; return course.save(); }) .then((course) => resolve({ status: 200, message: 'Operation has done successfully !', course: course })) .catch(err => reject({ status: 500, message: 'Internal Server Error !' })); }); module.exports.updateLevel = (data) => new Promise((resolve, reject) => { course.find({ _id: data.course_id }) .then(courses => { if (courses.length == 0) { reject({ status: 404, message: 'Course Not Found !' }); } const course = courses[0]; for (var i = 0; i < course.levels.length; i++) { if (course.levels[i].number == data.old_number) { course.levels[i].number = data.number; course.levels[i].name = data.name; break; } } return course.save(); }) .then((course) => resolve({ status: 200, message: 'Operation has done successfully !', course: course })) .catch(err => reject({ status: 500, message: 'Internal Server Error !' })); }); module.exports.addLevel = (data) => new Promise((resolve, reject) => { course.find({ _id: data.course_id }) .then(courses => { if (courses.length == 0) { reject({ status: 404, message: 'Course Not Found !' }); } const course = courses[0]; course.levels.push({ number: data.number, name: data.name }) return course.save(); }) .then((course) => resolve({ status: 200, message: 'Operation has done successfully !', course: course })) .catch(err => reject({ status: 500, message: 'Internal Server Error !' })); }); <file_sep># Tutor_Backend <file_sep>'use strict'; const student = require('../../models/student'); const purchase = require('../../models/purchase'); const mongoose = require('mongoose'); const querystring = require('querystring'); const config = require('../../config/config.json'); const http = require('https'); const user = require('../../models/user'); const randomstring = require("randomstring"); module.exports.getStudent = (user_id) => new Promise((resolve, reject) => { student.find({ user_id: user_id }) .then(students => { if (students.length == 0) { reject({ status: 404, message: 'User Not Found !' }); } var student = students[0]; var subjects = student.paid_subjects; var expireDate = new Date(); expireDate.setDate(expireDate.getDate() + 365); var newSubjects = []; for (var i = 0; i < subjects.length; i++) { if (subjects[i].date < expireDate) { newSubjects.push(subjects[i]); } } student.paid_subjects = newSubjects; return student.save(); }) .then(student => { var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds var firstDate = new Date(); var subjects = student.paid_subjects; for (var i = 0; i < subjects.length; i++) { subjects[i].remain_date = 365 - Math.round(Math.abs((firstDate.getTime() - subjects[i].date.getTime()) / (oneDay))); } resolve(student); }) .catch(err => reject({ status: 500, message: 'Internal Server Error !' })); }); module.exports.getCheckoutID = (user_id, price) => new Promise((resolve, reject) => { user.find({ 'email': user_id }) .then(users => { if (users.length == 0) { reject({ status: 404, message: 'User Not Found !' }); } const user = users[0]; var path = '/v1/checkouts'; var data = querystring.stringify({ 'authentication.userId': config.payment_user_id, 'authentication.password': config.payment_password, 'authentication.entityId': config.payment_entity_id, 'amount': price, 'currency': 'ZAR', 'paymentType': 'DB', 'merchantTransactionId': randomstring.generate(55), 'customer.givenName': user.user_info.first_name, 'customer.surname': user.user_info.last_name, 'customer.email': user.email, 'shipping.street1': 'Forum 2', 'shipping.street2': '33 Hoofd Street', 'shipping.city': 'Braamfontein', 'shipping.state': 'Gauteng', 'shipping.postcode': '2000', 'shipping.country': 'ZA', 'shopperResultUrl': 'com.snowsea.accountingtutors.payments://shopper_result', 'notificationUrl': 'https://tshiamo.herokuapp.com/api/students/checkout/notification' }); var options = { port: 443, host: 'oppwa.com', path: path, method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': data.length } }; var postRequest = http.request(options, function (res) { res.setEncoding('utf8'); res.on('data', function (chunk) { var jsonRes = JSON.parse(chunk); resolve(jsonRes); }); }); postRequest.write(data); postRequest.end(); }) .catch(err => reject({ status: 500, message: 'Internal Server Error !' })); }); module.exports.getCheckoutStatus = (id) => new Promise((resolve, reject) => { var result = ''; var path = '/v1/checkouts/' + id + '/payment'; path += '?authentication.userId=' + config.payment_user_id path += '&authentication.password=' + config.payment_password path += '&authentication.entityId=' + config.payment_entity_id var options = { port: 443, host: 'oppwa.com', path: path, method: 'GET', }; var postRequest = http.request(options, function (res) { res.setEncoding('utf8'); res.on('data', function (chunk) { result += chunk; }); res.on('end', function () { const jsonRes = JSON.parse(result); resolve(jsonRes.result); // your code here if you want to use the results ! }); }); postRequest.end(); }) .catch(err => reject({ status: 500, message: 'Internal Server Error !' })); module.exports.purchaseSuccess = (user_id, course_number, level_number, subject_number) => new Promise((resolve, reject) => { student.find({ user_id: user_id }) .then(students => { let student = students[0]; student.paid_subjects.push({ course_number: course_number, level_number: level_number, subject_number: subject_number, date: new Date() }); student.save(); }) .then((student) => resolve({ status: 200, message: 'Paid successfully' })) .catch(err => reject({ status: 500, message: 'Internal Server Error !' })); }); <file_sep>const user = require('../../models/user'); const student = require('../../models/student'); const lecturer = require('../../models/lecturer'); var bcrypt = require('bcrypt-nodejs'); exports.register = (email, password, user_info) => new Promise((resolve, reject) => { const salt = bcrypt.genSaltSync(10); const hash = bcrypt.hashSync(password, salt); if (user_info.user_type == undefined) user_info.user_type = 0; const newUser = new user({ email: email, user_info: user_info, hashed_password: <PASSWORD>, created_at: new Date() }); var newUserDetail; if (user_info.user_type == 1) { newUserDetail = new lecturer({ user_id: email, subjects: [] }); } else if (user_info.user_type == 0) { newUserDetail = new student({ user_id: email, paid_subjects: [] }); } newUser.isNew = true; newUserDetail.isNew = true; newUser.save() .then(() => newUserDetail.save()) .then(() => { return user.find({ email: email }); }) .then((users)=>resolve({ status: 201, message: 'User Registered Sucessfully !', user: users[0] })) .catch(err => { if (err.code == 11000) { reject({ status: 409, message: 'User Already Registered !' }); } else { reject({ status: 500, message: 'Internal Server Error !' }); } }); }); <file_sep>'use strict' const mongoose = require('mongoose'); const Schema = mongoose.Schema; const userSchema = mongoose.Schema({ email: String, hashed_password: String, user_info: { first_name: String, last_name: String, country: String, phone_number: String, user_type: Number }, created_at: String, temp_password: String, temp_password_time: String, }); module.exports = mongoose.model('user', userSchema);<file_sep>'use strict'; const jwt = require('jsonwebtoken'); const config = require('../config/config.json') exports.checkToken = function(req) { var token = req.headers['x-access-token']; var id = req.headers['id']; if (token) { try { var decoded = jwt.verify(token, config.secret); return (decoded === id); } catch (err) { return false; } } else { return false; } }<file_sep>'use strict'; const express = require('express'); const questions = require('../../functions/question/question'); var router = express.Router(); router.get('/questions/:is_answered', (req, res) => { questions.getQuestions(is_answered) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); router.get('/user_questions', (req, res) => { const user_id = req.headers['id']; questions.getUserQuestions(user_id) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); router.post('/ask', (req, res) => { const user_id = req.headers['id']; const course_number = req.body['course_number']; const level_number = req.body['level_number']; const subject_number = req.body['subject_number']; const title = req.body['question']['title']; const content = req.body['question']['content']; questions.ask(user_id, course_number, level_number, subject_number, title, content) .then(result => { res.status(200).json(result) }) .catch(err => res.status(err.status).json(null)); }); router.post('/answer', (req, res) => { const user_id = req.headers['id']; const question_id = req.body['_id']; const answer = req.body['answer']['content']; questions.answer(user_id, question_id, answer) .then(result => { res.status(200).json(result) }) .catch(err => res.status(err.status).json(null)); }); router.get('/:course_number/:level_number/:subject_number', (req, res) => { const course_number = req.params['course_number']; const level_number = req.params['level_number']; const subject_number = req.params['subject_number']; questions.getQuestions(course_number, level_number, subject_number) .then(result => res.status(200).json(result)) .catch(err => res.status(err.status).json(null)); }); module.exports = router;
ab559bdd84d02266e7df5ea0ab0cfa6ffbd18661
[ "JavaScript", "Markdown" ]
14
JavaScript
jsdevninja/Tutor_Backend
a5ae1796252d718233cec0cb22c3f49b58b3b882
b7777121656155c6502c95b4fd3995534c3f9995