branch_name
stringclasses
15 values
target
stringlengths
26
10.3M
directory_id
stringlengths
40
40
languages
sequencelengths
1
9
num_files
int64
1
1.47k
repo_language
stringclasses
34 values
repo_name
stringlengths
6
91
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
input
stringclasses
1 value
refs/heads/master
<repo_name>koga117/proyecto-sena<file_sep>/Capadelogica/LGestionUsuario.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using Capadedatos; using Capadelogica; using System.Data; using System.Net.Mail; namespace Presentacion { public class LGestionUsuario { public string a{get;set;} public string b{get;set;} public string c{get;set;} public string d{get;set;} public string e{get;set;} public string f{get;set;} public string g{get;set;} public string h{get;set;} public string i{get;set;} public string j{get;set;} public string k{get;set;} public string valor{get;set;} public string correo; public string Lregistrar(bool Guardar = true) { if (b.Length >= 10) i = b.Replace(' ', '.').Substring(0, 9); else i = b.Replace(' ', '.'); i = i + a.Substring(a.Length - 4); i = i.ToLower(); Random aleatorio = new Random(); string contrasena = ""; string[] vals = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}; for (int i3 = 1; i3 <= 5; i3++) { contrasena = contrasena + vals[aleatorio.Next(vals.GetUpperBound(0) + 1)]; } j = contrasena; //MailMessage mail = new MailMessage(); //mail.To.Add(new MailAddress(correo)); //mail.From = new MailAddress("<EMAIL>"); //mail.Subject = " Registro Exitoso"; //mail.Body = "Bienvenido su usuario es: " +i+ correo + " y su contraseña es: " + j; //mail.IsBodyHtml = false; //SmtpClient cl = new SmtpClient("smtp.live.com", 587); //using (cl) //{ // cl.Credentials = new System.Net.NetworkCredential("<EMAIL>", "<PASSWORD>"); // cl.EnableSsl = true; // cl.Send(mail); //} if (Guardar) { DGestionUsuario instancia = new DGestionUsuario(); return instancia.Dregistrar(a, b, c, d, e, f, g, h, i, contrasena, k); } else { return "Datos generados correctamente"; } } public DataTable Lconsultar() { DGestionUsuario instancia = new DGestionUsuario(); return instancia.Dconsultar(); } public DataTable ConsultaEspecificaNombre() { DGestionUsuario instancia = new DGestionUsuario(); instancia.recibido=valor; return instancia.ConsultaEspecificaNombre(); } public string Lactualizar() { DGestionUsuario instancia = new DGestionUsuario(); return instancia.Dactualizar(a, b, c, d, e); } public string Leliminar(string a ) { DGestionUsuario instancia = new DGestionUsuario(); return instancia.Deliminar(a); } } } <file_sep>/Presentacion/Ploadscreen.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Presentacion { public partial class Ploadscreen : Form { public Ploadscreen() { InitializeComponent(); timer1.Start(); } private void timer1_Tick(object sender, EventArgs e) { progressBar1.Value = progressBar1.Value + 2; // progressBar1.Value = progressBar1.Value + 2; // progressBar1.Style = ProgressBarStyle.Continuous; if (Convert.ToInt32(progressBar1.Value) == 100) { timer1.Stop(); timer1.Enabled = false; this.Hide(); PLogin da = new PLogin(); da.Show(); } } } } <file_sep>/Presentacion/PRegistroempleado.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Capadelogica; namespace Presentacion { public partial class PRegistroempleado : Form { public PRegistroempleado() { InitializeComponent(); } PMenu m = new PMenu(); private void pictureBox3_Click(object sender, EventArgs e) { this.Hide(); } private void pictureBox1_Click(object sender, EventArgs e) { if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "" || textBox5.Text == "" || textBox7.Text == "" || textBox8.Text == "" || textBox9.Text == "" || textBox10.Text == "" || textBox11.Text == "") { MessageBox.Show("Verifique, valores incompletos", "Validacion de campos vacios", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { LGestionUsuario instancia = new LGestionUsuario(); instancia.a = textBox1.Text; instancia.b = textBox2.Text; instancia.c = textBox3.Text; instancia.d = textBox4.Text; instancia.e = textBox5.Text; instancia.f = textBox7.Text; instancia.g = textBox8.Text; instancia.h = textBox9.Text; instancia.i = textBox10.Text; instancia.j = textBox11.Text; instancia.k = label13.Text; string respuesta = instancia.Lregistrar(); if (respuesta == "1") { MessageBox.Show("Registro exitoso", "Confirmacion", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("No se pudo registrar el nuevo usuario,vuelva a intentarlo", "Confirmacion", MessageBoxButtons.OK, MessageBoxIcon.Error); } } LGestionUsuario instancia3 = new LGestionUsuario(); DataTable tabla = new DataTable(); tabla = instancia3.Lconsultar();//invocacion dgb1.DataSource = tabla; } private void PRegistroempleado_Load(object sender, EventArgs e) { PPerfil instancia1 = new PPerfil(); label12.Text = instancia1.devolverPerfil(); PCedula instancia2 = new PCedula(); label13.Text = instancia2.compartir(); LGestionUsuario instancia3 = new LGestionUsuario(); DataTable tabla = new DataTable(); tabla = instancia3.Lconsultar();//invocacion dgb1.DataSource = tabla; if (tabla.Rows.Count == 0) { MessageBox.Show("Sin datos de consulta"); } } private void pictureBox5_Click(object sender, EventArgs e) { if (textBox12.Text == "") { MessageBox.Show("Debe ingresar un dato a consultar"); } else { LGestionUsuario instancia = new LGestionUsuario(); instancia.valor = textBox12.Text; //instancia.valor = textBox6.Text; instancia.ConsultaEspecificaNombre(); DataTable tabla = new DataTable(); tabla = instancia.ConsultaEspecificaNombre(); dgb1.DataSource = tabla; } } private void dgb1_CellClick(object sender, DataGridViewCellEventArgs e) { textBox14.Text = dgb1.CurrentRow.Cells[0].Value.ToString(); textBox15.Text = dgb1.CurrentRow.Cells[5].Value.ToString(); textBox16.Text = dgb1.CurrentRow.Cells[4].Value.ToString(); textBox17.Text = dgb1.CurrentRow.Cells[7].Value.ToString(); textBox18.Text = dgb1.CurrentRow.Cells[8].Value.ToString(); } private void pictureBox4_Click(object sender, EventArgs e) { LGestionUsuario instancia = new LGestionUsuario(); //string respuesta = instancia.Lactualizar(textBox14.Text,textBox15.Text,textBox16.Text,textBox17.Text,textBox18.Text); LGestionUsuario comdatos = new LGestionUsuario(); comdatos.a = textBox14.Text; comdatos.b = textBox15.Text; comdatos.c = textBox16.Text; comdatos.d = textBox17.Text; comdatos.e = textBox18.Text; string respuesta = comdatos.Lactualizar(); if (respuesta == "1") { MessageBox.Show("Actualizacion exitosa"); } else { MessageBox.Show("Vuelva a intentarlo", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } LGestionUsuario instancia3 = new LGestionUsuario(); DataTable tabla = new DataTable(); tabla = instancia3.Lconsultar();//invocacion dgb1.DataSource = tabla; } private void pictureBox2_Click(object sender, EventArgs e) { string Cedula = dgb1.CurrentRow.Cells[0].Value.ToString(); LGestionUsuario instancia = new LGestionUsuario(); instancia.Leliminar(Cedula); string respuesta = instancia.Leliminar(Cedula); if (respuesta == "1") { MessageBox.Show("Eliminacion exitosa"); } else { MessageBox.Show("No se elimino el usuario"); } } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } public void SoloNumeros(KeyPressEventArgs e) { if (Char.IsNumber(e.KeyChar)) { e.Handled = false; } else if (Char.IsSeparator(e.KeyChar)) { e.Handled = true; } else if (Char.IsLetter(e.KeyChar)) { e.Handled = true; } } private void textBox2_KeyPress(object sender, KeyPressEventArgs e) { if (Char.IsNumber(e.KeyChar)) { e.Handled = true; } else if (Char.IsSeparator(e.KeyChar)) { e.Handled = false; } else if (Char.IsLetter(e.KeyChar)) { e.Handled = false; } } private void textBox3_KeyPress(object sender, KeyPressEventArgs e) { if (Char.IsNumber(e.KeyChar)) { e.Handled = true; } else if (Char.IsSeparator(e.KeyChar)) { e.Handled = false; } else if (Char.IsLetter(e.KeyChar)) { e.Handled = false; } } private void textBox4_KeyPress(object sender, KeyPressEventArgs e) { if (Char.IsNumber(e.KeyChar)) { e.Handled = true; } else if (Char.IsSeparator(e.KeyChar)) { e.Handled = false; } else if (Char.IsLetter(e.KeyChar)) { e.Handled = false; } } private void textBox5_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox8_KeyPress(object sender, KeyPressEventArgs e) { if (Char.IsNumber(e.KeyChar)) { e.Handled = true; } else if (Char.IsSeparator(e.KeyChar)) { e.Handled = false; } else if (Char.IsLetter(e.KeyChar)) { e.Handled = false; } } private void textBox9_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox12_KeyPress(object sender, KeyPressEventArgs e) { if (Char.IsNumber(e.KeyChar)) { e.Handled = true; } else if (Char.IsSeparator(e.KeyChar)) { e.Handled = false; } else if (Char.IsLetter(e.KeyChar)) { e.Handled = false; } } private void textBox14_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox16_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox17_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox18_KeyPress(object sender, KeyPressEventArgs e) { if (Char.IsNumber(e.KeyChar)) { e.Handled = true; } else if (Char.IsSeparator(e.KeyChar)) { e.Handled = false; } else if (Char.IsLetter(e.KeyChar)) { e.Handled = false; } } private void button1_Click(object sender, EventArgs e) { LGestionUsuario instancia = new LGestionUsuario(); instancia.a = textBox1.Text; instancia.b = textBox2.Text; instancia.j = textBox10.Text; instancia.k = textBox11.Text; instancia.Lregistrar(false); textBox10.Text = instancia.i; textBox11.Text = instancia.j; } } } <file_sep>/Capadedatos/DGestionUsuario.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; namespace Capadedatos { public class DGestionUsuario : Dconexion { public string recibido { get; set; } public string Dregistrar(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k) { // try // { SqlCommand insertar = new SqlCommand("creacionusuario", CadenaConexion()); insertar.CommandType = CommandType.StoredProcedure; insertar.Parameters.Add("@cedula", SqlDbType.BigInt).Value = a; insertar.Parameters.Add("@nombre", SqlDbType.VarChar, 120).Value = b; insertar.Parameters.Add("@genero", SqlDbType.Char, 1).Value = c; insertar.Parameters.Add("@cargo", SqlDbType.Char, 1).Value = d; insertar.Parameters.Add("@tel_fijo", SqlDbType.Int).Value = e; insertar.Parameters.Add("@direccion", SqlDbType.VarChar, 50).Value = f; insertar.Parameters.Add("@Eps", SqlDbType.VarChar, 50).Value = g; insertar.Parameters.Add("@celular", SqlDbType.BigInt).Value = h; insertar.Parameters.Add("@usuario", SqlDbType.VarChar, 50).Value = i; insertar.Parameters.Add("@contrasena", SqlDbType.VarChar, 50).Value = j; insertar.Parameters.Add("@registro", SqlDbType.BigInt).Value = k; insertar.Connection.Open(); insertar.ExecuteNonQuery(); return "1"; } //catch (Exception x) //{ // return x.ToString(); //} //} public DataTable Dconsultar() { try { SqlDataAdapter Cgeneral = new SqlDataAdapter("CGU", CadenaConexion()); Cgeneral.SelectCommand.CommandType = CommandType.StoredProcedure; DataTable tabla = new DataTable(); Cgeneral.Fill(tabla); return tabla; } catch { DataTable tabla = new DataTable(); return tabla; } } public DataTable ConsultaEspecificaNombre() { SqlDataAdapter consultaEn = new SqlDataAdapter("CEN", CadenaConexion()); consultaEn.SelectCommand.CommandType = CommandType.StoredProcedure; consultaEn.SelectCommand.Parameters.Add("@Nombre", SqlDbType.VarChar, 120).Value = recibido; //consultaEn.SelectCommand.Parameters.Add("@Cedula", SqlDbType.BigInt).Value = recibido; DataTable tabla = new DataTable(); consultaEn.Fill(tabla); return tabla; } public string Dactualizar(string a, string b, string c, string d,string e) { SqlCommand ActualizarDatos = new SqlCommand("actualizarusuario", CadenaConexion()); ActualizarDatos.CommandType = CommandType.StoredProcedure; ActualizarDatos.Parameters.Add("@Cedula", SqlDbType.BigInt).Value = a; ActualizarDatos.Parameters.Add("@direccion", SqlDbType.VarChar, 120).Value = b; ActualizarDatos.Parameters.Add("@tel_fijo", SqlDbType.BigInt).Value = c; ActualizarDatos.Parameters.Add("@celular", SqlDbType.BigInt).Value = d; ActualizarDatos.Parameters.Add("@estado", SqlDbType.Char,1).Value = e; ActualizarDatos.Connection.Open(); ActualizarDatos.ExecuteNonQuery(); return "1"; } public string Deliminar(string a) { try { SqlCommand Camestado = new SqlCommand("eliminarusuario", CadenaConexion()); Camestado.CommandType = CommandType.StoredProcedure;// establece el procedimiento almacenado Camestado.Parameters.Add("@Cedula", SqlDbType.BigInt).Value = a; Camestado.Connection.Open();//abre la conexion Camestado.ExecuteNonQuery(); return "1"; } catch { return "2"; } } } } <file_sep>/Presentacion/PGestionCliente.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Capadelogica; namespace Presentacion { public partial class PGestionCliente : Form { public PGestionCliente() { InitializeComponent(); } private void pictureBox2_Click(object sender, EventArgs e) { this.Hide(); } private void pictureBox6_Click(object sender, EventArgs e) { PMenu m = new PMenu(); m.Show(); this.Hide(); } private void pictureBox1_Click(object sender, EventArgs e) { if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" || textBox5.Text=="" ) { MessageBox.Show("Verifique, valores incompletos", "Validacion de campos vacios", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { try { LGestionCliente instancia = new LGestionCliente(); string respuesta = instancia.LRegistrar(textBox1.Text, textBox2.Text, textBox3.Text, textBox5.Text, label6.Text); if (respuesta == "1") { MessageBox.Show("Registro exitoso", "Confirmacion", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("No se pudo registrar el nuevo cliente,vuelva a intentarlo", "Confirmacion", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception) { MessageBox.Show("La cedula que intenta registrar ya existe"); } } LGestionCliente instancia3 = new LGestionCliente(); DataTable tabla = new DataTable(); tabla = instancia3.LConsultar();//invocacion dataGridView1.DataSource = tabla; } private void PGestionCliente_Load(object sender, EventArgs e) { PPerfil instancia1= new PPerfil(); label12.Text=instancia1.devolverPerfil(); PCedula instancia2 = new PCedula(); label6.Text = instancia2.compartir(); LGestionCliente instancia3 = new LGestionCliente(); DataTable tabla = new DataTable(); tabla = instancia3.LConsultar();//invocacion dataGridView1.DataSource = tabla; if (tabla.Rows.Count == 0) { MessageBox.Show("Sin datos de consulta"); } } private void pictureBox5_Click(object sender, EventArgs e) { if (textBox8.Text == "") { MessageBox.Show("Debe ingresar un dato a consultar"); } else { LGestionCliente instancia = new LGestionCliente(); instancia.valor = textBox8.Text; DataTable tabla = new DataTable(); tabla = instancia.LConsultaEspecificacodigo_cliente(); dataGridView1.DataSource = tabla; } } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { textBox4.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString(); textBox6.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString(); textBox7.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString(); textBox9.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString(); textBox10.Text = dataGridView1.CurrentRow.Cells[4].Value.ToString(); } private void pictureBox4_Click(object sender, EventArgs e) { LGestionCliente instancia = new LGestionCliente(); //string respuesta = instancia.Lactualizar(textBox14.Text,textBox15.Text,textBox16.Text,textBox17.Text,textBox18.Text); LGestionCliente comdatos = new LGestionCliente(); //comdatos.a = textBox4.Text; //comdatos.b = textBox6.Text; //comdatos.c = textBox7.Text; //comdatos.d = dateTimePicker2.Text; string respuesta = comdatos.Lactualizar(textBox4.Text, textBox6.Text, textBox7.Text,textBox9.Text,textBox10.Text); if (respuesta == "1") { MessageBox.Show("Actualizacion exitosa"); } else { MessageBox.Show("Vuelva a intentarlo", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void pictureBox3_Click(object sender, EventArgs e) { string Codigo_cliente = dataGridView1.CurrentRow.Cells[0].Value.ToString(); LGestionUsuario instancia = new LGestionUsuario(); instancia.Leliminar(Codigo_cliente); string respuesta = instancia.Leliminar(Codigo_cliente); if (respuesta == "1") { MessageBox.Show("Eliminacion exitosa"); } else { MessageBox.Show("No se elimino el cliente"); } } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } public void SoloNumeros(KeyPressEventArgs e) { if (Char.IsNumber(e.KeyChar)) { e.Handled = false; } else if (Char.IsSeparator(e.KeyChar)) { e.Handled = true; } else if (Char.IsLetter(e.KeyChar)) { e.Handled = true; } } private void textBox2_KeyPress(object sender, KeyPressEventArgs e) { SoloLetras(e); } public void SoloLetras(KeyPressEventArgs e) { if (Char.IsNumber(e.KeyChar)) { e.Handled = true; } else if (Char.IsSeparator(e.KeyChar)) { e.Handled = false; } else if (Char.IsLetter(e.KeyChar)) { e.Handled = false; } } private void textBox3_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox8_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox4_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox6_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox7_KeyPress(object sender, KeyPressEventArgs e) { SoloLetras(e); } private void textBox9_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } } } <file_sep>/Presentacion/PInventarioMat.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Presentacion { public partial class PInventarioMat : Form { public PInventarioMat() { InitializeComponent(); } PMenu m = new PMenu(); private void pictureBox3_Click(object sender, EventArgs e) { this.Hide(); } private void pictureBox6_Click(object sender, EventArgs e) { m.Show(); this.Hide(); } private void tabPage1_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void FormInventarioMat_Load(object sender, EventArgs e) { } } } <file_sep>/Capadelogica/LGestionFactura.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using Capadedatos; using Capadelogica; using System.Data; namespace Capadelogica { public class LGestionFactura { public string[] LConsultarCliente(string a) { DGestionFactura Instancia = new DGestionFactura(); return Instancia.DConsultarCliente(a); } public DataTable ConsultaDetalle_factura(string a) { DGestionFactura instancia = new DGestionFactura(); instancia.recibido = valor; return instancia.ConsultaDetalle_factura(a); } public DataTable LConsultaArticulo(string a) { DGestionFactura Instancia = new DGestionFactura(); return Instancia.DConsultaArticulo(a); } public DataTable LDatosArticulo(string a) { DGestionFactura Instancia = new DGestionFactura(); return Instancia.DDatosPorArticulo(a); } public DataTable LConsultaServicios() { DGestionFactura Instancia = new DGestionFactura(); return Instancia.DConsultaServicios(); } public DataTable LDatosServicio(string a) { DGestionFactura Instancia = new DGestionFactura(); return Instancia.DDatosPorServicio(a); } public string valor; public string LRegistrar(string a, string b, string c, string d, string e, string f) { DGestionFactura instancia = new DGestionFactura(); return instancia.DRegistrar(a, b, c, d, e, f); } public string LRegistrarF(string a, string b) { DGestionFactura instancia = new DGestionFactura(); return instancia.DregistrarF(a, b); } public DataTable Lconsultar() { DGestionFactura instancia = new DGestionFactura(); return instancia.Dconsultar(); } public DataTable LconsultaEspecificaCodigo_factura() { DGestionFactura instancia = new DGestionFactura(); instancia.recibido = valor; return instancia.ConsultaEspecificaCodigo_factura(); } public bool LconsultaDetalleServicio(string a, string b, string c) { DGestionFactura instancia = new DGestionFactura(); return instancia.Detalle_servicio(a, b, c); } public string[] LValor_total(string a) { DGestionFactura instanciav = new DGestionFactura(); return instanciav.DValor_total(a); } public int LCambio(int paga, int valor_total) { int cambio = 0; cambio = paga - valor_total ; return cambio; } public int promedio_horas(int horas_trabajadas,int paga) { int cambio=0; cambio = paga / horas_trabajadas; return cambio; } } } <file_sep>/Capadelogica/LUsuario.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Capadelogica { public class LUsuario { //public string PRegistroUsuario(string a,string b,string c,string d,string e,string f,string g,string h) //{ //} } } <file_sep>/Capadedatos/DGestionArticulo.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; namespace Capadedatos { public class DGestionArticulo:Dconexion { public string recibido; public string DRegistrar(string a, string b, string c, string d) { // try // { SqlDataAdapter insertar1 = new SqlDataAdapter("ConsultarCodigocliente", CadenaConexion()); insertar1.SelectCommand.CommandType = CommandType.StoredProcedure; insertar1.SelectCommand.Parameters.Add("@Cedula_cliente", SqlDbType.BigInt).Value = a; DataTable tabla = new DataTable(); insertar1.Fill(tabla); String r = tabla.Rows[0][0].ToString(); //a = Convert.ToString(tabla); //string r = tabla[0][0]; SqlCommand insertar = new SqlCommand("Insertararticulo", CadenaConexion()); insertar.CommandType = CommandType.StoredProcedure; insertar.Parameters.Add("@Codigo_cliente", SqlDbType.BigInt).Value = r; insertar.Parameters.Add("@tipo_prenda", SqlDbType.VarChar, 50).Value = b; insertar.Parameters.Add("@fecha_registro", SqlDbType.Date).Value = c; insertar.Parameters.Add("@Registro", SqlDbType.BigInt).Value = d; insertar.Connection.Open(); insertar.ExecuteNonQuery(); return "1"; //} //catch (Exception x) //{ // return x.ToString(); //} } public DataTable DConnsultarcliente () { SqlDataAdapter MyClient = new SqlDataAdapter("ConsultarClientesCC",CadenaConexion()); MyClient.SelectCommand.CommandType = CommandType.StoredProcedure; DataTable tabla = new DataTable(); MyClient.Fill(tabla); return tabla; } public DataTable Dconsultar() { try { SqlDataAdapter Cgeneral = new SqlDataAdapter("CGA", CadenaConexion()); Cgeneral.SelectCommand.CommandType = CommandType.StoredProcedure; DataTable tabla = new DataTable(); Cgeneral.Fill(tabla); return tabla; } catch { DataTable tabla = new DataTable(); return tabla; } } public DataTable ConsultaEspecificaCodigo_articulo() { SqlDataAdapter consultaEs = new SqlDataAdapter("CEA", CadenaConexion()); consultaEs.SelectCommand.CommandType = CommandType.StoredProcedure; consultaEs.SelectCommand.Parameters.Add("@Codigo_articulo",SqlDbType.BigInt).Value = recibido; //consultaEs.SelectCommand.Parameters.Add("Codigo_cliente Bigint ", SqlDbType.BigInt).Value = recibido; DataTable tabla = new DataTable(); consultaEs.Fill(tabla); return tabla; } public string Dactualizar(string a, string b,string c) { SqlCommand ActualizarDatos = new SqlCommand("Actualizararticulo", CadenaConexion()); ActualizarDatos.CommandType = CommandType.StoredProcedure; ActualizarDatos.Parameters.Add("@Codigo_articulo", SqlDbType.BigInt).Value = a; ActualizarDatos.Parameters.Add("@Tipo_prenda", SqlDbType.VarChar,50).Value = b; ActualizarDatos.Parameters.Add("@fecha_registro", SqlDbType.Date).Value = c; ActualizarDatos.Connection.Open(); ActualizarDatos.ExecuteNonQuery(); return "1"; } public string Deliminar(string a) { try { SqlCommand Camestado = new SqlCommand("eliminararticulo", CadenaConexion()); Camestado.CommandType = CommandType.StoredProcedure;// establece el procedimiento almacenado Camestado.Parameters.Add("Codigo_articulo", SqlDbType.BigInt).Value = a; Camestado.Connection.Open();//abre la conexion Camestado.ExecuteNonQuery(); return "1"; } catch { return "2"; } } } } <file_sep>/Presentacion/PCedula.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Presentacion { public class PCedula { static string cedula; public void recibir(string a) { cedula = a; } public string compartir() { return cedula; } } public class Numero_identificacion { static string CedulaC; public void recibirc(string b) { CedulaC = b; } } } <file_sep>/Capadedatos/DGestionCliente.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; using Capadedatos; namespace Capadedatos { public class DGestionCliente : Dconexion { public string recibido; public string DRegistrar(string a, string b, string c, string d, string e) { try { SqlCommand insertar = new SqlCommand("creacioncliente", CadenaConexion()); insertar.CommandType = CommandType.StoredProcedure; insertar.Parameters.Add("@cedula_cliente", SqlDbType.BigInt).Value = a; insertar.Parameters.Add("@Nombre", SqlDbType.VarChar, 120).Value = b; insertar.Parameters.Add("@Tel_fijo", SqlDbType.Int).Value = c; insertar.Parameters.Add("@Direccion", SqlDbType.VarChar, 120).Value = d; insertar.Parameters.Add("@Registro", SqlDbType.BigInt).Value = e; insertar.Connection.Open(); insertar.ExecuteNonQuery(); return "1"; } catch (Exception) { throw; } } public DataTable Dconsultar() { try { SqlDataAdapter Cgeneral = new SqlDataAdapter("Consultarcliente", CadenaConexion()); Cgeneral.SelectCommand.CommandType = CommandType.StoredProcedure; DataTable tabla = new DataTable(); Cgeneral.Fill(tabla); return tabla; } catch { DataTable tabla = new DataTable(); return tabla; } } public DataTable DConsultaEspecificaCodigo_cliente() { SqlDataAdapter consultaEs = new SqlDataAdapter("CEC", CadenaConexion()); consultaEs.SelectCommand.CommandType = CommandType.StoredProcedure; consultaEs.SelectCommand.Parameters.Add("@Codigo_cliente", SqlDbType.BigInt).Value = recibido; DataTable tabla = new DataTable(); consultaEs.Fill(tabla); return tabla; } public string Dactualizar(string a, string b, string c, string d,string e) { SqlCommand ActualizarDatos = new SqlCommand("Actualizarcliente", CadenaConexion()); ActualizarDatos.CommandType = CommandType.StoredProcedure; ActualizarDatos.Parameters.Add("@Codigo_cliente", SqlDbType.BigInt).Value = a; ActualizarDatos.Parameters.Add("@Cedula_cliente", SqlDbType.BigInt).Value = b; ActualizarDatos.Parameters.Add("@Nombre_cliente", SqlDbType.VarChar, 50).Value = c; ActualizarDatos.Parameters.Add("@tel_fijo", SqlDbType.Int).Value = d; ActualizarDatos.Parameters.Add("@direccion", SqlDbType.VarChar, 50).Value = e; ActualizarDatos.Connection.Open(); ActualizarDatos.ExecuteNonQuery(); return "1"; } public string Deliminar(string a) { //try //{ SqlCommand Camestado = new SqlCommand("eliminarcliente", CadenaConexion()); Camestado.CommandType = CommandType.StoredProcedure;// establece el procedimiento almacenado Camestado.Parameters.Add("@Codigo_cliente", SqlDbType.BigInt).Value = a; Camestado.Connection.Open();//abre la conexion Camestado.ExecuteNonQuery(); return "1"; } //catch //{ // return "2"; //} } } //}<file_sep>/Presentacion/SeleccionImagen.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; //Nueva libreria a adicionar para permitir crear objetos MemoryStream using Capadelogica; namespace Presentacion { public partial class SeleccionImagen : Form { public SeleccionImagen() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { OpenFileDialog dialogo = new OpenFileDialog(); //Se crea el nuevo objeto cuadro de dialogo DialogResult resultado = dialogo.ShowDialog(); //Se muestra esperando una acción del usuario if (resultado == DialogResult.OK) //Si selecciona un archivo, se muestra en el ptb1 { ptb1.Image = Image.FromFile(dialogo.FileName); } } private void button2_Click(object sender, EventArgs e) { MemoryStream memoria = new MemoryStream(); //Crea un objeto Stream como Buffer (Datos en un espacio de memoria) ptb1.Image.Save(memoria, System.Drawing.Imaging.ImageFormat.Jpeg); //Almacena la imagen en el Buffer byte[] memoria_imagen = memoria.ToArray(); //Se extrae la cadena para almacenarla en una variable tipo binario LImagen Instancia = new LImagen(); //Instancia de la clase string respuesta = Instancia.RecibirImagen(memoria_imagen); //Sobrecarga del dato binario al metodo RecibirImagen if (respuesta == "1") { MessageBox.Show("Inserción exitosa de la imagen"); PLogin instancia = new PLogin(); instancia.clsBotonCircular1.Image = ptb1.Image; } else { MessageBox.Show(respuesta); } } } } <file_sep>/Capadelogica/LGestionArticulo.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using Capadedatos; using Capadelogica; using System.Data; namespace Capadelogica { public class LGestionArticulo { public DataTable LConsultarCliente() { DGestionArticulo Instancia = new DGestionArticulo(); return Instancia.DConnsultarcliente(); } public string valor; public string LRegistrar(string a, string b,string c,string d) { DGestionArticulo instancia = new DGestionArticulo(); return instancia.DRegistrar(a,b,c,d); } public DataTable LConsultar() { DGestionArticulo instancia = new DGestionArticulo(); instancia.recibido = valor; return instancia.Dconsultar(); } public DataTable ConsultaEspecificaCodigo_articulo() { DGestionArticulo instancia = new DGestionArticulo(); instancia.recibido = valor; return instancia.ConsultaEspecificaCodigo_articulo(); } public string Lactualizar(string a, string b,string c) { DGestionArticulo instancia = new DGestionArticulo(); return instancia.Dactualizar(a,b,c); } public string Leliminar(string a) { DGestionArticulo instancia = new DGestionArticulo(); return instancia.Deliminar(a); } } } <file_sep>/Capadedatos/Dconexion.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; namespace Capadedatos { public class Dconexion { public SqlConnection CadenaConexion() { SqlConnection conexion = new SqlConnection("Data Source=DESKTOP-8V0F2FN\\SQLEXPRESS;Initial Catalog=Modisteria_Elsa;Integrated Security=True"); return conexion; } } } <file_sep>/Capadelogica/LGestionCliente.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using Capadedatos; using Capadelogica; using System.Data; namespace Capadelogica { public class LGestionCliente { public string valor; public string LRegistrar(string a, string b, string c, string d, string e) { DGestionCliente instancia = new DGestionCliente(); return instancia.DRegistrar(a, b, c, d, e); } public DataTable LConsultar() { DGestionCliente instancia = new DGestionCliente(); return instancia.Dconsultar(); } public DataTable LConsultaEspecificacodigo_cliente() { DGestionCliente instancia = new DGestionCliente(); instancia.recibido = valor; return instancia.DConsultaEspecificaCodigo_cliente(); } public string Lactualizar(string a, string b, string c, string d,string e) { DGestionCliente instancia = new DGestionCliente(); return instancia.Dactualizar(a, b, c, d,e); } public string Leliminar(string a) { DGestionUsuario instancia = new DGestionUsuario(); return instancia.Deliminar(a); } } } <file_sep>/Capadelogica/LImagen.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using Capadedatos; namespace Capadelogica { public class LImagen { public string RecibirImagen(byte[] a) { DImagen Instancia = new DImagen(); return Instancia.InsertarImagen(a); } } } <file_sep>/Presentacion/PPerfil.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Presentacion { public class PPerfil { static string Cargo; public void recibir(string nombre) { Cargo = nombre; } public string devolverPerfil() { return Cargo; } } } <file_sep>/Capadedatos/DatosdeConsultaRegistradoPor.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; namespace Capadedatos { public class DatosdeConsultaRegistradoPor : Dconexion { public string Consultar(string a) { SqlDataAdapter ConsultarDatos = new SqlDataAdapter("ConsultarRegistrado", CadenaConexion()); ConsultarDatos.SelectCommand.CommandType = CommandType.StoredProcedure; ConsultarDatos.SelectCommand.Parameters.Add("@nombreusuario", SqlDbType.VarChar, 120).Value = a; DataTable Tabla = new DataTable(); ConsultarDatos.Fill(Tabla); string cedula = Tabla.Rows[0][0].ToString(); return cedula; } public string ConsultarC(string a) { SqlDataAdapter ConsultarDatos = new SqlDataAdapter("ConsultarRegistradoC", CadenaConexion()); ConsultarDatos.SelectCommand.CommandType = CommandType.StoredProcedure; ConsultarDatos.SelectCommand.Parameters.Add("@nombreusuario", SqlDbType.VarChar, 120).Value = a; DataTable Tabla = new DataTable(); ConsultarDatos.Fill(Tabla); string Cargo = Tabla.Rows[0][0].ToString(); return Cargo; } public string ConsultarCodigo_cliente(string a) { SqlDataAdapter ConsultarDatos = new SqlDataAdapter("ConsultarCodigo_cliente", CadenaConexion()); ConsultarDatos.SelectCommand.CommandType = CommandType.StoredProcedure; ConsultarDatos.SelectCommand.Parameters.Add("@codigo_cliente", SqlDbType.BigInt).Value = a; DataTable Tabla = new DataTable(); ConsultarDatos.Fill(Tabla); string codigo_cliente = Tabla.Rows[0][0].ToString(); return codigo_cliente; } } } <file_sep>/Capadedatos/Dlogin.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; namespace Capadedatos { public class Dlogin : Dconexion//herencia { public string Dvalidacion(string cargo, string Nu, string c) { try { SqlCommand consulta = new SqlCommand("validacionusuario", CadenaConexion()); consulta.CommandType = CommandType.StoredProcedure; consulta.Parameters.Add("@var_tipousuario", SqlDbType.Char, 1).Value = cargo; consulta.Parameters.Add("@var_usuario", SqlDbType.VarChar, 50).Value = Nu; consulta.Parameters.Add("@var_contrasena", SqlDbType.VarChar, 50).Value = c; consulta.Connection.Open(); SqlDataReader validar = consulta.ExecuteReader(); if (validar.Read() == true) { return "1"; } else { return "2"; } } catch(Exception error) { return error.ToString(); } } } } <file_sep>/Capadelogica/Llogin.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using Capadedatos; namespace Capadelogica { public class Llogin { public string Validacion(string tipo,string nombre,string contraseña) { Dlogin enviovalidacion=new Dlogin(); return enviovalidacion.Dvalidacion(tipo,nombre,contraseña); } } } <file_sep>/Capadelogica/ConsultaRegistradoPor.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using Capadedatos; namespace Capadelogica { public class ConsultaRegistradoPor { public string LConsultaRP(string a) { DatosdeConsultaRegistradoPor Insatancia = new DatosdeConsultaRegistradoPor(); return Insatancia.Consultar(a); } public string LConsultaCCL(string a) { DatosdeConsultaRegistradoPor Insatancia = new DatosdeConsultaRegistradoPor(); return Insatancia.Consultar(a); } public string LConsultaRPC(string a) { DatosdeConsultaRegistradoPor Insatancia = new DatosdeConsultaRegistradoPor(); return Insatancia.ConsultarC(a); } public string LConsultaCargo(string a) { DatosdeConsultaRegistradoPor Insatancia = new DatosdeConsultaRegistradoPor(); return Insatancia.ConsultarC(a); } } } <file_sep>/Presentacion/PMenusecre.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Presentacion { public partial class PMenusecre : Form { public PMenusecre() { InitializeComponent(); } private void pictureBox1_Click(object sender, EventArgs e) { PRegCliente Reg = new PRegCliente(); Reg.Show(); this.Hide(); } private void pictureBox2_Click(object sender, EventArgs e) { Pfactura Fa = new Pfactura(); Fa.Show(); this.Hide(); } private void pictureBox4_Click(object sender, EventArgs e) { PinventarioPren Pren = new PinventarioPren(); Pren.Show(); this.Hide(); } private void label4_Click(object sender, EventArgs e) { } private void label2_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void pictureBox6_Click(object sender, EventArgs e) { PGestionservicio Gesserv = new PGestionservicio(); Gesserv.Show(); this.Hide(); } private void pictureBox3_Click_1(object sender, EventArgs e) { Pfactura Fa = new Pfactura(); Fa.Show(); this.Hide(); } private void pictureBox4_Click_1(object sender, EventArgs e) { PLogin L = new PLogin(); L.Show(); this.Hide(); } } } <file_sep>/Presentacion/PGestionArticulo.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Capadelogica; namespace Presentacion { public partial class PinventarioPren : Form { public PinventarioPren() { InitializeComponent(); } PMenu m = new PMenu(); private void pictureBox2_Click(object sender, EventArgs e) { this.Hide(); } private void pictureBox6_Click(object sender, EventArgs e) { m.Show(); this.Hide(); } private void pictureBox1_Click(object sender, EventArgs e) { if (textBox1.Text == "") { MessageBox.Show("Verifique, valores incompletos", "Validacion de campos vacios", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { LGestionArticulo instancia = new LGestionArticulo(); string respuesta = instancia.LRegistrar(comboBox1.Text,textBox1.Text,Convert.ToString(dateTimePicker1.Value),label4.Text); if (respuesta == "1") { MessageBox.Show("Registro exitoso", "Confirmacion", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("No se pudo registrar la nueva prenda,vuelva a intentarlo", "Confirmacion", MessageBoxButtons.OK, MessageBoxIcon.Error); } } LGestionArticulo instancia3 = new LGestionArticulo(); DataTable tabla = new DataTable(); tabla = instancia3.LConsultar();//invocacion dataGridView2.DataSource = tabla; } private void PinventarioPren_Load(object sender, EventArgs e) { PPerfil instancia1 = new PPerfil(); label5.Text = instancia1.devolverPerfil(); PCedula instancia2 = new PCedula(); label4.Text = instancia2.compartir(); LGestionArticulo instancia3 = new LGestionArticulo(); DataTable tabla = new DataTable(); tabla = instancia3.LConsultar();//invocacion dataGridView2.DataSource = tabla; if (tabla.Rows.Count == 0) { MessageBox.Show("Sin datos de consulta"); } } private void pictureBox5_Click(object sender, EventArgs e) { if (textBox4.Text == "") { MessageBox.Show("Debe ingresar un dato a consultar"); } else { LGestionArticulo instancia = new LGestionArticulo(); instancia.valor = textBox4.Text; instancia.ConsultaEspecificaCodigo_articulo(); DataTable tabla = new DataTable(); tabla = instancia.ConsultaEspecificaCodigo_articulo(); dataGridView2.DataSource = tabla; } } private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e) { textBox5.Text = dataGridView2.CurrentRow.Cells[1].Value.ToString(); textBox6.Text = dataGridView2.CurrentRow.Cells[2].Value.ToString(); dateTimePicker2.Text = dataGridView2.CurrentRow.Cells[3].Value.ToString(); } private void pictureBox3_Click(object sender, EventArgs e) { LGestionArticulo instancia = new LGestionArticulo(); LGestionArticulo comdatos = new LGestionArticulo(); string respuesta = comdatos.Lactualizar(textBox5.Text, textBox6.Text, Convert.ToString(dateTimePicker2.Value)); if (respuesta == "1") { MessageBox.Show("Actualizacion exitosa"); } else { MessageBox.Show("Vuelva a intentarlo", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void pictureBox4_Click(object sender, EventArgs e) { string Codigo_articulo = dataGridView2.CurrentRow.Cells[0].Value.ToString(); LGestionArticulo instancia = new LGestionArticulo(); instancia.Leliminar(Codigo_articulo); string respuesta = instancia.Leliminar(Codigo_articulo); if (respuesta == "1") { MessageBox.Show("Eliminacion exitosa"); } else { MessageBox.Show("No se elimino la prenda"); } } private void comboBox1_Enter(object sender, EventArgs e) { LGestionArticulo Instancia = new LGestionArticulo(); DataTable tabla = new DataTable(); tabla = Instancia.LConsultarCliente(); comboBox1.DataSource = tabla; comboBox1.ValueMember = "Cedula_cliente"; } private void comboBox1_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } public void SoloNumeros(KeyPressEventArgs e) { if (Char.IsNumber(e.KeyChar)) { e.Handled = false; } else if (Char.IsSeparator(e.KeyChar)) { e.Handled = true; } else if (Char.IsLetter(e.KeyChar)) { e.Handled = true; } } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { SoloLetras(e); } public void SoloLetras(KeyPressEventArgs e) { if (Char.IsNumber(e.KeyChar)) { e.Handled = true; } else if (Char.IsSeparator(e.KeyChar)) { e.Handled = false; } else if (Char.IsLetter(e.KeyChar)) { e.Handled = false; } } private void textBox4_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox5_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox6_KeyPress(object sender, KeyPressEventArgs e) { SoloLetras(e); } } }<file_sep>/Capadelogica/LGestionservicio.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using Capadedatos; using Capadelogica; using System.Data; namespace Capadelogica { public class LGestionservicio { public string valor; public string LRegistrar(string a, string b, string c, string d, string e,string f ) { DGestionservicio instancia = new DGestionservicio(); return instancia.DRegistrar(a, b, c, d, e,f); } public DataTable LConsultar() { DGestionservicio instancia = new DGestionservicio(); return instancia.Dconsultar(); } public DataTable ConsultaEspecificaCodigo_servicio() { DGestionservicio instancia = new DGestionservicio(); instancia.recibido = valor; return instancia.ConsultaEspecificaCodigo_servicio(); } public string Lactualizar(string a, string b, string c, string d, string e, string f) { DGestionservicio instancia = new DGestionservicio(); return instancia.Dactualizar(a, b, c, d,e,f); } public string Leliminar(string a) { DGestionservicio instancia = new DGestionservicio(); return instancia.Deliminar(a); } } } <file_sep>/Presentacion/Pfactura.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Presentacion { public class Pfactura { static string dato; public void recibir(string codigoC) { dato = codigoC; } public string devolverCodigo_cliente() { return dato; } } } <file_sep>/Presentacion/PLogin.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Capadelogica; using System.IO; namespace Presentacion { public partial class PLogin : Form { public PLogin() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { } private void FormLogin_Load(object sender, EventArgs e) { } private void pictureBox2_MouseHover(object sender, EventArgs e) { pictureBox2.Size = new Size(56, 59); } private void pictureBox2_MouseLeave(object sender, EventArgs e) { pictureBox2.Size = new Size(52, 50); } private void textBox1_TextChanged(object sender, EventArgs e) { } private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked == true) { textBox2.UseSystemPasswordChar = false; } else { textBox2.UseSystemPasswordChar = true; } } private void pictureBox2_Click(object sender, EventArgs e)//Metodo { string nombreusuario = textBox1.Text; string contraseña = textBox2.Text; string tipo; if (radioButton1.Checked == true) { tipo = "Administrador"; } else if (radioButton2.Checked == true) { tipo = "Secretaria"; } else { tipo = "Cajero"; } if (radioButton1.Checked == false && radioButton2.Checked == false && radioButton3.Checked == false || textBox1.Text == "" || textBox2.Text == "") { MessageBox.Show("no se pueden dejar espacios en blanco por favor verifique que todos estén diligenciados", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { Llogin Enviodedatos = new Llogin();//Define un objeto,instancicacion string valor = Enviodedatos.Validacion(tipo, nombreusuario, contraseña);//Sobrecarga al metodo if (valor == "2") { MessageBox.Show("Intente de nuevo", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (valor == "1") { MessageBoxButtons botones = MessageBoxButtons.YesNoCancel; DialogResult respuesta = MessageBox.Show("Desea seleccionar una imagen para su perfil", "Modisteria y sastreria", botones, MessageBoxIcon.Question); if (respuesta == DialogResult.No) { MessageBox.Show("Se le proporcionara una imagen general"); } else if (respuesta == DialogResult.Yes) { MessageBox.Show("Por favor seleccione la imagen"); SeleccionImagen I = new SeleccionImagen(); this.Hide(); I.Show(); MemoryStream memoria = new MemoryStream(); byte[] memoria_imagen = memoria.ToArray(); LImagen instancia2 = new LImagen(); string imagen = instancia2.RecibirImagen(memoria_imagen); } PMenu m = new PMenu();//instanciando la clase PMenu m.perfil = tipo; m.Show();//Muestra el objeto ConsultaRegistradoPor instancia = new ConsultaRegistradoPor(); string cargo = instancia.LConsultaCargo(textBox1.Text); MessageBox.Show(cargo); PPerfil instancia1 = new PPerfil(); instancia1.recibir(cargo); //este codigo consulta la cedula para el registrado por instancia ConsultaRegistradoPor Instancia = new ConsultaRegistradoPor(); string cedula = Instancia.LConsultaCCL(textBox1.Text); MessageBox.Show(cedula); //Comunico el dato de cedula a una clase accesible para PCedula miinstancia = new PCedula(); miinstancia.recibir(cedula); m.Show();//Mostrando un objeto this.Hide();//el form actual es ocultado } else { MessageBox.Show(valor, "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } } <file_sep>/Capadedatos/DImagen.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; namespace Capadedatos { public class DImagen { public string InsertarImagen(byte[] a) { try { SqlConnection conexion = new SqlConnection("Data source=DESKTOP-8V0F2FN\\SQLEXPRESS;Initial catalog=Modisteria_Elsa;Integrated security=true"); SqlCommand Insertar_Imagen = new SqlCommand("InsertImagen", conexion); Insertar_Imagen.CommandType = CommandType.StoredProcedure; Insertar_Imagen.Parameters.Add("@Ima", SqlDbType.VarBinary, 8000).Value = a; Insertar_Imagen.Connection.Open(); Insertar_Imagen.ExecuteNonQuery(); return "1"; } catch (Exception x) { return x.ToString(); } } } } <file_sep>/Presentacion/PMenu.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Presentacion { public partial class PMenu : Form { public string perfil; public PMenu() { InitializeComponent(); } private void pictureBox1_Click(object sender, EventArgs e) { PGestionCliente Reg = new PGestionCliente(); Reg.Show(); //this.Hide(); } private void pictureBox3_Click(object sender, EventArgs e) { PGestionfactura Fa = new PGestionfactura(); Fa.Show(); //this.Hide(); } private void pictureBox2_Click(object sender, EventArgs e) { PinventarioPren Pren = new PinventarioPren(); Pren.Show(); //this.Hide(); } private void FormMenu_Load(object sender, EventArgs e) { if (perfil == "Administrador") { pictureBox6.Visible = true; label6.Visible = true; pictureBox1.Visible = true; label1.Visible = true; pictureBox2.Visible = true; label2.Visible = true; pictureBox5.Visible = true; label5.Visible = true; pictureBox3.Visible = true; label3.Visible = true; } if (perfil == "Secretaria") { pictureBox6.Visible = true; label6.Visible = true; pictureBox1.Visible = true; label1.Visible = true; pictureBox2.Visible = true; label2.Visible = true; pictureBox3.Visible = false; label3.Visible = false; pictureBox5.Visible = false; label5.Visible = false; pictureBox1.Location = new Point(74, 90); label1.Location = new Point(80, 67); pictureBox2.Location = new Point(427, 90); label2.Location = new Point(446, 67); this.Size = new Size(577, 337); } if (perfil == "Cajero") { pictureBox6.Visible = true; label6.Visible = true; pictureBox1.Visible = true; label1.Visible = true; pictureBox2.Visible = true; label2.Visible = true; pictureBox3.Visible = true; label5.Visible = false; pictureBox3.Location=new Point(74, 90); label3.Location = new Point(80, 67); this.Size=new Size(418,421); } PPerfil instancia = new PPerfil(); label4.Text = instancia.devolverPerfil(); PCedula instancia22 = new PCedula(); label7.Text = instancia22.compartir(); } private void pictureBox4_Click_1(object sender, EventArgs e) { PLogin L = new PLogin(); L.Show(); this.Hide(); } private void pictureBox6_Click_1(object sender, EventArgs e) { PGestionservicio servicio = new PGestionservicio(); servicio.Show(); } private void pictureBox5_Click(object sender, EventArgs e) { PRegistroempleado empleado = new PRegistroempleado(); empleado.Show(); } } } <file_sep>/Capadedatos/DGestionFactura.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; using Capadedatos; namespace Capadedatos { public class DGestionFactura : Dconexion { public DataTable ConsultaDetalle_factura(string a) { SqlDataAdapter consultaEs = new SqlDataAdapter("detalle_servicioF", CadenaConexion()); consultaEs.SelectCommand.CommandType = CommandType.StoredProcedure; consultaEs.SelectCommand.Parameters.Add("@codigo_factura", SqlDbType.BigInt).Value = (a); DataTable tabla = new DataTable(); consultaEs.Fill(tabla); return tabla; } public string[] DConsultarCliente(string a) { try { SqlDataAdapter Consultar = new SqlDataAdapter("ConsultarNombreCliente", CadenaConexion()); Consultar.SelectCommand.CommandType = CommandType.StoredProcedure; Consultar.SelectCommand.Parameters.Add("@cedula_cliente", SqlDbType.BigInt).Value = Convert.ToInt32(a); DataTable tabla = new DataTable(); Consultar.Fill(tabla); string[] resultado = { tabla.Rows[0][0].ToString(), tabla.Rows[0][1].ToString() }; return resultado; } catch { string[] resultado = { "Cliente no registrado", "Cliente no registrado" }; return resultado; } } public DataTable DConsultaArticulo(string a) { try { SqlDataAdapter adaptador = new SqlDataAdapter("ConsultaArticulo", CadenaConexion()); adaptador.SelectCommand.CommandType = CommandType.StoredProcedure; adaptador.SelectCommand.Parameters.Add("@codigo_cliente", SqlDbType.BigInt).Value = Convert.ToInt32(a); DataTable ds = new DataTable(); adaptador.Fill(ds); return ds; } catch { return null; } } public DataTable DDatosPorArticulo(string b) { SqlDataAdapter adaptador = new SqlDataAdapter("DatosporArticulo", CadenaConexion()); adaptador.SelectCommand.CommandType = CommandType.StoredProcedure; adaptador.SelectCommand.Parameters.Add("@codigo_articulo", SqlDbType.BigInt).Value = Convert.ToInt32(b); DataTable ds = new DataTable(); adaptador.Fill(ds); return ds; } public DataTable DConsultaServicios() { SqlDataAdapter adaptador = new SqlDataAdapter("ConsultaServicio", CadenaConexion()); adaptador.SelectCommand.CommandType = CommandType.StoredProcedure; DataTable ds = new DataTable(); adaptador.Fill(ds); return ds; } public DataTable DDatosPorServicio(string b) { SqlDataAdapter adaptador = new SqlDataAdapter("DatosporServicio", CadenaConexion()); adaptador.SelectCommand.CommandType = CommandType.StoredProcedure; adaptador.SelectCommand.Parameters.Add("@codigo_servicio", SqlDbType.BigInt).Value = Convert.ToInt32(b); DataTable ds = new DataTable(); adaptador.Fill(ds); return ds; } public string recibido; public string DRegistrar(string a, string b, string c, string d, string e, string f) { //try //{ SqlCommand insertar = new SqlCommand("Actualizar_factura", CadenaConexion()); insertar.CommandType = CommandType.StoredProcedure; insertar.Parameters.Add("@codigo_factura", SqlDbType.BigInt).Value = a; insertar.Parameters.Add("@Valor_total_servicios", SqlDbType.Real).Value = b; insertar.Parameters.Add("@paga", SqlDbType.Real).Value = c; insertar.Parameters.Add("@cambio", SqlDbType.Real).Value = d; insertar.Parameters.Add("@fecha_factura", SqlDbType.Date).Value = e; insertar.Parameters.Add("@registro", SqlDbType.BigInt).Value = f; insertar.Connection.Open(); insertar.ExecuteNonQuery(); return "1"; //} //catch (Exception x) //{ // return x.ToString(); //} } public string DregistrarF(string a, string b) { SqlCommand insertarf = new SqlCommand("InsertarfacturaSimple", CadenaConexion()); insertarf.CommandType = CommandType.StoredProcedure; insertarf.Parameters.Add("@codigo_cliente", SqlDbType.BigInt).Value = a; insertarf.Parameters.Add("@registro", SqlDbType.BigInt).Value = b; insertarf.Parameters.Add("@codigo_factura", SqlDbType.BigInt).Direction = ParameterDirection.Output; insertarf.Connection.Open(); insertarf.ExecuteNonQuery(); string Codigo_factura = insertarf.Parameters["@codigo_factura"].Value.ToString(); return Codigo_factura; } public DataTable Dconsultar() { try { SqlDataAdapter Cgeneral = new SqlDataAdapter("CGF", CadenaConexion()); Cgeneral.SelectCommand.CommandType = CommandType.StoredProcedure; DataTable tabla = new DataTable(); Cgeneral.Fill(tabla); return tabla; } catch { DataTable tabla = new DataTable(); return tabla; } } public DataTable ConsultaEspecificaCodigo_factura() { SqlDataAdapter consultaEn = new SqlDataAdapter("CEF", CadenaConexion()); consultaEn.SelectCommand.CommandType = CommandType.StoredProcedure; consultaEn.SelectCommand.Parameters.Add("@Codigo_factura", SqlDbType.VarChar, 120).Value = recibido; //consultaEn.SelectCommand.Parameters.Add("@Registro", SqlDbType.BigInt).Value = recibido; //consultaEn.SelectCommand.Parameters.Add("@Codigo_cliente", SqlDbType.BigInt).Value = recibido; DataTable tabla = new DataTable(); consultaEn.Fill(tabla); return tabla; } public bool Detalle_servicio(string a, string b, string c) { SqlCommand insertar = new SqlCommand("Insertar_detalle_servicio", CadenaConexion()); insertar.CommandType = CommandType.StoredProcedure; insertar.Parameters.Add("@codigo_articulo", SqlDbType.BigInt).Value = a; insertar.Parameters.Add("@codigo_servicio", SqlDbType.BigInt).Value = b; insertar.Parameters.Add("@codigo_factura", SqlDbType.BigInt).Value = c; insertar.Connection.Open(); insertar.ExecuteNonQuery(); return true; } public string[] DValor_total(string a) { SqlCommand insertarv = new SqlCommand("Valor_total", CadenaConexion()); insertarv.CommandType = CommandType.StoredProcedure; insertarv.Parameters.Add("@codigo_factura", SqlDbType.BigInt).Value = a; insertarv.Parameters.Add("@valor_total", SqlDbType.Real).Direction = ParameterDirection.Output; insertarv.Parameters.Add("@horas_trabajadas", SqlDbType.Decimal).Direction = ParameterDirection.Output; insertarv.Connection.Open(); insertarv.ExecuteNonQuery(); string Valor_total = insertarv.Parameters["@valor_total"].Value.ToString(); string Horas_trabajadas = insertarv.Parameters["@horas_trabajadas"].Value.ToString(); string[] resultado = { Valor_total, Horas_trabajadas }; return resultado; } } } <file_sep>/Presentacion/PGestionfactura.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Capadelogica; namespace Presentacion { public partial class PGestionfactura : Form { public PGestionfactura() { InitializeComponent(); } PMenu m = new PMenu(); private void pictureBox3_Click(object sender, EventArgs e) { this.Hide(); } private void pictureBox6_Click(object sender, EventArgs e) { m.Show(); this.Hide(); } private void comboBox2_Enter(object sender, EventArgs e) { LGestionFactura Instancia = new LGestionFactura(); DataTable ConjuntoDatos = new DataTable(); ConjuntoDatos = Instancia.LConsultaServicios(); comboBox2.DataSource = ConjuntoDatos; comboBox2.ValueMember = "Codigo_servicio"; comboBox2.DisplayMember = "Descripcion"; } private void comboBox2_SelectionChangeCommitted(object sender, EventArgs e) { LGestionFactura Instancia = new LGestionFactura(); DataTable ConjuntoDatos = new DataTable(); ConjuntoDatos = Instancia.LDatosServicio(comboBox2.SelectedValue.ToString()); textBox3.Text = ConjuntoDatos.Rows[0][1].ToString(); } private void pictureBox1_Click_1(object sender, EventArgs e) { if (llcodigo_factura.Text == "" || label21.Text == "" || textBox5.Text == "" || label22.Text == "" || textBox2.Text == ""|| dateTimePicker1.Text == "") { MessageBox.Show("Verifique, valores incompletos", "Validacion de campos vacios", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { LGestionFactura instancia = new LGestionFactura(); string respuesta = instancia.LRegistrar(llcodigo_factura.Text, label21.Text, textBox5.Text, label22.Text, Convert.ToString(dateTimePicker1.Value),label4.Text); if (respuesta == "1") { MessageBox.Show("Registro exitoso", "Confirmacion", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("No se pudo registrar la nueva factura,vuelva a intentarlo", "Confirmacion", MessageBoxButtons.OK, MessageBoxIcon.Error); } } LGestionFactura instancia3 = new LGestionFactura(); DataTable tabla = new DataTable(); tabla = instancia3.Lconsultar();//invocacion dataGridView1.DataSource = tabla; } private void PGestionfactura_Load(object sender, EventArgs e) { PPerfil instancia1 = new PPerfil(); label1.Text = instancia1.devolverPerfil(); PCedula instancia2 = new PCedula(); label4.Text = instancia2.compartir(); LGestionFactura instancia4 = new LGestionFactura(); DataTable tabla = new DataTable(); tabla = instancia4.Lconsultar();//invocacion dataGridView1.DataSource = tabla; if (tabla.Rows.Count == 0) { MessageBox.Show("Sin datos de consulta"); } } private void pictureBox4_Click(object sender, EventArgs e) { if (textBox10.Text == "") { MessageBox.Show("Debe ingresar un dato a consultar"); } else { LGestionFactura instancia = new LGestionFactura(); instancia.valor = textBox10.Text; DataTable tabla = new DataTable(); tabla = instancia.LconsultaEspecificaCodigo_factura(); dataGridView1.DataSource = tabla; } } private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e) { LGestionFactura instancia = new LGestionFactura(); DataTable ConjuntoDatos = new DataTable(); ConjuntoDatos = instancia.LDatosArticulo(comboBox1.SelectedValue.ToString()); textBox2.Text = ConjuntoDatos.Rows[0][2].ToString(); } private void comboBox1_Enter(object sender, EventArgs e) { } //private void textBox1_KeyPress(object sender, KeyPressEventArgs e) //{ // SoloLetras(e); //} private void comboBox1_KeyPress(object sender, KeyPressEventArgs e) { SoloLetras(e); } public void SoloLetras(KeyPressEventArgs e) { if (Char.IsNumber(e.KeyChar)) { e.Handled = true; } else if (Char.IsSeparator(e.KeyChar)) { e.Handled = false; } else if (Char.IsLetter(e.KeyChar)) { e.Handled = false; } } private void comboBox2_KeyPress(object sender, KeyPressEventArgs e) { SoloLetras(e); } private void textBox2_KeyPress(object sender, KeyPressEventArgs e) { SoloLetras(e); } private void textBox3_KeyPress(object sender, KeyPressEventArgs e) { SoloLetras(e); } private void textBox4_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } public void SoloNumeros(KeyPressEventArgs e) { if (Char.IsNumber(e.KeyChar)) { e.Handled = false; } else if (Char.IsSeparator(e.KeyChar)) { e.Handled = true; } else if (Char.IsLetter(e.KeyChar)) { e.Handled = true; } } private void textBox5_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox9_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox11_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox10_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void pictureBox2_Click(object sender, EventArgs e) { LGestionFactura Instancia = new LGestionFactura(); Instancia.LconsultaDetalleServicio(comboBox1.SelectedValue.ToString(), comboBox2.SelectedValue.ToString(), llcodigo_factura.Text); LGestionFactura instancia = new LGestionFactura(); DataTable tabla1 = new DataTable(); tabla1 = instancia.ConsultaDetalle_factura(llcodigo_factura.Text);//invocacion dataGridView2.DataSource = tabla1; dataGridView2.Visible = true; LGestionFactura instanciav = new LGestionFactura(); string[] resultado = instanciav.LValor_total(llcodigo_factura.Text); label21.Text = resultado[0]; label17.Text = resultado[1]; LGestionFactura instancia1 = new LGestionFactura(); if (textBox5.Text != "" && label21.Text != "") { label22.Text = instancia1.LCambio(Convert.ToInt32(textBox5.Text), Convert.ToInt32(label21.Text)).ToString(); } label23.Text = instancia.promedio_horas(Convert.ToInt32(label17.Text), Convert.ToInt32(label21.Text)).ToString(); } private void textBox5_TextChanged(object sender, EventArgs e) { LGestionFactura instancia = new LGestionFactura(); if (textBox5.Text != "" && label21.Text != "") { label22.Text = instancia.LCambio(Convert.ToInt32(textBox5.Text), Convert.ToInt32(label21.Text)).ToString(); } } private void button1_Click(object sender, EventArgs e) { LGestionFactura InstanciaRegistrar_articulo = new LGestionFactura(); string[] resultado = InstanciaRegistrar_articulo.LConsultarCliente(textBox1.Text); label7.Text = resultado[1]; LGestionFactura instancia_articulo = new LGestionFactura(); DataTable ConjuntoDatos = new DataTable(); label20.Text = resultado[0]; ConjuntoDatos = instancia_articulo.LConsultaArticulo(resultado[0]); comboBox1.DataSource = ConjuntoDatos; comboBox1.ValueMember = "Codigo_articulo"; comboBox1.DisplayMember = "Tipo_prenda"; LGestionFactura instanciaRegistrar_factura = new LGestionFactura(); llcodigo_factura.Text = instanciaRegistrar_factura.LRegistrarF(label20.Text, label4.Text); } } } <file_sep>/Presentacion/PGestionservicio.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Capadelogica; namespace Presentacion { public partial class PGestionservicio : Form { public PGestionservicio() { InitializeComponent(); } private void pictureBox3_Click(object sender, EventArgs e) { this.Hide(); } private void pictureBox1_Click(object sender, EventArgs e) { if (textBox5.Text=="" ||textBox1.Text == "" || comboBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" || dateTimePicker1.Text == "") { MessageBox.Show("Verifique, valores incompletos", "Validacion de campos vacios", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { LGestionservicio instancia = new LGestionservicio(); string respuesta = instancia.LRegistrar( textBox1.Text, comboBox1.Text, textBox2.Text, textBox3.Text, Convert.ToString(dateTimePicker1.Value), label6.Text); if (respuesta == "1") { MessageBox.Show("Registro exitoso", "Confirmacion", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("No se pudo registrar el nuevo servicio,vuelva a intentarlo", "Confirmacion", MessageBoxButtons.OK, MessageBoxIcon.Error); } } LGestionservicio instancia3 = new LGestionservicio(); DataTable tabla = new DataTable(); tabla = instancia3.LConsultar();//invocacion dataGridView1.DataSource = tabla; } private void PGestionservicio_Load(object sender, EventArgs e) { PPerfil instancia1 = new PPerfil(); label3.Text = instancia1.devolverPerfil(); PCedula instancia2 = new PCedula(); label6.Text = instancia2.compartir(); LGestionservicio instancia3 = new LGestionservicio(); DataTable tabla = new DataTable(); tabla = instancia3.LConsultar();//invocacion dataGridView1.DataSource = tabla; if (tabla.Rows.Count == 1) { MessageBox.Show("Sin datos de consulta"); } } private void pictureBox5_Click(object sender, EventArgs e) { if (textBox4.Text == "") { MessageBox.Show("Debe ingresar un dato a consultar"); } else { LGestionservicio instancia = new LGestionservicio(); instancia.valor = textBox4.Text; instancia.ConsultaEspecificaCodigo_servicio(); DataTable tabla = new DataTable(); tabla = instancia.ConsultaEspecificaCodigo_servicio(); dataGridView1.DataSource = tabla; } } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { textBox7.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString(); textBox8.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString(); comboBox2.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString(); textBox9.Text = dataGridView1.CurrentRow.Cells[4].Value.ToString(); textBox10.Text = dataGridView1.CurrentRow.Cells[5].Value.ToString(); dateTimePicker1.Text = dataGridView1.CurrentRow.Cells[6].Value.ToString(); } private void pictureBox4_Click(object sender, EventArgs e) { LGestionservicio instancia = new LGestionservicio(); LGestionservicio comdatos = new LGestionservicio(); string respuesta = comdatos.Lactualizar(textBox7.Text, textBox8.Text,comboBox2.Text, textBox9.Text,textBox10.Text, Convert.ToString(dateTimePicker2.Value)); if (respuesta == "1") { MessageBox.Show("Actualizacion exitosa"); } else { MessageBox.Show("Vuelva a intentarlo", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void pictureBox2_Click(object sender, EventArgs e) { string Codigo_servicio = dataGridView1.CurrentRow.Cells[1].Value.ToString(); LGestionservicio instancia = new LGestionservicio(); instancia.Leliminar(Codigo_servicio); string respuesta = instancia.Leliminar(Codigo_servicio); if (respuesta == "1") { MessageBox.Show("Eliminacion exitosa"); } else { MessageBox.Show("No se elimino el servicio"); } } private void textBox5_Click(object sender, EventArgs e) { LGestionArticulo instancia = new LGestionArticulo(); DataTable tabla = new DataTable(); tabla = instancia.LConsultar();//invocacion dataGridView2.DataSource = tabla; dataGridView2.Visible = true; } private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e) { textBox5.Text = dataGridView2.CurrentRow.Cells[1].Value.ToString(); } private void textBox5_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } public void SoloNumeros(KeyPressEventArgs e) { if (Char.IsNumber(e.KeyChar)) { e.Handled = false; } else if (Char.IsSeparator(e.KeyChar)) { e.Handled = true; } else if (Char.IsLetter(e.KeyChar)) { e.Handled = true; } } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { SoloLetras(e); } public void SoloLetras(KeyPressEventArgs e) { if (Char.IsNumber(e.KeyChar)) { e.Handled = true; } else if (Char.IsSeparator(e.KeyChar)) { e.Handled = false; } else if (Char.IsLetter(e.KeyChar)) { e.Handled = false; } } private void comboBox1_KeyPress(object sender, KeyPressEventArgs e) { SoloLetras(e); } private void textBox3_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox4_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox7_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } private void textBox8_KeyPress(object sender, KeyPressEventArgs e) { SoloLetras(e); } private void comboBox2_KeyPress(object sender, KeyPressEventArgs e) { SoloLetras(e); } private void textBox10_KeyPress(object sender, KeyPressEventArgs e) { SoloNumeros(e); } } }
dddeedaac94f0e9195c1806ef325e8c5ae71d44b
[ "C#" ]
31
C#
koga117/proyecto-sena
9536f25e4d79a27351b7c213850842a87567624a
7058c5e1c037f38a4051b4d0b723436ef241befa
refs/heads/master
<file_sep>module.exports = function (grunt) { var i18n = ! grunt.option('DskipI18n'), lint = ! grunt.option('DskipLint'); // Automagically load grunt tasks. require('load-grunt-config')(grunt, { config : { pkg : grunt.file.readJSON('package.json'), jitgrun : true, target : 'dist/', } }); // Time how long tasks take. require('time-grunt')(grunt); grunt.registerTask('default', ['dev']); }; <file_sep>module.exports = { server : { options : { port : '3000', hostname : 'localhost', base : 'dist', keepalive : true } } }<file_sep># space-cmd-r A simple game project using Phaser and ES6 ## Install Install node and bower dependencies: ``` npm install bower install ``` ## Build Build the source: ``` grunt ``` Run a server and open and launch a browser: ``` grunt server ``` <file_sep>module.exports = { build : { files : [{ expand : true, cwd : 'assets/', src : ['*.png'], dest : '<%= target %>/assets' }] } };<file_sep>import Player from '../classes/Player'; import Enemy from '../classes/Enemy'; import EnemyOrange from '../classes/EnemyOrange'; import EnemyPurple from '../classes/EnemyPurple'; export default class Play extends Phaser.State { constructor () { this.enemyTime = 0; this.enemyLimit = 5; this.baseSpeed = 1; this.scoreString = 'Score: '; }; preload () { this.stage.backgroundColor = '#000000'; }; create () { var bullets, explosionEmitter, i; this.starfield = this.game.add.tileSprite(0, 0, 700, 600, 'starfield'); this.starfield.alpha = 0; this.overlay = this.game.add.tileSprite(0, 0, 700, 600, 'overlay'); bullets = this.game.add.group(); bullets.enableBody = true; bullets.physicsBodyType = Phaser.Physics.ARCADE; bullets.createMultiple(30, 'bullet'); bullets.setAll('anchor.x', 0.5); bullets.setAll('anchor.y', 1); bullets.setAll('outOfBoundsKill', true); bullets.setAll('checkWorldBounds', true); this.bullets = bullets; explosionEmitter = this.game.add.emitter(0, 0, 1000); explosionEmitter.makeParticles('particle-orange'); explosionEmitter.minParticleSpeed.setTo(-200, -200); explosionEmitter.maxParticleSpeed.setTo(200, 200); explosionEmitter.minParticleScale = 0.2; explosionEmitter.maxParticleScale = 1; explosionEmitter.gravity = 0; this.explosionEmitter = explosionEmitter; this.score = 0; this.scoreLabel = this.game.add.text(this.game.world.width - 200, 10, this.scoreString + this.score, { font : '34px Helvetica', fill : '#FFFFFF' }); this.player = new Player(this.game, this.bullets); this.setupEnemies(); //enemies.enableBody = true; //enemies.physicsBodyType = Phaser.Physics.ARCADE; //enemies.createMultiple(30, 'enemy'); //enemies.setAll('anchor.x', 0.5); //enemies.setAll('anchor.y', 0.5); //this.enemies = enemies; this.add.tween(this.starfield).to({ alpha: 1 }, 1000, Phaser.Easing.Bounce.InOut, true); this.cursors = this.game.input.keyboard.createCursorKeys(); // Add two seconds to the enemy spawn timer. this.enemyTime = this.game.time.now + 2000; }; setupEnemies () { var i; this.enemies = { orange : this.game.add.group(), purple : this.game.add.group() }; for (i = 0; i < this.enemyLimit; i += 1) { this.enemies.orange.addChild(new EnemyOrange(this.game, this.player, 0, 0)); this.enemies.purple.addChild(new EnemyPurple(this.game, this.player, 0, 0)); } } update () { var enemy = this.enemies.orange.getFirstExists(false); //var enemy, i; // Adjust the base speed as needed. if (this.cursors.up.isDown) { this.baseSpeed = 1.5; } else if (this.cursors.down.isDown) { this.baseSpeed = 0.5; } else { this.baseSpeed = 1; } //this.baseSpeed = this.cursors.up.isDown ? 1.5 : 1; if (this.game.time.now > this.enemyTime) { this.enemyTime = this.game.time.now + ((Math.random() * 5000/this.baseSpeed) + 500); if (enemy) { enemy.spawn((Math.random() * (this.game.width - enemy.body.width) + enemy.body.halfWidth), 0); } } // Adjust the enemy velocity based on the base speed. //this.enemies.setAll('body.velocity.y', 200 * this.baseSpeed); this.enemies.orange.forEachAlive(enemy => { enemy.speedModifier = this.baseSpeed; if (enemy.body.y > this.game.world.height) { enemy.kill(); } }, this); this.checkCollisions(); // Scroll the background this.starfield.tilePosition.y += (2 * this.baseSpeed); this.overlay.tilePosition.y += (1 * this.baseSpeed); // update the score... this.scoreLabel.text = this.scoreString + this.score; if (this.score > 500) { this.add.tween(this.starfield).to({ alpha: 0 }, 1000, Phaser.Easing.Bounce.InOut, true); } }; checkCollisions () { this.game.physics.arcade.overlap(this.bullets, this.enemies.orange, this.collisionHandler, null, this); this.game.physics.arcade.overlap(this.enemies.orange, this.player, this.gameover, null, this); }; render () { if (window.debug) { this.game.debug.body(this.player); } }; gameover (player, enemy) { player.kill(); enemy.kill(); this.explosion(enemy.body.x, enemy.body.y); setTimeout(() => { this.game.state.start('gameover'); }, 1000); }; explosion (x, y, particle) { var quantity = (Math.random() * 80) + 20; this.explosionEmitter.x = x; this.explosionEmitter.y = y; this.explosionEmitter.start(true, 300, null, quantity); }; collisionHandler (bullet, enemy) { // When a bullet hits an enemy we kill them both bullet.kill(); enemy.damage(1); if (!enemy.alive) { this.explosion(enemy.x, enemy.y, enemy.particle); this.score += enemy.score; } }; };<file_sep>module.exports = { build : { files : [ { expand : true, src : ['assets/*.wav'], dest : '<%= target %>' }, { src : 'index.html', dest : '<%= target %>' }, { src : './bower_components/phaser/build/custom/phaser-arcade-physics.min.js', dest : '<%= target %>/lib/phaser.min.js' } ] } }<file_sep>export default class Enemy extends Phaser.Sprite { constructor (game, x, y, sprite) { super(game, x, y, sprite); this.anchor.setTo(0.5, 0.5); // Is the enemy alive? this.alive = false; this.exists = false; this.enableBody = true; this.maxHP = 1; this.score = 10; this.speed = 1; this.speedModifier = 1; // Enabled arcade physics and add to the game. game.physics.enable(this, Phaser.Physics.ARCADE); game.add.existing(this); } spawn (x, y) { this.reset(x, y, this.maxHP); } kill () { super.kill(); } update (baseSpeed) { this.body.velocity.y = 200 * this.speedModifier; this.angle += 3; } };<file_sep>export default class GameOver extends Phaser.State { preload () { }; create () { this.title = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'gameover'); this.title.anchor.setTo(0.5, 0.5); this.spaceBar = this.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); }; update () { if (this.spaceBar.isDown) { this.game.state.start('menu'); } } }
19269cb203fb1453d3d9d5cf2eef618e5482dc63
[ "JavaScript", "Markdown" ]
8
JavaScript
CWHopkins/space-cmd-r
cbf55b0053bc8eb1dccec973666cf917fb067726
dd5ba3339ab05afab8447b987986f19bc21eb4c7
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.applet.Applet; import java.awt.Graphics; import java.awt.Color; /** * * @author bushra */ public class NewApplet extends Applet { /** * Initialization method that will be called after the applet is loaded into * the browser. */ public void init() { resize(950, 650); } @Override public void paint(Graphics g) { g.setColor(Color.CYAN); g.fillRect (0,0,950,500); g.setColor(Color.green); g.fillRect (0,500,950,650); //right home ground floor g.setColor(Color.gray); int a[] = {142,142,166,166}; int b[] = {560,512,512,560}; g.fillPolygon(a, b, 4); g.setColor(Color.yellow); int c[] = {142,142,500,500,166,166}; int d[] = {512,366,366,403,403,512}; g.fillPolygon(c, d, 6); g.setColor(Color.darkGray); int e[] = {142,137,500,500}; int f[] = {366,335,335,366}; g.fillPolygon(e, f, 4); //garage g.setColor(Color.white); int eg[] = {166,166,500,500}; int fg[] = {560,403,403,560}; g.fillPolygon(eg, fg, 4); g.setColor(Color.lightGray); g.drawRect(180, 415, 305, 20); g.drawRect(180, 455, 305, 20); g.drawRect(180, 495, 305, 20); g.drawRect(180, 535, 305, 20); // int efg[] = {354,354,522,522}; int ffg[] = {335,245,245,335}; g.fillPolygon(efg, ffg, 4); // g.setColor(Color.DARK_GRAY); int afg[] = {336,502,522}; int agg[] = {245,193,245}; g.fillPolygon(afg, agg, 3); //right gray g.setColor(Color.gray); int eqd[] = {900,900,944,935}; int fqd[] = {357,324,324,357}; g.fillPolygon(eqd, fqd, 4); //right short building g.setColor(Color.yellow); int eq1d[] = {900,900,935,935}; int fqd1[] = {560,357,357,560}; g.fillPolygon(eq1d, fqd1, 4); //right g.setColor(Color.gray); int aa[] = {500,500,900,900}; int ba[] = {560,512,512,560}; g.fillPolygon(aa, ba, 4); g.setColor(Color.YELLOW); int aaa[] = {500,500,900,900}; int baa[] = {512,337,337,512}; g.fillPolygon(aaa, baa, 4); g.setColor(Color.darkGray); int ed[] = {500,490,910,900}; int fd[] = {337,294,294,337}; g.fillPolygon(ed, fd, 4); //rightroof g.setColor(Color.DARK_GRAY); int edd[] = {520,480,693,930,880}; int fdd[] = {245,138,100,138,183}; g.fillPolygon(edd, fdd, 5); //right2 g.setColor(Color.lightGray); int e5d[] = {520,520,880,880}; int f5d[] = {294,158,158,294}; g.fillPolygon(e5d, f5d, 4); //door g.setColor(Color.black); int e7d[] = {540,540,660,660}; int f7d[] = {560,374,374,560}; g.fillPolygon(e7d, f7d, 4); int e1d[] = {720,720,870,870}; int f1d[] = {540,384,384,540}; g.fillPolygon(e1d, f1d, 4); g.setColor(Color.white); int e3d[] = {550,550,650,650}; int f3d[] = {550,394,394,550}; g.fillPolygon(e3d, f3d, 4); int esd[] = {730,730,860,860}; int fsd[] = {520,404,404,520}; g.fillPolygon(esd, fsd, 4); g.setColor(Color.black); g.drawRect(560, 398, 20, 145); g.drawRect(590, 398, 20, 145); g.drawRect(620, 398, 20, 145); g.drawRect(745, 410, 20, 103); g.drawRect(785, 410, 20, 103); g.drawRect(825, 410, 20, 103); g.fillRect(700, 337, 2, 223); g.fillRect(900, 337, 2, 223); g.fillRect(500, 337, 2, 223); g.fillRect(520, 155, 2, 140); g.fillRect(880, 155, 2, 140); //window g.fillRect(570, 180, 60, 100); g.fillRect(670, 180, 60, 100); g.fillRect(770, 180, 60, 100); g.fillRect(390, 265, 60, 70); //tree1 g.setColor (new Color(96, 25, 25)); int tre [] = {30,40,50,60}; int tree [] = {550,400,400,550}; g.fillPolygon (tre, tree, 4); g.setColor (new Color(20, 112, 50)); g.fillArc (-10,350,120,80,0,360); g.fillArc (-10,320,130,80,0,360); g.fillArc (-10,290,110,100,0,360); g.fillArc (0,260,60,90,0,360); } }
a8f35f0b36084c5485f2bfa61a515e73a7420678
[ "Java" ]
1
Java
sjbushra/simple-home-using-java-applet
8d5c7f1ddcc20f09efcb3dffe3154e14b5ec1b6c
d20106857be576fe8b21dc9aa241bbb72df5422d
refs/heads/master
<file_sep><!-- Header --> <?php include "header.php"; ?> <div class="container page"> <div class="ten columns offset-by-one"> <h2>CONCEJOS</h2> <div class="acordeon"> <h3><NAME></h3> <p> <p><img src="images/cuando-duermes.jpg" alt=""></p> <p>Dormir con las piernas levemente elevadas, con 1 o 2 almohadas en los pies, favorece el retorno en la circulación de la sangre.</p> </p> <h3>HAZ EJERCICIO</h3> <p> <p><img src="images/haz-ejercicio-1.png" alt=""></p> <p>Haz ejercicio de forma regular al menos 3 veces a la semana para reactivar el flujo de sangre, son buenos ejercicios caminar, bailar, nadar o andar en bicicleta.</p> </p> <h3>CUIDA TUS POSTURAS</h3> <p> <p><img src="images/cuida-tus-posturas-1.png" alt=""></p> <p>Cuida las posturas: no estar mucho tiempo de pie sin caminar, arrodillarse lo menos posible y no estar muchas horas sentado.</p> </p> <h3>DIETA SANA</h3> <p> <p><img src="images/dieta-sana-1.png" alt=""></p> <p>Mantén una dieta sana a base de frutas, verduras, legumbres, cereales, aceite de oliva, con pocas carnes grasas, poca fritura y pocos embutidos.</p> </p> </div> </div> </div> <!-- Footer --> <?php include "footer.php"; ?><file_sep><!-- Header --> <?php include "header.php"; ?> <div class="container page"> <div class="ten columns offset-by-one"> <h2>QUIÉN SOY</h2> <div class="acordeon"> <h3>FORMACIÓN ACADEMICA</h3> <p> <h4>PREGRADO</h4> <ul> <li>UNIVERSIDAD METROPOLITANA Barranquilla (Colombia) Médico Cirujano</li> <li>INTERNADO ROTATORIO HOSPITAL SAN JUAN DE DIOS DE CUCUTA (N. de Santander)</li> </ul> <h4>POSGRADO</h4> <ul> <li>UNIVERSIDAD DEL SALVADOR DE BUENOS AIRES (Argentina) 1994 – 1995</li> <li>CATEDRA DE MEDICINA – CURSO ANUAL DE CIRUGIA: Con rotación por el servicio de cirugía general del Hospital Tornu con evaluación final.</li> <li>UNIVERSIDAD DEL SALVADOR DE BUENOS AIRES (Argentina) 1995 – 1997: Especialidad en cirugía vascular periférica. Cumplimiento por aval de la Universidad el Salvador, cuatro años en el servicio de cirugía vascular en el Hospital Ale<NAME> (Haedo) Argentina.</li> </ul> <h4>ESPECIALIZACIÓN SUPERIOR DE FLEBOLOGIA Y LINFOLOGIA</h4> <ul> <li>Asociación Médica Argentina – Escuela Argentina de Linfología.</li> <li>Cumpliendo horas teóricas: 320 y horas practicas: 100</li> <li>Trabajo Monográfico de Linfología: Linfangitis</li> <li>BsAs.– Argentina 30 de Noviembre de 2001.</li> </ul> </p> <h3>EXPERIENCIA PROFESIONAL</h3> <p> <h4>Clínica vascular de Bogotá:</h4> <ul> <li>Servicio de consulta externa en el manejo de patología arterial, venosa y linfática – pie diabético</li> <li>Servicio de cirugía vascular programada y fotoobliteracion venosa con laser</li> <li>Estudio vascular no invasivo (dúplex Scan, doppler)</li> <li>Atención de consulta vascular para la asociación de diabéticos.</li> <li>Hospital cancerológico en consulta. Hospital San Rafael y Carlos Lleras deBogotá.</li> </ul> <h4>Clínica general del norte:</h4> <ul> <li>Consulta externa, cirugía vascular periférica programada, control de pacientes hospitalizados, estudios vasculares no invasivos (dúplex Scan, doppler)</li> <li>Manejo de programas FER (ferrocarriles nacionales de Colombia)</li> <li>PTOS (Puertos de Colombia) desde 2003 hasta septiembre de 2005</li> </ul> <h4>Clínica Renacer:</h4> <ul> <li>PTOS (Puertos de Colombia) desde 2003 hasta septiembre de 2005</li> </ul> <h4>IPS diagnosticar:</h4> <ul> <li>PTOS (Puertos de Colombia) desde 2003 hasta septiembre de 2005</li> </ul> <h4>EPS Famisanar: </h4> <ul> <li>PTOS (Puertos de Colombia) desde 2003 hasta septiembre de 2005</li> </ul> <h4><NAME>:</h4> <ul> <li>PTOS (Puertos de Colombia) desde 2003 hasta septiembre de 2005</li> </ul> </p> <h3>SEMINARIOS Y SIMPOSIOS</h3> <p> <ul> <li>FUNDACION PARA EL ESTUDIO DE LAS ENFERMEDADS CIRCULATORIAS Hospital Tornu de la MCBA, PRIMERAS JORNADAS DE MICROCIRCULACION. Diciembre 6 de 1995.</li> <li>V CONGRESO INTERNACIONAL DE FLEBOLOGIA Y LINFOLOGIA DEL 3,4 Y 5 de Octubre de 1996.</li> <li>VII CONGRESO INTERNACIONAL DE FLEBOLOGIA Y LINFOLOGIA 1,2 y 3 de Octubre de 1998. Colegio Argentino De Cirugía Venosa y Linfática.</li> <li>PRIMER CURSO IBERO ARGENTINO DE LASER Y LUZ PULSADA INTENSA. 5 DE Julio de 1999 BsAs.– Argentina.</li> <li>CURSO DE EDUCACION MEDICA CONTINUADA Y ACTUALIZACION EN ENFERMEDAD VENOSA 7 Y 9 De Abril de 1999 BsAs.– Argentina. </li> <li>XVI SIMPOSIO NACIONAL DE FLEBOLOGIA IX DE CIRUGIA PLASTICA 6 y 7 de Julio de 2001 BsAs.– Argentina.</li> <li>I. JORNADAS DE FLEBOLOGIA Y LINFOLOGIA. Universidad J<NAME> 12 de Junio de 2001 BsAs.– Argentina.</li> <li>CURSO SUPERIOR DE FLEBOLOGIA Y LINFOLOGIA. SEMINARIO FLEBOPOSTURAL. Asociación Medica Argentina. 29 – 30 de Marzo de 2001 BsAs.– Argentina.</li> <li>FORUM VENOSO LATINOAMERICANO 18 – 19 – 20 de Octubre de 2001. BsAs.– Argentina.</li> <li>SIMPOSIO CUIDADOS AVANZADOS DE HERIDAS 8-11 de Mayo de 2001. BsAs.– Argentina</li> <li>SIMPOSIO: ENFOQUE TERAPEUTICO ACTUAL DE LA PATOLOGIA ESTETICA DEL TEJIDO ADIPOSO. Paniculopatiaedemato-fibroso esclerosa (PEFE) Las celulitis. 8 – 9 y 10 de Marzo de 2002 BsAs.– Argentina. </li> <li>SIMPOSIO DE DIABETES Y ENFERMEDAD CARDIOVASCULAR. Febrero 28 de 2003. Barranquilla – Colombia. Asociación Colombiana de Angiología y cirugía Vascular.</li> <li>III SIMPOSIO DE CARDIOLOGIA Y I DE ANGIOLOGIA Y CIRUGIA VASCULAR de Santa Marta – Colombia. 25 Y 26 de Julio del 2003.</li> </ul> </p> </div> </div> </div> <!-- Footer --> <?php include "footer.php"; ?><file_sep><!-- Header --> <?php include "header.php"; ?> <div class="container page"> <div class="ten columns offset-by-one"> <h2>VENOSAS</h2> <div class="acordeon"> <h3>VARISES</h3> <p> <p><img src="images/varices.png" alt=""></p> <p>Las várices son venas dilatadas que se inflaman y se elevan a la superficie de la piel. Pueden ser de un color morado o azul oscuro y parecer estar torcidas y abultadas. Las várices se encuentran comúnmente en las partes posteriores de las pantorrillas o en la cara interna de la pierna.</p> <p>Se desarrollan cuando las válvulas venosas que permiten que la sangre fluya hacia el corazón dejan de funcionar adecuadamente. Como resultado, la sangre se acumula en las venas y provoca las dilataciones. Entre los más significativos según avanza la enfermedad, destacan: </p> <ul> <li>Visualización de la red venosa de las piernas. En general, pueden verse varices en cara antero externa de muslos, detrás de las rodillas, y en cara interna de piernas, pero al principio no suelen aparecer otros síntomas.</li> <li>Pesadez y cansancio en las piernas. Sobre todo cuando se está mucho tiempo inmóvil de pie, y a última hora del día.</li> <li>Dolor. De intensidad variable según las personas. Normalmente se localiza en los trayectos de las venas afectadas, principalmente tobillo y pantorrilla. Puede empezar o aumentar con un simple roce, o un golpe de poca importancia. Calambres. Principalmente nocturnos.</li> <li>Hormigueos. Especialmente cuando las piernas permanecen mucho tiempo en la misma postura, por ejemplo en el cine o durante viajes en autocar o avión.</li> <li>Sensación de calor o picores y escozores. Principalmente en tobillo y dorso del pie. Debe evitarse el rascado, pues pueden hacerse heridas con facilidad, al ser la piel más débil por la mala circulación y, también por este motivo, infectarse con facilidad.</li> <li>Hinchazón o edema de los pies y tobillos. Aparece, según avanza la enfermedad. Cambios de coloración en la piel. Manchas parduscas o violáceas.</li> </ul> </p> <h3>INSUFICIENCIA VENOSA</h3> <p> <p><img src="images/insuficiencia-venosa.png" alt=""></p> <p>Es una afección en la cual las venas tienen problemas para retornar la sangre de las piernas al corazón.</p> <h4>Principales Síntomas</h4> <ul> <li>Dolor intenso, pesadez o calambres en las piernas</li> <li>Picazón y hormigueo</li> <li>Dolor que empeora al pararse</li> <li>Dolor que mejora al levantar las piernas</li> <li>Hinchazón de las piernas</li> </ul> <p>Enrojecimiento de piernas y tobillosLas personas con insuficiencia venosa crónica también pueden presentar:</p> <ul> <li>Cambios en el color de la piel alrededor de los tobillos</li> <li>Venas varicosas superficiales</li> <li>Engrosamiento y endurecimiento de la piel en las piernas y en los tobillos (lipodermatoesclerosis)</li> <li>Úlceras en las piernas y en los tobillos</li> </ul> </p> <h3>TROMBOSIS VENOSA</h3> <p><img src="images/Trombosis-venosa.png" alt=""></p> <p> <p>La trombosis venosa o tromboembolismo venoso, es la formación de una masa hemática dentro de una vena durante la vida. Esta puede clasificarse en trombosis venosa superficial (tromboflebitis superficial), o bien, trombosis venosa profunda.</p> </p> <h3>ÚLCERA VENOSA</h3> <p> <p><img src="images/Ulcera-venosa.png" alt=""></p> <p>Úlcera venosa o úlcera varicosa es un tipo de úlcera producida por un deficiente funcionamiento del sistema venoso, generalmente en las piernas. Son la primera causa de lesión crónica, representando entre el 70 y el 90% de éstas Suelen desarrollarse fundamentalmente a lo largo de la zona distal y medial de la pierna.</p> </p> </div> </div> </div> <!-- Footer --> <?php include "footer.php"; ?><file_sep><!-- Header --> <?php include "header.php"; ?> <div class="container page"> <div class="ten columns offset-by-one"> <h2>DIAGNOSTICOS</h2> <div class="acordeon"> <h3>DUPLEX COLOR</h3> <p> <p><img src="images/diagnostico.png" alt=""></p> <p>La ecografía duplex o simplemente eco-Doppler, es una variedad de la ecografía tradicional, basada por tanto en el empleo de ultrasonidos, en la que aprovechando el efecto Doppler, es posible visualizar las ondas de velocidad del flujo que atraviesa ciertas estructuras del cuerpo, por lo general vasos sanguíneos, y que son inaccesibles a la visión directa. </p> </p> </div> </div> </div> <!-- Footer --> <?php include "footer.php"; ?><file_sep><!-- Header --> <?php include "header.php"; ?> <div class="container page"> <div class="ten columns offset-by-one"> <h2>LINFATICOS</h2> <div class="acordeon"> <h3>LINFEDEMA</h3> <p> <p><img src="images/linfedema.png" alt=""></p> <p>El linfedema se debe a depósito de proteínas con alto peso molecular (PM) en el intersticio, debido a una falla en el transporte de linfa, originando edema. Es un cuadro lentamente progresivo de origen primario o secundario principalmente a cirugía oncológica en la extremidad superior e infecciosa en las inferiores. Las complicaciones más frecuentes son las infecciones bacterianas de la piel recidivantes que agravan el cuadro. Su tratamiento se basa fundamentalmente en el drenaje linfático manual (DLM), presoterapia computarizada, elastocompresión graduada y benzopironas. A pesar de ser una patología irreversible, detectada a tiempo y bien manejada permite detener su evolución y mejorar la calidad de vida. </p> </p> </div> </div> </div> <!-- Footer --> <?php include "footer.php"; ?><file_sep><!-- Header --> <?php include "header.php"; ?> <div class="container banner"> <div id="owl-demo" class="owl-carousel owl-theme"> <div class="item"><img src="images/fullimage1.jpg" alt=""></div> <div class="item"><img src="images/fullimage2.jpg" alt=""></div> <div class="item"><img src="images/fullimage3.jpg" alt=""></div> </div> </div> <div class="sonbra__banner"></div> <div class="container inicio"> <div class="eight columns"> <img class="twelve columns" src="images/banner-mision.png" alt=""> <div class="twelve columns"> <br> <h3><img width="20px" src="images/corazon-wh.png" alt="">&nbsp;TU SALUD ES LO MÁS IMPORTANTE</h3> <div class="row cajas__inicio"> <div class="six columns"> <img class="twelve columns" src="images/venas-varices.jpg" alt=""> <p>Las várices son venas dilatadas que se inflaman y se elevan a la superficie de la piel. Pueden ser de un color morado o azul oscuro y parecer estar torcidas...</p> <a class="botones__red" href="cuida-tu-salud.php">LEER MÁS</a> </div> <div class="six columns"> <img class="twelve columns" src="images/escleroterapia.jpg" alt=""> <p>Escleroterapia corresponde a un método seguro y efectivo para la eliminación de venas reticulares (a 5 mm de diámetro) y de telangiectasias o arañas...</p> <a class="botones__red" href="cuida-tu-salud.php">LEER MÁS</a> </div> </div> </div> </div> <div class="four columns contacto"> <div class="fondo--titulo--contacto"> <h2>CONTÁCTENOS</h2> </div> <div class="border-form"> <p>Los campos marcados con ( <span>*</span> ) con obligatorios</p> <hr> <form action="send.php" method="post"> Nombre ( <span>*</span> )<br> <input type="text" name="nombre" id="nombre" required> <br> Correo ( <span>*</span> )<br> <input type="email" name="email" id="email" required><br> Teléfono ( <span>*</span> )<br> <input type="text" name="telefono" id="telefono" required> Asunto<br> <input type="text" name="asunto" id="asunto" required><br> Mensaje<br> <textarea name="comentarios" id="comentarios" required></textarea> <input class="botton-large" type="submit" value="ENVIAR"> </form> </div> </div> <div class="twelve columns"> <br> <h3><img width="20px" src="images/icon-consejos.png" alt="">&nbsp;CONSEJOS QUE TE AYUDARAN</h3> <div class="row consejos"> <div class="three columns"> <a class="twelve columns" href="consejos.php"><img class="twelve columns" src="images/cuando-duermes-1.jpg" alt=""></a> <div class="twelve columns caja__consejos"> <a href="consejos.php">CUANDO DUERMES</a> </div> </div> <div class="three columns"> <a class="twelve columns" href="consejos.php"><img class="twelve columns" src="images/haz-ejercicio.png" alt=""></a> <div class="twelve columns caja__consejos"> <a href="consejos.php">HAZ EJERCICIO</a> </div> </div> <div class="three columns"> <a class="twelve columns" href="consejos.php"><img class="twelve columns" src="images/cuida-tus-posturas.png" alt=""></a> <div class="twelve columns caja__consejos"> <a href="consejos.php">CUIDA TUS POSTURAS</a> </div> </div> <div class="three columns"> <a class="twelve columns" href="consejos.php"><img class="twelve columns" src="images/dieta-sana.png" alt=""></a> <div class="twelve columns caja__consejos"> <a href="consejos.php">DIETA SANA</a> </div> </div> </div> </div> </div> <!-- Footer --> <?php include "footer.php"; ?><file_sep><!-- Header --> <?php include "header.php"; ?> <div class="container page gracias"> <h3>GRACIAS POR CONTACTARNOS</h3> <h4>Tu mensaje ha sido recibido exitosamente y protno te contactaremos.</h4> </div> <!-- Footer --> <?php include "footer.php"; ?><file_sep><!-- Header --> <?php include "header.php"; ?> <div class="container page"> <div class="ten columns offset-by-one"> <h2>CUIDA TU SALUD</h2> <div class="acordeon"> <h3>VENAS VARICES</h3> <p> <p><img src="images/varices-1.png" alt=""></p> <p>Las várices son venas dilatadas que se inflaman y se elevan a la superficie de la piel. Pueden ser de un color morado o azul oscuro y parecen estar torcidas y abultadas. Las várices se encuentran comúnmente en las partes posteriores de las pantorrillas o en la cara interna de la pierna. Se desarrollan cuando las válvulas venosas que permiten que la sangre fluya hacia el corazón dejen de funcionar adecuadamente. Como resultado, la sangre se acumula en las venas y provoca las dilataciones.</p> <p>Entre los más significativos según avanza la enfermedad, destacan:</p> <ul> <li><span>Visualización de la red venosa de las piernas:</span> En general, pueden verse varices en cara antero externa de muslos, detrás de las rodillas, y en cara interna de piernas, pero al principio no suelen aparecer otros síntomas.</li> <li><span>Pesadez y cansancio en las piernas:</span> Sobre todo cuando se está mucho tiempo inmóvil de pie, y a última hora del día.</li> <li><span>Dolor. De intensidad variable según las personas:</span> Normalmente se localiza en los trayectos de las venas afectadas, principalmente tobillo y pantorrilla. Puede empezar o aumentar con un simple roce, o un golpe de poca importancia.</li> <li><span>Calambres:</span> Principalmente nocturnos.</li> <li><span>Hormigueos:</span> Especialmente cuando las piernas permanecen mucho tiempo en la misma postura, por ejemplo en el cine o durante viajes en autocar o avión.</li> <li><span>Sensación de calor o picores y escozores:</span> Principalmente en tobillo y dorso del pie. Debe evitarse el rascado, pues pueden hacerse heridas con facilidad, al ser la piel más débil por la mala circulación y, también por este motivo, infectarse con facilidad.</li> <li><span>Hinchazón o edema de los pies y tobillos:</span> Aparece, según avanza la enfermedad.</li> <li><span>Cambios de coloración en la piel:</span> Manchas parduscas o violáceas.</li> </ul> </p> <h3>ESCLEROTERAPIA</h3> <p> <p><img src="images/escleroterapia-1.png" alt=""></p> <p>CORRESPONDE A UN MÉTODO SEGURO Y EFECTIVO PARA LA ELIMINACIÓN DE VENAS RETICULARES (< A 5 MM DE DIÁMETRO) Y DE TELANGIECTASIAS O ARAÑAS VASCULARES.</p> <p>En este procedimiento de carácter ambulatorio, una pequeña cantidad de una solución esclerosante es inyectada mediante una microaguja en el interior de estos microvasos. La reacción inflamatoria química que se produce de manera secundaria en el interior hará que se colapsen su paredes, produciendo su cierre y reabsorción tisular posterior.</p> <p>Este procedimiento lo realizamos mediante Transiluminación para una correcta visión anatómica de los vasos venosos nutrientes de la telangiectasias.</p> <p>También podemos realizar la Escleroterapia con catéter ecoguíada, es decir, en vasos de mayor calibre y cuando está indicada, inyectamos una espuma (foam) directamente en el interior de los vasos venosos, bajo visión ecográfica (ultrasonido) directa con su correspondiente reabsorción o eliminación posterior.</p> <p>Estos procedimientos se harán bajo indicación directa de su Cirujano Vascular certificado. </p> </p> </div> </div> </div> <!-- Footer --> <?php include "footer.php"; ?><file_sep><!-- Header --> <?php include "header.php"; ?> <div class="container page"> <div class="ten columns offset-by-one"> <h2>CONTÁCTANOS</h2> <form action="send.php" method="post"> <div class="six columns"> Nombre ( <span>*</span> )<br> <input type="text" name="nombre" id="nombre" required> <br> Correo ( <span>*</span> )<br> <input type="email" name="email" id="email" required><br> Teléfono ( <span>*</span> )<br> <input type="text" name="telefono" id="telefono" required> </div> <div class="six columns"> Asunto<br> <input type="text" name="asunto" id="asunto" required><br> Mensaje<br> <textarea name="comentarios" id="comentarios" required></textarea> </div> <div class="twelve columns botton__enviar"> <p>Los campos marcados con ( <span>*</span> ) con obligatorios</p><input type="submit" value="ENVIAR"> </div> </form> </div> </div> <!-- Footer --> <?php include "footer.php"; ?><file_sep><!-- Header --> <?php include "header.php"; ?> <div class="container page"> <div class="ten columns offset-by-one"> <h2>ARTERIALES</h2> <div class="acordeon"> <h3>ANEURISMA</h3> <p> <p><img src="images/aneurisma.png" alt=""></p> <p>Es un ensanchamiento o abombamiento anormal de una porción de una arteria debido a una debilidad en la pared del vaso sanguíneo.</p> <h4>Principales Síntomas</h4> <p>Los síntomas dependen de la localización del aneurisma. Si el aneurisma se presenta cerca de la superficie corporal, frecuentemente se observa dolor e hinchazón con una masa pulsátil.</p> <p>Los aneurismas dentro del cuerpo y el cerebro a menudo son asintomáticos.</p> <p>Si un aneurisma se rompe, se puede presentar dolor, presión arterial baja, frecuencia cardíaca rápida y mareo. El riesgo de muerte después de una ruptura es alto.</p> </p> <h3>ARTERIOSCLEROSIS</h3> <p> <p><img src="images/arteriosclerosis.png" alt=""></p> <p>Arteriosclerosis es una enfermedad de los vasos sanguíneos producida por un acumulo de colesterol, que hace que la sangre circule con mayor dificultad por las mismas y aumente el riesgo de producir obstrucciones. Esta enfermedad se desarrolla lentamente, puede comenzar en edades.</p> <h4>Principales Síntomas</h4> <p>Los síntomas que usted tendrá dependerán de cuáles arterias se encuentran gravemente obstruidas y qué parte del cuerpo resulta afectada por la reducción en el flujo de sangre. Normalmente no hay síntomas hasta que una o más arterias están tan obstruidas con placa, que se reduce drásticamente el flujo de sangre. Esta reducción en el flujo de sangre y oxígeno a algunas partes del cuerpo (como el corazón), se denomina isquemia y puede ocasionar dolor o molestias. Algunas personas no tienen síntomas hasta que se forma un coágulo de sangre que obstruye por completo una arteria ya estrechada, y causa un ataque cardiaco o derrame cerebral.</p> <ul> <li>Si resultan afectadas las arterias que transportan sangre al músculo del corazón, usted tendrá una enfermedad de las arterias coronarias (EAC). Puede tener un dolor en el pecho llamado angina de pecho, que se presenta cuando se esfuerza demasiado y desaparece cuando descansa. También podría tener un ataque cardiaco.</li> <li>Si resultan afectadas las arterias que transportan sangre al cerebro, usted tendrá una enfermedad cerebrovascular. Podría tener un ataque isquémico transitorio (AIT) o un derrame cerebral.</li> <li>Si resultan afectadas las arterias que transportan sangre a las piernas, usted tendrá una enfermedad arterial periférica (EAP). Cuando camina puede sentir un dolor denominado claudicación intermitente en los músculos de la pantorrilla o muslo. Este dolor desaparece cuando se detiene y descansa.</li> </ul> <p>Todas estas condiciones son graves y no deben ignorarse. También pueden bloquearse con placa las arterias que transportan sangre a los intestinos, riñones y otros órganos. Esto puede provocar una emergencia médica similar al ataque cardiaco o derrame cerebral. La aterosclerosis también puede ocasionar disfunción eréctil en los hombres.</p> </p> <h3>PIE DIABÉTICO</h3> <p><img src="images/pie-diabetico.png" alt=""></p> <p> <p>El pie diabético, según el Consenso Internacional sobre Pie Diabético es una infección, ulceración o destrucción de los tejidos profundos relacionados con alteraciones neurológicas y distintos grados de enfermedad vascular periférica en las extremidades inferiores que afecta a pacientes con diabetes mellitus.</p> <p>Es importante remarcar que no debe confundirse "pie diabético" con el pie de una persona diabética, ya que no todos los diabéticos desarrollan esta complicación que depende en gran medida del control que se tenga de la enfermedad, de los factores intrínsecos y ambientales asociados al paciente y en definitiva del estado evolutivo de la patología de base.</p> <h4>Principales Síntomas</h4> <p>Calambres que se agravan por la noche, parestesias y dolor que en ocasiones es muy intenso y se acompaña de hiperestesias, hasta el punto de que el paciente no tolera el roce de las sábanas.</p> <p>La pérdida de la sensibilidad vibratoria es uno de los síntomas más precoces. Hay una disminución o abolición de la sensibilidad propioceptiva.</p> <p>La hipoestesia (disminución de la sensibilidad) permite que se produzcan lesiones que son advertidas tardíamente por los pacientes.</p> </p> </div> </div> </div> <!-- Footer --> <?php include "footer.php"; ?>
92556f69bcdb1881835ddd18621d090e77e17e5c
[ "PHP" ]
10
PHP
gydoar/Delcy
1762462f60465007dd0aff3a12653abb39c2a53f
1ec2f39850c45c8a3172b971e74f9b660447824a
refs/heads/master
<repo_name>tareqbader/wordcount-project<file_sep>/wordcount/views.py from django.http import HttpResponse from django.shortcuts import render import operator def homepage(request): return render(request, 'home.html', {'x': 'Hi I am Designing My Second WepSite'}) def count(request): fulltext = request.GET['fulltext'] # request.GET[] we use it to get the value of url parameter which is named here as 'fulltext' and we store it in variable words = fulltext.split() # split() function split a string into words depending on space worddictionary = {} for word in words: if word in worddictionary: # increase by 1 worddictionary[word] += 1 else: # add to wordsdictionary worddictionary[word] = 1 wordsorted = sorted(worddictionary.items(), key=operator.itemgetter(1), reverse=True) return render(request, 'count.html', {'fulltext': fulltext, 'words': len(words), 'wordsorted': wordsorted}) def about(request): return render(request, 'about.html') <file_sep>/templates/count.html <h1>Text Entered :</h1> {{fulltext}} <h3><a href="{% url 'home' %}">Return Home</a></h3> <h2>Number of Words in Text is {{words}} </h2> <h2>Word count :</h2> {% for word, total in wordsorted %} {{word}}-{{total}} <br /> {% endfor %}
9aef94e8d83e831e6e123897be46b39fa2a73c2e
[ "Python", "HTML" ]
2
Python
tareqbader/wordcount-project
95e0ffa0b6b5e7d7015c51bef36dbf2d71977757
626f2d7e47d714fcded629f5b9d3fcc4616260fc
refs/heads/master
<repo_name>nad314/core-game<file_sep>/core-game/gameMesh/glGameMesh.h #pragma once namespace core { class glGameMesh { public: GLuint buff[6]; GLuint vao; int ind; glGameMesh() { memset(buff, 0, sizeof(buff)); ind = 0; } GAMEDLL ~glGameMesh(); GAMEDLL void dispose(); GAMEDLL bool make(GameMesh& mesh, glShader& shader, const char* pos, const char* nor, const char* tex); GAMEDLL bool make(GameMesh& mesh, glShader& shader, const char* pos, const char* nor, const char* tan, const char* btan, const char* tex); GAMEDLL void drawTris(); GAMEDLL void drawQuads(); }; } <file_sep>/core-game/glTexture/glTexture.h #pragma once namespace core { class glTexture { private: GLuint t; public: glTexture() : t(0) {} GAMEDLL ~glTexture(); inline operator GLuint&() { return t; } inline operator const GLuint() const { return t; } inline glTexture& bind() { glBindTexture(GL_TEXTURE_2D, t); return *this; } inline glTexture& bind(const int& n) { glExt::activeTexture(GL_TEXTURE0 + n); bind(); return *this; } inline static void unbind() { glBindTexture(GL_TEXTURE_2D, 0); } inline static void unbind(const int& n) { glExt::activeTexture(GL_TEXTURE0 + n); unbind(); } GAMEDLL void dispose(); GAMEDLL bool make(const Image& img); GAMEDLL bool construct(Image& img); //construct an image from opengl GAMEDLL bool loadPng(char* path); GAMEDLL void genMipmaps(); }; } <file_sep>/core-game/glExt/glExtensions.defines.h #pragma once #define GL_BUFFER_SIZE 0x8764 #define GL_BUFFER_USAGE 0x8765 #define GL_QUERY_COUNTER_BITS 0x8864 #define GL_CURRENT_QUERY 0x8865 #define GL_QUERY_RESULT 0x8866 #define GL_QUERY_RESULT_AVAILABLE 0x8867 #define GL_ARRAY_BUFFER 0x8892 #define GL_ELEMENT_ARRAY_BUFFER 0x8893 #define GL_ARRAY_BUFFER_BINDING 0x8894 #define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 #define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F #define GL_READ_ONLY 0x88B8 #define GL_WRITE_ONLY 0x88B9 #define GL_READ_WRITE 0x88BA #define GL_BUFFER_ACCESS 0x88BB #define GL_BUFFER_MAPPED 0x88BC #define GL_BUFFER_MAP_POINTER 0x88BD #define GL_STREAM_DRAW 0x88E0 #define GL_STREAM_READ 0x88E1 #define GL_STREAM_COPY 0x88E2 #define GL_STATIC_DRAW 0x88E4 #define GL_STATIC_READ 0x88E5 #define GL_STATIC_COPY 0x88E6 #define GL_DYNAMIC_DRAW 0x88E8 #define GL_DYNAMIC_READ 0x88E9 #define GL_DYNAMIC_COPY 0x88EA #define GL_SAMPLES_PASSED 0x8914 #define GL_SRC1_ALPHA 0x8589 #define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 #define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 #define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 #define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899 #define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A #define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B #define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C #define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D #define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E #define GL_FOG_COORD_SRC 0x8450 #define GL_FOG_COORD 0x8451 #define GL_CURRENT_FOG_COORD 0x8453 #define GL_FOG_COORD_ARRAY_TYPE 0x8454 #define GL_FOG_COORD_ARRAY_STRIDE 0x8455 #define GL_FOG_COORD_ARRAY_POINTER 0x8456 #define GL_FOG_COORD_ARRAY 0x8457 #define GL_FOG_COORD_ARRAY_BUFFER_BINDING 0x889D #define GL_SRC0_RGB 0x8580 #define GL_SRC1_RGB 0x8581 #define GL_SRC2_RGB 0x8582 #define GL_SRC0_ALPHA 0x8588 #define GL_SRC2_ALPHA 0x858A #define GL_MAP_READ_BIT 0x0001 #define GL_MAP_WRITE_BIT 0x0002 #define GL_MAP_PERSISTENT_BIT 0x00000040 #define GL_MAP_COHERENT_BIT 0x00000080 #define GL_DYNAMIC_STORAGE_BIT 0x0100 #define GL_CLIENT_STORAGE_BIT 0x0200 #define GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT 0x00004000 #define GL_BUFFER_IMMUTABLE_STORAGE 0x821F #define GL_BUFFER_STORAGE_FLAGS 0x8220 #define GL_SHADER_STORAGE_BUFFER 0x90D2 #define GL_SHADER_STORAGE_BUFFER_BINDING 0x90D3 #define GL_SHADER_STORAGE_BUFFER_START 0x90D4 #define GL_SHADER_STORAGE_BUFFER_SIZE 0x90D5 #define GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS 0x90D6 #define GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS 0x90D7 #define GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS 0x90D8 #define GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS 0x90D9 #define GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS 0x90DA #define GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS 0x90DB #define GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS 0x90DC #define GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS 0x90DD #define GL_MAX_SHADER_STORAGE_BLOCK_SIZE 0x90DE #define GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT 0x90DF #define GL_SHADER_STORAGE_BARRIER_BIT 0x2000 #define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001 #define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002 #define GL_UNIFORM_BARRIER_BIT 0x00000004 #define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008 #define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020 #define GL_COMMAND_BARRIER_BIT 0x00000040 #define GL_PIXEL_BUFFER_BARRIER_BIT 0x00000080 #define GL_TEXTURE_UPDATE_BARRIER_BIT 0x00000100 #define GL_BUFFER_UPDATE_BARRIER_BIT 0x00000200 #define GL_FRAMEBUFFER_BARRIER_BIT 0x00000400 #define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800 #define GL_ATOMIC_COUNTER_BARRIER_BIT 0x00001000 #define GL_ALL_BARRIER_BITS 0xFFFFFFFF #define GL_R32F 0x822E #define GL_R16F 0x822D #define GL_DEPTH_COMPONENT16 0x81A5 #define GL_DEPTH_COMPONENT24 0x81A6 #define GL_DEPTH_COMPONENT32 0x81A7 #define GL_DEPTH_COMPONENT32F 0x8CAC #define GL_DEPTH_COMPONENT32F_NV 0x8DAB #define GL_VERTEX_SHADER_ARB 0x8B31 #define GL_GEOMETRY_SHADER_ARB 0x8DD9 #define GL_FRAGMENT_SHADER_ARB 0x8B30 #define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB #define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD #define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 #define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A #define GL_COMPUTE_SHADER 0x91B9 #define GL_MAX_COMPUTE_UNIFORM_BLOCKS 0x91BB #define GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS 0x91BC #define GL_MAX_COMPUTE_IMAGE_UNIFORMS 0x91BD #define GL_MAX_COMPUTE_SHARED_MEMORY_SIZE 0x8262 #define GL_MAX_COMPUTE_UNIFORM_COMPONENTS 0x8263 #define GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS 0x8264 #define GL_MAX_COMPUTE_ATOMIC_COUNTERS 0x8265 #define GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS 0x8266 #define GL_MAX_COMPUTE_LOCAL_INVOCATIONS 0x90EB #define GL_MAX_COMPUTE_WORK_GROUP_COUNT 0x91BE #define GL_MAX_COMPUTE_WORK_GROUP_SIZE 0x91BF #define GL_COMPUTE_LOCAL_WORK_SIZE 0x8267 #define GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER 0x90EC #define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER 0x90ED #define GL_DISPATCH_INDIRECT_BUFFER 0x90EE #define GL_DISPATCH_INDIRECT_BUFFER_BINDING 0x90EF #define GL_COMPUTE_SHADER_BIT 0x00000020 #define GL_UNIFORM 0x92E1 #define GL_UNIFORM_BLOCK 0x92E2 #define GL_PROGRAM_INPUT 0x92E3 #define GL_PROGRAM_OUTPUT 0x92E4 #define GL_BUFFER_VARIABLE 0x92E5 #define GL_SHADER_STORAGE_BLOCK 0x92E6 #define GL_IS_PER_PATCH 0x92E7 #define GL_VERTEX_SUBROUTINE 0x92E8 #define GL_TESS_CONTROL_SUBROUTINE 0x92E9 #define GL_TESS_EVALUATION_SUBROUTINE 0x92EA #define GL_GEOMETRY_SUBROUTINE 0x92EB #define GL_FRAGMENT_SUBROUTINE 0x92EC #define GL_COMPUTE_SUBROUTINE 0x92ED #define GL_VERTEX_SUBROUTINE_UNIFORM 0x92EE #define GL_TESS_CONTROL_SUBROUTINE_UNIFORM 0x92EF #define GL_TESS_EVALUATION_SUBROUTINE_UNIFORM 0x92F0 #define GL_GEOMETRY_SUBROUTINE_UNIFORM 0x92F1 #define GL_FRAGMENT_SUBROUTINE_UNIFORM 0x92F2 #define GL_COMPUTE_SUBROUTINE_UNIFORM 0x92F3 #define GL_TRANSFORM_FEEDBACK_VARYING 0x92F4 #define GL_ACTIVE_RESOURCES 0x92F5 #define GL_MAX_NAME_LENGTH 0x92F6 #define GL_MAX_NUM_ACTIVE_VARIABLES 0x92F7 #define GL_MAX_NUM_COMPATIBLE_SUBROUTINES 0x92F8 #define GL_NAME_LENGTH 0x92F9 #define GL_TYPE 0x92FA #define GL_ARRAY_SIZE 0x92FB #define GL_OFFSET 0x92FC #define GL_BLOCK_INDEX 0x92FD #define GL_ARRAY_STRIDE 0x92FE #define GL_MATRIX_STRIDE 0x92FF #define GL_IS_ROW_MAJOR 0x9300 #define GL_ATOMIC_COUNTER_BUFFER_INDEX 0x9301 #define GL_BUFFER_BINDING 0x9302 #define GL_BUFFER_DATA_SIZE 0x9303 #define GL_NUM_ACTIVE_VARIABLES 0x9304 #define GL_ACTIVE_VARIABLES 0x9305 #define GL_REFERENCED_BY_VERTEX_SHADER 0x9306 #define GL_REFERENCED_BY_TESS_CONTROL_SHADER 0x9307 #define GL_REFERENCED_BY_TESS_EVALUATION_SHADER 0x9308 #define GL_REFERENCED_BY_GEOMETRY_SHADER 0x9309 #define GL_REFERENCED_BY_FRAGMENT_SHADER 0x930A #define GL_REFERENCED_BY_COMPUTE_SHADER 0x930B #define GL_TOP_LEVEL_ARRAY_SIZE 0x930C #define GL_TOP_LEVEL_ARRAY_STRIDE 0x930D #define GL_LOCATION 0x930E #define GL_LOCATION_INDEX 0x930F #define GL_TEXTURE0 0x84C0 #define GL_TEXTURE1 0x84C1 #define GL_TEXTURE2 0x84C2 #define GL_TEXTURE3 0x84C3 #define GL_TEXTURE4 0x84C4 #define GL_TEXTURE5 0x84C5 #define GL_TEXTURE6 0x84C6 #define GL_TEXTURE7 0x84C7 #define GL_TEXTURE8 0x84C8 #define GL_TEXTURE9 0x84C9 #define GL_TEXTURE10 0x84CA #define GL_TEXTURE11 0x84CB #define GL_TEXTURE12 0x84CC #define GL_TEXTURE13 0x84CD #define GL_TEXTURE14 0x84CE #define GL_TEXTURE15 0x84CF #define GL_TEXTURE16 0x84D0 #define GL_TEXTURE17 0x84D1 #define GL_TEXTURE18 0x84D2 #define GL_TEXTURE19 0x84D3 #define GL_TEXTURE20 0x84D4 #define GL_TEXTURE21 0x84D5 #define GL_TEXTURE22 0x84D6 #define GL_TEXTURE23 0x84D7 #define GL_TEXTURE24 0x84D8 #define GL_TEXTURE25 0x84D9 #define GL_TEXTURE26 0x84DA #define GL_TEXTURE27 0x84DB #define GL_TEXTURE28 0x84DC #define GL_TEXTURE29 0x84DD #define GL_TEXTURE30 0x84DE #define GL_TEXTURE31 0x84DF #define GL_CLAMP_TO_EDGE 0x812F typedef unsigned short GLhalf; #define GL_COMPARE_REF_TO_TEXTURE 0x884E #define GL_CLIP_DISTANCE0 0x3000 #define GL_CLIP_DISTANCE1 0x3001 #define GL_CLIP_DISTANCE2 0x3002 #define GL_CLIP_DISTANCE3 0x3003 #define GL_CLIP_DISTANCE4 0x3004 #define GL_CLIP_DISTANCE5 0x3005 #define GL_CLIP_DISTANCE6 0x3006 #define GL_CLIP_DISTANCE7 0x3007 #define GL_MAX_CLIP_DISTANCES 0x0D32 #define GL_MAJOR_VERSION 0x821B #define GL_MINOR_VERSION 0x821C #define GL_NUM_EXTENSIONS 0x821D #define GL_CONTEXT_FLAGS 0x821E #define GL_COMPRESSED_RED 0x8225 #define GL_COMPRESSED_RG 0x8226 #define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x00000001 #define GL_RGBA32F 0x8814 #define GL_RGB32F 0x8815 #define GL_RGBA16F 0x881A #define GL_RGB16F 0x881B #define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD #define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF #define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 #define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 #define GL_CLAMP_READ_COLOR 0x891C #define GL_FIXED_ONLY 0x891D #define GL_MAX_VARYING_COMPONENTS 0x8B4B #define GL_TEXTURE_1D_ARRAY 0x8C18 #define GL_PROXY_TEXTURE_1D_ARRAY 0x8C19 #define GL_TEXTURE_2D_ARRAY 0x8C1A #define GL_PROXY_TEXTURE_2D_ARRAY 0x8C1B #define GL_TEXTURE_BINDING_1D_ARRAY 0x8C1C #define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D #define GL_R11F_G11F_B10F 0x8C3A #define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B #define GL_RGB9_E5 0x8C3D #define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E #define GL_TEXTURE_SHARED_SIZE 0x8C3F #define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 #define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F #define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 #define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 #define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 #define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 #define GL_PRIMITIVES_GENERATED 0x8C87 #define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 #define GL_RASTERIZER_DISCARD 0x8C89 #define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A #define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B #define GL_INTERLEAVED_ATTRIBS 0x8C8C #define GL_SEPARATE_ATTRIBS 0x8C8D #define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E #define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F #define GL_RGBA32UI 0x8D70 #define GL_RGB32UI 0x8D71 #define GL_RGBA16UI 0x8D76 #define GL_RGB16UI 0x8D77 #define GL_RGBA8UI 0x8D7C #define GL_RGB8UI 0x8D7D #define GL_RGBA32I 0x8D82 #define GL_RGB32I 0x8D83 #define GL_RGBA16I 0x8D88 #define GL_RGB16I 0x8D89 #define GL_RGBA8I 0x8D8E #define GL_RGB8I 0x8D8F #define GL_RED_INTEGER 0x8D94 #define GL_GREEN_INTEGER 0x8D95 #define GL_BLUE_INTEGER 0x8D96 #define GL_RGB_INTEGER 0x8D98 #define GL_RGBA_INTEGER 0x8D99 #define GL_BGR_INTEGER 0x8D9A #define GL_BGRA_INTEGER 0x8D9B #define GL_SAMPLER_1D_ARRAY 0x8DC0 #define GL_SAMPLER_2D_ARRAY 0x8DC1 #define GL_SAMPLER_1D_ARRAY_SHADOW 0x8DC3 #define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 #define GL_SAMPLER_CUBE_SHADOW 0x8DC5 #define GL_UNSIGNED_INT_VEC2 0x8DC6 #define GL_UNSIGNED_INT_VEC3 0x8DC7 #define GL_UNSIGNED_INT_VEC4 0x8DC8 #define GL_INT_SAMPLER_1D 0x8DC9 #define GL_INT_SAMPLER_2D 0x8DCA #define GL_INT_SAMPLER_3D 0x8DCB #define GL_INT_SAMPLER_CUBE 0x8DCC #define GL_INT_SAMPLER_1D_ARRAY 0x8DCE #define GL_INT_SAMPLER_2D_ARRAY 0x8DCF #define GL_UNSIGNED_INT_SAMPLER_1D 0x8DD1 #define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 #define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 #define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 #define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY 0x8DD6 #define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 #define GL_QUERY_WAIT 0x8E13 #define GL_QUERY_NO_WAIT 0x8E14 #define GL_QUERY_BY_REGION_WAIT 0x8E15 #define GL_QUERY_BY_REGION_NO_WAIT 0x8E16 #define GL_BUFFER_ACCESS_FLAGS 0x911F #define GL_BUFFER_MAP_LENGTH 0x9120 #define GL_BUFFER_MAP_OFFSET 0x9121 #define GL_DEPTH_COMPONENT32F 0x8CAC #define GL_DEPTH32F_STENCIL8 0x8CAD #define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD #define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 #define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 #define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 #define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 #define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 #define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 #define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 #define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 #define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 #define GL_FRAMEBUFFER_DEFAULT 0x8218 #define GL_FRAMEBUFFER_UNDEFINED 0x8219 #define GL_DEPTH_STENCIL_ATTACHMENT 0x821A #define GL_MAX_RENDERBUFFER_SIZE 0x84E8 #define GL_DEPTH_STENCIL 0x84F9 #define GL_UNSIGNED_INT_24_8 0x84FA #define GL_DEPTH24_STENCIL8 0x88F0 #define GL_TEXTURE_STENCIL_SIZE 0x88F1 #define GL_TEXTURE_RED_TYPE 0x8C10 #define GL_TEXTURE_GREEN_TYPE 0x8C11 #define GL_TEXTURE_BLUE_TYPE 0x8C12 #define GL_TEXTURE_ALPHA_TYPE 0x8C13 #define GL_TEXTURE_DEPTH_TYPE 0x8C16 #define GL_UNSIGNED_NORMALIZED 0x8C17 #define GL_FRAMEBUFFER_BINDING 0x8CA6 #define GL_DRAW_FRAMEBUFFER_BINDING 0x8CA6 #define GL_RENDERBUFFER_BINDING 0x8CA7 #define GL_READ_FRAMEBUFFER 0x8CA8 #define GL_DRAW_FRAMEBUFFER 0x8CA9 #define GL_READ_FRAMEBUFFER_BINDING 0x8CAA #define GL_RENDERBUFFER_SAMPLES 0x8CAB #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 #define GL_FRAMEBUFFER_COMPLETE 0x8CD5 #define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 #define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 #define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB #define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC #define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD #define GL_MAX_COLOR_ATTACHMENTS 0x8CDF #define GL_COLOR_ATTACHMENT0 0x8CE0 #define GL_COLOR_ATTACHMENT1 0x8CE1 #define GL_COLOR_ATTACHMENT2 0x8CE2 #define GL_COLOR_ATTACHMENT3 0x8CE3 #define GL_COLOR_ATTACHMENT4 0x8CE4 #define GL_COLOR_ATTACHMENT5 0x8CE5 #define GL_COLOR_ATTACHMENT6 0x8CE6 #define GL_COLOR_ATTACHMENT7 0x8CE7 #define GL_COLOR_ATTACHMENT8 0x8CE8 #define GL_COLOR_ATTACHMENT9 0x8CE9 #define GL_COLOR_ATTACHMENT10 0x8CEA #define GL_COLOR_ATTACHMENT11 0x8CEB #define GL_COLOR_ATTACHMENT12 0x8CEC #define GL_COLOR_ATTACHMENT13 0x8CED #define GL_COLOR_ATTACHMENT14 0x8CEE #define GL_COLOR_ATTACHMENT15 0x8CEF #define GL_COLOR_ATTACHMENT16 0x8CF0 #define GL_COLOR_ATTACHMENT17 0x8CF1 #define GL_COLOR_ATTACHMENT18 0x8CF2 #define GL_COLOR_ATTACHMENT19 0x8CF3 #define GL_COLOR_ATTACHMENT20 0x8CF4 #define GL_COLOR_ATTACHMENT21 0x8CF5 #define GL_COLOR_ATTACHMENT22 0x8CF6 #define GL_COLOR_ATTACHMENT23 0x8CF7 #define GL_COLOR_ATTACHMENT24 0x8CF8 #define GL_COLOR_ATTACHMENT25 0x8CF9 #define GL_COLOR_ATTACHMENT26 0x8CFA #define GL_COLOR_ATTACHMENT27 0x8CFB #define GL_COLOR_ATTACHMENT28 0x8CFC #define GL_COLOR_ATTACHMENT29 0x8CFD #define GL_COLOR_ATTACHMENT30 0x8CFE #define GL_COLOR_ATTACHMENT31 0x8CFF #define GL_DEPTH_ATTACHMENT 0x8D00 #define GL_STENCIL_ATTACHMENT 0x8D20 #define GL_FRAMEBUFFER 0x8D40 #define GL_RENDERBUFFER 0x8D41 #define GL_RENDERBUFFER_WIDTH 0x8D42 #define GL_RENDERBUFFER_HEIGHT 0x8D43 #define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 #define GL_STENCIL_INDEX1 0x8D46 #define GL_STENCIL_INDEX4 0x8D47 #define GL_STENCIL_INDEX8 0x8D48 #define GL_STENCIL_INDEX16 0x8D49 #define GL_RENDERBUFFER_RED_SIZE 0x8D50 #define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 #define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 #define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 #define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 #define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 #define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 #define GL_MAX_SAMPLES 0x8D57 #define GL_INDEX 0x8222 #define GL_TEXTURE_LUMINANCE_TYPE 0x8C14 #define GL_TEXTURE_INTENSITY_TYPE 0x8C15 #define GL_FRAMEBUFFER_SRGB 0x8DB9 #define GL_HALF_FLOAT 0x140B #define GL_MAP_READ_BIT 0x0001 #define GL_MAP_WRITE_BIT 0x0002 #define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 #define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 #define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 #define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 #define GL_COMPRESSED_RED_RGTC1 0x8DBB #define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC #define GL_COMPRESSED_RG_RGTC2 0x8DBD #define GL_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE #define GL_RG 0x8227 #define GL_RG_INTEGER 0x8228 #define GL_R8 0x8229 #define GL_R16 0x822A #define GL_RG8 0x822B #define GL_RG16 0x822C #define GL_R16F 0x822D #define GL_R32F 0x822E #define GL_RG16F 0x822F #define GL_RG32F 0x8230 #define GL_R8I 0x8231 #define GL_R8UI 0x8232 #define GL_R16I 0x8233 #define GL_R16UI 0x8234 #define GL_R32I 0x8235 #define GL_R32UI 0x8236 #define GL_RG8I 0x8237 #define GL_RG8UI 0x8238 #define GL_RG16I 0x8239 #define GL_RG16UI 0x823A #define GL_RG32I 0x823B #define GL_RG32UI 0x823C #define GL_VERTEX_ARRAY_BINDING 0x85B5 #define GL_CLAMP_VERTEX_COLOR 0x891A #define GL_CLAMP_FRAGMENT_COLOR 0x891B #define GL_ALPHA_INTEGER 0x8D97 <file_sep>/core-game/glFramebuffer/glFramebuffer.cpp #include <core> #include <core-forms> #include <core-game> namespace core { GAMEDLL bool glFramebuffer::build(const int w, const int h) { try { glGetError(); glExt::genFramebuffers(1, &name); glExt::bindFramebuffer(GL_FRAMEBUFFER, name); if (glGetError() != 0) throw core::exception("Couldn't build framebuffer\n"); glGenTextures(1, &rgb); if (glGetError() != 0) throw core::exception("Couldn't build rgb texture\n"); glGenTextures(1, &depth); if (glGetError() != 0) throw core::exception("Couldn't build depth texture\n"); glBindTexture(GL_TEXTURE_2D, rgb); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glExt::genRenderBuffers(1, &depth); glExt::bindRenderBuffer(GL_RENDERBUFFER, depth); glExt::renderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, w, h); glExt::framebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth); glExt::framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rgb, 0); GLenum DrawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glExt::drawBuffers(1, DrawBuffers); if (glExt::checkFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) throw core::exception("Framebuffer build error\n"); unbind(); } catch (std::exception& e) { core::Debug::log("%s\n", e.what()); dispose(); return false; } return true; } GAMEDLL void glFramebuffer::resize(const int w, const int h) { if (name == 0) return; glExt::bindRenderBuffer(GL_RENDERBUFFER, depth); glExt::renderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, w, h); glBindTexture(GL_TEXTURE_2D, rgb); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); } GAMEDLL void glFramebuffer::drawToScreen(const int w, const int h) const{ glExt::bindFramebuffer(GL_READ_FRAMEBUFFER, *this); glExt::bindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glExt::blitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); glExt::bindFramebuffer(GL_READ_FRAMEBUFFER, 0); } GAMEDLL void glFramebuffer::dispose() { if (glIsTexture(rgb)) glDeleteTextures(1, &rgb); glExt::deleteRenderBuffers(1, &depth); glExt::deleteFramebuffers(1, &name); name = rgb = depth = 0; } } <file_sep>/core-game/gameMesh/gameMesh.cpp #include <core> #include <core-forms> #include <core-game> namespace core { GAMEDLL void GameMesh::computeNormals() { vec3 nor; size_t i; normal.reserve(position.count()); normal.count() = position.count(); for (i = 0; i < normal.count(); ++i) normal[i] = vec3(0.0f); for (i = 0; i < indices.count(); i += 3) { nor = vector::normal(position[indices[i]], position[indices[i+1]], position[indices[i+2]]); normal[indices[i]] += nor; normal[indices[i+1]] += nor; normal[indices[i+2]] += nor; } for (i = 0; i < normal.count(); ++i) normal[i].normalize(); } GAMEDLL void GameMesh::computeTangentSpace(buffer<vec3>& tangents, buffer<vec3>& bitangents) { tangents.reserve(position.count()); tangents.count() = position.count(); bitangents.reserve(position.count()); bitangents.count() = position.count(); size_t i; for (i = 0; i < tangents.count(); ++i) { tangents[i] = vec3(0.0f); bitangents[i] = vec3(0.0f); } for (i = 0; i < indices.count(); i += 3) { vec3 d1 = position[indices[i + 1]] - position[indices[i]]; vec3 d2 = position[indices[i + 2]] - position[indices[i]]; vec2 uv1 = texcoord[indices[i + 1]] - texcoord[indices[i]]; vec2 uv2 = texcoord[indices[i + 2]] - texcoord[indices[i]]; float r = 1.0f / (uv1.x*uv2.y - uv1.y*uv2.x); vec3 tg = ((d1*uv2.y - d2*uv1.y)*r).normalize(); vec3 btg = ((d2*uv1.x - d1*uv2.x)*r).normalize(); tangents[indices[i]] += tg; tangents[indices[i+1]] += tg; tangents[indices[i+2]] += tg; bitangents[indices[i]] += btg; bitangents[indices[i+1]] += btg; bitangents[indices[i+2]] += btg; } for (i = 0; i < tangents.count(); ++i) { tangents[i].normalize(); bitangents[i].normalize(); float f = (vector::dot(vector::cross(normal[i], tangents[i]), bitangents[i])<0.0f) ? -1.0f : 1.0f; tangents[i] = (normal[i] * vector::dot(normal[i], tangents[i]) - tangents[i]).normalize()*f; //bitangents[i] = (vector::cross(normal[indices[i]], tangents[i])*f).normalize(); } } } <file_sep>/core-game/glFrame/glFrame.cpp #include <core> #include <core-forms> #include <core-game> namespace core { GAMEDLL int glFrame::onMouseMove(const eventInfo& e) { if (!visible) return e; int f = flags&2; if (e.x() >= rect.x && e.x() <= rect.z && e.y() >= rect.y && e.y() <= rect.w) __hover(); else __unhover(); /* eventInfo translated = e; translated.lP = MAKELPARAM((short)e.x() - rect.x, (short)e.y() - rect.y); */ eventInfo translated = e.translateEvent(-rect.x, -rect.y); if (f > 0 || (flags & 2) > 0) { for (auto& i : items) i->onMouseMove(translated); invalidate(); return 1; } if (e.y() < rect.y || e.y() > rect.w) { hide(); invalidate(); return 0; } return 0; } GAMEDLL int glFrame::onRightButtonDown(const eventInfo& e) { if ((flags & 2) > 0) for (auto& i : items) if (i->onRightButtonDown(e)) return 1; return 0; } GAMEDLL int glFrame::onRightButtonUp(const eventInfo& e) { for (auto& i : items) if (i->onRightButtonUp(e)) return 1; return 0; } GAMEDLL int glFrame::onPaint(const eventInfo& e) { if (!visible) return e; glTranslatef((float)rect.x, (float)rect.y, 0.0f); for (auto& i : items) i->onPaint(e); glTranslatef((float)-rect.x, (float)-rect.y, 0.0f); return 0; } GAMEDLL int glFrame::onLButtonDown(const eventInfo& e) { if ((flags & 2) > 0) for (auto& i : items) if (i->onLButtonDown(e)) return 1; return 0; } GAMEDLL int glFrame::onLButtonUp(const eventInfo& e) { for (auto& i : items) if (i->onLButtonUp(e)) return 1; return 0; } GAMEDLL int glFrame::onResize(const eventInfo& e) { return e; } GAMEDLL int glFrame::onLButtonDblClk(const eventInfo& e) { if ((flags & 2) > 0) for (auto& i : items) if (i->onLButtonDblClk(e)) return 1; return 0; } GAMEDLL Rect glFrame::nextHorizontal() { Rect r(0,0,0,0); for (auto& i : items) r = r.max(i->rect); r.x = r.z; r.w = r.y; return r; } GAMEDLL Rect glFrame::nextVertical() { Rect r(0, 0, 0, 0); for (auto& i : items) r = r.max(i->rect); r.z = r.x; r.y = r.w; return r; } GAMEDLL glFrame& glFrame::wrap() { Rect nh = nextHorizontal(); Rect nv = nextVertical(); rect.z = rect.x + nh.x; rect.w = rect.y + nv.y; return *this; } } <file_sep>/core-game/glShader/glShader.cpp #include <core> #include <core-forms> #include <core-game> namespace core { GAMEDLL glShader& glShader::dispose() { if (glExt::isProgram(program)) glExt::deleteObject(program); if (glExt::isShader(fragment)) glExt::deleteObject(fragment); if (glExt::isShader(vertex)) glExt::deleteObject(vertex); vertex = fragment = program = 0; return *this; } GAMEDLL bool glShader::load(const char* vertexPath, const char* fragmentPath, const char* fragName) { dispose(); glGetError(); char *v=NULL, *f=NULL; if (!Path::fileToString(vertexPath, &v)) return 0; if (!Path::fileToString(fragmentPath, &f)) { delete[] v; return 0; } program = glExt::createProgramObject(); vertex = glExt::createShaderObject(GL_VERTEX_SHADER_ARB); fragment = glExt::createShaderObject(GL_FRAGMENT_SHADER_ARB); glExt::shaderSource(vertex, 1, const_cast<const char**>(&v), NULL); glExt::shaderSource(fragment, 1, const_cast<const char**>(&f), NULL); glExt::compileShader(vertex); glExt::compileShader(fragment); glExt::attachObject(program, vertex); glExt::attachObject(program, fragment); glExt::bindFragDataLocation(program, 0, fragName); glExt::linkProgram(program); delete[] v; delete[] f; return glGetError()==0; } GAMEDLL glShader& glShader::printDebugInfo() { char c[256]; int l; glExt::getShaderInfoLog(vertex, 256, &l, c); Debug::log("Vertex Shader Log:\n%s\n", c); glExt::getShaderInfoLog(fragment, 256, &l, c); Debug::log("Fragment Shader Log:\n%s\n", c); return *this; } } <file_sep>/core-game/view/view.h #pragma once namespace core { class View { public: matrixf projection; matrixf modelview; float fov; virtual ~View() {} GAMEDLL View& perspective(const int& width, const int& height, const float& FoV, const float& znear, const float& zfar); GAMEDLL View& perspective(Window& wnd, const float& FoV, const float& znear, const float& zfar); GAMEDLL vec4 project(const vec4& v, const Window& wnd) const; GAMEDLL vec4 unproject(const vec4& v, const Window& wnd) const; GAMEDLL vec4 mult(const vec4& v) const; GAMEDLL vec4 multInv(const vec4& v) const; GAMEDLL vec4 projectFull(const vec4& v, const Window& wnd) const; GAMEDLL vec4 unprojectFull(const vec4& v, const Window& wnd) const; }; } <file_sep>/core-game/glControl/glImageButton.h #pragma once namespace core { class glImageButton : public ImageButton { protected: glTexture glDef, glHov, glAct; float pos[8]; GAMEDLL static float tex[8]; public: glImageButton() : ImageButton() {} glImageButton(const vec4i& r) : ImageButton(r) {} glImageButton(const vec4i& r, Image* img, Form& f) : ImageButton(r, img, f) {} virtual ~glImageButton() {} GAMEDLL virtual ImageButton& make(const vec4i& r, Image* img, Form& f); GAMEDLL virtual ImageButton& make(const vec4i& r, Image* img, Form& f, buttonFunc func); GAMEDLL virtual ImageButton& prerender(); GAMEDLL virtual ButtonObject& move(const vec4i& r) override; GAMEDLL virtual int onPaint(const eventInfo& e) override; inline virtual void manualUnhover() { __unhover(); } }; } <file_sep>/core-game/speleoMesh/glSpeleoModel.h #pragma once namespace core { class glSpeleoModel { private: buffer<glSpeleoMesh> mesh; buffer<glTexture> albedo; buffer<glTexture> normal; public: glSpeleoModel() {} ~glSpeleoModel() {} GAMEDLL bool make(const TModel& model, glShader& shader, const char* pos, const char* tex); GAMEDLL void dispose(); GAMEDLL void draw(); }; }<file_sep>/core-game/view/view.cpp #include <core> #include <core-forms> #include <core-game> namespace core { GAMEDLL View& View::perspective(const int& width, const int& height, const float& FoV, const float& znear, const float& zfar) { if (height == 0) return *this; projection.projection(FoV, (float)width / height, znear, zfar); fov = FoV; return *this; } GAMEDLL View& View::perspective(Window& window, const float &FoV, const float& znear, const float& zfar) { return perspective(window.width, window.height, FoV, znear, zfar); } GAMEDLL vec4 View::project(const vec4& v, const Window& wnd) const { vec4 r(0.0f); if (v.w == 0.0f)return r; r.w = 1.0f / v.w; r.x = (v.x*r.w*0.5f + 0.5f)*wnd.width + 0; r.y = (v.y*r.w*0.5f + 0.5f)*wnd.height + 0; r.z = (1.0f + v.z*r.w)*0.5f; return r; } GAMEDLL vec4 View::unproject(const vec4& v, const Window& wnd) const { if (v.w == 0.0f) return vec4(0.0f); vec4 r = v / vec4((float)wnd.width, (float)wnd.height, 1.0f, 1.0f) - vec4(0.5f, 0.5f, 0.0f, 0.0f); r /= vec4(0.5f, 0.5f, 0.5f, 1.0f); r.x /= r.w; r.y /= r.w; r.z = (r.z - 1.0f) / r.w; r.w = 1.0f; return r; } GAMEDLL vec4 View::mult(const vec4& v) const { return modelview*projection*v; } GAMEDLL vec4 View::multInv(const vec4& v) const { matrixf inv = modelview*projection; inv.invert(); return inv*v; } GAMEDLL vec4 View::projectFull(const vec4& v, const Window& wnd) const { return project(modelview*projection*v, wnd); } GAMEDLL vec4 View::unprojectFull(const vec4& v, const Window& wnd) const { vec4 p = multInv(unproject(v, wnd)); return p / p.w; } } <file_sep>/core-game/view/glview.h #pragma once namespace core { class glView : public View { public: GAMEDLL glView& sendTo(glShader& shader, const char* modelviewName, const char* projectionName); GAMEDLL glView& sendTo(glShader& shader, const uint& modelviewName, const uint& projectionName); }; } <file_sep>/core-game/glTextureMaterial/glTextureMaterial.cpp #include <core> #include <core-forms> #include <core-game> namespace core { GAMEDLL const int glTextureMaterial::fileChunk::type_image = 1; GAMEDLL const int glTextureMaterial::fileChunk::subtype_diffuse = 1; GAMEDLL const int glTextureMaterial::fileChunk::subtype_normal = 2; GAMEDLL const int glTextureMaterial::fileChunk::type_scale_vector = 2; GAMEDLL bool glTextureMaterial::save(const char* path, const char* tempDir) { bool ret = 1; Path::pushDir(); Path::cd(tempDir); Image img; ret &= diffuse.construct(img); ret &= img.savePng("tmp.diffuse"); ret &= normal.construct(img); ret &= img.savePng("tmp.normal"); //file to file FILE* f; fileChunk chunk; char* data = NULL; if (!(f = fopen(path, "wb"))) ret = 0; if (ret) { chunk.type = fileChunk::type_image; chunk.subtype = fileChunk::subtype_diffuse; chunk.bytes = Path::getFileSize("tmp.diffuse"); fwrite(&chunk, sizeof(chunk), 1, f); ret &= Path::fileToString("tmp.diffuse", &data); fwrite(data, 1, chunk, f); delete[] data; data = NULL; if (!ret) core::Debug::print("Could not save diffuse image\n"); } if (ret) { chunk.type = fileChunk::type_image; chunk.subtype = fileChunk::subtype_normal; chunk.bytes = Path::getFileSize("tmp.normal"); fwrite(&chunk, sizeof(chunk), 1, f); ret &= Path::fileToString("tmp.normal", &data); fwrite(data, 1, chunk, f); delete[] data; data = NULL; if (!ret) core::Debug::print("Could not save normal image\n"); } if (ret) { chunk.type = fileChunk::type_scale_vector; chunk.subtype = 0; chunk.bytes = sizeof(vec2); fwrite(&chunk, sizeof(chunk), 1, f); fwrite(&scale, sizeof(vec2), 1, f); } fclose(f); //remove files remove("tmp.diffuse"); remove("tmp.normal"); Path::popDir(); return ret; } GAMEDLL bool glTextureMaterial::load(const char* path, const char* tempDir) { Path::pushDir(); Path::cd(tempDir); FILE *f; if (!(f = fopen(path, "rb"))) return 0; bool ret = 1; fileChunk chunk; while (!feof(f)) { fread(&chunk, sizeof(chunk), 1, f); switch (chunk.type) { case fileChunk::type_image: { char* data = new char[chunk]; FILE* ff = fopen("tmp.png", "wb"); if (ff == NULL) { ret = 0; break; } fread(data, chunk, 1, f); fwrite(data, chunk, 1, ff); fclose(ff); delete[] data; if (chunk.subtype == fileChunk::subtype_diffuse) ret &= diffuse.loadPng("tmp.png"); else if (chunk.subtype == fileChunk::subtype_normal) ret &= normal.loadPng("tmp.png"); break; } case fileChunk::type_scale_vector: { fread(&scale, sizeof(scale), 1, f); break; } } } remove("tmp.png"); Path::popDir(); return ret; } GAMEDLL glTextureMaterial& glTextureMaterial::makeDefault(const int size) { Image img; img.make(size, size, 32); int n = size*size * 4; Core2D::clearImage(img, Color(255)); diffuse.make(img); Core2D::clearImage(img, core::Color(128, 128, 255, 255)); normal.make(img); return *this; } } <file_sep>/core-game/glShader/glComputeShader.cpp #include <core> #include <core-forms> #include <core-game> namespace core { GAMEDLL glComputeShader& glComputeShader::dispose() { if (glExt::isProgram(program)) glExt::deleteObject(program); if (glExt::isShader(shader)) glExt::deleteObject(shader); program = shader = 0; return *this; } GAMEDLL bool glComputeShader::load(const char* path) { dispose(); glGetError(); char *v = NULL; if (!Path::fileToString(path, &v)) return 0; program = glExt::createProgramObject(); shader = glExt::createShaderObject(GL_COMPUTE_SHADER); glExt::shaderSource(shader, 1, const_cast<const char**>(&v), NULL); glExt::compileShader(shader); glExt::attachObject(program, shader); glExt::linkProgram(program); delete[] v; return glGetError() == 0; } GAMEDLL glComputeShader& glComputeShader::printDebugInfo() { char c[256]; int l; glExt::getShaderInfoLog(shader, 256, &l, c); Debug::log("Compute Shader Log:\n%s\n", c); return *this; } } <file_sep>/core-game/gameMesh/gameMesh.h #pragma once namespace core { class GameMesh { public: buffer<vec3> position; buffer<vec3> normal; buffer<vec2> texcoord; buffer<int> indices; GAMEDLL void computeNormals(); GAMEDLL void computeTangentSpace(buffer<vec3>& tangents, buffer<vec3>& bitangents); }; } <file_sep>/core-game/glTexture/glTexture.cpp #include <core> #include <core-forms> #include <core-game> namespace core { GAMEDLL glTexture::~glTexture() { dispose(); } GAMEDLL void glTexture::dispose() { if (glIsTexture(t)) glDeleteTextures(1, &t); t = 0; } GAMEDLL bool glTexture::construct(Image& img) { vec2i size; int format; int bpp; bind(); glGetError(); //clear error glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &size.x); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &size.y); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &format); switch (format) { case GL_RED: bpp = 8; case GL_RGB: bpp = 24; case GL_RGBA: bpp = 32; default: bpp = 32; } img.make(size.x, size.y, bpp); glGetTexImage(GL_TEXTURE_2D, 0, format, GL_UNSIGNED_BYTE, img.data); unbind(); return glGetError()==0; } GAMEDLL bool glTexture::make(const Image& img) { if (img.width == 0 || img.height == 0) return 0; dispose(); glBindTexture(GL_TEXTURE_2D, 0); glGenTextures(1, &t); glBindTexture(GL_TEXTURE_2D, t); if (!glIsTexture(t)) return 0; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); int format; int internalFormat; switch (img.bits) { case 8: format = GL_R; internalFormat = GL_R; break; case 24: format = GL_RGB; internalFormat = GL_RGB; break; case 32: format = GL_RGBA; internalFormat = GL_RGBA; break; default: format = GL_RGBA; internalFormat = GL_RGBA; break; } glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, img.width, img.height, 0, format, GL_UNSIGNED_BYTE, img.data); return 1; } GAMEDLL bool glTexture::loadPng(char* path) { Image img; if (!img.loadPng(path)) return 0; return make(img); } GAMEDLL void glTexture::genMipmaps() { bind(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glExt::generateMipmap(GL_TEXTURE_2D); unbind(); } } <file_sep>/core-game/glControl/glFrameImageButton.h #pragma once namespace core { class glFrameImageButton: public glImageButton { protected: glAnimatedFrame* frame; public: glFrameImageButton() :glImageButton(), frame(NULL) {} GAMEDLL virtual int onPaint(const eventInfo& e) override; virtual glFrameImageButton& setFrame(glAnimatedFrame* f) { frame = f; return *this; } }; }<file_sep>/core-game/glShader/glShader.h #pragma once namespace core { class glShader { protected: GLuint vertex; GLuint fragment; GLuint program; public: glShader() : vertex(0), fragment(0), program(0) {} glShader(const char* vp, const char* fp, const char* fragName) : vertex(0), fragment(0), program(0) { load(vp, fp, fragName); } ~glShader() { dispose(); } GAMEDLL glShader& dispose(); GAMEDLL bool load(const char* vertexPath, const char* fragmentPath, const char* fragName); inline glShader& start() { glExt::useProgram(program); return *this; } inline glShader& stop() { glExt::useProgram(0); return *this; } inline operator const GLint() const { return program; } inline operator const GLuint() const { return program; } GAMEDLL glShader& printDebugInfo(); }; class glComputeShader { protected: GLuint shader; GLuint program; public: glComputeShader() : program(0) {} glComputeShader(const char* path) : program(0) { load(path); } ~glComputeShader() { dispose(); } GAMEDLL glComputeShader& dispose(); GAMEDLL bool load(const char* path); inline operator GLint() { return program; } GAMEDLL glComputeShader& printDebugInfo(); inline glComputeShader& start() { glExt::useProgramObject(program); return *this; } inline glComputeShader& stop() { glExt::useProgramObject(0); return *this; } }; } <file_sep>/core-game/glControl/glImageButton.cpp #include <core> #include <core-forms> #include <core-game> namespace core { GAMEDLL float glImageButton::tex[8] = {0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f}; GAMEDLL ImageButton& glImageButton::make(const vec4i& r, Image* img, Form& f) { ImageButton::make(r, img, f); move(r); return *this; } GAMEDLL ImageButton& glImageButton::make(const vec4i& r, Image* img, Form& f, buttonFunc func) { ImageButton::make(r, img, f, func); move(r); return *this; } GAMEDLL ImageButton& glImageButton::prerender() { prerendered = true; def.make(rect.z - rect.x, rect.w - rect.y, 32); hov.make(rect.z - rect.x, rect.w - rect.y, 32); act.make(rect.z - rect.x, rect.w - rect.y, 32); Core2D::clearImage(def, backColor); Core2D::blendImage(Rect(0, 0, (int)def.width, (int)def.height), *ref, def); Core2D::clearImage(hov, backColorHover); Core2D::blendImage(Rect(0, 0, (int)hov.width, (int)hov.height), *refHov, hov); Core2D::clearImage(act, backColorActivated); Core2D::blendImage(Rect(0, 0, (int)act.width, (int)act.height), *refHov, act); glDef.make(def); glAct.make(act); glHov.make(hov); return *this; } GAMEDLL ButtonObject& glImageButton::move(const vec4i& r) { ButtonObject::move(r); pos[0] = (float)r.x; pos[1] = (float)r.y; pos[2] = (float)r.z; pos[3] = (float)r.y; pos[4] = (float)r.z; pos[5] = (float)r.w; pos[6] = (float)r.x; pos[7] = (float)r.w; return *this; } GAMEDLL int glImageButton::onPaint(const eventInfo& e) { if (ref == NULL) return 1; if (!prerendered) prerender(); glBindTexture(GL_TEXTURE_2D, (flags & 4) ? glAct : ((flags & 2 || pinned()) ? glHov : glDef)); glVertexPointer(2, GL_FLOAT, 0, pos); glTexCoordPointer(2, GL_FLOAT, 0, tex); glDrawArrays(GL_QUADS, 0, 4); glBindTexture(GL_TEXTURE_2D, 0); return 0; } }<file_sep>/core-game/glFrame/glFrame.h #pragma once namespace core { class glFrame : public Control { protected: bool visible; buffer<Control*> items; Form* form; public: glFrame():Control(), visible(true), items(), form(NULL) {} virtual ~glFrame() {} inline glFrame& make(Form* f) { form = f; return *this; } inline void invalidate() { __invalidate(); if (form)form->invalidate(); } GAMEDLL virtual int onMouseMove(const eventInfo& e); GAMEDLL virtual int onRightButtonDown(const eventInfo& e); GAMEDLL virtual int onRightButtonUp(const eventInfo& e); GAMEDLL virtual int onPaint(const eventInfo& e); GAMEDLL virtual int onLButtonDown(const eventInfo& e); GAMEDLL virtual int onLButtonUp(const eventInfo& e); GAMEDLL virtual int onResize(const eventInfo& e); GAMEDLL virtual int onLButtonDblClk(const eventInfo& e); virtual int show() { visible = 1; __invalidate(); return 0; } virtual int hide() { __unhover(); visible = 0; __invalidate(); return 0; } virtual void push(Control& c) { items.push_back(&c); if (form)form->setControlColors(c); } GAMEDLL virtual Rect nextHorizontal(); GAMEDLL virtual Rect nextVertical(); GAMEDLL virtual glFrame& wrap(); }; } <file_sep>/core-game/glFrame/glAnimatedFrame.cpp #include <core> #include <core-forms> #include <core-game> namespace core { GAMEDLL int glAnimatedFrame::onPaint(const eventInfo& e) { if (!visible && timer.stop().ms()>fadeInterval) return 0; float t = std::min(1.0f, timer.stop().ms() / fadeInterval); if (!visible) t = 1.0f - t; glColor4f(1.0f, 1.0f, 1.0f, t); bool v = visible; visible = true; glFrame::onPaint(e); visible = v; glColor4f(1.0f, 1.0f, 1.0f, 1.0f); if (t < 1.0f) invalidate(); return 0; } }<file_sep>/core-game/main/core-game.h #pragma once #ifdef __WIN #if defined GAME_DLL_EXPORT #define GAMEDLL __declspec(dllexport) #else #define GAMEDLL __declspec(dllimport) #endif #else #define GAMEDLL #endif using namespace core::opengl; #include <view/view.h> #include <glExt/glExtensions.h> #include <glShader/glShader.h> #include <gameMesh/gameMesh.h> #include <gameMesh/glGameMesh.h> #include <view/glview.h> #include <glTexture/glTexture.h> #include <glTextureMaterial/glTextureMaterial.h> #include <frustum/frustum.h> #include <glFramebuffer/glFramebuffer.h> //controls #include <glControl/glImageButton.h> #include <glFrame/glFrame.h> #include <glFrame/glAnimatedFrame.h> #include <glControl/glFrameImageButton.h> //speleo #include <speleoMesh/glSpeleoMesh.h> #include <speleoMesh/glSpeleoModel.h><file_sep>/core-game/view/glview.cpp #include <core> #include <core-forms> #include <core-game> namespace core { GAMEDLL glView& glView::sendTo(glShader& shader, const char* modelviewName, const char* projectionName) { int l[2]; l[0] = glExt::getUniformLocation(shader, modelviewName); l[1] = glExt::getUniformLocation(shader, projectionName); glExt::uniformMatrix4fv(l[0], 1, false, modelview); glExt::uniformMatrix4fv(l[1], 1, false, projection); return *this; } GAMEDLL glView& glView::sendTo(glShader& shader, const uint& modelviewName, const uint& projectionName) { glExt::uniformMatrix4fv(modelviewName, 1, false, modelview); glExt::uniformMatrix4fv(projectionName, 1, false, projection); return *this; } } <file_sep>/core-game/glTextureMaterial/glTextureMaterial.h #pragma once namespace core { class glTextureMaterial { protected: public: glTexture diffuse; glTexture normal; vec2 scale; struct fileChunk { GAMEDLL static const int type_image; GAMEDLL static const int subtype_diffuse; GAMEDLL static const int subtype_normal; GAMEDLL static const int type_scale_vector; int type; // 1-image int subtype; //1-map, 2-normal map int bytes; operator int() { return bytes; } }; glTextureMaterial(): diffuse(), normal(), scale(1.0f, 1.0f){} ~glTextureMaterial(){ dispose(); } GAMEDLL bool save(const char* path, const char* tempDir); GAMEDLL bool load(const char* path, const char* tempDir); inline void genMipmaps() { diffuse.genMipmaps(); normal.genMipmaps(); } inline void dispose() { diffuse.dispose(); normal.dispose(); scale = vec2(1.0f, 1.0f); } GAMEDLL glTextureMaterial& makeDefault(const int size); }; }<file_sep>/core-game/glExt/glExtensions.cpp #include <core> #include <core-forms> #include <core-game> #ifndef __WIN #include <GL/glx.h> #endif namespace core { namespace opengl { GAMEDLL buffer<int> glExt::error; GAMEDLL int glExt::errCounter; GAMEDLL int glExt::version = 0; //buffers GAMEDLL void (APIENTRY* glExt::bindBuffer) (GLenum target, GLuint buffer); GAMEDLL void (APIENTRY* glExt::bufferData) (GLenum target, GLsizeiptrARB size, const GLvoid* data, GLenum usage); GAMEDLL void (APIENTRY* glExt::bufferSubData) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid* data); GAMEDLL void (APIENTRY* glExt::deleteBuffers) (GLsizei n, const GLuint* buffers); GAMEDLL void (APIENTRY* glExt::genBuffers) (GLsizei n, GLuint* buffers); GAMEDLL void (APIENTRY* glExt::getBufferParameteriv) (GLenum target, GLenum pname, GLint* params); GAMEDLL void (APIENTRY* glExt::getBufferPointerv) (GLenum target, GLenum pname, GLvoid** params); GAMEDLL void (APIENTRY* glExt::getBufferSubData) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid* data); GAMEDLL GLboolean(APIENTRY* glExt::isBuffer) (GLuint buffer); GAMEDLL GLvoid* (APIENTRY* glExt::mapBuffer) (GLenum target, GLenum access); GAMEDLL GLvoid* (APIENTRY* glExt::mapBufferRange) (GLenum target, GLintptrARB offset, GLsizeiptrARB length, GLenum access); GAMEDLL GLboolean(APIENTRY* glExt::unmapBuffer) (GLenum target); GAMEDLL void (APIENTRY* glExt::bufferStorage) (GLenum, GLsizeiptrARB, const GLvoid*, GLbitfield); GAMEDLL void (APIENTRY* glExt::bindBufferBase) (GLenum target, GLuint index, GLuint buffer); //arrays GAMEDLL void (APIENTRY* glExt::genVertexArrays) (GLsizei n, GLuint *arrays); GAMEDLL void (APIENTRY* glExt::bindVertexArray) (GLuint array); GAMEDLL void (APIENTRY* glExt::deleteVertexArrays) (GLsizei n, GLuint *arrays); GAMEDLL void (APIENTRY* glExt::enableVertexAttribArray) (GLuint index); GAMEDLL void (APIENTRY* glExt::vertexAttribPointer) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* pointer); GAMEDLL GLboolean (APIENTRY* glExt::isVertexArray) (GLuint array); //framebuffers GAMEDLL void (APIENTRY* glExt::genFramebuffers) (GLsizei n, GLuint *framebuffers); GAMEDLL void (APIENTRY* glExt::deleteFramebuffers) (GLsizei n, const GLuint *framebuffers); GAMEDLL void (APIENTRY* glExt::bindFramebuffer) (GLenum target, GLuint framebuffer); GAMEDLL void (APIENTRY* glExt::framebufferTexture2D) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); GAMEDLL void (APIENTRY* glExt::genRenderBuffers) (GLsizei n, GLuint *buffer); GAMEDLL void (APIENTRY* glExt::deleteRenderBuffers) (GLsizei n, const GLuint *buffer); GAMEDLL void (APIENTRY* glExt::bindRenderBuffer) (GLenum target, const GLuint buffer); GAMEDLL void (APIENTRY* glExt::framebufferRenderbuffer) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); GAMEDLL void (APIENTRY* glExt::renderbufferStorage) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); GAMEDLL GLenum(APIENTRY* glExt::checkFramebufferStatus) (GLenum target); GAMEDLL void (APIENTRY* glExt::blitFramebuffer) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); GAMEDLL void (APIENTRY* glExt::drawBuffers) (GLsizei n, const GLenum *bufs); //misc GAMEDLL void (APIENTRY* glExt::memoryBarrier) (GLbitfield barriers); GAMEDLL void (APIENTRY* glExt::texStorage2D) (GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height); GAMEDLL void (APIENTRY* glExt::generateMipmap) (GLuint target); //shaders GAMEDLL GLint(APIENTRY* glExt::deleteObject) (GLenum object); GAMEDLL void (APIENTRY* glExt::shaderSource) (GLuint shader, GLenum number_strings, const char **strings, GLint *length); GAMEDLL void (APIENTRY* glExt::compileShader) (GLenum shader); GAMEDLL void (APIENTRY* glExt::attachObject) (GLenum program, GLenum shader); GAMEDLL void (APIENTRY* glExt::linkProgram) (GLenum program); GAMEDLL void (APIENTRY* glExt::useProgramObject) (GLhandleARB object); GAMEDLL void (APIENTRY* glExt::useProgram) (GLuint program); GAMEDLL glExt::GLhandleARB(APIENTRY* glExt::createProgramObject) (); GAMEDLL glExt::GLhandleARB(APIENTRY* glExt::createShaderObject) (GLenum shaderType); GAMEDLL void (APIENTRY* glExt::activeTexture) (GLenum texture); GAMEDLL GLint(APIENTRY* glExt::getUniformLocation) (GLhandleARB program, const GLcharARB *name); GAMEDLL GLint(APIENTRY* glExt::getAttribLocation) (GLhandleARB program, const GLcharARB *name); GAMEDLL void (APIENTRY* glExt::getShaderInfoLog) (GLuint shader, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog); GAMEDLL void (APIENTRY* glExt::bindFragDataLocation) (GLuint program, GLuint colorNumber, const char *name); GAMEDLL void (APIENTRY* glExt::uniform1i) (GLint location, GLint v0); GAMEDLL void (APIENTRY* glExt::uniformMatrix4fv) (GLint location, GLsizei count, bool transpose, const GLfloat *value); GAMEDLL void (APIENTRY* glExt::uniformMatrix4dv) (GLint location, GLsizei count, bool transpose, const GLdouble *value); GAMEDLL void (APIENTRY* glExt::uniform4fv) (GLint location, int count, GLfloat *v0); GAMEDLL void (APIENTRY* glExt::uniformMatrix3fv) (GLint location, GLsizei count, bool transpose, const GLfloat *value); GAMEDLL void (APIENTRY* glExt::uniform1f) (GLint location, GLfloat v0); GAMEDLL void (APIENTRY* glExt::uniform4iv) (GLint location, int count, GLint *v0); GAMEDLL void (APIENTRY* glExt::uniform3fv) (GLint location, int count, GLfloat *v0); GAMEDLL void (APIENTRY* glExt::uniform2fv) (GLint location, int count, GLfloat* v0); GAMEDLL GLboolean (APIENTRY* glExt::isProgram) (GLuint program); GAMEDLL GLboolean (APIENTRY* glExt::isShader) (GLuint shader); //compute GAMEDLL void (APIENTRY* glExt::dispatchCompute) (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z); GAMEDLL GLuint(APIENTRY* glExt::getProgramResourceIndex) (GLuint program, GLenum programInterface, const char* name); GAMEDLL void (APIENTRY* glExt::shaderStorageBlockBinding) (GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding); GAMEDLL void (APIENTRY* glExt::bindImageTexture) (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); GAMEDLL void* glExt::get(const char* name) { static char extName[256]; #ifdef __WIN void *f = wglGetProcAddress(name); #else void *f = (void (*))glXGetProcAddress((const byte*)name); #endif if (!f) { memset(extName, 0, sizeof(extName)); strcpy(extName, name); strcat(extName, "ARB"); #ifdef __WIN f = wglGetProcAddress(extName); #else f = (void (*))glXGetProcAddress((const byte*)extName); #endif } if (!f) { error.push_back(errCounter); core::Debug::log("error: %s\n", name); } ++errCounter; return f; } GAMEDLL void glExt::init() { error.clear(); errCounter = 0; //buffers 1.5 bindBuffer = (decltype(bindBuffer))get("glBindBuffer"); //1.5 bufferData = (decltype(bufferData))get("glBufferData"); //1.5 bufferSubData = (decltype(bufferSubData))get("glBufferSubData"); //1.5 deleteBuffers = (decltype(deleteBuffers))get("glDeleteBuffers"); //1.5 genBuffers = (decltype(genBuffers))get("glGenBuffers"); //1.5 getBufferParameteriv = (decltype(getBufferParameteriv))get("glGetBufferParameteriv"); //1.5 getBufferPointerv = (decltype(getBufferPointerv))get("glGetBufferPointerv"); //1.5 getBufferSubData = (decltype(getBufferSubData))get("glGetBufferSubData"); //1.5 isBuffer = (decltype(isBuffer))get("glIsBuffer"); //1.5 mapBuffer = (decltype(mapBuffer))get("glMapBuffer"); //1.5 unmapBuffer = (decltype(unmapBuffer))get("glUnmapBuffer"); //1.5 if (error.size() == 0) version = 150; //array 2.0 enableVertexAttribArray = (decltype(enableVertexAttribArray))get("glEnableVertexAttribArray"); //2.0 vertexAttribPointer = (decltype(vertexAttribPointer))get("glVertexAttribPointer"); //2.0 //FBO 2.0 drawBuffers = (decltype(drawBuffers))get("glDrawBuffers"); //2.0 //shaders 2.0 deleteObject = (decltype(deleteObject))get("glDeleteObject"); //2.0 shaderSource = (decltype(shaderSource))get("glShaderSource"); //2.0 compileShader = (decltype(compileShader))get("glCompileShader"); //2.0 attachObject = (decltype(attachObject))get("glAttachObject"); //2.0 linkProgram = (decltype(linkProgram))get("glLinkProgram"); //2.0 useProgramObject = (decltype(useProgramObject))get("glUseProgramObject"); //2.0 useProgram = (decltype(useProgram))get("glUseProgram"); //2.0 createProgramObject = (decltype(createProgramObject))get("glCreateProgram"); //2.0 createShaderObject = (decltype(createShaderObject))get("glCreateShader"); //2.0 getUniformLocation = (decltype(getUniformLocation))get("glGetUniformLocation"); //2.0 getAttribLocation = (decltype(getAttribLocation))get("glGetAttribLocation"); //2.0 getShaderInfoLog = (decltype(getShaderInfoLog))get("glGetShaderInfoLog"); //2.0 uniform1i = (decltype(uniform1i))get("glUniform1i"); //2.0 uniform1f = (decltype(uniform1f))get("glUniform1f"); //2.0 uniformMatrix4fv = (decltype(uniformMatrix4fv))get("glUniformMatrix4fv"); //2.0 uniform4fv = (decltype(uniform4fv))get("glUniform4fv"); //2.0 uniformMatrix3fv = (decltype(uniformMatrix3fv))get("glUniformMatrix3fv"); //2.0 uniform3fv = (decltype(uniform3fv))get("glUniform3fv"); //2.0 uniform2fv = (decltype(uniform2fv))get("glUniform2fv"); //2.0 uniform4iv = (decltype(uniform4iv))get("glUniform4iv"); //2.0 isProgram = (decltype(isProgram))get("glIsProgram"); //2.0 isShader = (decltype(isShader))get("glIsShader"); //2.0 activeTexture = (decltype(activeTexture))get("glActiveTexture"); //2.0 if (error.size() == 0) version = 200; //buffers 3.0 bindBufferBase = (decltype(bindBufferBase))get("glBindBufferBase"); //3.0 mapBufferRange = (decltype(mapBufferRange))get("glMapBufferRange"); //3.0 //arrays 3.0 genVertexArrays = (decltype(genVertexArrays))get("glGenVertexArrays"); //3.0 bindVertexArray = (decltype(bindVertexArray))get("glBindVertexArray"); //3.0 deleteVertexArrays = (decltype(deleteVertexArrays))get("glDeleteVertexArrays"); //3.0 isVertexArray = (decltype(isVertexArray))get("glIsVertexArray"); //3.0 //framebuffers 3.0 genFramebuffers = (decltype(genFramebuffers))get("glGenFramebuffersEXT"); //3.0 deleteFramebuffers = (decltype(deleteFramebuffers))get("glDeleteFramebuffersEXT"); //3.0 bindFramebuffer = (decltype(bindFramebuffer))get("glBindFramebufferEXT"); //3.0 genRenderBuffers = (decltype(genRenderBuffers))get("glGenRenderbuffersEXT"); //3.0 deleteRenderBuffers = (decltype(deleteRenderBuffers))get("glDeleteRenderbuffersEXT"); //3.0 bindRenderBuffer = (decltype(bindRenderBuffer))get("glBindRenderbufferEXT"); //3.0 framebufferRenderbuffer = (decltype(framebufferRenderbuffer))get("glFramebufferRenderbufferEXT"); //3.0 renderbufferStorage = (decltype(renderbufferStorage))get("glRenderbufferStorageEXT"); //3.0 checkFramebufferStatus = (decltype(checkFramebufferStatus))get("glCheckFramebufferStatusEXT"); //3.0 blitFramebuffer = (decltype(blitFramebuffer))get("glBlitFramebufferEXT"); //3.0 //misc 3.0 generateMipmap = (decltype(generateMipmap))get("glGenerateMipmap"); //3.0 //shaders 3.0 bindFragDataLocation = (decltype(bindFragDataLocation))get("glBindFragDataLocation"); //3.0 if (error.size() == 0) version = 300; //FBO 3.2 framebufferTexture2D = (decltype(framebufferTexture2D))get("glFramebufferTexture2DEXT"); //3.2 if (error.size() == 0) version = 320; //misc 4.2 memoryBarrier = (decltype(memoryBarrier))get("glMemoryBarrier"); //4.2 texStorage2D = (decltype(texStorage2D))get("glTexStorage2D"); //4.2 if (error.size() == 0) version = 420; //compute 4.3 dispatchCompute = (decltype(dispatchCompute))get("glDispatchCompute"); //4.3 getProgramResourceIndex = (decltype(getProgramResourceIndex))get("glGetProgramResourceIndex"); //4.3 shaderStorageBlockBinding = (decltype(shaderStorageBlockBinding))get("glShaderStorageBlockBinding"); //4.3 bindImageTexture = (decltype(bindImageTexture))get("glBindImageTexture"); //4.2 if (error.size() == 0) version = 430; //buffers 4.4 bufferStorage = (decltype(bufferStorage))get("glBufferStorage"); //4.4 uniformMatrix4dv = (decltype(uniformMatrix4dv))get("glUniformMatrix4dv"); //2.0 if (error.size() == 0) version = 440; } } }<file_sep>/core-game/glFramebuffer/glFramebuffer.h #pragma once namespace core { class glFramebuffer { private: GLuint name; GLuint rgb; GLuint depth; public: glFramebuffer() :name(0), rgb(0), depth(0) {} ~glFramebuffer() { dispose(); } inline operator const GLuint() const { return name; } inline const GLuint texture() const { return rgb; } GAMEDLL virtual void dispose(); GAMEDLL virtual bool build(const int w, const int h); GAMEDLL virtual void resize(const int w, const int h); inline void bind() { glExt::bindFramebuffer(GL_FRAMEBUFFER, name); } inline void unbind() { glExt::bindFramebuffer(GL_FRAMEBUFFER, 0); } GAMEDLL void drawToScreen(const int w, const int h) const; }; } <file_sep>/core-game/speleoMesh/glSpeleoMesh.h #pragma once namespace core { class glSpeleoMesh { public: GLuint buff[2]; GLuint vao; int ind; glSpeleoMesh() { memset(buff, 0, sizeof(buff)); ind = 0; vao = 0; } GAMEDLL ~glSpeleoMesh(); GAMEDLL void dispose(); GAMEDLL bool make(const TMesh& mesh, glShader& shader, const char* pos, const char* tex); GAMEDLL void drawTris(); GAMEDLL void drawQuads(); }; } <file_sep>/core-game/frustum/frustum.h #pragma once namespace core { class Frustum { public: vec4 p[6]; vec3 v[8]; GAMEDLL void get(const View& view, const core::Window& wnd); GAMEDLL const bool aabbIntersection(vec3 a, vec3 b) const; GAMEDLL const bool sphereIntersection(vec3 c, float r) const; }; } <file_sep>/core-game/speleoMesh/glSpeleoModel.cpp #include <core> #include <core-forms> #include <core-game> namespace core { GAMEDLL void glSpeleoModel::dispose() { mesh.clear(); albedo.clear(); normal.clear(); } GAMEDLL bool glSpeleoModel::make(const TModel& model, glShader& shader, const char* cpos, const char* ctex) { try { mesh.reserve(model.mesh.size()); albedo.reserve(model.albedo.size()); normal.reserve(model.normal.size()); mesh.count() = model.mesh.size(); albedo.count() = model.albedo.size(); normal.count() = model.normal.size(); for (size_t i = 0; i < model.mesh.size(); ++i) if (!mesh[i].make(model.mesh[i], shader, cpos, ctex)) throw core::exception("OpenGL buffer error\n"); for (size_t i = 0; i < model.albedo.size(); ++i) if (!albedo[i].make(model.albedo[i])) throw core::exception("OpenGL texture error\n"); for (size_t i = 0; i < model.normal.size(); ++i) if (!normal[i].make(model.normal[i])) throw core::exception("OpenGL texture error\n"); glExt::activeTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); glExt::bindVertexArray(0); glExt::bindBuffer(GL_ARRAY_BUFFER, 0); glExt::bindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } catch (std::exception& e) { Debug::error("%s\n", e.what()); return false; } return true; } GAMEDLL void glSpeleoModel::draw() { const size_t count = std::min(mesh.size(), std::min(albedo.size(), normal.size())); for (size_t i = 0; i < count; ++i) { glExt::activeTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, normal[i]); glExt::activeTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, albedo[i]); mesh[i].drawTris(); } glExt::bindVertexArray(0); glExt::bindBuffer(GL_ARRAY_BUFFER, 0); glExt::activeTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, 0); glExt::activeTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); } } <file_sep>/core-game/glExt/glExtensions.h #pragma once #include <glExt/glExtensions.defines.h> namespace core { namespace opengl { class glExt { private: GAMEDLL static int errCounter; GAMEDLL static int version; GAMEDLL static void* get(const char* name); public: GAMEDLL static buffer<int> error; typedef int GLsizeiptrARB; typedef int GLintptrARB; typedef unsigned int GLhandleARB; typedef char GLcharARB; static const int supportedVersion() { return version; } GAMEDLL static void init(); //buffers GAMEDLL static void (APIENTRY* bindBuffer) (GLenum target, GLuint buffer); GAMEDLL static void (APIENTRY* bufferData) (GLenum target, GLsizeiptrARB size, const GLvoid* data, GLenum usage); GAMEDLL static void (APIENTRY* bufferSubData) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid* data); GAMEDLL static void (APIENTRY* deleteBuffers) (GLsizei n, const GLuint* buffers); GAMEDLL static void (APIENTRY* genBuffers) (GLsizei n, GLuint* buffers); GAMEDLL static void (APIENTRY* getBufferParameteriv) (GLenum target, GLenum pname, GLint* params); GAMEDLL static void (APIENTRY* getBufferPointerv) (GLenum target, GLenum pname, GLvoid** params); GAMEDLL static void (APIENTRY* getBufferSubData) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid* data); GAMEDLL static GLboolean(APIENTRY* isBuffer) (GLuint buffer); GAMEDLL static GLvoid* (APIENTRY* mapBuffer) (GLenum target, GLenum access); GAMEDLL static GLvoid* (APIENTRY* mapBufferRange) (GLenum target, GLintptrARB offset, GLsizeiptrARB length, GLenum access); GAMEDLL static GLboolean(APIENTRY* unmapBuffer) (GLenum target); GAMEDLL static void (APIENTRY* bufferStorage) (GLenum, GLsizeiptrARB, const GLvoid*, GLbitfield); GAMEDLL static void (APIENTRY* bindBufferBase) (GLenum target, GLuint index, GLuint buffer); //arrays GAMEDLL static void (APIENTRY* genVertexArrays) (GLsizei n, GLuint *arrays); GAMEDLL static void (APIENTRY* bindVertexArray) (GLuint array); GAMEDLL static void (APIENTRY* deleteVertexArrays) (GLsizei n, GLuint *arrays); GAMEDLL static void (APIENTRY* enableVertexAttribArray) (GLuint index); GAMEDLL static void (APIENTRY* vertexAttribPointer) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* pointer); GAMEDLL static GLboolean(APIENTRY* isVertexArray) (GLuint array); //framebuffers GAMEDLL static void (APIENTRY* genFramebuffers) (GLsizei n, GLuint *framebuffers); GAMEDLL static void (APIENTRY* deleteFramebuffers) (GLsizei n, const GLuint *framebuffers); GAMEDLL static void (APIENTRY* bindFramebuffer) (GLenum target, GLuint framebuffer); GAMEDLL static void (APIENTRY* framebufferTexture2D) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); GAMEDLL static void (APIENTRY* genRenderBuffers) (GLsizei n, GLuint *buffer); GAMEDLL static void (APIENTRY* deleteRenderBuffers) (GLsizei n, const GLuint *buffer); GAMEDLL static void (APIENTRY* bindRenderBuffer) (GLenum target, const GLuint buffer); GAMEDLL static void (APIENTRY* framebufferRenderbuffer) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); GAMEDLL static void (APIENTRY* renderbufferStorage) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); GAMEDLL static GLenum(APIENTRY* checkFramebufferStatus) (GLenum target); GAMEDLL static void (APIENTRY* blitFramebuffer) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); GAMEDLL static void (APIENTRY* drawBuffers) (GLsizei n, const GLenum *bufs); //misc GAMEDLL static void (APIENTRY* memoryBarrier) (GLbitfield barriers); GAMEDLL static void (APIENTRY* texStorage2D) (GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height); GAMEDLL static void (APIENTRY* generateMipmap) (GLuint target); //shaders GAMEDLL static GLint(APIENTRY* deleteObject) (GLenum object); GAMEDLL static void (APIENTRY* shaderSource) (GLuint shader, GLenum number_strings, const char **strings, GLint *length); GAMEDLL static void (APIENTRY* compileShader) (GLenum shader); GAMEDLL static void (APIENTRY* attachObject) (GLenum program, GLenum shader); GAMEDLL static void (APIENTRY* linkProgram) (GLenum program); GAMEDLL static void (APIENTRY* useProgramObject) (GLhandleARB object); GAMEDLL static void (APIENTRY* useProgram) (GLuint program); GAMEDLL static GLhandleARB(APIENTRY* createProgramObject) (); GAMEDLL static GLhandleARB(APIENTRY* createShaderObject) (GLenum shaderType); GAMEDLL static void (APIENTRY* activeTexture) (GLenum texture); GAMEDLL static GLint (APIENTRY* getUniformLocation) (GLhandleARB program, const GLcharARB *name); GAMEDLL static GLint (APIENTRY* getAttribLocation) (GLhandleARB program, const GLcharARB *name); GAMEDLL static void (APIENTRY* getShaderInfoLog) (GLuint shader, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog); GAMEDLL static void (APIENTRY* bindFragDataLocation) (GLuint program, GLuint colorNumber, const char *name); GAMEDLL static void (APIENTRY* uniform1i) (GLint location, GLint v0); GAMEDLL static void (APIENTRY* uniformMatrix4fv) (GLint location, GLsizei count, bool transpose, const GLfloat *value); GAMEDLL static void (APIENTRY* uniformMatrix4dv) (GLint location, GLsizei count, bool transpose, const GLdouble *value); GAMEDLL static void (APIENTRY* uniform4fv) (GLint location, int count, GLfloat *v0); GAMEDLL static void (APIENTRY* uniformMatrix3fv) (GLint location, GLsizei count, bool transpose, const GLfloat *value); GAMEDLL static void (APIENTRY* uniform1f) (GLint location, GLfloat v0); GAMEDLL static void (APIENTRY* uniform4iv) (GLint location, int count, GLint *v0); GAMEDLL static void (APIENTRY* uniform3fv) (GLint location, int count, GLfloat *v0); GAMEDLL static void (APIENTRY* uniform2fv) (GLint location, int count, GLfloat* v0); GAMEDLL static GLboolean (APIENTRY* isProgram) (GLuint program); GAMEDLL static GLboolean (APIENTRY* isShader) (GLuint shader); //compute GAMEDLL static void (APIENTRY* dispatchCompute) (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z); GAMEDLL static GLuint(APIENTRY* getProgramResourceIndex) (GLuint program, GLenum programInterface, const char* name); GAMEDLL static void (APIENTRY* shaderStorageBlockBinding) (GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding); GAMEDLL static void (APIENTRY* bindImageTexture) (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); }; } }<file_sep>/core-game/gameMesh/glGameMesh.cpp #include <core> #include <core-forms> #include <core-game> namespace core { GAMEDLL void glGameMesh::dispose() { if (glExt::isBuffer(buff[0])) glExt::deleteBuffers(6, buff); if (glExt::isVertexArray(vao)) glExt::deleteVertexArrays(1, &vao); memset(buff, 0, sizeof(buff)); ind = 0; } GAMEDLL glGameMesh::~glGameMesh() { dispose(); } GAMEDLL bool glGameMesh::make(GameMesh& mesh, glShader& shader, const char* pos, const char* nor, const char* tex) { if (mesh.position.count() < 1 || mesh.indices.count() < 0) return 0; ind = mesh.indices.count(); int index; vao = 0; glExt::genVertexArrays(1, &vao); glExt::genBuffers(6, buff); glExt::bindVertexArray(vao); glExt::bindBuffer(GL_ARRAY_BUFFER, buff[0]); glExt::bufferData(GL_ARRAY_BUFFER, mesh.position.count() * sizeof(vec3), mesh.position, GL_STATIC_DRAW); index = glExt::getAttribLocation(shader, pos); glExt::enableVertexAttribArray(index); glExt::vertexAttribPointer(index, 3, GL_FLOAT, false, 0, 0); glExt::bindBuffer(GL_ARRAY_BUFFER, buff[1]); glExt::bufferData(GL_ARRAY_BUFFER, mesh.normal.count() * sizeof(vec3), mesh.normal, GL_STATIC_DRAW); index = glExt::getAttribLocation(shader, nor); glExt::enableVertexAttribArray(index); glExt::vertexAttribPointer(index, 3, GL_FLOAT, false, 0, 0); glExt::bindBuffer(GL_ARRAY_BUFFER, buff[2]); glExt::bufferData(GL_ARRAY_BUFFER, mesh.texcoord.count() * sizeof(vec2), mesh.texcoord, GL_STATIC_DRAW); index = glExt::getAttribLocation(shader, tex); glExt::enableVertexAttribArray(index); glExt::vertexAttribPointer(index, 2, GL_FLOAT, false, 0, 0); glExt::bindBuffer(GL_ELEMENT_ARRAY_BUFFER, buff[3]); glExt::bufferData(GL_ELEMENT_ARRAY_BUFFER, mesh.indices.count() * sizeof(int), mesh.indices, GL_STATIC_DRAW); glExt::bindVertexArray(0); return 1; } GAMEDLL bool glGameMesh::make(GameMesh& mesh, glShader& shader, const char* pos, const char* nor, const char* tan, const char* btan, const char* tex) { if (mesh.position.count() < 1 || mesh.indices.count() < 0) return 0; buffer<vec3> tangents; buffer<vec3> bitangents; mesh.computeTangentSpace(tangents, bitangents); ind = mesh.indices.count(); int index; vao = 0; glExt::genVertexArrays(1, &vao); glExt::genBuffers(6, buff); glExt::bindVertexArray(vao); glExt::bindBuffer(GL_ARRAY_BUFFER, buff[0]); glExt::bufferData(GL_ARRAY_BUFFER, mesh.position.count() * sizeof(vec3), mesh.position, GL_STATIC_DRAW); index = glExt::getAttribLocation(shader, pos); glExt::enableVertexAttribArray(index); glExt::vertexAttribPointer(index, 3, GL_FLOAT, false, 0, 0); glExt::bindBuffer(GL_ARRAY_BUFFER, buff[1]); glExt::bufferData(GL_ARRAY_BUFFER, mesh.normal.count() * sizeof(vec3), mesh.normal, GL_STATIC_DRAW); index = glExt::getAttribLocation(shader, nor); glExt::enableVertexAttribArray(index); glExt::vertexAttribPointer(index, 3, GL_FLOAT, false, 0, 0); glExt::bindBuffer(GL_ARRAY_BUFFER, buff[2]); glExt::bufferData(GL_ARRAY_BUFFER, tangents.count() * sizeof(vec3), tangents, GL_STATIC_DRAW); index = glExt::getAttribLocation(shader, tan); glExt::enableVertexAttribArray(index); glExt::vertexAttribPointer(index, 3, GL_FLOAT, false, 0, 0); glExt::bindBuffer(GL_ARRAY_BUFFER, buff[3]); glExt::bufferData(GL_ARRAY_BUFFER, bitangents.count() * sizeof(vec3), bitangents, GL_STATIC_DRAW); index = glExt::getAttribLocation(shader, btan); glExt::enableVertexAttribArray(index); glExt::vertexAttribPointer(index, 3, GL_FLOAT, false, 0, 0); glExt::bindBuffer(GL_ARRAY_BUFFER, buff[4]); glExt::bufferData(GL_ARRAY_BUFFER, mesh.texcoord.count() * sizeof(vec2), mesh.texcoord, GL_STATIC_DRAW); index = glExt::getAttribLocation(shader, tex); glExt::enableVertexAttribArray(index); glExt::vertexAttribPointer(index, 2, GL_FLOAT, false, 0, 0); glExt::bindBuffer(GL_ELEMENT_ARRAY_BUFFER, buff[5]); glExt::bufferData(GL_ELEMENT_ARRAY_BUFFER, mesh.indices.count() * sizeof(int), mesh.indices, GL_STATIC_DRAW); glExt::bindVertexArray(0); return 1; } GAMEDLL void glGameMesh::drawTris() { glExt::bindVertexArray(vao); glDrawElements(GL_TRIANGLES, ind, GL_UNSIGNED_INT, 0); } GAMEDLL void glGameMesh::drawQuads() { glExt::bindVertexArray(vao); glDrawElements(GL_QUADS, ind, GL_UNSIGNED_INT, 0); } } <file_sep>/core-game/speleoMesh/glSpeleoMesh.cpp #include <core> #include <core-forms> #include <core-game> namespace core { GAMEDLL void glSpeleoMesh::dispose() { glExt::bindVertexArray(0); glExt::bindBuffer(GL_ARRAY_BUFFER, 0); glExt::bindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); if (buff[0] && glExt::isBuffer(buff[0])) glExt::deleteBuffers(2, buff); if (vao && glExt::isVertexArray(vao)) glExt::deleteVertexArrays(1, &vao); memset(buff, 0, sizeof(buff)); vao = 0; ind = 0; } GAMEDLL glSpeleoMesh::~glSpeleoMesh() { dispose(); } GAMEDLL bool glSpeleoMesh::make(const TMesh& mesh, glShader& shader, const char* pos, const char* tex) { glGetError(); //clear current error if (mesh.position.size() < 1 || mesh.indices.size() < 1) return 0; ind = 0; int index; int err = 0; buffer<vec3> pbuf(mesh.indices.size()); for (auto& i : mesh.indices) pbuf.push_back(mesh.position[i]); vao = 0; try { glExt::genVertexArrays(1, &vao); err = glGetError(); if (err != 0) { dispose(); throw core::exception("glGenVertexArrays error"); } glExt::genBuffers(2, buff); err = glGetError(); if (err != 0) { dispose(); throw core::exception("glGenBuffers error"); } glExt::bindVertexArray(vao); glExt::bindBuffer(GL_ARRAY_BUFFER, buff[0]); glExt::bufferData(GL_ARRAY_BUFFER, pbuf.size() * sizeof(vec3), pbuf, GL_STATIC_DRAW); if (glGetError()) throw core::exception("Error creating position buffer"); index = glExt::getAttribLocation(shader, pos); glExt::enableVertexAttribArray(index); glExt::vertexAttribPointer(index, 3, GL_FLOAT, false, 0, 0); if (glGetError()) throw core::exception("Error indexing position buffer"); glExt::bindBuffer(GL_ARRAY_BUFFER, buff[1]); glExt::bufferData(GL_ARRAY_BUFFER, mesh.texcoord.size() * sizeof(vec2), mesh.texcoord, GL_STATIC_DRAW); if (glGetError()) throw core::exception("Error creating texcoord buffer"); index = glExt::getAttribLocation(shader, tex); glExt::enableVertexAttribArray(index); glExt::vertexAttribPointer(index, 2, GL_FLOAT, false, 0, 0); if (glGetError()) throw core::exception("Error indexing texcoord buffer"); glExt::bindVertexArray(0); glExt::bindBuffer(GL_ARRAY_BUFFER, 0); ind = mesh.indices.size(); } catch (std::exception& e) { core::Debug::log("%s\n", e.what()); dispose(); glExt::bindVertexArray(0); return false; } return true; } GAMEDLL void glSpeleoMesh::drawTris() { glExt::bindVertexArray(vao); glDrawArrays(GL_TRIANGLES, 0, ind); } GAMEDLL void glSpeleoMesh::drawQuads() { glExt::bindVertexArray(vao); glDrawArrays(GL_QUADS, 0, ind); } } <file_sep>/makefile PROJ = core-game OUT = libcore-game.so BIN = bin BUILD = build CC = g++ -std=gnu++11 -msse -msse2 -msse3 -msse4 -mavx -mstackrealign -pthread -Wl,--no-as-needed #WARN = -Wall -fpermissive -Wno-write-strings -Wno-unused-result -Wno-unknown-pragmas -Wno-format-security -Wno-parentheses WARN = -w DEFINE = -DDLL_EXPORT BIN = bin BUILD = build INCLUDE = -I"../core/core" -I"core-game/" -I"../core-forms/core-forms" -I"/usr/include" FLAGS = -O2 $(INCLUDE) $(WARN) $(DEFINE) -fPIC LIBS = -L"lib" -lfreetype -lcore -lpthread OBJ = \ frustum/frustum.o \ gameMesh/gameMesh.o \ gameMesh/glGameMesh.o \ glControl/glFrameImageButton.o \ glControl/glImageButton.o \ glExt/glExtensions.o \ glFrame/glAnimatedFrame.o \ glFrame/glFrame.o \ glFramebuffer/glFramebuffer.o \ glShader/glComputeShader.o \ glShader/glShader.o \ glTexture/glTexture.o \ glTextureMaterial/glTextureMaterial.o \ speleoMesh/glSpeleoMesh.o \ speleoMesh/glSpeleoModel.o \ view/glview.o \ view/view.o all: $(OBJ) $(CC) -shared $(BIN)/* -o $(BUILD)/$(OUT) $(LIBS) $(OBJ): %.o: $(PROJ)/%.cpp $(CC) -c $< -o $(BIN)/$(notdir $@) $(FLAGS) clean: rm -rf $(BUILD) rm -rf $(BIN) sudo rm -rf /usr/local/lib/$(OUT) init: mkdir $(BUILD) mkdir $(BIN) install: sudo cp $(BUILD)/$(OUT) /usr/local/lib/ <file_sep>/core-game/glControl/glFrameImageButton.cpp #include <core> #include <core-forms> #include <core-game> namespace core { GAMEDLL int glFrameImageButton::onPaint(const eventInfo& e) { if (ref == NULL) return 1; if (!prerendered) prerender(); glBindTexture(GL_TEXTURE_2D, (flags & 4) ? glAct : ((flags & 2 || pinned() || frame&&frame->isVisible()) ? glHov : glDef)); glVertexPointer(2, GL_FLOAT, 0, pos); glTexCoordPointer(2, GL_FLOAT, 0, tex); glDrawArrays(GL_QUADS, 0, 4); glBindTexture(GL_TEXTURE_2D, 0); return 0; } } <file_sep>/core-game/frustum/frustum.cpp #include <core> #include <core-forms> #include <core-game> namespace core { GAMEDLL void Frustum::get(const View& view, const core::Window& wnd) { v[0] = view.unprojectFull(vec4(0, 0, 0, 1), wnd); v[1] = view.unprojectFull(vec4((float)wnd.width, 0, 0, 1), wnd); v[2] = view.unprojectFull(vec4((float)wnd.width, (float)wnd.height, 0, 1), wnd); v[3] = view.unprojectFull(vec4(0, (float)wnd.height, 0, 1), wnd); v[4] = view.unprojectFull(vec4(0, 0, 1.0f, 1.0f), wnd); v[5] = view.unprojectFull(vec4((float)wnd.width, 0, 1.0f, 1.0f), wnd); v[6] = view.unprojectFull(vec4((float)wnd.width, (float)wnd.height, 1.0f, 1.0f), wnd); v[7] = view.unprojectFull(vec4(0, (float)wnd.height, 1.0f, 1.0f), wnd); p[0] = Math::plane(v[0], v[1], v[2]); p[1] = Math::plane(v[4], v[7], v[6]); p[2] = Math::plane(v[0], v[4], v[5]); p[3] = Math::plane(v[2], v[6], v[7]); p[4] = Math::plane(v[0], v[3], v[7]); p[5] = Math::plane(v[2], v[1], v[5]); } GAMEDLL const bool Frustum::aabbIntersection(vec3 a, vec3 b) const { vec3 v[8], n; v[0] = vec3(a.x, a.y, a.z); v[1] = vec3(b.x, a.y, a.z); v[2] = vec3(b.x, b.y, a.z); v[3] = vec3(a.x, b.y, a.z); v[4] = vec3(a.x, a.y, b.z); v[5] = vec3(b.x, a.y, b.z); v[6] = vec3(b.x, b.y, b.z); v[7] = vec3(a.x, b.y, b.z); for (int i = 0; i < 6; ++i) { int cnt = 8; //Distance = DotProduct(V, N) + D n = vec3(p[i].x, p[i].y, p[i].z); for (int j = 0; j < 8; ++j) { if (Math::dot(v[j], n) + p[i].w > 0.0f) --cnt; } if (cnt == 0)return 0; } return 1; } GAMEDLL const bool Frustum::sphereIntersection(vec3 c, float r) const { for (int i = 0; i < 6; ++i) { int cnt = 8; //Distance = DotProduct(V, N) + D vec3 n = vec3(p[i].x, p[i].y, p[i].z); if (Math::dot(c, n) + p[i].w > r) return 0; } return 1; } }<file_sep>/core-game/glFrame/glAnimatedFrame.h #pragma once namespace core { class glAnimatedFrame: public glFrame { public: Timer<float> timer; float fadeInterval; glAnimatedFrame() :glFrame(), fadeInterval(125.0f) {} virtual ~glAnimatedFrame() {} virtual int show() { if (!visible)timer.start(); return glFrame::show(); } virtual int hide() { if(visible)timer.start(); return glFrame::hide(); } GAMEDLL virtual int onPaint(const eventInfo& e); virtual bool isVisible() { return visible || (!visible&&timer.stop() < fadeInterval); } }; }
102a077c42b4cd6db63a7391ca8c6a913c76437a
[ "C", "Makefile", "C++" ]
36
C++
nad314/core-game
d1448457d9d2f6a3dc30efea367c2f4f467853bc
d9f770f1c6265aba36b34952e9a24a841a2ebae5
refs/heads/master
<repo_name>BridgeNB/Redux-Project-Readable<file_sep>/src/components/NewComment.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import { guid } from '../api/util'; import { addComment } from '../actions/commentActions' class NewComment extends Component { handleSubmit = (e) => { e.preventDefault() const postId = this.props.match.params.postId const commendBody = e.target.body.value const author = e.target.author.value const submitComment = { id: guid(), parentId: postId, timestamp: Date.now(), body: commendBody, author: author } this.props.addComment(submitComment, postId, () => this.props.history.push(`/posts/${postId}`)) } render() { return ( <form onSubmit={this.handleSubmit}> <ul className='comment-form'> <li> <label>Name <span className="required">*</span></label> <input type="text" name="author" className="field-long" /> </li> <li> <label>Comment <span className="required">*</span></label> <textarea name="body" id="field5" className="field-long field-textarea"></textarea> </li> <button>Submit</button> </ul> </form> ) } } function mapStateToProps(comment) { return { comment: comment } } export default connect(mapStateToProps, {addComment}) (NewComment); <file_sep>/src/components/SinglePost.js import React, { Component } from 'react' import { connect } from 'react-redux' import { Link } from 'react-router-dom' import { fetchCommentsForPost } from '../actions/commentActions' import { votePost, fetchAllPosts, deletePost } from '../actions/postActions' import { Button, Well } from 'react-bootstrap' class SinglePost extends Component { componentDidMount() { this.props.fetchCommentsForPost(this.props.post.id) } afterPostDelete = (postId) => { const id = this.props.post.id; this.props.deletePost(id, () => {}); } render() { let { post, votePost, fetchAllPosts } = this.props; return ( <div className="single-post"> <div className="single-post-detail"> <Link to={`/${post.category}/${post.id}`}> <div className="post-title"><h3>{ post.title }</h3></div> </Link> <div className="post-body"><Well bsSize="large">{ post.body }</Well></div> <div className="post-author">Author: <Button bsStyle="info">{ post.author }</Button></div> <div className="post-category">Category: <Button bsStyle="info">{ post.category }</Button></div> <div className="post-action-button"> <Link to={`/${post.category}/${post.id}/edit`}><Button>Edit</Button></Link> <Link to={`/${post.category}/${post.id}/comment`}><Button>Comment</Button></Link> <Button onClick={(e) => this.afterPostDelete(e)}>Delete</Button> </div> </div> <div className="single-post-bottom"> <div className="comments-summary"> <span>{ post.commentCount } <strong>Comments</strong></span> <span>{ post.voteScore } <strong>Votes</strong></span> </div> <div className="post-votes"> <Button onClick={() => { votePost(post.id, "upVote") fetchAllPosts() }}>Vote up</Button> <Button onClick={() => { votePost(post.id, "downVote") fetchAllPosts() }}>Vote down</Button> </div> </div> </div> ); } } function mapStateToProps({ comments }, { post }) { return { comments: comments[post.id] } } export default connect(mapStateToProps, {votePost, fetchAllPosts, fetchCommentsForPost, deletePost})(SinglePost) <file_sep>/src/reducers/comments.js import * as Types from '../actions/types' function comments(state = {}, action) { const { comments, commentId, postId, editedComment } = action switch(action.type) { case Types.ADD_COMMENT: return Object.assign({}, state, {[postId]: comments}) case Types.FETCH_COMMENTS: { let newState = { ...state } if (action.comments.length > 0) { const key = action.comments[0].parentId newState[key] = action.comments } else { newState[action.postId] = [] } return newState; } case Types.EDIT_COMMENT: return { ...state, [postId]: state[postId].map(comment => { if(comment.id === commentId) { comment = editedComment } return comment }) } case Types.VOTE_COMMENT: return { ...state, [postId]: state[postId].map(comment => { if(comment.id === commentId) { comment = editedComment } return comment }) } default: return state; } } export default comments <file_sep>/src/actions/commentActions.js import * as API from '../api/index'; import * as Types from './types'; export const fetchCommentsForPost = (postId) => { return (dispatch) => { API.fetchComment(postId).then(comments => { dispatch({type: Types.FETCH_COMMENTS, postId, comments}) }) } } export const addComment = (comment, postId, callback) => { return (dispatch) => { API.addComment(comment).then(() => callback()) dispatch({ type: Types.ADD_COMMENT, postId, comment}) } } export const deleteComment = (commentId, callback) => { return (dispatch) => { API.deleteComment(commentId).then(() => callback()) dispatch({ type: Types.DELETE_COMMENT, commentId}) } } export const editComment = (commentId, postId, timestamp, body, callback) => { return (dispatch) => { API.editComment(commentId, timestamp, body) .then(editedComment => { dispatch({ type: Types.EDIT_COMMENT, editedComment, commentId, postId }) }).then(() => callback()) } } export const voteComment = (commentId, postId, option) => { return (dispatch) => { API.voteComment(commentId, option).then((editedComment) => { dispatch({type: Types.VOTE_COMMENT, editedComment, commentId, postId}) }) } } <file_sep>/src/actions/postActions.js import * as API from '../api/index'; import * as Types from './types'; export const fetchAllPosts = () => { return (dispatch) => { API.fetchPosts().then(posts => { dispatch({ type: Types.FETCH_POSTS, posts }) }) } } export const addPost = (post, callback) => { return (dispatch) => { API.addPost(post).then(() => callback()) dispatch({ type: Types.ADD_POST, post}) } } export const deletePost = (postId, callback) => { return (dispatch) => { API.deletePost(postId).then(() => callback()) dispatch({ type: Types.DELETE_POST, postId}) } } export const editPost = (postId, title, body, callback) => { return (dispatch) => { API.editPost(postId, title, body).then(editedPost => { dispatch({ type: Types.EDIT_POST, editedPost, postId }) }).then(() => callback()) } } export const fetchPostsByCategory = (category) => { return (dispatch) => { API.fetchPostsByCategory(category).then(posts => { dispatch({ type: Types.FETCH_POSTS_BY_CATEGORY, posts}) }) } } export const votePost = (postId, option) => { return (dispatch) => { API.votePost(postId, option).then( post => { dispatch({ type: Types.VOTE_POST, postId, option}) }) } } export const sortPost = (option) => { return (dispatch) => { dispatch({ type: Types.SORT_POST, option}) } } <file_sep>/src/reducers/posts.js import * as Types from '../actions/types' import sortBy from "sort-by" function posts(state = [], action) { const { post, postId, editedPost, posts, option } = action switch(action.type) { case Types.FETCH_POSTS: return posts.filter(post => !(post.deleted)) case Types.ADD_POST: return state.concat([post]) case Types.DELETE_POST: return state.filter((post) => post.id !== postId) case Types.EDIT_POST: return state.map(post => { if (post.id === postId) { post = editedPost } return post }) case Types.FETCH_POSTS_BY_CATEGORY: return posts.filter(post => !(post.deleted)) case Types.VOTE_POST: return state.map(post => { if (post.id === action.postId) { if (action.option === "upVote") { post.voteScore += 1 } if (action.option === "downVote") { post.voteScore -= 1 } } return post }) case Types.SORT_POST: return [].concat(state.sort(sortBy(option)).reverse()) default: return state } } export default posts <file_sep>/src/components/App.js import React, {Component} from 'react'; import PropTypes from 'prop-types'; import { Grid, Button } from 'react-bootstrap'; import { Route, Switch, withRouter, Link} from 'react-router-dom'; import {connect} from 'react-redux'; import * as actions from '../actions/categoryActions'; import CategoryList from './CategoryList'; import NewPost from './NewPost'; import DetailedPost from './DetailedPost'; import EditPost from './EditPost'; import NewComment from './NewComment'; import EditComment from './EditComment'; import "../App.css"; class App extends Component { static propTypes = { categories: PropTypes.array, posts: PropTypes.array } componentDidMount() { this.props.fetchCategories() } render() { const {categories} = this.props return ( <div className="whole-app"> <div className="app-head"> <h1>Bridge's Forum</h1> </div> <div className="category-changer"> <h2>Choose Posts by Category</h2> <div className="category-list"> {categories && categories.map(category => { const { name, path } = category; return ( <Link key={name} to={`/${path}`}> <Button className="category-tag">{name.charAt(0).toUpperCase() + name.slice(1)}</Button> </Link> ) })} </div> </div> <div> <Grid> <Switch> <Route path="/" exact component={CategoryList}/> <Route path="/create" exact component={NewPost}/> <Route path="/:category" exact component={CategoryList}/> <Route path="/:category/:postId" exact component={DetailedPost}/> <Route path="/:category/:postId/edit" exact component={EditPost}/> <Route path="/:category/:postId/comment" exact component={NewComment}/> <Route path="/:category/:postId/:commentId/edit" exact component={EditComment}/> </Switch> </Grid> </div> </div> ); } } function mapStateToProps({categories}) { return {categories: categories} } export default withRouter(connect(mapStateToProps, actions)(App)); <file_sep>/src/actions/categoryActions.js import * as API from '../api/index' import * as Types from './types' export const fetchCategories = () => { return (dispatch) => { API.fetchCategories().then(res => { dispatch({ type: Types.FETCH_CATEGORIES, res}) }) } }
36dd27420eae80c8bf18c6f51c17d1e5e42cfe52
[ "JavaScript" ]
8
JavaScript
BridgeNB/Redux-Project-Readable
a06f964c91906b07922d2f1e1395758da2a547db
e5a53c7ac1175a358ea341fd413b4d32b6bab539
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Nobel { class Nobel { static void Main(string[] args) { //2. List<NobelDíj> nobelDíjak = new List<NobelDíj>(); foreach (var sor in File.ReadAllLines("nobel.csv").Skip(1)) { nobelDíjak.Add(new NobelDíj(sor)); } //Console.WriteLine($"Sorok száma: {nobelDíjak.Count}"); //3. var ABM = nobelDíjak.FirstOrDefault(x => x.TeljesNév == "<NAME>"); Console.WriteLine($"3. feladat: {ABM.Típus}"); //4. Console.WriteLine($"4. feladat: { nobelDíjak.First(x => x.Évszám == 2017 && x.Típus == NobelDíj.NobelDíjTípus.irodalmi).TeljesNév}"); //5. feladat: Feltétel: Szervezet, 1990-től, béke Console.WriteLine($"5. feladat: "); nobelDíjak .Where(x => x.Vezetéknév == "" && x.Évszám >= 1990 && x.Típus == NobelDíj.NobelDíjTípus.béke) .ToList() .ForEach(x => Console.WriteLine($"\t{x.Évszám}: {x.Keresztnév}")); //6. Console.WriteLine($"6. feladat: "); nobelDíjak.Where(x => x.Vezetéknév.Contains("Curie")).ToList() .ForEach(x => Console.WriteLine($"\t{x.Évszám}: {x.TeljesNév}({x.Típus})")); //7. Console.WriteLine($"7. feladat:"); nobelDíjak.GroupBy(x => x.Típus) .Select(gr => new { Típus = gr.Key, db = gr.Count() }).ToList() .ForEach(x => Console.WriteLine($"\t{x.Típus,-25}{x.db} db")); //8. Console.WriteLine($"8. feladat: orvosi.txt"); string filename = "orvosi.txt"; List<string> orvosi = new List<string>(); nobelDíjak.Where(x => x.Típus == NobelDíj.NobelDíjTípus.orvosi) .OrderBy(x => x.Évszám) .Select(x => x.Évszám + ":" + x.TeljesNév).ToList() .ForEach(x => orvosi.Add(x)); File.WriteAllLines(filename, orvosi); Console.ReadKey(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nobel { class NobelDíj { public enum NobelDíjTípus { fizikai, kémiai, orvosi, irodalmi, béke, közgazdaságtani } public int Évszám { get; set; } public NobelDíjTípus Típus { get; set; } public string Keresztnév { get; set; } public string Vezetéknév { get; set; } public string TeljesNév { get => Keresztnév + " " + Vezetéknév; } public NobelDíj(string sor) { string[] s = sor.Split(';'); Évszám = int.Parse(s[0]); Enum.TryParse(s[1], out NobelDíjTípus nt); Típus = nt; Keresztnév = s[2]; Vezetéknév = s[3]; } } }
5ad62ca1f5b9e5df90a345ea66c68358c80842cf
[ "C#" ]
2
C#
zeon77/Szf_prg_2018-10-02_Nobel-dijak
59ccdbe947a60a0b3816e4fdb5172ae050a423f2
578faef03cfd2a78b65c0d4c67204bed9bffe4ab
refs/heads/master
<file_sep># raytracing-learning ray tracingの勉強 https://raytracing.github.io<file_sep>#define STB_IMAGE_WRITE_IMPLEMENTATION #include <iostream> #include <random> #include "stb_image_write.h" #include "sphere.h" #include "hitable_list.h" #include "camera.h" struct Color { unsigned char r, g, b, a; Color() = default; Color(unsigned char _r, unsigned char _g, unsigned char _b, unsigned char _a) : r(_r), g(_g), b(_b), a(_a) {}; }; vec3 random_in_unit_sphere() { vec3 p; std::random_device seed_gen; std::mt19937 engine(seed_gen()); std::uniform_real_distribution<> dist(0, 1); do { p = 2.0f * vec3(dist(engine), dist(engine), dist(engine)) - vec3(1, 1, 1); } while (p.squared_length() >= 1); return p; } vec3 calc_color(const ray& r, hitable* world) { hit_record rec; if (world->hit(r, 0.0001f, FLT_MAX, rec)) { vec3 target = rec.p + rec.normal + random_in_unit_sphere(); return 0.5f * calc_color(ray(rec.p, target - rec.p), world); } else { vec3 unit_direction = unit_vector(r.direction()); float t = 0.5f * (unit_direction.y() + 1.0f); return (1.0f - t) * vec3(1.0f, 1.0f, 1.0f) + t * vec3(0.5f, 0.7f, 1.0f); } } int main() { const int width = 200; const int height = 100; const int ns = 100; // output buffer Color colors[height][width]; hitable* list[2]; list[0] = new sphere(vec3(0, 0, -1), 0.5f); list[1] = new sphere(vec3(0, -100.5f, -1), 100); hitable* world = new hitable_list(list, 2); camera cam; // random std::random_device seed_gen; std::mt19937 engine(seed_gen()); std::uniform_real_distribution<> dist(0, 1); for (int j = height - 1; j >= 0; j--) { for (int i = 0; i < width; i++) { vec3 col(0, 0, 0); for (int s = 0; s < ns; s++) { float u = float(i + dist(engine)) / float(width); float v = float(height - j + dist(engine)) / float(height); ray r = cam.get_ray(u, v); vec3 p = r.point_at_parameter(2.0f); col += calc_color(r, world); } col /= float(ns); col = vec3(sqrt(col[0]), sqrt(col[1]), sqrt(col[2])); int ir = int(255.99f * col.r()); int ig = int(255.99f * col.g()); int ib = int(255.99f * col.b()); //std::cout << ir << " " << ig << " " << ib << "\n"; colors[j][i] = Color(ir, ig, ib, 255); } } // output image stbi_write_png("output.png", width, height, sizeof(Color), colors, 0); }
f71a18c0a20b09401efe7ebccebaa537c5d8b587
[ "Markdown", "C++" ]
2
Markdown
butislime/raytracing-learning
75a76f6b74861a6b67ca68f7fc1e0d3c0929b249
c38a7ab2091eaf564e12d89ba218a7e0f1ba162c
refs/heads/master
<file_sep>class ApplicationController < ActionController::Base protect_from_forgery # def mapquest_api # directions = Typhoeus.get( # "http://www.mapquestapi.com/directions/v2/route?key=Fmjtd%7Cluubn90z29%2Cr0%3Do5-902wda&from=San+Diego,CA&to=Los+Angeles,CA" # ) # @results = JSON.parse(directions.body) # return @results # end def fiveoneone_api(origin, destination) url = "http://services.my511.org/traffic/getpathlist.aspx?token=<PASSWORD>?&o=#{origin}&d=#{destination}" @results = Nokogiri::XML(open(url)) return @results end end <file_sep>TrafficEstimatorApp::Application.routes.draw do root to: "home#index" get "/cities/:id", to: "cities#show" end <file_sep>class CitiesController < ApplicationController def show require 'nokogiri' require 'open-uri' @traveltimes = [] @origin = City.find(params[:id]) @cities = City.all @cities.each do |city| drive_time = fiveoneone_api(@origin.node, city.node) current_traffic = @results.xpath("/paths/path[1]/currentTravelTime").text normal_traffic = @results.xpath("/paths/path[1]/typicalTravelTime").text @traveltimes << [current_traffic, normal_traffic] end end end <file_sep># 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) City.create( name: "San Jose", node: 347 ) City.create( name: "San Francisco", node: 780 ) City.create( name: "Oakland", node: 1279 ) City.create( name: "Fremont", node: 44 ) City.create( name: "Santa Rosa", node: 274 ) City.create( name: "Hayward", node: 800 ) City.create( name: "Sunnyvale", node: 276 ) City.create( name: "Concord", node: 696 ) City.create( name: "Santa Clara", node: 366 ) City.create( name: "Vallejo", node: 712 ) City.create( name: "Berkeley", node: 1222 ) City.create( name: "Fairfield", node: 1200 ) City.create( name: "Richmond", node: 1230 ) City.create( name: "Antioch", node: 723 ) City.create( name: "Daly City", node: 88 )<file_sep>class HomeController < ApplicationController include HomeHelper def index ## FOR MAPQUEST # drive_time = mapquest_api # @current_condition = drive_time["route"]["realTime"]/60 # @normal_condition = drive_time["route"]["time"]/60 end def show end end <file_sep>module HomeHelper # def mapquest_api # directions = Typhoeus.get( # "http://www.mapquestapi.com/directions/v2/route?key=<KEY>&from=San+Diego,CA&to=Los+Angeles,CA" # ) # @results = JSON.parse(directions.body) # return @results # end # mapquest_api(origin, dest) end <file_sep>class City < ActiveRecord::Base attr_accessible :name, :node end
501b0bcc89981597c63353535355b209ab751b35
[ "Ruby" ]
7
Ruby
jeesong/baytrafficestimator
c6f2562e764a7b9ddf22ebb9818c22391eecb286
bc2819904ecbf8024c99d65273d5edc390ae6b09
refs/heads/master
<repo_name>umakusumuru/EmployeeEditView<file_sep>/README.md # EmployeeEditView Edit view for Employee <file_sep>/index.js /** * AngularJS * @author vinu <<EMAIL>> */ /** * Main App Creation */ <<<<<<< HEAD var editviewapp = angular.module('KaakateeyaEmpEdit', ['ui.router', 'ngAnimate', 'ngSanitize', 'ui.bootstrap', 'angular-loading-bar', 'ngAnimate', 'ngIdle', 'ngMaterial', 'ngMessages', 'ngAria', 'ngPassword', 'jcs-autoValidate', 'angularPromiseButtons', 'KaakateeyaRegistration', 'oc.lazyLoad' ]); editviewapp.apipath = 'http://172.16.17.32:8025/Api/'; // editviewapp.apipath = 'http://172.16.17.32:8010/Api/'; editviewapp.env = 'dev'; ======= var regapp = angular.module('KaakateeyaEmpReg', ['ui.router', 'ngAnimate', 'ngSanitize', 'ui.bootstrap', 'angular-loading-bar', 'ngAnimate', 'ngIdle', 'ngMaterial', 'ngMessages', 'ngAria', 'ngPassword', 'jcs-autoValidate', 'angularPromiseButtons', 'KaakateeyaRegistration', 'oc.lazyLoad' ]); regapp.apipath = 'http://172.16.17.32:8025/Api/'; // regapp.apipath = 'http://172.16.17.32:8010/Api/'; regapp.env = 'dev'; >>>>>>> d43c54e4e3d91d181712ba9e4a4e2f94ead83678 regapp.GlobalImgPath = 'http://d16o2fcjgzj2wp.cloudfront.net/'; regapp.GlobalImgPathforimage = 'https://s3.ap-south-1.amazonaws.com/kaakateeyaprod/'; regapp.prefixPath = 'Images/ProfilePics/'; regapp.S3PhotoPath = ''; regapp.Mnoimage = regapp.GlobalImgPath + "Images/customernoimages/Mnoimage.jpg"; regapp.Fnoimage = regapp.GlobalImgPath + "Images/customernoimages/Fnoimage.jpg"; regapp.accesspathdots = regapp.GlobalImgPathforimage + regapp.prefixPath; regapp.BucketName = 'kaakateeyaprod'; regapp.editName = 'edit/:custId/'; regapp.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', '$ocLazyLoadProvider', function($stateProvider, $urlRouterProvider, $locationProvider, $ocLazyLoadProvider) { var states = [ { name: 'reg', url: '', subname: [], abstract: true }, { name: 'reg.basicRegistration', url: '/Education', subname: ['common/directives/datePickerDirective.js'] }, { name: 'reg.secondaryRegistration', url: '/secondaryRegistrationurl', subname: ['common/directives/datePickerDirective.js'] } ]; $ocLazyLoadProvider.config({ debug: true }); $urlRouterProvider.otherwise('/Education'); _.each(states, function(item) { var innerView = {}; var regitem = item.name.slice(4); innerView = { "topbar@": { templateUrl: "templates/topheader.html" }, "lazyLoadView@": { templateUrl: 'app/' + regitem + '/index.html', controller: regitem + 'Ctrl as page' }, "bottompanel@": { templateUrl: "templates/footer.html" } }; $stateProvider.state(item.name, { url: item.url, <<<<<<< HEAD views: innerView // resolve: { // Any property in resolve should return a promise and is executed before the view is loaded // loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) { // // you can lazy load files for an existing module // var edit = item.name.slice(9); // if (editviewapp.env === 'dev') { // return $ocLazyLoad.load(['app/' + edit + '/controller/' + edit + 'ctrl.js', 'app/' + edit + '/model/' + edit + 'Mdl.js', 'app/' + edit + '/service/' + edit + 'service.js', item.subname]); // } else { // return $ocLazyLoad.load(['app/' + edit + '/src/script.min.js', item.subname]); // } ======= views: innerView, resolve: { // Any property in resolve should return a promise and is executed before the view is loaded loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) { // you can lazy load files for an existing module // var edit = item.name.slice(9); if (regapp.env === 'dev') { return $ocLazyLoad.load(['app/' + regitem + '/controller/' + regitem + 'ctrl.js', 'app/' + regitem + '/model/' + regitem + 'Mdl.js', 'app/' + regitem + '/service/' + regitem + 'service.js', item.subname]); } else { return $ocLazyLoad.load(['app/' + regitem + '/src/script.min.js', item.subname]); } >>>>>>> d43c54e4e3d91d181712ba9e4a4e2f94ead83678 // // return $ocLazyLoad.load(['app/' + edit + '/controller/' + edit + 'ctrl.js', 'app/' + edit + '/model/' + edit + 'Mdl.js', 'app/' + edit + '/service/' + edit + 'service.js', item.subname]); // }] // } }); $locationProvider.html5Mode(true); }); }]);<file_sep>/app/basicRegistration/controller/basicRegistrationctrl.js (function(angular) { 'use strict'; function controller(basicRegistrationModel, scope) { /* jshint validthis:true */ var vm = this; vm.init = function() { vm.model = basicRegistrationModel; vm.model.scope = scope; }; vm.init(); } angular .module('KaakateeyaEmpReg') .controller('basicRegistrationCtrl', controller) controller.$inject = ['basicRegistrationModel', '$scope']; })(angular);<file_sep>/app/basicRegistration/service/basicRegistrationservice.js (function(angular) { 'use strict'; function factory(http) { return { submitBasicRegistration: function(obj) { console.log(obj); return http.post(regApp.apipath + 'Registration/RegisterCustomerHomepages', JSON.stringify(obj)); }, emailExists: function(obj) { return http.get(regApp.apipath + 'StaticPages/getEmailMobilenumberexists', { params: obj }); } }; } angular .module('KaakateeyaEmpReg') .factory('basicRegistrationService', factory) factory.$inject = ['$http']; })(angular);<file_sep>/app/basicRegistration/model/basicRegistrationMdl.js (function(angular) { 'use strict'; function factory(basicRegistrationService, getArray, commondependency, filter, authSvc, timeout, route, SelectBindServicereg) { var model = {}; model.scope = {}; model.init = function() { model.pageload(); return model; }; // start declaretion // model.childStayingWith = 'childStayingWith'; // model.Religion = 'Religion'; // model.Caste = 'Caste'; // model.Country = 'Country'; // model.month = 'month'; model.reg = {}; model.monthArr = []; model.reg.Chkprivacy = true; model.emailrequired = true; model.mobilenumberrequired = true; model.mobilecountrycoderequired = true; var monthArr = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; //end declaration model.monthBind = function() { var option = []; _.each(monthArr, function(item) { option.push({ "label": item, "title": item, "value": item }); }); return option; }; model.date = function(str, from, to) { var Arr = []; // Arr.push({ "label": str, "title": str, "value": '' }); for (var i = from; i <= to; i++) { var strValue = null; if (i <= 9) { strValue = "0" + i; } else { strValue = i; } Arr.push({ "label": strValue, "title": strValue, "value": strValue }); } return Arr; }; model.year = function(str, from, to) { var Arr = []; // Arr.push({ "label": str, "title": str, "value": '' }); for (var i = to; i >= from; i--) { Arr.push({ "label": i, "title": i, "value": i }); } return Arr; }; model.pageload = function() { model.monthArr = model.monthBind(); model.dateArr = model.date('', 1, 31); model.yearArr = model.year('', 1936, 1998); timeout(function() { model.postedby = getArray.GArray('childStayingWith'); console.log('arrayyyyy'); console.log(model.postedby); model.religion = getArray.GArray('Religion'); model.Mothertongue = getArray.GArray('Mothertongue'); model.Caste = getArray.GArray('Caste'); // model.countryCode = getArray.GArray('countryCode'); }, 1000); timeout(function() { // model.Country = getArray.GArray('Country'); var Country = [], CountryCode = []; SelectBindServicereg.CountryWithCode().then(function(response) { _.each(response.data, function(item) { Country.push({ "label": item.Name, "title": item.Name, "value": item.ID }); CountryCode.push({ "label": item.CountryCode, "title": item.CountryCode, "value": item.ID }); }); console.log('test..'); console.log(Country); model.Country = Country; model.countryCode = CountryCode; }); }, 100); }; model.statuses = ['Planned', 'Confirmed', 'Cancelled']; model.dayChange = function(obj, type) { var months31 = 'Jan,Mar,May,Jul,Aug,Oct,Dec'; var minth30 = 'Apr,Jun,Sep,Nov'; var month28 = 'Feb'; if ((obj.ddlDD <= 30 && minth30.indexOf(obj.ddlMM) !== -1) || (obj.ddlDD <= 31 && months31.indexOf(obj.ddlMM) !== -1) || ((obj.ddlDD <= 28 && month28.indexOf(obj.ddlMM) !== -1))) { } else { if (type === 'day') { obj.ddlMM = ''; } else { model.dateArr = []; model.dateArr = model.date('DD', 1, 31); obj.ddlDD = ''; } } }; model.changeBind = function(parentval, parentval2) { if (parentval !== undefined && parentval !== null && parentval !== '' && parentval2 !== undefined && parentval2 !== null && parentval2 !== '') model.casteArr = commondependency.casteDepedency(commondependency.listSelectedVal(parentval), commondependency.listSelectedVal(parentval2)); }; model.regSubmit = function(obj) { var valmm = _.indexOf(monthArr, obj.ddlMM); valmm = (valmm != -1 ? parseInt(valmm) + 1 : 0); valmm = valmm >= 10 ? valmm : '0' + valmm; var date = obj.ddlDD + '-' + valmm + '-' + obj.ddlYear; var inputObj = { strFirstName: obj.txtfirstname, strLastName: obj.txtlastname, dtDOB: date !== '' ? filter('date')(date, 'yyyy-MM-dd') : null, intGenderID: obj.rbtngender, intReligionID: obj.ddlreligion, intMotherTongueID: obj.ddlmothertongue, intCasteID: obj.ddlcaste, intCountryLivingID: obj.ddlcountry, intMobileCode: obj.ddlmobilecountry, intLandCode: obj.ddllandcountry, IsCustomer: 0, strMobileNo: (obj.txtMobileNo !== '') && (obj.txtMobileNo !== null) && (obj.txtMobileNo !== undefined) ? (obj.txtMobileNo) : "0000000000", ID: 1, strAreaCode: (obj.txtArea !== '') && (obj.txtArea !== null) && (obj.txtArea !== undefined) ? obj.txtArea : '', strLandNo: (obj.txtlandNum !== '') && (obj.txtlandNum !== null) && (obj.txtlandNum !== undefined) ? obj.txtlandNum : '', strEmail: (obj.txtEmail !== '') && ((obj.txtEmail) !== null) && ((obj.txtEmail) !== undefined) ? obj.txtEmail : "<EMAIL>", strPassword: (obj.txtpassword !== '') && (obj.txtpassword !== null) && (obj.txtpassword !== undefined) ? obj.txtpassword : "<PASSWORD>", intProfileRegisteredBy: null, intEmpID: 2, intCustPostedBY: obj.ddlpostedby, //strMobileVerificationCode: obj. }; console.log(inputObj); basicRegistrationService.submitBasicRegistration(inputObj).then(function(res) { console.log(res); model.genderID = 0; authSvc.login(model.reg.txtEmail, "Admin@123").then(function(response) { console.log(response); authSvc.user(response.response !== null ? response.response[0] : null); model.genderID = response.response[0].GenderID; // window.location = "registration/seconadryRegistration/" + obj.txtfirstname + "/" + obj.txtlastname + "/" + obj.ddlcountry + "/" + response.response[0].GenderID; route.go('registration.seconadryRegistration', { fn: obj.txtfirstname, ln: obj.txtlastname, countryID: obj.ddlcountry, genderID: response.response[0].GenderID }); return false; }); }); }; model.valueExists = function(type, flag, val) { if (val !== undefined) { basicRegistrationService.emailExists({ iflagEmailmobile: flag, EmailMobile: val }).then(function(response) { console.log(response); if (response.data === 1) { if (type === 'email') { model.reg.txtEmail = ''; alert('Email Already Exists'); } else { model.reg.txtMobileNo = ''; alert('Mobile number Already Exists'); } } else { if (model.reg.Chkfree_reg === true) { if (type === 'email') { model.emailrequired = true; model.mobilenumberrequired = false; model.mobilecountrycoderequired = false; } else { model.emailrequired = false; model.mobilenumberrequired = true; model.mobilecountrycoderequired = true; } } } }); } }; model.mobilemailvalidation = function() { if (model.reg.Chkfree_reg === true) { if ((model.reg.txtEmail === null || model.reg.txtEmail === "" || model.reg.txtEmail === undefined) && (model.reg.txtMobileNo === null || model.reg.txtMobileNo === "" || model.reg.txtMobileNo === undefined)) { model.emailrequired = false; model.mobilenumberrequired = true; model.mobilecountrycoderequired = true; } else if ((model.reg.txtEmail !== null && model.reg.txtEmail !== "" && model.reg.txtEmail !== undefined) || (model.reg.txtMobileNo !== null && model.reg.txtMobileNo !== "" && model.reg.txtMobileNo !== undefined)) { model.emailrequired = false; model.mobilenumberrequired = false; model.mobilecountrycoderequired = false; } } else { model.emailrequired = true; model.mobilenumberrequired = true; model.mobilecountrycoderequired = true; } }; // model.scope.$watch(function() { // return model.reg.ddlcountry; // }, function(current, original) { // model.reg.ddllandcountry = model.reg.ddlmobilecountry = current; // }); model.redirectprivacy = function(type) { window.open('registration/privacyPolicy', '_blank'); }; return model.init(); } angular .module('KaakateeyaEmpReg') .factory('basicRegistrationModel', factory) factory.$inject = ['basicRegistrationService', 'getArray', 'Commondependency', '$filter', 'authSvc', '$timeout', 'route', 'SelectBindServicereg' ]; // factory.$inject = ['basicRegistrationService', '$scope', 'getArray', 'Commondependency', // '$filter', 'authSvc', '$timeout', 'route', 'SelectBindServicereg', // ]; })(angular);
9f7def741941b0900d2d5f8a780326c3ebbe04b8
[ "Markdown", "JavaScript" ]
5
Markdown
umakusumuru/EmployeeEditView
d1f91e86e9e39a32ff04006eb05527638c705e78
e63052a7e691a48b376d3f2790a7b9fdb2aeb208
refs/heads/master
<repo_name>dariushooks/RookMusicPlayer<file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/adapters/SongsAdapter.java package com.rookieandroid.rookiemusicplayer.adapters; import android.content.Context; import android.net.Uri; import android.os.Handler; import android.support.v4.media.session.PlaybackStateCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.rookieandroid.rookiemusicplayer.R; import com.rookieandroid.rookiemusicplayer.helpers.SectionIndexFixer; import com.rookieandroid.rookiemusicplayer.Songs; import java.util.ArrayList; import java.util.Locale; import static com.rookieandroid.rookiemusicplayer.App.currentState; import static com.rookieandroid.rookiemusicplayer.App.lettersSongs; import static com.rookieandroid.rookiemusicplayer.App.sectionsSongs; public class SongsAdapter extends RecyclerView.Adapter<SongsAdapter.SongViewHolder> { private final String TAG = SongsAdapter.class.getSimpleName(); private ArrayList<Songs> songs; private ListItemClickListener listener; private Context context; private int previousPosition; private int currentlyPlaying = 1; private ImageView currentSong; private ImageView previousSong; private int position; private Handler playingHandler = new Handler(); public interface ListItemClickListener { void onListItemClick(int position); void onLongListItemClick(int position); } public SongsAdapter(ArrayList<Songs> songs, ListItemClickListener listener) { this.songs = songs; this.listener = listener; setHasStableIds(true); lettersSongs.clear(); sectionsSongs.clear(); for (int i = 0; i < this.songs.size(); i++) { String song = this.songs.get(i).getTitle(); if(Character.isLetter(song.charAt(0))) { String letter = song.charAt(0) + ""; if(lettersSongs.isEmpty()) { lettersSongs.add(letter.toUpperCase()); sectionsSongs.add(i); } else if(!lettersSongs.contains(letter) && lettersSongs.size() < 26) { lettersSongs.add(letter.toUpperCase()); sectionsSongs.add(i); } } else { if(!lettersSongs.contains("#") && lettersSongs.size() < 26) { lettersSongs.add("#"); sectionsSongs.add(i); } } } new SectionIndexFixer().fixIndex(lettersSongs, sectionsSongs); /*for(int i = 0; i < 27; i++) { //Log.i(TAG, "Letter " + lettersSongs.get(i) + "\tSection " + sectionsSongs.get(i)); }*/ } @NonNull @Override public SongViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.songs_list, parent, false); return new SongViewHolder(view); } @Override public void onBindViewHolder(@NonNull SongViewHolder holder, int position) { holder.bind(position); } @Override public long getItemId(int position) { return Integer.parseInt(songs.get(position).getId()); } @Override public int getItemViewType(int position) { return Integer.parseInt(songs.get(position).getId()); } @Override public int getItemCount() { return songs.size(); } private Runnable updateCurrentlyPlaying = new Runnable() { @Override public void run() { if(currentState == PlaybackStateCompat.STATE_PLAYING) { switch(currentlyPlaying) { case 1: currentSong.setBackgroundColor(context.getColor(R.color.nowPlaying)); currentSong.setImageResource(R.drawable.ic_currentlyplaying2); currentlyPlaying = 2; break; case 2: currentSong.setBackgroundColor(context.getColor(R.color.nowPlaying)); currentSong.setImageResource(R.drawable.ic_currentlyplaying3); currentlyPlaying = 3; break; case 3: currentSong.setBackgroundColor(context.getColor(R.color.nowPlaying)); currentSong.setImageResource(R.drawable.ic_currentlyplaying4); currentlyPlaying = 4; break; case 4: currentSong.setBackgroundColor(context.getColor(R.color.nowPlaying)); currentSong.setImageResource(R.drawable.ic_currentlyplaying1); currentlyPlaying = 1; break; } playingHandler.postDelayed(this, 300); } else { currentSong.setBackgroundColor(context.getColor(R.color.nowPlaying)); currentSong.setImageResource(R.drawable.ic_currentlyplaying1); currentlyPlaying = 1; playingHandler.post(this); } } }; class SongViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { private ImageView albumArt; private ImageView songPlaying; private TextView songName; private TextView songArtist; private TextView songDuration; public SongViewHolder(@NonNull View itemView) { super(itemView); albumArt = itemView.findViewById(R.id.songArt); songPlaying = itemView.findViewById(R.id.songPlaying); songName = itemView.findViewById(R.id.songName); songArtist = itemView.findViewById(R.id.songArtist); songDuration = itemView.findViewById(R.id.songDuration); itemView.setOnClickListener(this); itemView.setOnLongClickListener(this); } public void bind(int position) { Uri artUri = Uri.parse(songs.get(position).getArt()); Glide.with(context).load(artUri).placeholder(R.drawable.noalbumart).fallback(R.drawable.noalbumart).error(R.drawable.noalbumart).into(albumArt); songName.setText(songs.get(position).getTitle()); songArtist.setText(songs.get(position).getArtist()); String duration; long minutes = (songs.get(position).getDuration() / 1000) / 60; long seconds = (songs.get(position).getDuration() / 1000) % 60; if(seconds > 9) duration = String.format(Locale.US, "%d:%d", minutes, seconds); else duration = String.format(Locale.US, "%d:%d%d", minutes, 0, seconds); songDuration.setText(duration); } @Override public void onClick(View view) { /*if(previousSong == null) { previousSong = songPlaying; previousPosition = getAdapterPosition(); } else { playingHandler.removeCallbacks(updateCurrentlyPlaying); previousSong.setBackgroundColor(context.getColor(R.color.transparent)); previousSong.setImageResource(0); previousSong = songPlaying; previousPosition = getAdapterPosition(); }*/ position = getAdapterPosition(); listener.onListItemClick(position); /*currentSong = songPlaying; currentSong.setBackgroundColor(context.getColor(R.color.nowPlaying)); currentSong.setImageResource(R.drawable.ic_currentlyplaying2); currentlyPlaying = 1; playingHandler.post(updateCurrentlyPlaying);*/ } @Override public boolean onLongClick(View view) { int clickedPosition = getAdapterPosition(); listener.onLongListItemClick(clickedPosition); return true; } } } <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/MediaPlaybackService.java package com.rookieandroid.rookiemusicplayer; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.BitmapFactory; import android.media.AudioAttributes; import android.media.AudioFocusRequest; import android.media.AudioManager; import android.media.MediaMetadataRetriever; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.os.ResultReceiver; import android.provider.MediaStore; import android.support.v4.media.MediaBrowserCompat; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaSessionCompat; import android.support.v4.media.session.PlaybackStateCompat; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import androidx.media.MediaBrowserServiceCompat; import androidx.media.session.MediaButtonReceiver; import com.rookieandroid.rookiemusicplayer.adapters.QueueAdapter; import com.rookieandroid.rookiemusicplayer.architecture.SavedDetails; import com.rookieandroid.rookiemusicplayer.architecture.StateViewModel; import com.rookieandroid.rookiemusicplayer.helpers.ControlReceiver; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Locale; import static com.rookieandroid.rookiemusicplayer.App.ACTIVITY_RESTORE; import static com.rookieandroid.rookiemusicplayer.App.ADD_ALBUM_ARTIST_PLAYLIST; import static com.rookieandroid.rookiemusicplayer.App.ADD_SONG; import static com.rookieandroid.rookiemusicplayer.App.CHANNEL_1; import static com.rookieandroid.rookiemusicplayer.App.CLEAR; import static com.rookieandroid.rookiemusicplayer.App.FROM_ALBUM; import static com.rookieandroid.rookiemusicplayer.App.FROM_PLAYLIST; import static com.rookieandroid.rookiemusicplayer.App.GET_ARTIST_ALBUM; import static com.rookieandroid.rookiemusicplayer.App.GET_CURRENT_POSITION; import static com.rookieandroid.rookiemusicplayer.App.GET_PLAYBACKSTATE; import static com.rookieandroid.rookiemusicplayer.App.GET_QUEUE_POSITION; import static com.rookieandroid.rookiemusicplayer.App.INITIALIZE_QUEUE_CHANGE; import static com.rookieandroid.rookiemusicplayer.App.MEDIA_DELETED; import static com.rookieandroid.rookiemusicplayer.App.PLAY_BUTTON_START; import static com.rookieandroid.rookiemusicplayer.App.QUEUE_CLICK; import static com.rookieandroid.rookiemusicplayer.App.QUEUE_END; import static com.rookieandroid.rookiemusicplayer.App.QUEUE_NEXT; import static com.rookieandroid.rookiemusicplayer.App.RECEIVE_ARTIST_ALBUM; import static com.rookieandroid.rookiemusicplayer.App.RECEIVE_CURRENT_POSITION; import static com.rookieandroid.rookiemusicplayer.App.RECEIVE_PLAYBACKSTATE; import static com.rookieandroid.rookiemusicplayer.App.RECEIVE_QUEUE_POSITION; import static com.rookieandroid.rookiemusicplayer.App.RECENTLY_ADDED; import static com.rookieandroid.rookiemusicplayer.App.RESTORE_SAVED_QUEUE; import static com.rookieandroid.rookiemusicplayer.App.SAVE_QUEUE; import static com.rookieandroid.rookiemusicplayer.App.SET_ELAPSED_TIME; import static com.rookieandroid.rookiemusicplayer.App.SET_FROM; import static com.rookieandroid.rookiemusicplayer.App.SET_POSITION; import static com.rookieandroid.rookiemusicplayer.App.SET_QUEUE_ALBUM; import static com.rookieandroid.rookiemusicplayer.App.SET_QUEUE_ARTIST; import static com.rookieandroid.rookiemusicplayer.App.SET_QUEUE_LIBRARY; import static com.rookieandroid.rookiemusicplayer.App.SET_QUEUE_LIBRARY_SONGS; import static com.rookieandroid.rookiemusicplayer.App.SET_QUEUE_PLAYLIST; import static com.rookieandroid.rookiemusicplayer.App.SET_QUEUE_SEARCH; import static com.rookieandroid.rookiemusicplayer.App.SET_UP_NEXT; import static com.rookieandroid.rookiemusicplayer.App.SHUFFLE_QUEUE; import static com.rookieandroid.rookiemusicplayer.App.SKIP_NEXT; import static com.rookieandroid.rookiemusicplayer.App.SKIP_PREVIOUS; import static com.rookieandroid.rookiemusicplayer.App.addToQueue; import static com.rookieandroid.rookiemusicplayer.App.albumSongs; import static com.rookieandroid.rookiemusicplayer.App.artistSongs; import static com.rookieandroid.rookiemusicplayer.App.deleteFromQueue; import static com.rookieandroid.rookiemusicplayer.App.librarySongs; import static com.rookieandroid.rookiemusicplayer.App.nowPlayingFrom; import static com.rookieandroid.rookiemusicplayer.App.playlistSongs; import static com.rookieandroid.rookiemusicplayer.App.queueAdapter; import static com.rookieandroid.rookiemusicplayer.App.queueDisplay; import static com.rookieandroid.rookiemusicplayer.App.savedSongs; import static com.rookieandroid.rookiemusicplayer.App.savedState; import static com.rookieandroid.rookiemusicplayer.App.searchSong; import static com.rookieandroid.rookiemusicplayer.App.songs; public class MediaPlaybackService extends MediaBrowserServiceCompat implements AudioManager.OnAudioFocusChangeListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, QueueAdapter.QueueChange { private static final String MY_MEDIA_ROOT_ID = "media_root_id"; private static final String TAG = MediaPlaybackService.class.getSimpleName(); private ArrayList<Songs> queue = new ArrayList<>(); private int position; private int from; private int currentState = PlaybackStateCompat.STATE_NONE; private int shuffle; private int repeat; private int elapsed; private boolean repeatAll = false; private boolean repeatOne = false; private MediaSessionCompat mediaSession; private ComponentName mediaButtonReceiver; private PlaybackStateCompat.Builder stateBuilder; private MediaPlayer mediaPlayer; private Handler handler = new Handler(); private NotificationCompat.Builder builder; //SYNC UI STATE private StateViewModel stateViewModel; private int syncPosition; private int syncElapsed; private int syncDuration; private int syncShuffle; private int syncRepeat; private int syncPlayState; private String syncNowPlayingFrom; private int syncFrom; @Override public void onCreate() { super.onCreate(); //MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); mediaPlayer.setAudioAttributes(new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build()); mediaPlayer.setVolume(1f, 1f); mediaPlayer.setOnCompletionListener(this); mediaPlayer.setOnErrorListener(this); mediaPlayer.setOnPreparedListener(this); // Create a MediaSessionCompat mediaButtonReceiver = new ComponentName(this, ControlReceiver.class); mediaSession = new MediaSessionCompat(this, MediaPlaybackService.class.getSimpleName(), mediaButtonReceiver, null); // Enable callbacks from MediaButtons and TransportControls mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS | MediaSessionCompat.FLAG_HANDLES_QUEUE_COMMANDS); // Set an initial PlaybackState with ACTION_PLAY, so media buttons can start the player stateBuilder = new PlaybackStateCompat.Builder() .setState(PlaybackStateCompat.STATE_NONE, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 0) .setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_PLAY); mediaSession.setPlaybackState(stateBuilder.build()); // MySessionCallback() has methods that handle callbacks from a media controller mediaSession.setCallback(mediaCallbacks); mediaSession.setActive(true); Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); mediaButtonIntent.setClass(this, ControlReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0); mediaSession.setMediaButtonReceiver(pendingIntent); // Set the session's token so that client activities can communicate with it. setSessionToken(mediaSession.getSessionToken()); //BroadcastReceiver //Handles headphones coming unplugged. cannot be done through a manifest receiver IntentFilter filter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY); registerReceiver(broadcastReceiver, filter); stateViewModel = new StateViewModel(getApplication()); } @Override public int onStartCommand(Intent intent, int flags, int startId) { MediaButtonReceiver.handleIntent(mediaSession, intent); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); //Log.i(TAG, "SERVICE BEING DESTROYED"); abandonAudioFocus(); unregisterReceiver(broadcastReceiver); mediaPlayer.release(); mediaSession.release(); NotificationManagerCompat.from(this).cancel(1); } /*///////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// SESSION CALLBACKS /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////*/ private MediaSessionCompat.Callback mediaCallbacks = new MediaSessionCompat.Callback() { @Override public void onPlay() { super.onPlay(); if(successfullyRetrievedAudioFocus() == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { startForegroundService(new Intent(MediaPlaybackService.this, MediaPlaybackService.class)); mediaSession.setActive(true); mediaPlayer.start(); //SET PLAYBACK STATE currentState = PlaybackStateCompat.STATE_PLAYING; stateBuilder.setState(PlaybackStateCompat.STATE_PLAYING, mediaPlayer.getCurrentPosition(), 1); stateBuilder.setActions(PlaybackStateCompat.ACTION_SEEK_TO | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS); mediaSession.setPlaybackState(stateBuilder.build()); //SHOW PLAY NOTIFICATION buildNotification(MediaPlaybackService.this, queue.get(position)); handler.post(updateQueueState); } } @Override public void onStop() { super.onStop(); abandonAudioFocus(); stopService(new Intent(MediaPlaybackService.this, MediaPlaybackService.class)); mediaSession.setActive(false); mediaPlayer.stop(); } @Override public void onPlayFromMediaId(String mediaId, Bundle extras) { super.onPlayFromMediaId(mediaId, extras); //Log.i(TAG, "Playing from media id: " + mediaId); if(successfullyRetrievedAudioFocus() == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { startForegroundService(new Intent(MediaPlaybackService.this, MediaPlaybackService.class)); mediaSession.setActive(true); playSong(mediaId); buildMetadata(queue.get(position)); //SET PLAYBACK STATE currentState = PlaybackStateCompat.STATE_PLAYING; stateBuilder.setState(PlaybackStateCompat.STATE_PLAYING, mediaPlayer.getCurrentPosition(), 1); stateBuilder.setActions(PlaybackStateCompat.ACTION_SEEK_TO | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS); mediaSession.setPlaybackState(stateBuilder.build()); //SHOW PLAY NOTIFICATION buildNotification(MediaPlaybackService.this, queue.get(position)); handler.post(updateQueueState); } } @Override public void onPause() { super.onPause(); if(mediaPlayer.isPlaying()) { mediaPlayer.pause(); //SET PLAYBACK STATE currentState = PlaybackStateCompat.STATE_PAUSED; stateBuilder.setState(PlaybackStateCompat.STATE_PAUSED, mediaPlayer.getCurrentPosition(), 0); stateBuilder.setActions(PlaybackStateCompat.ACTION_SEEK_TO | PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS); mediaSession.setPlaybackState(stateBuilder.build()); //SHOW PAUSE NOTIFICATION buildNotification(MediaPlaybackService.this, queue.get(position)); } } @Override public void onCommand(String command, Bundle extras, ResultReceiver cb) { super.onCommand(command, extras, cb); switch (command) { case GET_CURRENT_POSITION: Bundle currentPosition = new Bundle(); currentPosition.putInt("currentPosition", getCurrentPosition()); cb.send(RECEIVE_CURRENT_POSITION, currentPosition); break; case GET_ARTIST_ALBUM: Bundle currentArtistAlbum = new Bundle(); currentArtistAlbum.putParcelable("currentArtistAlbum", getCurrentArtistAlbum()); cb.send(RECEIVE_ARTIST_ALBUM, currentArtistAlbum); break; case GET_QUEUE_POSITION: Bundle queuePosition = new Bundle(); queuePosition.putInt("queuePosition", position); queuePosition.putInt("currentElapsed", mediaPlayer.getCurrentPosition()); queuePosition.putInt("currentFrom", from); cb.send(RECEIVE_QUEUE_POSITION, queuePosition); break; case GET_PLAYBACKSTATE: Bundle playbackState = new Bundle(); playbackState.putInt("currentState", currentState); cb.send(RECEIVE_PLAYBACKSTATE, playbackState); break; } } @Override public void onCustomAction(String action, Bundle extras) { super.onCustomAction(action, extras); switch (action) { case ADD_SONG: addSongToQueue(extras.getParcelable("ADD_SONG"), extras.getInt("QUEUE_POSITION")); break; case ADD_ALBUM_ARTIST_PLAYLIST: addAlbumOrArtistToQueue(extras.getInt("QUEUE_POSITION")); break; case SET_POSITION: setPosition(extras.getInt("CURRENT_QUEUE_POSITION")); break; case CLEAR: queue.clear(); break; case ACTIVITY_RESTORE: activityRestore(); break; case SET_QUEUE_LIBRARY: queue.addAll(songs); from = extras.getInt("FROM"); break; case SET_QUEUE_LIBRARY_SONGS: queue.addAll(librarySongs); from = extras.getInt("FROM"); break; case SET_QUEUE_ARTIST: queue.addAll(artistSongs); from = extras.getInt("FROM"); break; case SET_QUEUE_ALBUM: queue.addAll(albumSongs); from = extras.getInt("FROM"); break; case SET_QUEUE_SEARCH: queue.addAll(searchSong); from = extras.getInt("FROM"); break; case SET_QUEUE_PLAYLIST: queue.addAll(playlistSongs); from = extras.getInt("FROM"); break; case SET_UP_NEXT: setQueueDisplay(); break; case QUEUE_CLICK: queueClick(extras.getInt("clickedIndex")); break; case SHUFFLE_QUEUE: mediaSession.setShuffleMode(PlaybackStateCompat.SHUFFLE_MODE_ALL); break; case SAVE_QUEUE: saveQueue(); break; case RESTORE_SAVED_QUEUE: queue.addAll(savedSongs); break; case INITIALIZE_QUEUE_CHANGE: queueAdapter.initializeQueueChange(MediaPlaybackService.this); break; case SET_ELAPSED_TIME: elapsed = extras.getInt("CURRENT_ELAPSED_TIME"); setSong(queue.get(position).getId()); break; case SET_FROM: from = extras.getInt("CURRENT_FROM"); break; case PLAY_BUTTON_START: playButtonStart(); break; case MEDIA_DELETED: mediaDeleted(extras.getParcelable("DELETE_SONG")); break; } } @Override public void onSkipToPrevious() { super.onSkipToPrevious(); if(!queue.isEmpty()) { String mediaId; if(mediaPlayer.getCurrentPosition() < 5000 && position > 0) { stateBuilder.setState(PlaybackStateCompat.STATE_SKIPPING_TO_PREVIOUS, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 0); mediaSession.setPlaybackState(stateBuilder.build()); updateQueueDisplay(SKIP_PREVIOUS); position--; } mediaId = queue.get(position).getId(); if(currentState == PlaybackStateCompat.STATE_PLAYING) playSong(mediaId); else setSong(mediaId); buildMetadata(queue.get(position)); buildNotification(MediaPlaybackService.this, queue.get(position)); } } @Override public void onSkipToNext() { super.onSkipToNext(); if(repeatAll && position == queue.size() - 1) { position = 0; setQueueDisplay(); position = -1; } if(!queue.isEmpty() && position < queue.size() - 1) { stateBuilder.setState(PlaybackStateCompat.STATE_SKIPPING_TO_NEXT, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 0); mediaSession.setPlaybackState(stateBuilder.build()); position++; String mediaId = queue.get(position).getId(); if(currentState == PlaybackStateCompat.STATE_PLAYING) playSong(mediaId); else setSong(mediaId); buildMetadata(queue.get(position)); updateQueueDisplay(SKIP_NEXT); buildNotification(MediaPlaybackService.this, queue.get(position)); } } @Override public void onSeekTo(long pos) { super.onSeekTo(pos); mediaPlayer.seekTo((int)pos); stateBuilder.setState(PlaybackStateCompat.STATE_PLAYING, mediaPlayer.getCurrentPosition(), 1); stateBuilder.setActions(PlaybackStateCompat.ACTION_SEEK_TO | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS); mediaSession.setPlaybackState(stateBuilder.build()); } @Override public void onSetRepeatMode(int repeatMode) { super.onSetRepeatMode(repeatMode); mediaSession.setRepeatMode(repeatMode); repeat = repeatMode; switch (repeatMode) { case PlaybackStateCompat.REPEAT_MODE_ALL: repeatAll = true; break; case PlaybackStateCompat.REPEAT_MODE_ONE: repeatAll = false; repeatOne = true; break; case PlaybackStateCompat.REPEAT_MODE_NONE: repeatAll = false; repeatOne = false; break; } } @Override public void onSetShuffleMode(int shuffleMode) { super.onSetShuffleMode(shuffleMode); mediaSession.setShuffleMode(shuffleMode); shuffle = shuffleMode; Songs current; switch (shuffleMode) { case PlaybackStateCompat.SHUFFLE_MODE_ALL: if(!queue.isEmpty()) { current = queue.get(position); queue.remove(position); Collections.shuffle(queue); queue.add(0, current); position = 0; setQueueDisplay(); } break; case PlaybackStateCompat.SHUFFLE_MODE_NONE: if(!queue.isEmpty()) { current = queue.get(position); if(from == FROM_ALBUM || from == FROM_PLAYLIST) Collections.sort(queue, Comparator.comparing(Songs::getTrack)); else if(from == RECENTLY_ADDED) Collections.sort(queue, Comparator.comparing(Songs::getTrack).reversed()); else Collections.sort(queue, Comparator.comparing(Songs::getTitle)); position = queue.indexOf(current); setQueueDisplay(); } break; } saveQueue(); } }; /*///////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////*/ /*///////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// METHODS FOR SAVING UI STATE /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////*/ private void saveQueue() { stateViewModel.deleteSavedQueue(); stateViewModel.insertAll(queue); /*for(int i = 0; i < queue.size(); i++) { String id = queue.get(i).getId(); String title = queue.get(i).getTitle(); String album = queue.get(i).getAlbum(); String albumKey = queue.get(i).getAlbumKey(); String art = queue.get(i).getArt(); String artist = queue.get(i).getArtist(); String artistKey = queue.get(i).getArtistKey(); long duration = queue.get(i).getDuration(); String path = queue.get(i).getPath(); int track = queue.get(i).getTrack(); stateViewModel.insert(new SavedQueue(id, title, album, albumKey, art, artist, artistKey, duration, path, track)); }*/ //Log.i(TAG, "QUEUE SAVED"); } private void updateSavedState() { syncPosition = position; syncShuffle = shuffle; syncRepeat = repeat; syncPlayState = currentState; syncElapsed = mediaPlayer.getCurrentPosition(); syncDuration = mediaPlayer.getDuration(); syncNowPlayingFrom = nowPlayingFrom; syncFrom = from; SavedDetails details = new SavedDetails(syncPosition, syncShuffle, syncRepeat, syncPlayState, syncElapsed, syncDuration, syncNowPlayingFrom, syncFrom); if(savedState.isEmpty()) stateViewModel.insert(details); else { details.setId(savedState.get(0).getId()); stateViewModel.update(details); } //Log.i(TAG, "SAVED STATE UPDATED"); } /*///////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////*/ private void activityRestore() { if(mediaPlayer.isPlaying()) { stateBuilder.setState(PlaybackStateCompat.STATE_PLAYING, mediaPlayer.getCurrentPosition(), 1); stateBuilder.setActions(PlaybackStateCompat.ACTION_SEEK_TO | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS); mediaSession.setPlaybackState(stateBuilder.build()); } else { stateBuilder.setState(PlaybackStateCompat.STATE_PAUSED, mediaPlayer.getCurrentPosition(), 0); stateBuilder.setActions(PlaybackStateCompat.ACTION_SEEK_TO | PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS); mediaSession.setPlaybackState(stateBuilder.build()); } buildMetadata(queue.get(position)); } private void buildMetadata(Songs currentSong) { MediaMetadataCompat.Builder metadata = new MediaMetadataCompat.Builder(); metadata.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, currentSong.getId()); metadata.putString(MediaMetadataCompat.METADATA_KEY_TITLE, currentSong.getTitle()); metadata.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, currentSong.getArtist()); metadata.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, currentSong.getAlbum()); metadata.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, currentSong.getDuration()); metadata.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, currentSong.getPath()); metadata.putString(MediaMetadataCompat.METADATA_KEY_ART_URI, currentSong.getArt()); mediaSession.setMetadata(metadata.build()); } private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(mediaPlayer != null && mediaPlayer.isPlaying()) mediaPlayer.pause(); } }; /*///////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// METHODS FOR AUDIO FOCUS /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////*/ private int successfullyRetrievedAudioFocus() { int result; AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if(audioManager != null) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { AudioAttributes playbackAttributes = new AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_GAME) .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) .build(); AudioFocusRequest focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN) .setAudioAttributes(playbackAttributes) .setAcceptsDelayedFocusGain(true) .setOnAudioFocusChangeListener(this) .build(); result = audioManager.requestAudioFocus(focusRequest); } else result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); } else result = AudioManager.AUDIOFOCUS_REQUEST_FAILED; return result; } private void abandonAudioFocus() { AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if(audioManager != null) audioManager.abandonAudioFocus(this); } @Override public void onAudioFocusChange(int focusChange) { switch (focusChange) { case AudioManager.AUDIOFOCUS_LOSS: { if(mediaPlayer.isPlaying()) mediaPlayer.stop(); break; } case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: { mediaPlayer.pause(); break; } case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: { if( mediaPlayer != null ) mediaPlayer.setVolume(0.3f, 0.3f); break; } case AudioManager.AUDIOFOCUS_GAIN: { if( mediaPlayer != null ) { if( !mediaPlayer.isPlaying() ) mediaPlayer.start(); mediaPlayer.setVolume(1.0f, 1.0f); } break; } } } /*///////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////*/ /*///////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// METHODS FOR NOTIFICATIONS /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////*/ private void buildNotification(Context context, Songs currentSong) { Intent intent = new Intent(context, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Long.parseLong(currentSong.getId())); MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setDataSource(context, uri); byte[] cover = retriever.getEmbeddedPicture(); builder = new NotificationCompat.Builder(context, CHANNEL_1); builder.setSmallIcon(R.drawable.ic_noartistart); builder.setContentTitle(currentSong.getTitle()) .setContentText(currentSong.getArtist() + " - " + currentSong.getAlbum()); if(cover != null) builder.setLargeIcon(BitmapFactory.decodeByteArray(cover, 0, cover.length)); else builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.noalbumart)); builder.setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_LOW) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC); if(currentState == PlaybackStateCompat.STATE_PLAYING) { builder.setOngoing(true); builder.setStyle(new androidx.media.app.NotificationCompat.MediaStyle().setShowActionsInCompactView(0,1,2).setMediaSession(mediaSession.getSessionToken())); builder.addAction(R.drawable.ic_fast_rewind, "Back", MediaButtonReceiver.buildMediaButtonPendingIntent(MediaPlaybackService.this, PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)); builder.addAction(R.drawable.ic_pause, "Pause", MediaButtonReceiver.buildMediaButtonPendingIntent(MediaPlaybackService.this, PlaybackStateCompat.ACTION_PLAY_PAUSE)); builder.addAction(R.drawable.ic_fast_forward, "Forward", MediaButtonReceiver.buildMediaButtonPendingIntent(MediaPlaybackService.this, PlaybackStateCompat.ACTION_SKIP_TO_NEXT)); startForeground(1, builder.build()); } else { builder.setOngoing(false); builder.setStyle(new androidx.media.app.NotificationCompat.MediaStyle().setShowActionsInCompactView(0, 1, 2).setMediaSession(mediaSession.getSessionToken())); builder.addAction(R.drawable.ic_fast_rewind, "Back", MediaButtonReceiver.buildMediaButtonPendingIntent(MediaPlaybackService.this, PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)); builder.addAction(R.drawable.ic_play, "Play", MediaButtonReceiver.buildMediaButtonPendingIntent(MediaPlaybackService.this, PlaybackStateCompat.ACTION_PLAY_PAUSE)); builder.addAction(R.drawable.ic_fast_forward, "Forward", MediaButtonReceiver.buildMediaButtonPendingIntent(MediaPlaybackService.this, PlaybackStateCompat.ACTION_SKIP_TO_NEXT)); NotificationManagerCompat.from(MediaPlaybackService.this).notify(1, builder.build()); } } private Runnable updateQueueState = new Runnable() { @Override public void run() { if(currentState == PlaybackStateCompat.STATE_PLAYING) { //Log.i(TAG, "Time Updating to " + calculateTime(mediaPlayer.getCurrentPosition())); updateSavedState(); handler.postDelayed(this, 2000); } else { //Log.i(TAG, "Time Paused at " + calculateTime(mediaPlayer.getCurrentPosition())); updateSavedState(); stopForeground(false); } } }; private String calculateTime(int time) { String calculated; int minutes = time / 1000 / 60; int seconds = time/ 1000 % 60; if(seconds > 9) calculated = String.format(Locale.US, "%d:%d", minutes, seconds); else calculated = String.format(Locale.US, "%d:%d%d", minutes, 0, seconds); return calculated; } /*///////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////*/ private int getCurrentPosition(){ return mediaPlayer.getCurrentPosition(); } private Songs getCurrentArtistAlbum() { return queue.get(position); } /*///////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// METHODS FOR QUEUE CONTROL /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////*/ private void mediaDeleted(Songs deleteSong) { deleteFromQueue.clear(); for(int i = 0; i < queue.size(); i++) if(queue.get(i).getTitle().equals(deleteSong.getTitle())) deleteFromQueue.add(queue.get(i)); queue.removeAll(deleteFromQueue); setQueueDisplay(); } private void playButtonStart() { if(successfullyRetrievedAudioFocus() == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { startForegroundService(new Intent(MediaPlaybackService.this, MediaPlaybackService.class)); mediaSession.setActive(true); if(shuffle == PlaybackStateCompat.SHUFFLE_MODE_ALL) Collections.shuffle(queue); playSong(queue.get(position).getId()); buildMetadata(queue.get(position)); //SET PLAYBACK STATE currentState = PlaybackStateCompat.STATE_PLAYING; stateBuilder.setState(PlaybackStateCompat.STATE_PLAYING, mediaPlayer.getCurrentPosition(), 1); stateBuilder.setActions(PlaybackStateCompat.ACTION_SEEK_TO | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS); mediaSession.setPlaybackState(stateBuilder.build()); //SHOW PLAY NOTIFICATION buildNotification(MediaPlaybackService.this, queue.get(position)); handler.post(updateQueueState); } } private void setQueueDisplay() { queueDisplay.clear(); if(queue.size() - position > 20) queueDisplay.addAll(queue.subList(position + 1, position + 21)); else if(queue.size() - position < 20 && queue.size() != 1) queueDisplay.addAll(queue.subList(position + 1, queue.size())); queueAdapter.notifyDataSetChanged(); } @Override public void updateQueueOrder(int from, int to) { int fromPosition = queue.indexOf(queueDisplay.get(from)); if (from < to) for (int i = from; i < to; i++) Collections.swap(queueDisplay, i, i + 1); else for (int i = from; i > to; i--) Collections.swap(queueDisplay, i, i - 1); queueAdapter.notifyItemMoved(from, to); Collections.swap(queue, fromPosition, fromPosition + (to - from)); saveQueue(); } @Override public void updateQueueDismiss(int index) { queue.remove(queueDisplay.get(index)); saveQueue(); queueDisplay.remove(index); queueAdapter.notifyItemRemoved(index); } private void updateQueueDisplay(int action) { switch (action) { case SKIP_NEXT: if (queue.size() - position > 0) { queueDisplay.remove(0); queueAdapter.notifyItemRemoved(0); if(queue.size() - position > 20) { queueDisplay.add(queue.get(position + 20)); queueAdapter.notifyItemInserted(queueDisplay.size() - 1); } } break; case SKIP_PREVIOUS: if(queue.size() - position > 20) { queueDisplay.remove(queueDisplay.size() - 1); queueAdapter.notifyItemRemoved(queueDisplay.size() - 1); } queueDisplay.add(0, queue.get(position)); queueAdapter.notifyItemInserted(0); break; } } private void queueClick(int index) { position += index + 1; } private void setPosition(int position){ this.position = position; } private void addSongToQueue(Songs song, int add) { switch (add) { case QUEUE_NEXT: queue.add(position + 1, song); queueDisplay.remove(queueDisplay.size() - 1); queueDisplay.add(0, queue.get(position + 1)); queueAdapter.notifyItemRemoved(queueDisplay.size() - 1); queueAdapter.notifyItemInserted(0); break; case QUEUE_END: queue.add(song); break; } saveQueue(); } private void addAlbumOrArtistToQueue(int add) { switch (add) { case QUEUE_NEXT: queue.addAll(position + 1, addToQueue); queueDisplay.addAll(0, addToQueue); if(queueDisplay.size() > 20) { queueDisplay.subList(20, queueDisplay.size()).clear(); } queueAdapter.notifyDataSetChanged(); break; case QUEUE_END: queue.addAll(addToQueue); break; } saveQueue(); } /*///////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////*/ /*///////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// METHODS FOR MEDIA PLAYER /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////*/ private void playSong(String mediaId) { saveQueue(); Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Long.parseLong(mediaId)); try { mediaPlayer.reset(); mediaPlayer.setAudioAttributes(new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build()); mediaPlayer.setDataSource(this, uri); mediaPlayer.prepareAsync(); stateBuilder.setState(PlaybackStateCompat.STATE_PLAYING, mediaPlayer.getCurrentPosition(), 1); stateBuilder.setActions(PlaybackStateCompat.ACTION_SEEK_TO | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS); mediaSession.setPlaybackState(stateBuilder.build()); handler.post(updateQueueState); } catch (IOException e) { e.printStackTrace(); } } private void setSong(String mediaId) { saveQueue(); Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Long.parseLong(mediaId)); try { mediaPlayer.reset(); mediaPlayer.setAudioAttributes(new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build()); mediaPlayer.setDataSource(this, uri); mediaPlayer.prepareAsync(); stateBuilder.setState(PlaybackStateCompat.STATE_PAUSED, mediaPlayer.getCurrentPosition(), 0); stateBuilder.setActions(PlaybackStateCompat.ACTION_SEEK_TO | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS); mediaSession.setPlaybackState(stateBuilder.build()); } catch (IOException e) { e.printStackTrace(); } } @Override public void onCompletion(MediaPlayer mediaPlayer) { if(currentState != PlaybackStateCompat.STATE_NONE) { if(!repeatOne) { if(repeatAll && position == queue.size() - 1) position = 0; else position++; } if(!queue.isEmpty() && position < queue.size() - 1) { String mediaId = queue.get(position).getId(); playSong(mediaId); buildMetadata(queue.get(position)); updateQueueDisplay(SKIP_NEXT); buildNotification(MediaPlaybackService.this, queue.get(position)); } } } @Override public void onPrepared(MediaPlayer mediaPlayer) { if(currentState == PlaybackStateCompat.STATE_PLAYING) mediaPlayer.start(); else mediaPlayer.seekTo(elapsed); } @Override public boolean onError(MediaPlayer mediaPlayer, int i, int i1) { if(!queue.isEmpty() && position < queue.size() - 1) { String mediaId = queue.get(position).getId(); playSong(mediaId); buildMetadata(queue.get(position)); updateQueueDisplay(SKIP_NEXT); buildNotification(MediaPlaybackService.this, queue.get(position)); } else { } return false; } /*///////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////*/ @Nullable @Override public BrowserRoot onGetRoot(@NonNull String clientPackageName, int clientUid, @Nullable Bundle rootHints) { return new BrowserRoot(MY_MEDIA_ROOT_ID, null); } @Override public void onLoadChildren(@NonNull String parentId, @NonNull Result<List<MediaBrowserCompat.MediaItem>> result) { ArrayList<MediaBrowserCompat.MediaItem> mediaItems = new ArrayList<>(); MediaBrowserCompat.MediaItem mediaItem; result.sendResult(null); } } <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/helpers/SectionContent.java package com.rookieandroid.rookiemusicplayer.helpers; import com.rookieandroid.rookiemusicplayer.Albums; import com.rookieandroid.rookiemusicplayer.AlbumsSections; import java.util.ArrayList; public class SectionContent { private Albums album; private ArrayList<Albums> albums; private ArrayList<AlbumsSections> albumsSections; private ArrayList<Albums> section0 = new ArrayList<>(); private ArrayList<Albums> sectionA = new ArrayList<>(); private ArrayList<Albums> sectionB = new ArrayList<>(); private ArrayList<Albums> sectionC = new ArrayList<>(); private ArrayList<Albums> sectionD = new ArrayList<>(); private ArrayList<Albums> sectionE = new ArrayList<>(); private ArrayList<Albums> sectionF = new ArrayList<>(); private ArrayList<Albums> sectionG = new ArrayList<>(); private ArrayList<Albums> sectionH = new ArrayList<>(); private ArrayList<Albums> sectionI = new ArrayList<>(); private ArrayList<Albums> sectionJ = new ArrayList<>(); private ArrayList<Albums> sectionK = new ArrayList<>(); private ArrayList<Albums> sectionL = new ArrayList<>(); private ArrayList<Albums> sectionM = new ArrayList<>(); private ArrayList<Albums> sectionN = new ArrayList<>(); private ArrayList<Albums> sectionO = new ArrayList<>(); private ArrayList<Albums> sectionP = new ArrayList<>(); private ArrayList<Albums> sectionQ = new ArrayList<>(); private ArrayList<Albums> sectionR = new ArrayList<>(); private ArrayList<Albums> sectionS = new ArrayList<>(); private ArrayList<Albums> sectionT = new ArrayList<>(); private ArrayList<Albums> sectionU = new ArrayList<>(); private ArrayList<Albums> sectionV = new ArrayList<>(); private ArrayList<Albums> sectionW = new ArrayList<>(); private ArrayList<Albums> sectionX = new ArrayList<>(); private ArrayList<Albums> sectionY = new ArrayList<>(); private ArrayList<Albums> sectionZ = new ArrayList<>(); public SectionContent(ArrayList<Albums> albums, ArrayList<AlbumsSections> albumsSections) { this.albums = albums; this.albumsSections = albumsSections; } public SectionContent(Albums album, ArrayList<AlbumsSections> albumsSections) { this.album = album; this.albumsSections = albumsSections; } public void sectionAlbums() { for(int i = 0; i < albums.size(); i++) { String album = albums.get(i).getAlbum(); char sectionLetter = album.charAt(0); boolean letter = Character.isLetter(sectionLetter); if(!letter) section0.add(albums.get(i)); else addToSection(albums.get(i), sectionLetter); } addAllSections(); } private void addToSection(Albums album, Character letter) { switch(Character.toUpperCase(letter)) { case 'A': sectionA.add(album); break; case 'B': sectionB.add(album); break; case 'C': sectionC.add(album); break; case 'D': sectionD.add(album); break; case 'E': sectionE.add(album); break; case 'F': sectionF.add(album); break; case 'G': sectionG.add(album); break; case 'H': sectionH.add(album); break; case 'I': sectionI.add(album); break; case 'J': sectionJ.add(album); break; case 'K': sectionK.add(album); break; case 'L': sectionL.add(album); break; case 'M': sectionM.add(album); break; case 'N': sectionN.add(album); break; case 'O': sectionO.add(album); break; case 'P': sectionP.add(album); break; case 'Q': sectionQ.add(album); break; case 'R': sectionR.add(album); break; case 'S': sectionS.add(album); break; case 'T': sectionT.add(album); break; case 'U': sectionU.add(album); break; case 'V': sectionV.add(album); break; case 'W': sectionW.add(album); break; case 'X': sectionX.add(album); break; case 'Y': sectionY.add(album); break; case 'Z': sectionZ.add(album); break; } } private void addAllSections() { albumsSections.add(new AlbumsSections(section0, null)); albumsSections.add(new AlbumsSections(sectionA, null)); albumsSections.add(new AlbumsSections(sectionB, null)); albumsSections.add(new AlbumsSections(sectionC, null)); albumsSections.add(new AlbumsSections(sectionD, null)); albumsSections.add(new AlbumsSections(sectionE, null)); albumsSections.add(new AlbumsSections(sectionF, null)); albumsSections.add(new AlbumsSections(sectionG, null)); albumsSections.add(new AlbumsSections(sectionH, null)); albumsSections.add(new AlbumsSections(sectionI, null)); albumsSections.add(new AlbumsSections(sectionJ, null)); albumsSections.add(new AlbumsSections(sectionK, null)); albumsSections.add(new AlbumsSections(sectionL, null)); albumsSections.add(new AlbumsSections(sectionM, null)); albumsSections.add(new AlbumsSections(sectionN, null)); albumsSections.add(new AlbumsSections(sectionO, null)); albumsSections.add(new AlbumsSections(sectionP, null)); albumsSections.add(new AlbumsSections(sectionQ, null)); albumsSections.add(new AlbumsSections(sectionR, null)); albumsSections.add(new AlbumsSections(sectionS, null)); albumsSections.add(new AlbumsSections(sectionT, null)); albumsSections.add(new AlbumsSections(sectionU, null)); albumsSections.add(new AlbumsSections(sectionV, null)); albumsSections.add(new AlbumsSections(sectionW, null)); albumsSections.add(new AlbumsSections(sectionX, null)); albumsSections.add(new AlbumsSections(sectionY, null)); albumsSections.add(new AlbumsSections(sectionZ, null)); } public AlbumsSections getSection() { AlbumsSections section = null; char sectionLetter = album.getAlbum().charAt(0); if(!Character.isLetter(sectionLetter)) section = albumsSections.get(0); else { switch (Character.toString(sectionLetter).toUpperCase()) { case "A": section = albumsSections.get(1); break; case "B": section = albumsSections.get(2); break; case "C": section = albumsSections.get(3); break; case "D": section = albumsSections.get(4); break; case "E": section = albumsSections.get(5); break; case "F": section = albumsSections.get(6); break; case "G": section = albumsSections.get(7); break; case "H": section = albumsSections.get(8); break; case "I": section = albumsSections.get(9); break; case "J": section = albumsSections.get(10); break; case "K": section = albumsSections.get(11); break; case "L": section = albumsSections.get(12); break; case "M": section = albumsSections.get(13); break; case "N": section = albumsSections.get(14); break; case "O": section = albumsSections.get(15); break; case "P": section = albumsSections.get(16); break; case "Q": section = albumsSections.get(17); break; case "R": section = albumsSections.get(18); break; case "S": section = albumsSections.get(19); break; case "T": section = albumsSections.get(20); break; case "U": section = albumsSections.get(21); break; case "V": section = albumsSections.get(22); break; case "W": section = albumsSections.get(23); break; case "X": section = albumsSections.get(24); break; case "Y": section = albumsSections.get(25); break; case "Z": section = albumsSections.get(26); break; } } return section; } } <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/Songs.java package com.rookieandroid.rookiemusicplayer; import android.os.Parcelable; import android.os.Parcel; import androidx.annotation.Nullable; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity(tableName = "saved_queue") public class Songs implements Parcelable { @PrimaryKey(autoGenerate = true) private int rowId; private String id; private String title; private String album; private String albumKey; private String art; private String artist; private String artistKey; private Long duration; private String path; private int track; public Songs(String id, String title, String album, String albumKey, String art, String artist, String artistKey, Long duration, String path, int track) { this.id = id; this.title = title; this.album = album; this.albumKey = albumKey; this.art = art; this.artist = artist; this.artistKey = artistKey; this.duration = duration; this.path = path; this.track = track; } //GETTERS public int getRowId() { return rowId; } public String getId() {return id;} public String getTitle() {return title;} public String getAlbum() {return album;} public String getAlbumKey() {return albumKey;} public String getArt() {return art;} public String getArtist() {return artist;} public String getArtistKey() {return artistKey;} public String getPath() {return path;} public Long getDuration() {return duration;} public int getTrack() {return track;} //SETTERS public void setRowId(int rowId) { this.rowId = rowId; } public void setId(String id) { this.id = id; } public void setTitle(String title) { this.title = title; } public void setAlbum(String album) { this.album = album; } public void setAlbumKey(String albumKey) { this.albumKey = albumKey; } public void setArt(String art) { this.art = art; } public void setArtist(String artist) { this.artist = artist; } public void setArtistKey(String artistKey) { this.artistKey = artistKey; } public void setDuration(Long duration) { this.duration = duration; } public void setPath(String path) { this.path = path; } public void setTrack(int track) { this.track = track; } protected Songs(Parcel in) { id = in.readString(); title = in.readString(); album = in.readString(); albumKey = in.readString(); art = in.readString(); artist = in.readString(); artistKey = in.readString(); path = in.readString(); if (in.readByte() == 0) { duration = null; } else { duration = in.readLong(); } track = in.readInt(); } public static final Creator<Songs> CREATOR = new Creator<Songs>() { @Override public Songs createFromParcel(Parcel in) { return new Songs(in); } @Override public Songs[] newArray(int size) { return new Songs[size]; } }; @Override public int describeContents() {return 0;} @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(id); parcel.writeString(title); parcel.writeString(album); parcel.writeString(albumKey); parcel.writeString(art); parcel.writeString(artist); parcel.writeString(artistKey); parcel.writeString(path); if (duration == null) { parcel.writeByte((byte) 0); } else { parcel.writeByte((byte) 1); parcel.writeLong(duration); } parcel.writeInt(track); } } <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/fragments/AlbumsFragment.java package com.rookieandroid.rookiemusicplayer.fragments; import android.content.Context; import android.os.Bundle; import android.transition.Fade; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.SharedElementCallback; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.rookieandroid.rookiemusicplayer.Albums; import com.rookieandroid.rookiemusicplayer.AlbumsSections; import com.rookieandroid.rookiemusicplayer.helpers.IndexScroller; import com.rookieandroid.rookiemusicplayer.helpers.MediaControlDialog; import com.rookieandroid.rookiemusicplayer.R; import com.rookieandroid.rookiemusicplayer.adapters.AlbumsAdapter; import com.rookieandroid.rookiemusicplayer.adapters.AlbumsSectionsAdapter; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.rookieandroid.rookiemusicplayer.App.ARTIST_DETAIL; import static com.rookieandroid.rookiemusicplayer.App.FROM_ARTIST; import static com.rookieandroid.rookiemusicplayer.App.FROM_LIBRARY; import static com.rookieandroid.rookiemusicplayer.App.FROM_SEARCH; import static com.rookieandroid.rookiemusicplayer.App.SEARCH; import static com.rookieandroid.rookiemusicplayer.App.lettersAlbums; import static com.rookieandroid.rookiemusicplayer.App.sectionsAlbums; public class AlbumsFragment extends Fragment implements AlbumsAdapter.ListItemClickListener { private View rootView; private AlbumsSectionsAdapter albumsSectionsAdapter; private AlbumsAdapter albumsAdapter; private RecyclerView recyclerView; private ArrayList<AlbumsSections> albumsSections; private ArrayList<Albums> albums; private NowPlayingAlbum nowPlayingAlbum; private MediaControlDialog mediaControlDialog; private IndexScroller indexScroller; private int code; private int from; private int position; private MediaControlDialog.UpdateLibrary updateLibrary; public AlbumsFragment(ArrayList<AlbumsSections> albumsSections, MediaControlDialog.UpdateLibrary updateLibrary) { this.albumsSections = albumsSections; this.updateLibrary = updateLibrary; } public AlbumsFragment(ArrayList<Albums> albums, int code, MediaControlDialog.UpdateLibrary updateLibrary) { this.albums = albums; this.code = code; this.updateLibrary = updateLibrary; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setSharedElementEnterTransition(new App.DetailsTransition().setDuration(500)); //setSharedElementReturnTransition(new App.DetailsTransition()); setExitSharedElementCallback(new SharedElementCallback() { @Override public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) { RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(position); if(viewHolder == null) return; sharedElements.put(names.get(0), viewHolder.itemView.findViewById(R.id.gridArt)); } }); setExitTransition(new Fade()); setReenterTransition(new Fade().setStartDelay(500)); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); rootView = getLayoutInflater().inflate(R.layout.fragment_albums, container, false); recyclerView = rootView.findViewById(R.id.albumSections); switch (code) { case ARTIST_DETAIL: albumsAdapter = new AlbumsAdapter(albums, this, this); GridLayoutManager gridlayoutManager1 = new GridLayoutManager(getContext(), 2); recyclerView.setLayoutManager(gridlayoutManager1); recyclerView.setAdapter(albumsAdapter); rootView.findViewById(R.id.indexScroller).setVisibility(View.GONE); rootView.findViewById(R.id.indexLetter).setVisibility(View.GONE); from = FROM_ARTIST; break; case SEARCH: albumsAdapter = new AlbumsAdapter(albums, this, this); GridLayoutManager gridlayoutManager2 = new GridLayoutManager(getContext(), 2); recyclerView.setLayoutManager(gridlayoutManager2); recyclerView.setAdapter(albumsAdapter); rootView.findViewById(R.id.indexScroller).setVisibility(View.GONE); rootView.findViewById(R.id.indexLetter).setVisibility(View.GONE); from = FROM_SEARCH; break; default: albumsAdapter = new AlbumsAdapter(albums, this, this); //albumsSectionsAdapter = new AlbumsSectionsAdapter(albumsSections,this); //LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()); GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2); layoutManager.setInitialPrefetchItemCount(albums.size()); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(albumsAdapter); //rootView.findViewById(R.id.indexLetter).setVisibility(View.GONE); indexScroller = new IndexScroller(getContext(), rootView, recyclerView, layoutManager, sectionsAlbums, lettersAlbums); indexScroller.setScrolling(); from = FROM_LIBRARY; break; } postponeEnterTransition(); return rootView; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); /*recyclerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { recyclerView.removeOnLayoutChangeListener(this); final RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); View viewAtPosition = layoutManager.findViewByPosition(position); // Scroll to position if the view for the current position is null (not currently part of // layout manager children), or it's not completely visible. if (viewAtPosition == null || layoutManager.isViewPartiallyVisible(viewAtPosition, false, true)) { recyclerView.post(() -> layoutManager.scrollToPosition(position)); } } });*/ } @Override public void onListItemClick(Albums album, ImageView art, int position) { this.position = position; nowPlayingAlbum.sendAlbum(album, art, from, updateLibrary, position); } @Override public void onLongItemClick(Albums album) { if(code != SEARCH) { if(code == ARTIST_DETAIL) { mediaControlDialog = new MediaControlDialog(getContext(), album, albums, albumsAdapter, updateLibrary, FROM_ARTIST); mediaControlDialog.OpenDialog(); } else { /*SectionContent sectionContent = new SectionContent(album, albumsSections); AlbumsSections section = sectionContent.getSection(); albums = section.getSectionedAlbums(); albumsAdapter = section.getAlbumsAdapter();*/ mediaControlDialog = new MediaControlDialog(getContext(), album, albums, albumsAdapter, updateLibrary, FROM_LIBRARY); mediaControlDialog.OpenDialog(); } } } public interface NowPlayingAlbum { void sendAlbum(Albums album, ImageView sharedArt, int from, MediaControlDialog.UpdateLibrary updateLibrary, int position); } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); try { nowPlayingAlbum = (NowPlayingAlbum) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString().trim() + " must implement sendAlbum"); } } } <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/adapters/AlbumDetailsAdapter.java package com.rookieandroid.rookiemusicplayer.adapters; import android.content.Context; import android.os.Handler; import android.support.v4.media.session.PlaybackStateCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.rookieandroid.rookiemusicplayer.R; import com.rookieandroid.rookiemusicplayer.Songs; import java.util.ArrayList; import java.util.Locale; import static com.rookieandroid.rookiemusicplayer.App.currentState; public class AlbumDetailsAdapter extends RecyclerView.Adapter<AlbumDetailsAdapter.AlbumDetailsViewHolder> { private ArrayList<Songs> songs; private Context context; private ListItemClickListener listener; private int previousPosition; private int currentlyPlaying = 1; private ImageView currentSong; private ImageView previousSong; private int position; private Handler playingHandler = new Handler(); public interface ListItemClickListener { void onListItemClick(int position); void onLongListItemClick(int position); } public AlbumDetailsAdapter(ArrayList<Songs> songs, ListItemClickListener listener) { this.songs = songs; this.listener = listener; setHasStableIds(true); } @NonNull @Override public AlbumDetailsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.album_songs_list, parent, false); return new AlbumDetailsViewHolder(view); } @Override public void onBindViewHolder(@NonNull AlbumDetailsViewHolder holder, int position) { holder.bind(position); } @Override public int getItemCount() { return songs.size(); } @Override public int getItemViewType(int position) { return Integer.parseInt(songs.get(position).getId()); } @Override public long getItemId(int position) { return Integer.parseInt(songs.get(position).getId()); } private Runnable updateTrackPlaying = new Runnable() { @Override public void run() { if(currentState == PlaybackStateCompat.STATE_PLAYING) { switch(currentlyPlaying) { case 1: currentSong.setBackgroundColor(context.getColor(R.color.black)); currentSong.setImageResource(R.drawable.ic_currentlyplaying2); currentlyPlaying = 2; break; case 2: currentSong.setBackgroundColor(context.getColor(R.color.black)); currentSong.setImageResource(R.drawable.ic_currentlyplaying3); currentlyPlaying = 3; break; case 3: currentSong.setBackgroundColor(context.getColor(R.color.black)); currentSong.setImageResource(R.drawable.ic_currentlyplaying4); currentlyPlaying = 4; break; case 4: currentSong.setBackgroundColor(context.getColor(R.color.black)); currentSong.setImageResource(R.drawable.ic_currentlyplaying1); currentlyPlaying = 1; break; } playingHandler.postDelayed(this, 300); } else { currentSong.setBackgroundColor(context.getColor(R.color.black)); currentSong.setImageResource(R.drawable.ic_currentlyplaying1); currentlyPlaying = 1; playingHandler.post(this); } } }; class AlbumDetailsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { private TextView trackName; private TextView trackDuration; private TextView trackNumber; private TextView trackNumberOffset; private ImageView trackPlaying; public AlbumDetailsViewHolder(@NonNull View itemView) { super(itemView); trackName = itemView.findViewById(R.id.trackName); trackDuration = itemView.findViewById(R.id.trackDuration); trackNumber = itemView.findViewById(R.id.trackNumber); trackNumberOffset = itemView.findViewById(R.id.trackNumberOffset); trackPlaying = itemView.findViewById(R.id.trackPlaying); itemView.setOnClickListener(this); itemView.setOnLongClickListener(this); } public void bind(int position) { trackName.setText(songs.get(position).getTitle()); String duration; long minutes = (songs.get(position).getDuration() / 1000) / 60; long seconds = (songs.get(position).getDuration() / 1000) % 60; if(seconds > 9) duration = String.format(Locale.US, "%d:%d", minutes, seconds); else duration = String.format(Locale.US, "%d:%d%d", minutes, 0, seconds); trackDuration.setText(duration); setTrackNumber(songs.get(position).getTrack()); } private void setTrackNumber(int trackNum) { if(trackNum == 0 || trackNum == -1) trackNumber.setText(""); else if(trackNum > 1000) { if((trackNum - 1000) > 9) trackNumberOffset.setVisibility(View.GONE); trackNumber.setText(String.valueOf(trackNum - 1000)); } else { if(trackNum > 9) trackNumberOffset.setVisibility(View.GONE); trackNumber.setText(trackNum + ""); } } @Override public void onClick(View view) { /*if(previousSong == null) { previousSong = trackPlaying; previousPosition = getAdapterPosition(); } else { playingHandler.removeCallbacks(updateTrackPlaying); previousSong.setBackgroundColor(context.getColor(R.color.transparent)); previousSong.setImageResource(0); previousSong = trackPlaying; previousPosition = getAdapterPosition(); }*/ position = getAdapterPosition(); listener.onListItemClick(position); /*currentSong = trackPlaying; currentSong.setBackgroundColor(context.getColor(R.color.black)); currentSong.setImageResource(R.drawable.ic_currentlyplaying2); currentlyPlaying = 1; playingHandler.post(updateTrackPlaying);*/ } @Override public boolean onLongClick(View view) { int clickedPosition = getAdapterPosition(); listener.onLongListItemClick(clickedPosition); return true; } } } <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/architecture/StateRepository.java package com.rookieandroid.rookiemusicplayer.architecture; import android.app.Application; import android.os.AsyncTask; import androidx.lifecycle.LiveData; import com.rookieandroid.rookiemusicplayer.SavedStateDetails; import com.rookieandroid.rookiemusicplayer.Songs; import java.util.List; public class StateRepository { private SavedQueueDao savedQueueDao; private SavedDetailsDao savedDetailsDao; private LiveData<List<Songs>> savedQueue; private LiveData<List<SavedStateDetails>> savedStateDetails; public StateRepository(Application application) { StateDatabase stateDatabase = StateDatabase.getInstance(application); savedQueueDao = stateDatabase.savedQueueDao(); savedDetailsDao = stateDatabase.savedDetailsDao(); savedQueue = savedQueueDao.getSavedQueue(); savedStateDetails = savedDetailsDao.getSavedDetails(); } public void insertAll(List<Songs> savedQueue) { new InsertAllQueueAsyncTask(savedQueueDao).execute(savedQueue); } public void deleteSavedQueue() { new DeleteSavedQueueAsyncTask(savedQueueDao).execute(); } public void insert(SavedDetails savedDetails) { new InsertDetailsAsyncTask(savedDetailsDao).execute(savedDetails); } public void update(SavedDetails savedDetails) { new UpdateDetailsAsyncTask(savedDetailsDao).execute(savedDetails); } public void delete(SavedDetails savedDetails) { new DeleteDetailsAsyncTask(savedDetailsDao).execute(savedDetails); } public void deleteSavedDetails() { new DeleteDetailsAsyncTask(savedDetailsDao).execute(); } public LiveData<List<Songs>> getSavedQueue() { return savedQueue; } public LiveData<List<SavedStateDetails>> getSavedStateDetails() { return savedStateDetails; } private static class InsertAllQueueAsyncTask extends AsyncTask<List<Songs>, Void, Void> { private SavedQueueDao savedQueueDao; private InsertAllQueueAsyncTask(SavedQueueDao savedQueueDao) { this.savedQueueDao = savedQueueDao; } @Override protected Void doInBackground(List<Songs>... lists) { savedQueueDao.insertAll(lists[0]); return null; } } private static class DeleteSavedQueueAsyncTask extends AsyncTask<Void, Void, Void> { private SavedQueueDao savedQueueDao; private DeleteSavedQueueAsyncTask(SavedQueueDao savedQueueDao) { this.savedQueueDao = savedQueueDao; } @Override protected Void doInBackground(Void... voids) { savedQueueDao.deleteSavedQueue(); return null; } } private static class InsertDetailsAsyncTask extends AsyncTask<SavedDetails, Void, Void> { private SavedDetailsDao savedDetailsDao; private InsertDetailsAsyncTask(SavedDetailsDao savedDetailsDao) { this.savedDetailsDao = savedDetailsDao; } @Override protected Void doInBackground(SavedDetails... savedDetails) { savedDetailsDao.insert(savedDetails[0]); return null; } } private static class UpdateDetailsAsyncTask extends AsyncTask<SavedDetails, Void, Void> { private SavedDetailsDao savedDetailsDao; private UpdateDetailsAsyncTask(SavedDetailsDao savedDetailsDao) { this.savedDetailsDao = savedDetailsDao; } @Override protected Void doInBackground(SavedDetails... savedDetails) { savedDetailsDao.update(savedDetails[0]); return null; } } private static class DeleteDetailsAsyncTask extends AsyncTask<SavedDetails, Void, Void> { private SavedDetailsDao savedDetailsDao; private DeleteDetailsAsyncTask(SavedDetailsDao savedDetailsDao) { this.savedDetailsDao = savedDetailsDao; } @Override protected Void doInBackground(SavedDetails... savedDetails) { savedDetailsDao.delete(savedDetails[0]); return null; } } private static class DeleteSavedDetailsAsyncTask extends AsyncTask<Void, Void, Void> { private SavedDetailsDao savedDetailsDao; private DeleteSavedDetailsAsyncTask(SavedDetailsDao savedDetailsDao) { this.savedDetailsDao = savedDetailsDao; } @Override protected Void doInBackground(Void... voids) { savedDetailsDao.deleteSavedDetails(); return null; } } } <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/fragments/PlaylistDetailsFragment.java package com.rookieandroid.rookiemusicplayer.fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.loader.app.LoaderManager; import androidx.loader.content.Loader; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.rookieandroid.rookiemusicplayer.App; import com.rookieandroid.rookiemusicplayer.helpers.GetMedia; import com.rookieandroid.rookiemusicplayer.helpers.MediaControlDialog; import com.rookieandroid.rookiemusicplayer.Playlists; import com.rookieandroid.rookiemusicplayer.R; import com.rookieandroid.rookiemusicplayer.Songs; import com.rookieandroid.rookiemusicplayer.adapters.PlaylistsAdapter; import com.rookieandroid.rookiemusicplayer.adapters.SongsAdapter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import static com.rookieandroid.rookiemusicplayer.App.CLEAR; import static com.rookieandroid.rookiemusicplayer.App.FROM_PLAYLIST; import static com.rookieandroid.rookiemusicplayer.App.GET_PLAYLIST_SONGS; import static com.rookieandroid.rookiemusicplayer.App.GET_RECENT_SONGS; import static com.rookieandroid.rookiemusicplayer.App.PLAYLIST_MEDIA_LOADER; import static com.rookieandroid.rookiemusicplayer.App.RECENTLY_ADDED; import static com.rookieandroid.rookiemusicplayer.App.SET_POSITION; import static com.rookieandroid.rookiemusicplayer.App.SET_QUEUE_PLAYLIST; import static com.rookieandroid.rookiemusicplayer.App.SET_UP_NEXT; import static com.rookieandroid.rookiemusicplayer.App.SHUFFLE_QUEUE; import static com.rookieandroid.rookiemusicplayer.App.mediaBrowserHelper; import static com.rookieandroid.rookiemusicplayer.App.nowPlayingFrom; public class PlaylistDetailsFragment extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList>, SongsAdapter.ListItemClickListener, View.OnClickListener, MediaControlDialog.UpdatePlaylist { private final String TAG = PlaylistDetailsFragment.class.getSimpleName(); private View rootView; private Playlists currentPlaylist; private ArrayList<Songs> playlistSongs; private SongsAdapter playlistSongsAdapter; private RecyclerView recyclerView; private TextView playlistName; private TextView playlistCount; private TextView playlistDescription; private Button playAlbum; private Button shuffleAlbum; private ImageView albumMediaControl; private MediaControlDialog mediaControlDialog; public PlaylistDetailsFragment(Playlists currentPlaylist) { this.currentPlaylist = currentPlaylist; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); rootView = inflater.inflate(R.layout.fragment_playlist_details, container, false); playlistName = rootView.findViewById(R.id.albumDetailName); playlistName.setText(currentPlaylist.getPlaylist()); playlistCount = rootView.findViewById(R.id.numberOfSongs); rootView.findViewById(R.id.albumDetailArtist).setVisibility(View.GONE); playlistDescription = rootView.findViewById(R.id.playlistDescription); playlistDescription.setText(currentPlaylist.getDescription()); playAlbum = rootView.findViewById(R.id.playAlbum); playAlbum.setOnClickListener(this); shuffleAlbum = rootView.findViewById(R.id.shuffleAlbum); shuffleAlbum.setOnClickListener(this); albumMediaControl = rootView.findViewById(R.id.albumMediaControl); albumMediaControl.setOnClickListener(this); recyclerView = rootView.findViewById(R.id.albumDetailSongs); LoaderManager.getInstance(this).initLoader(PLAYLIST_MEDIA_LOADER, null, this); //Log.i(TAG, "FRAGMENT CURRENTLY VISIBLE: " + TAG); return rootView; } private void setQueue(int position) { mediaBrowserHelper.getMediaController().getTransportControls().sendCustomAction(CLEAR, null); Bundle queue = new Bundle(); queue.putInt("CURRENT_QUEUE_POSITION", position); if(currentPlaylist.getPlaylist().equals("Recently Added")) queue.putInt("FROM", RECENTLY_ADDED); else queue.putInt("FROM", FROM_PLAYLIST); mediaBrowserHelper.getMediaController().getTransportControls().sendCustomAction(SET_POSITION, queue); mediaBrowserHelper.getMediaController().getTransportControls().sendCustomAction(SET_QUEUE_PLAYLIST, queue); mediaBrowserHelper.getMediaController().getTransportControls().playFromMediaId(playlistSongs.get(position).getId(), null); mediaBrowserHelper.getMediaController().getTransportControls().sendCustomAction(SET_UP_NEXT, null); nowPlayingFrom = "Now playing from " + currentPlaylist.getPlaylist(); mediaBrowserHelper.setBottomSheetQueue(); } private void setPlaylistCount() { int pCount = playlistSongs.size(); String count; if(pCount == 1) { count = pCount + " song"; playlistCount.setText(count); } else { count = pCount + " songs"; playlistCount.setText(count); } } @Override public void onClick(View view) { Bundle from = new Bundle(); switch (view.getId()) { case R.id.playAlbum: Collections.sort(playlistSongs, Comparator.comparing(Songs::getTrack)); App.playlistSongs = playlistSongs; setQueue(0); break; case R.id.shuffleAlbum: Collections.shuffle(playlistSongs); App.playlistSongs = playlistSongs; setQueue(0); if(currentPlaylist.getPlaylist().equals("Recently Added")) from.putInt("FROM", RECENTLY_ADDED); else from.putInt("FROM", FROM_PLAYLIST); mediaBrowserHelper.getMediaController().getTransportControls().sendCustomAction(SHUFFLE_QUEUE, from); break; case R.id.albumMediaControl: ArrayList<Playlists> playlists = null; PlaylistsAdapter playlistsAdapter = null; mediaControlDialog = new MediaControlDialog(getContext(), currentPlaylist, playlists, playlistsAdapter, FROM_PLAYLIST); mediaControlDialog.OpenDialog(); break; } } @Override public void onListItemClick(int position) { Collections.sort(playlistSongs, Comparator.comparing(Songs::getTrack)); Collections.reverse(playlistSongs); App.playlistSongs = playlistSongs; setQueue(position); } @Override public void onLongListItemClick(int position) { if(!currentPlaylist.getPlaylist().equals("Recently Added")) { mediaControlDialog = new MediaControlDialog(getContext(), playlistSongs.get(position), currentPlaylist, playlistSongs, playlistSongsAdapter, this, FROM_PLAYLIST); mediaControlDialog.OpenDialog(); } } @Override public void updatePlaylistCount() { setPlaylistCount(); } @NonNull @Override public Loader<ArrayList> onCreateLoader(int id, @Nullable Bundle args) { if(currentPlaylist.getPlaylist().equals("Recently Added")) { return new GetMedia(getContext(), GET_RECENT_SONGS, -1); //playlistSongs = getMedia.getRecentlyAddedSongs(); } else { return new GetMedia(getContext(), GET_PLAYLIST_SONGS, -1, currentPlaylist); //playlistSongs = getMedia.getPlaylistSongs(currentPlaylist); } } @Override public void onLoadFinished(@NonNull Loader<ArrayList> loader, ArrayList data) { playlistSongs = (ArrayList<Songs>) data; setPlaylistCount(); LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()); playlistSongsAdapter = new SongsAdapter(playlistSongs, this); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(playlistSongsAdapter); } @Override public void onLoaderReset(@NonNull Loader<ArrayList> loader){} } <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/architecture/SavedDetailsDao.java package com.rookieandroid.rookiemusicplayer.architecture; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import com.rookieandroid.rookiemusicplayer.SavedStateDetails; import java.util.List; @Dao public interface SavedDetailsDao { @Insert void insert(SavedDetails savedDetails); @Delete void delete(SavedDetails savedDetails); @Update void update(SavedDetails savedDetails); @Query("DELETE FROM saved_details") void deleteSavedDetails(); @Query("SELECT * FROM saved_details") LiveData<List<SavedStateDetails>> getSavedDetails(); } <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/helpers/MediaBrowserHelperMotion.java package com.rookieandroid.rookiemusicplayer.helpers; import android.app.Activity; import android.content.ComponentName; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.res.ColorStateList; import android.media.AudioManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.os.ResultReceiver; import android.provider.MediaStore; import android.support.v4.media.MediaBrowserCompat; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaControllerCompat; import android.support.v4.media.session.MediaSessionCompat; import android.support.v4.media.session.PlaybackStateCompat; import android.view.View; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.cardview.widget.CardView; import androidx.constraintlayout.motion.widget.MotionLayout; import androidx.loader.app.LoaderManager; import androidx.loader.content.Loader; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.rookieandroid.rookiemusicplayer.Albums; import com.rookieandroid.rookiemusicplayer.Artists; import com.rookieandroid.rookiemusicplayer.MainActivity; import com.rookieandroid.rookiemusicplayer.MediaPlaybackService; import com.rookieandroid.rookiemusicplayer.Playlists; import com.rookieandroid.rookiemusicplayer.R; import com.rookieandroid.rookiemusicplayer.Songs; import com.rookieandroid.rookiemusicplayer.adapters.QueueAdapter; import com.rookieandroid.rookiemusicplayer.architecture.SavedDetails; import com.rookieandroid.rookiemusicplayer.architecture.StateViewModel; import java.util.ArrayList; import java.util.List; import java.util.Locale; import static com.rookieandroid.rookiemusicplayer.App.ACTIVITY_RESTORE; import static com.rookieandroid.rookiemusicplayer.App.ADD_ALBUM_ARTIST_PLAYLIST; import static com.rookieandroid.rookiemusicplayer.App.ADD_SONG; import static com.rookieandroid.rookiemusicplayer.App.CLEAR; import static com.rookieandroid.rookiemusicplayer.App.FROM_LIBRARY; import static com.rookieandroid.rookiemusicplayer.App.GET_ALBUM_SONGS; import static com.rookieandroid.rookiemusicplayer.App.GET_ARTIST_SONGS; import static com.rookieandroid.rookiemusicplayer.App.GET_CURRENT_POSITION; import static com.rookieandroid.rookiemusicplayer.App.GET_ARTIST_ALBUM; import static com.rookieandroid.rookiemusicplayer.App.GET_PLAYLIST_SONGS; import static com.rookieandroid.rookiemusicplayer.App.GET_QUEUE_POSITION; import static com.rookieandroid.rookiemusicplayer.App.INITIALIZE_QUEUE_CHANGE; import static com.rookieandroid.rookiemusicplayer.App.PLAYLIST_MEDIA_LOADER; import static com.rookieandroid.rookiemusicplayer.App.PLAY_BUTTON_START; import static com.rookieandroid.rookiemusicplayer.App.QUEUE_CLICK; import static com.rookieandroid.rookiemusicplayer.App.QUEUE_END; import static com.rookieandroid.rookiemusicplayer.App.BROWSER_MEDIA_LOADER; import static com.rookieandroid.rookiemusicplayer.App.QUEUE_NEXT; import static com.rookieandroid.rookiemusicplayer.App.RECEIVE_ARTIST_ALBUM; import static com.rookieandroid.rookiemusicplayer.App.RECEIVE_PLAYBACKSTATE; import static com.rookieandroid.rookiemusicplayer.App.RECEIVE_QUEUE_POSITION; import static com.rookieandroid.rookiemusicplayer.App.RESTORE_SAVED_QUEUE; import static com.rookieandroid.rookiemusicplayer.App.SAVE_QUEUE; import static com.rookieandroid.rookiemusicplayer.App.SET_ELAPSED_TIME; import static com.rookieandroid.rookiemusicplayer.App.SET_FROM; import static com.rookieandroid.rookiemusicplayer.App.SET_POSITION; import static com.rookieandroid.rookiemusicplayer.App.SET_QUEUE_LIBRARY; import static com.rookieandroid.rookiemusicplayer.App.SET_UP_NEXT; import static com.rookieandroid.rookiemusicplayer.App.addToQueue; import static com.rookieandroid.rookiemusicplayer.App.currentState; import static com.rookieandroid.rookiemusicplayer.App.itemTouchHelper; import static com.rookieandroid.rookiemusicplayer.App.nowPlayingFrom; import static com.rookieandroid.rookiemusicplayer.App.queueAdapter; import static com.rookieandroid.rookiemusicplayer.App.queueDisplay; import static com.rookieandroid.rookiemusicplayer.App.repeat; import static com.rookieandroid.rookiemusicplayer.App.savedSongs; import static com.rookieandroid.rookiemusicplayer.App.savedState; import static com.rookieandroid.rookiemusicplayer.App.shuffle; public class MediaBrowserHelperMotion implements QueueAdapter.ListItemClickListener { private final String TAG = MediaBrowserHelperMotion.class.getSimpleName(); private Context context; private MediaBrowserCompat mediaBrowserCompat; private MediaControllerCompat mediaControllerCompat; private int currentDuration; private int currentElapsed; private Songs artist_album; //ADDING TO QUEUE OR PLAYLIST private int content; private Songs song; private Albums album; private ArrayList<Songs> albumSongs; private Artists artist; private ArrayList<Songs> artistSongs; private Playlists playlist; private Playlists playlistToAdd; private ArrayList<Songs> playlistSongs; //UI private View rootView; private Handler timeHandler = new Handler(); private AudioManager audioManager; private RecyclerView recyclerView; private ImageView nowPlayingArt; private CardView nowPlayingArtHolder; private TextView nowPlayingName; private TextView nowPlayingArtist; private ImageButton nowPlayingButton; private ImageButton nowPlayingForward; private MotionLayout motionLayout; private FrameLayout frameLayout; private TextView nowPlayingNameExpanded; private TextView nowPlayingArtistAlbumExpanded; private TextView nowPlayingDurationExpanded; private TextView nowPlayingElapsedExpanded; private TextView nowPlayingFromExpanded; private ImageButton nowPlayingButtonExpanded; private ImageButton nowPlayingBackExpanded; private ImageButton nowPlayingForwardExpanded; private ImageButton nowPlayingSlideDown; private ProgressBar progressBar; private SeekBar seekBar; private SeekBar volumeBar; private Button shuffleExpanded; private View shuffleBackground; private Button repeatExpanded; private View repeatBackground; private ImageView upNextQueue; private ImageView upNextBackground; private ImageView upNextShuffle; private View upNextShuffleBackground; private ImageView upNextRepeat; private View upNextRepeatBackground; private boolean upNextIsShowing; //SAVING UI STATE private int savedPosition; private int savedElapsed; private int savedDuration; private int savedShuffle; private int savedRepeat; private int savedPlayState; private String savedNowPlayingFrom; private int savedFrom; private StateViewModel stateViewModel; public MediaBrowserHelperMotion(Context context, View rootView, StateViewModel stateViewModel) { this.context = context; this.rootView = rootView; this.stateViewModel = stateViewModel; } public void onCreate() { mediaBrowserCompat = new MediaBrowserCompat(context, new ComponentName(context, MediaPlaybackService.class), connectionCallbacks, null); mediaBrowserCompat.connect(); } public void onRestart() { if(!mediaBrowserCompat.isConnected()) mediaBrowserCompat.connect(); } public void onStop() { mediaControllerCompat.sendCommand(GET_QUEUE_POSITION, null, resultReceiver); } public void onDestroy() { if (MediaControllerCompat.getMediaController((Activity) context) != null) MediaControllerCompat.getMediaController((Activity) context).unregisterCallback(controllerCallbacks); mediaBrowserCompat.unsubscribe(mediaBrowserCompat.getRoot()); mediaBrowserCompat.disconnect(); } public void setVolumeBar() { int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); volumeBar.setProgress(currentVolume); } private final MediaBrowserCompat.ConnectionCallback connectionCallbacks = new MediaBrowserCompat.ConnectionCallback() { @Override public void onConnected() { String root = mediaBrowserCompat.getRoot(); mediaBrowserCompat.subscribe(root, subscriptionCallbacks); try { // Get the token for the MediaSession MediaSessionCompat.Token token = mediaBrowserCompat.getSessionToken(); // Create a MediaControllerCompat mediaControllerCompat = new MediaControllerCompat(context, token); mediaControllerCompat.registerCallback(controllerCallbacks); mediaControllerCompat.getTransportControls().setShuffleMode(PlaybackStateCompat.SHUFFLE_MODE_NONE); mediaControllerCompat.getTransportControls().setRepeatMode(PlaybackStateCompat.REPEAT_MODE_NONE); // Save the controller MediaControllerCompat.setMediaController((Activity) context, mediaControllerCompat); } catch (RemoteException e) { /*Log.e(MainActivity.class.getSimpleName(), "Error creating controller", e);*/ } // Finish building the UI buildTransportControls(); if(!savedSongs.isEmpty() && !savedState.isEmpty()) { if(currentState != PlaybackStateCompat.STATE_PLAYING) { savedPosition = savedState.get(0).getPosition(); savedElapsed = savedState.get(0).getElapsed(); savedDuration = savedState.get(0).getDuration(); savedFrom = savedState.get(0).getFrom(); shuffle = savedState.get(0).getShuffle(); mediaControllerCompat.getTransportControls().setShuffleMode(shuffle); repeat = savedState.get(0).getRepeat(); mediaControllerCompat.getTransportControls().setRepeatMode(repeat); currentState = savedState.get(0).getState(); nowPlayingFrom = savedState.get(0).getNow_playing_from(); mediaControllerCompat.getTransportControls().sendCustomAction(CLEAR, null); Bundle queuePosition = new Bundle(); queuePosition.putInt("CURRENT_QUEUE_POSITION", savedPosition); Bundle elapsedTime = new Bundle(); elapsedTime.putInt("CURRENT_ELAPSED_TIME", savedElapsed); Bundle from = new Bundle(); from.putInt("CURRENT_FROM", savedFrom); mediaControllerCompat.getTransportControls().sendCustomAction(SET_POSITION, queuePosition); mediaControllerCompat.getTransportControls().sendCustomAction(SET_FROM, from); mediaControllerCompat.getTransportControls().sendCustomAction(RESTORE_SAVED_QUEUE, null); mediaControllerCompat.getTransportControls().sendCustomAction(SET_ELAPSED_TIME, elapsedTime); progressBar.setMax(savedDuration); seekBar.setMax(savedDuration); String duration = calculateTime(savedDuration); nowPlayingDurationExpanded.setText(duration); progressBar.setProgress(savedElapsed); seekBar.setProgress(savedElapsed); String elapsed = calculateTime(savedElapsed); nowPlayingElapsedExpanded.setText(elapsed); } mediaControllerCompat.getTransportControls().sendCustomAction(ACTIVITY_RESTORE, null); mediaControllerCompat.getTransportControls().sendCustomAction(SET_UP_NEXT, null); setBottomSheetQueue(); } } @Override public void onConnectionSuspended() { // The Service has crashed. Disable transport controls until it automatically reconnects } @Override public void onConnectionFailed() { // The Service has refused our connection } }; private final MediaBrowserCompat.SubscriptionCallback subscriptionCallbacks = new MediaBrowserCompat.SubscriptionCallback() { @Override public void onChildrenLoaded(@NonNull String parentId, @NonNull List<MediaBrowserCompat.MediaItem> children) { super.onChildrenLoaded(parentId, children); if(children == null || children.isEmpty()) return; MediaBrowserCompat.MediaItem firstItem = children.get(0); // Play the first item? // Probably should check firstItem.isPlayable() } }; private Runnable updateTime = new Runnable() { @Override public void run() { if(currentState == PlaybackStateCompat.STATE_PLAYING) { mediaControllerCompat.sendCommand(GET_CURRENT_POSITION, null, new ResultReceiver(new Handler()) { @Override protected void onReceiveResult(int resultCode, Bundle resultData) { super.onReceiveResult(resultCode, resultData); currentElapsed = resultData.getInt("currentPosition"); progressBar.setProgress(currentElapsed); seekBar.setProgress(currentElapsed); String elapsedTime = calculateTime(currentElapsed); nowPlayingElapsedExpanded.setText(elapsedTime); } }); timeHandler.postDelayed(this, 1000); } } }; private final ResultReceiver resultReceiver = new ResultReceiver(new Handler()) { @Override protected void onReceiveResult(int resultCode, Bundle resultData) { super.onReceiveResult(resultCode, resultData); switch (resultCode) { /*case RECEIVE_CURRENT_POSITION: currentElapsed = resultData.getInt("currentPosition"); progressBar.setProgress(currentElapsed); seekBar.setProgress(currentElapsed); String elapsedTime = calculateTime(currentElapsed); nowPlayingElapsedExpanded.setText(elapsedTime); break;*/ case RECEIVE_ARTIST_ALBUM: artist_album = resultData.getParcelable("currentArtistAlbum"); GoToDialog goToDialog = new GoToDialog(context, artist_album); goToDialog.OpenDialog(); break; case RECEIVE_QUEUE_POSITION: savedPosition = resultData.getInt("queuePosition"); savedShuffle = shuffle; savedRepeat = repeat; savedPlayState = currentState; savedElapsed = resultData.getInt("currentElapsed"); savedDuration = currentDuration; savedNowPlayingFrom = nowPlayingFrom; savedFrom = resultData.getInt("currentFrom"); SavedDetails details = new SavedDetails(savedPosition, savedShuffle, savedRepeat, savedPlayState, savedElapsed, savedDuration, savedNowPlayingFrom, savedFrom); if(savedState.isEmpty()) stateViewModel.insert(details); else { details.setId(savedState.get(0).getId()); stateViewModel.update(details); } mediaControllerCompat.getTransportControls().sendCustomAction(SAVE_QUEUE, null); break; case RECEIVE_PLAYBACKSTATE: int state = resultData.getInt("currentState"); break; } } }; private final MediaControllerCompat.Callback controllerCallbacks = new MediaControllerCompat.Callback() { @Override public void onMetadataChanged(MediaMetadataCompat metadata) { super.onMetadataChanged(metadata); Uri uri = Uri.parse(metadata.getString(MediaMetadataCompat.METADATA_KEY_ART_URI)); Glide.with(context).load(uri).fallback(R.drawable.noalbumart).error(R.drawable.noalbumart).override(400).into(nowPlayingArt); if(motionLayout.getCurrentState() == R.id.end && currentState == PlaybackStateCompat.STATE_PLAYING) nowPlayingArtHolder.setCardElevation(30); nowPlayingName.setText(metadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE)); nowPlayingArtist.setText(metadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST)); nowPlayingNameExpanded.setText(metadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE)); String artist = metadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST); String album = metadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM); String expanded = artist + " - " + album; nowPlayingArtistAlbumExpanded.setText(expanded); if (currentState == PlaybackStateCompat.STATE_PLAYING) { nowPlayingButton.setBackground(context.getResources().getDrawable(R.drawable.ic_pause)); nowPlayingButtonExpanded.setBackground(context.getResources().getDrawable(R.drawable.ic_pause)); } else { nowPlayingButton.setBackground(context.getResources().getDrawable(R.drawable.ic_play)); nowPlayingButtonExpanded.setBackground(context.getResources().getDrawable(R.drawable.ic_play)); } setShuffle(shuffle); setRepeat(repeat); currentDuration = (int) metadata.getLong(MediaMetadataCompat.METADATA_KEY_DURATION); progressBar.setMax(currentDuration); seekBar.setMax(currentDuration); String d = calculateTime(currentDuration); nowPlayingDurationExpanded.setText(d); } @Override public void onRepeatModeChanged(int repeatMode) { super.onRepeatModeChanged(repeatMode); repeat = repeatMode; setRepeat(repeatMode); } @Override public void onShuffleModeChanged(int shuffleMode) { super.onShuffleModeChanged(shuffleMode); shuffle = shuffleMode; setShuffle(shuffleMode); } @Override public void onPlaybackStateChanged(PlaybackStateCompat state) { super.onPlaybackStateChanged(state); if(state == null) return; switch (state.getState()) { case PlaybackStateCompat.STATE_PLAYING: currentState = PlaybackStateCompat.STATE_PLAYING; timeHandler.post(updateTime); //nowPlayingNameExpanded.setSelected(true); //nowPlayingArtistAlbumExpanded.setSelected(true); nowPlayingButton.setBackground(context.getDrawable(R.drawable.ic_pause)); nowPlayingForward.setVisibility(View.VISIBLE); nowPlayingButtonExpanded.setBackground(context.getDrawable(R.drawable.ic_pause)); if(motionLayout.getCurrentState() == R.id.end) { nowPlayingArtHolder.animate().scaleX(1.35f); nowPlayingArtHolder.animate().scaleY(1.3f); nowPlayingArtHolder.setCardElevation(30f); } break; case PlaybackStateCompat.STATE_PAUSED: currentState = PlaybackStateCompat.STATE_PAUSED; //nowPlayingNameExpanded.setSelected(false); //nowPlayingArtistAlbumExpanded.setSelected(false); nowPlayingButton.setBackground(context.getDrawable(R.drawable.ic_play)); nowPlayingButtonExpanded.setBackground(context.getDrawable(R.drawable.ic_play)); if(motionLayout.getCurrentState() == R.id.end) { nowPlayingArtHolder.animate().scaleX(1f); nowPlayingArtHolder.animate().scaleY(1f); nowPlayingArtHolder.setCardElevation(0f); } break; } } }; @Override public void QueueListItemClick(int position) { Bundle click = new Bundle(); click.putInt("clickedIndex", position); mediaControllerCompat.getTransportControls().sendCustomAction(QUEUE_CLICK, click); mediaControllerCompat.getTransportControls().playFromMediaId(queueDisplay.get(position).getId(), null); mediaControllerCompat.getTransportControls().sendCustomAction(SET_UP_NEXT, null); } private String calculateTime(int time) { String calculated; int minutes = time / 1000 / 60; int seconds = time/ 1000 % 60; if(seconds > 9) calculated = String.format(Locale.US, "%d:%d", minutes, seconds); else calculated = String.format(Locale.US, "%d:%d%d", minutes, 0, seconds); return calculated; } public MediaControllerCompat getMediaController() { return mediaControllerCompat; } public void CollapseBottomSheet() { motionLayout.transitionToState(R.id.start); } public void setBottomSheetQueue() { queueAdapter = new QueueAdapter(this); recyclerView.setAdapter(queueAdapter); itemTouchHelper.attachToRecyclerView(recyclerView); mediaControllerCompat.getTransportControls().sendCustomAction(INITIALIZE_QUEUE_CHANGE, null); nowPlayingFromExpanded.setText(nowPlayingFrom); } private void setRepeat(int state) { switch(state) { case PlaybackStateCompat.REPEAT_MODE_ALL: repeatBackground.setBackgroundTintList(ColorStateList.valueOf(context.getColor(R.color.colorAccent))); repeatExpanded.setBackground(context.getDrawable(R.drawable.ic_repeat)); repeatExpanded.setBackgroundTintList(ColorStateList.valueOf(context.getColor(R.color.white))); break; case PlaybackStateCompat.REPEAT_MODE_ONE: repeatBackground.setBackgroundTintList(ColorStateList.valueOf(context.getColor(R.color.colorAccent))); repeatExpanded.setBackground(context.getDrawable(R.drawable.ic_repeat_one)); repeatExpanded.setBackgroundTintList(ColorStateList.valueOf(context.getColor(R.color.white))); break; case PlaybackStateCompat.REPEAT_MODE_NONE: repeatBackground.setBackgroundTintList(ColorStateList.valueOf(context.getColor(R.color.darkGray))); repeatExpanded.setBackground(context.getDrawable(R.drawable.ic_repeat)); repeatExpanded.setBackgroundTintList(ColorStateList.valueOf(context.getColor(R.color.colorAccent))); break; } } private void setShuffle(int state) { switch(state) { case PlaybackStateCompat.SHUFFLE_MODE_ALL: shuffleBackground.setBackgroundTintList(ColorStateList.valueOf(context.getColor(R.color.colorAccent))); shuffleExpanded.setBackgroundTintList(ColorStateList.valueOf(context.getColor(R.color.white))); break; case PlaybackStateCompat.SHUFFLE_MODE_NONE: shuffleBackground.setBackgroundTintList(ColorStateList.valueOf(context.getColor(R.color.darkGray))); shuffleExpanded.setBackgroundTintList(ColorStateList.valueOf(context.getColor(R.color.colorAccent))); break; } } public void addNext(Songs song) { Bundle next = new Bundle(); next.putParcelable("ADD_SONG", song); next.putInt("QUEUE_POSITION", QUEUE_NEXT); mediaControllerCompat.getTransportControls().sendCustomAction(ADD_SONG, next); Toast.makeText(context, "ADDED NEXT", Toast.LENGTH_SHORT).show(); } public void addNext(Albums album) { this.album = album; content = GET_ALBUM_SONGS; LoaderManager.getInstance((MainActivity) context).initLoader(BROWSER_MEDIA_LOADER, null, addNextCallbacks); } public void addNext(Artists artist) { this.artist = artist; content = GET_ARTIST_SONGS; LoaderManager.getInstance((MainActivity) context).initLoader(BROWSER_MEDIA_LOADER, null, addNextCallbacks); } public void addNext(Playlists playlist) { this.playlist = playlist; content = GET_PLAYLIST_SONGS; LoaderManager.getInstance((MainActivity) context).initLoader(BROWSER_MEDIA_LOADER, null, addNextCallbacks); } public void addLast(Songs song) { Bundle end = new Bundle(); end.putParcelable("ADD_SONG", song); end.putInt("QUEUE_POSITION", QUEUE_END); mediaControllerCompat.getTransportControls().sendCustomAction(ADD_SONG, end); Toast.makeText(context, "ADDED LAST", Toast.LENGTH_SHORT).show(); } public void addLast(Albums album) { this.album = album; content = GET_ALBUM_SONGS; LoaderManager.getInstance((MainActivity) context).initLoader(BROWSER_MEDIA_LOADER, null, addLastCallbacks); } public void addLast(Artists artist) { this.artist = artist; content = GET_ARTIST_SONGS; LoaderManager.getInstance((MainActivity) context).initLoader(BROWSER_MEDIA_LOADER, null, addLastCallbacks); } public void addLast(Playlists playlist) { this.playlist = playlist; content = GET_PLAYLIST_SONGS; LoaderManager.getInstance((MainActivity) context).initLoader(BROWSER_MEDIA_LOADER, null, addLastCallbacks); } public void addToPlaylist(Playlists playlist, Songs song) { //GET SONGS CURRENTLY IN PLAYLIST AND ADD NEW SONG this.playlist = playlist; this.song = song; content = GET_PLAYLIST_SONGS; LoaderManager.getInstance((MainActivity) context).initLoader(PLAYLIST_MEDIA_LOADER, null, addToPlaylistCallbacks); } public void addToPlaylist(Playlists playlist, Albums album) { this.album = album; this.playlist = playlist; content = GET_ALBUM_SONGS; LoaderManager.getInstance((MainActivity) context).initLoader(BROWSER_MEDIA_LOADER, null, addToPlaylistCallbacks); } public void addToPlaylist(Playlists playlist, Artists artist) { this.artist = artist; this.playlist = playlist; content = GET_ARTIST_SONGS; LoaderManager.getInstance((MainActivity) context).initLoader(BROWSER_MEDIA_LOADER, null, addToPlaylistCallbacks); } public void addToPlaylist(Playlists playlist, Playlists playlistToAdd) { this.playlist = playlist; this.playlistToAdd = playlistToAdd; content = GET_PLAYLIST_SONGS; LoaderManager.getInstance((MainActivity) context).initLoader(BROWSER_MEDIA_LOADER, null, addToPlaylistCallbacks); } private LoaderManager.LoaderCallbacks<ArrayList> addNextCallbacks = new LoaderManager.LoaderCallbacks<ArrayList>() { @NonNull @Override public Loader<ArrayList> onCreateLoader(int id, @Nullable Bundle args) { switch(content) { case GET_ALBUM_SONGS: return new GetMedia(context, content, -1, album); case GET_ARTIST_SONGS: return new GetMedia(context, content, -1, artist); case GET_PLAYLIST_SONGS: return new GetMedia(context, content, -1, playlist); default: return new GetMedia(context, -1, -1); } } @Override public void onLoadFinished(@NonNull Loader<ArrayList> loader, ArrayList data) { switch(content) { case GET_ALBUM_SONGS: albumSongs = data; if(!albumSongs.isEmpty()) { if(albumSongs.size() == 1) addNext(albumSongs.get(0)); else { addToQueue.clear(); addToQueue = albumSongs; Bundle next = new Bundle(); next.putInt("QUEUE_POSITION", QUEUE_NEXT); mediaControllerCompat.getTransportControls().sendCustomAction(ADD_ALBUM_ARTIST_PLAYLIST, next); } Toast.makeText(context, "ADDED NEXT", Toast.LENGTH_SHORT).show(); } break; case GET_ARTIST_SONGS: artistSongs = data; if(!artistSongs.isEmpty()) { if(artistSongs.size() == 1) addNext(artistSongs.get(0)); else { addToQueue.clear(); addToQueue = artistSongs; Bundle next = new Bundle(); next.putInt("QUEUE_POSITION", QUEUE_NEXT); mediaControllerCompat.getTransportControls().sendCustomAction(ADD_ALBUM_ARTIST_PLAYLIST, next); } Toast.makeText(context, "ADDED NEXT", Toast.LENGTH_SHORT).show(); } break; case GET_PLAYLIST_SONGS: playlistSongs = data; if(!playlistSongs.isEmpty()) { if(playlistSongs.size() == 1) addNext(playlistSongs.get(0)); else { addToQueue.clear(); addToQueue = playlistSongs; Bundle next = new Bundle(); next.putInt("QUEUE_POSITION", QUEUE_NEXT); mediaControllerCompat.getTransportControls().sendCustomAction(ADD_ALBUM_ARTIST_PLAYLIST, next); } } break; } } @Override public void onLoaderReset(@NonNull Loader<ArrayList> loader) { } }; private LoaderManager.LoaderCallbacks<ArrayList> addLastCallbacks = new LoaderManager.LoaderCallbacks<ArrayList>() { @NonNull @Override public Loader<ArrayList> onCreateLoader(int id, @Nullable Bundle args) { switch(content) { case GET_ALBUM_SONGS: return new GetMedia(context, content, -1, album); case GET_ARTIST_SONGS: return new GetMedia(context, content, -1, artist); case GET_PLAYLIST_SONGS: return new GetMedia(context, content, -1, playlist); default: return new GetMedia(context, -1, -1); } } @Override public void onLoadFinished(@NonNull Loader<ArrayList> loader, ArrayList data) { switch(content) { case GET_ALBUM_SONGS: albumSongs = data; if(!albumSongs.isEmpty()) { if(albumSongs.size() == 1) addLast(albumSongs.get(0)); else { addToQueue.clear(); addToQueue = albumSongs; Bundle end = new Bundle(); end.putInt("QUEUE_POSITION", QUEUE_END); mediaControllerCompat.getTransportControls().sendCustomAction(ADD_ALBUM_ARTIST_PLAYLIST, end); Toast.makeText(context, "ADDED LAST", Toast.LENGTH_SHORT).show(); } } break; case GET_ARTIST_SONGS: artistSongs = data; if(!artistSongs.isEmpty()) { if(artistSongs.size() == 1) addLast(artistSongs.get(0)); else { addToQueue.clear(); addToQueue = artistSongs; Bundle end = new Bundle(); end.putInt("QUEUE_POSITION", QUEUE_END); mediaControllerCompat.getTransportControls().sendCustomAction(ADD_ALBUM_ARTIST_PLAYLIST, end); Toast.makeText(context, "ADDED LAST", Toast.LENGTH_SHORT).show(); } } break; case GET_PLAYLIST_SONGS: playlistSongs = data; if(!playlistSongs.isEmpty()) { if(playlistSongs.size() == 1) addLast(playlistSongs.get(0)); else { addToQueue.clear(); addToQueue = playlistSongs; Bundle end = new Bundle(); end.putInt("QUEUE_POSITION", QUEUE_END); mediaControllerCompat.getTransportControls().sendCustomAction(ADD_ALBUM_ARTIST_PLAYLIST, end); Toast.makeText(context, "ADDED LAST", Toast.LENGTH_SHORT).show(); } } break; } } @Override public void onLoaderReset(@NonNull Loader<ArrayList> loader) { } }; private LoaderManager.LoaderCallbacks<ArrayList> addToPlaylistCallbacks = new LoaderManager.LoaderCallbacks<ArrayList>() { @NonNull @Override public Loader<ArrayList> onCreateLoader(int id, @Nullable Bundle args) { switch(content) { case GET_ALBUM_SONGS: return new GetMedia(context, content, -1, album); case GET_ARTIST_SONGS: return new GetMedia(context, content, -1, artist); case GET_PLAYLIST_SONGS: return new GetMedia(context, content, -1, playlistToAdd); default: return new GetMedia(context, -1, -1); } } @Override public void onLoadFinished(@NonNull Loader<ArrayList> loader, ArrayList data) { switch(content) { case GET_ALBUM_SONGS: albumSongs = data; for (int i = 0; i < albumSongs.size(); i++) { addToPlaylist(playlist, albumSongs.get(i)); } break; case GET_ARTIST_SONGS: artistSongs = data; for (int i = 0; i < artistSongs.size(); i++) { addToPlaylist(playlist, artistSongs.get(i)); } break; case GET_PLAYLIST_SONGS: playlistSongs = data; if(loader.getId() == PLAYLIST_MEDIA_LOADER) { playlistSongs.add(song); long playlistID = Long.parseLong(playlist.getId()); ContentResolver contentResolver = context.getContentResolver(); Uri playlistSongsUri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistID); //DELETE SONGS IN PLAYLIST MEMBER TABLE contentResolver.delete(playlistSongsUri, null, null); //RECREATE PLAYLIST MEMBER TABLE WITH NEW SONG AND INSERT ContentValues[] values = new ContentValues[playlistSongs.size()]; for(int i = 0; i < playlistSongs.size(); i++) { values[i] = new ContentValues(); values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, Long.valueOf(i)); values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, Long.parseLong(playlistSongs.get(i).getId())); values[i].put(MediaStore.Audio.Playlists.Members.PLAYLIST_ID, playlistID); } contentResolver.bulkInsert(playlistSongsUri, values); //Log.i(TAG, song.getTitle().toUpperCase() + " ADDED TO PLAYLIST " + playlist.getPlaylist().toUpperCase()); } else { for (int i = 0; i < playlistSongs.size(); i++) { addToPlaylist(playlist, playlistSongs.get(i)); } } break; } } @Override public void onLoaderReset(@NonNull Loader<ArrayList> loader) { } }; private void buildTransportControls() { /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //////////////////////////////////BOTTOM SHEET///////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// frameLayout = rootView.findViewById(R.id.fragment_container); recyclerView = rootView.findViewById(R.id.currentBottomSheetQueue); LinearLayoutManager layoutManager = new LinearLayoutManager(context); recyclerView.setLayoutManager(layoutManager); DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), layoutManager.getOrientation()); recyclerView.addItemDecoration(dividerItemDecoration); motionLayout = rootView.findViewById(R.id.bottomSheetPlaying); motionLayout.setTransitionListener(new MotionLayout.TransitionListener() { @Override public void onTransitionStarted(MotionLayout motionLayout, int i, int i1) { if((motionLayout.getStartState() == R.id.end || motionLayout.getStartState() == R.id.start) && upNextIsShowing) { upNextIsShowing = false; } else if(motionLayout.getEndState() == R.id.endQueue && !upNextIsShowing) { upNextIsShowing = true; } } @Override public void onTransitionChange(MotionLayout motionLayout, int i, int i1, float v) { } @Override public void onTransitionCompleted(MotionLayout motionLayout, int i) { if(motionLayout.getCurrentState() == R.id.start) { nowPlayingArtHolder.animate().scaleX(1f); nowPlayingArtHolder.animate().scaleY(1f); nowPlayingArtHolder.setCardElevation(0f); } else if(motionLayout.getCurrentState() == R.id.endQueue) { upNextShuffle.setAlpha(0f); upNextShuffleBackground.setAlpha(0f); upNextRepeat.setAlpha(0f); upNextRepeatBackground.setAlpha(0f); nowPlayingArtHolder.animate().scaleX(1f); nowPlayingArtHolder.animate().scaleY(1f); nowPlayingArtHolder.setCardElevation(0f); } else { if(shuffle == PlaybackStateCompat.SHUFFLE_MODE_ALL) { upNextShuffle.setAlpha(1f); upNextShuffleBackground.setAlpha(1f); } if(repeat == PlaybackStateCompat.REPEAT_MODE_ALL || repeat == PlaybackStateCompat.REPEAT_MODE_ONE) { if(repeat == PlaybackStateCompat.REPEAT_MODE_ONE) upNextRepeat.setImageResource(R.drawable.ic_repeat_one); else upNextRepeat.setImageResource(R.drawable.ic_repeat); upNextRepeat.setAlpha(1f); upNextRepeatBackground.setAlpha(1f); } if(currentState == PlaybackStateCompat.STATE_PLAYING) { nowPlayingArtHolder.animate().scaleX(1.35f); nowPlayingArtHolder.animate().scaleY(1.3f); nowPlayingArtHolder.setCardElevation(30f); } else { nowPlayingArtHolder.animate().scaleX(1f); nowPlayingArtHolder.animate().scaleY(1f); nowPlayingArtHolder.setCardElevation(0f); } } } @Override public void onTransitionTrigger(MotionLayout motionLayout, int i, boolean b, float v) { } }); nowPlayingArt = rootView.findViewById(R.id.currentArtBottomSheet); nowPlayingArtHolder = rootView.findViewById(R.id.currentArtBottomSheetHolder); nowPlayingName = rootView.findViewById(R.id.currentNameCollapsed); nowPlayingArtist = rootView.findViewById(R.id.currentArtistCollapsed); nowPlayingButton = rootView.findViewById(R.id.currentPlay); nowPlayingButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(!nowPlayingName.getText().equals("Not Playing")) { if(currentState == PlaybackStateCompat.STATE_PLAYING) { mediaControllerCompat.getTransportControls().pause(); } else { mediaControllerCompat.getTransportControls().play(); } } else { getMediaController().getTransportControls().sendCustomAction(CLEAR, null); Bundle queue = new Bundle(); queue.putInt("CURRENT_QUEUE_POSITION", 0); queue.putInt("FROM", FROM_LIBRARY); getMediaController().getTransportControls().sendCustomAction(SET_POSITION, queue); getMediaController().getTransportControls().sendCustomAction(SET_QUEUE_LIBRARY, queue); nowPlayingFrom = "Now playing from Library"; getMediaController().getTransportControls().sendCustomAction(PLAY_BUTTON_START, null); getMediaController().getTransportControls().sendCustomAction(SET_UP_NEXT, null); setBottomSheetQueue(); } } }); nowPlayingForward = rootView.findViewById(R.id.currentNext); nowPlayingForward.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mediaControllerCompat.getTransportControls().skipToNext(); } }); nowPlayingNameExpanded = rootView.findViewById(R.id.currentNameBottomSheet); nowPlayingElapsedExpanded = rootView.findViewById(R.id.currentTimeBottomSheet); nowPlayingDurationExpanded = rootView.findViewById(R.id.currentDurationBottomSheet); nowPlayingFromExpanded = rootView.findViewById(R.id.playingFrom); nowPlayingArtistAlbumExpanded = rootView.findViewById(R.id.currentArtistAlbumBottomSheet); nowPlayingArtistAlbumExpanded.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mediaControllerCompat.sendCommand(GET_ARTIST_ALBUM, null, resultReceiver); } }); nowPlayingSlideDown = rootView.findViewById(R.id.slideDownBottomSheet); nowPlayingButtonExpanded = rootView.findViewById(R.id.currentPlayBottomSheet); nowPlayingButtonExpanded.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(!nowPlayingName.getText().equals("Not Playing")) { if(currentState == PlaybackStateCompat.STATE_PLAYING) { mediaControllerCompat.getTransportControls().pause(); nowPlayingArtHolder.setCardElevation(0f); } else { mediaControllerCompat.getTransportControls().play(); nowPlayingArtHolder.setCardElevation(30f); } } else { getMediaController().getTransportControls().sendCustomAction(CLEAR, null); Bundle queue = new Bundle(); queue.putInt("CURRENT_QUEUE_POSITION", 0); queue.putInt("FROM", FROM_LIBRARY); getMediaController().getTransportControls().sendCustomAction(SET_POSITION, queue); getMediaController().getTransportControls().sendCustomAction(SET_QUEUE_LIBRARY, queue); nowPlayingFrom = "Now playing from Library"; getMediaController().getTransportControls().sendCustomAction(PLAY_BUTTON_START, null); getMediaController().getTransportControls().sendCustomAction(SET_UP_NEXT, null); setBottomSheetQueue(); } } }); nowPlayingBackExpanded = rootView.findViewById(R.id.currentBackBottomSheet); nowPlayingBackExpanded.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mediaControllerCompat.getTransportControls().skipToPrevious(); } }); nowPlayingForwardExpanded = rootView.findViewById(R.id.currentForwardBottomSheet); nowPlayingForwardExpanded.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mediaControllerCompat.getTransportControls().skipToNext(); } }); progressBar = rootView.findViewById(R.id.collapsedSeekBar); seekBar = rootView.findViewById(R.id.currentSeekBottomSheet); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if(fromUser) { mediaControllerCompat.getTransportControls().seekTo((long) progress); seekBar.setProgress(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); volumeBar = rootView.findViewById(R.id.volumeControlSeek); volumeBar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)); volumeBar.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)); volumeBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int volume, boolean fromUser) { audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); shuffleExpanded = rootView.findViewById(R.id.currentBottomSheetShuffle); shuffleBackground = rootView.findViewById(R.id.shuffleBackground); shuffleExpanded.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(shuffle == PlaybackStateCompat.SHUFFLE_MODE_NONE) { mediaControllerCompat.getTransportControls().setShuffleMode(PlaybackStateCompat.SHUFFLE_MODE_ALL); } else if(shuffle == PlaybackStateCompat.SHUFFLE_MODE_ALL) { mediaControllerCompat.getTransportControls().setShuffleMode(PlaybackStateCompat.SHUFFLE_MODE_NONE); } //setBottomSheetQueue(); } }); repeatExpanded = rootView.findViewById(R.id.currentBottomSheetRepeat); repeatBackground = rootView.findViewById(R.id.repeatBackground); repeatExpanded.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(repeat == PlaybackStateCompat.REPEAT_MODE_NONE) { mediaControllerCompat.getTransportControls().setRepeatMode(PlaybackStateCompat.REPEAT_MODE_ALL); } else if(repeat == PlaybackStateCompat.REPEAT_MODE_ALL) { mediaControllerCompat.getTransportControls().setRepeatMode(PlaybackStateCompat.REPEAT_MODE_ONE); } else if(repeat == PlaybackStateCompat.REPEAT_MODE_ONE) { mediaControllerCompat.getTransportControls().setRepeatMode(PlaybackStateCompat.REPEAT_MODE_NONE); } } }); upNextQueue = rootView.findViewById(R.id.upNextButton); upNextBackground = rootView.findViewById(R.id.upNextBackground); upNextShuffle = rootView.findViewById(R.id.upNextShuffle); upNextShuffleBackground = rootView.findViewById(R.id.upNextShuffleBackground); upNextRepeat = rootView.findViewById(R.id.upNextRepeat); upNextRepeatBackground = rootView.findViewById(R.id.upNextRepeatBackground); ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////BOTTOM SHEET///////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// } } <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/App.java package com.rookieandroid.rookiemusicplayer; import android.app.Application; import android.app.NotificationChannel; import android.app.NotificationManager; import android.graphics.BitmapFactory; import android.os.Build; import android.os.Handler; import android.transition.ChangeBounds; import android.transition.ChangeClipBounds; import android.transition.ChangeTransform; import android.transition.TransitionSet; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.RecyclerView; import com.rookieandroid.rookiemusicplayer.adapters.QueueAdapter; import com.rookieandroid.rookiemusicplayer.helpers.MediaBrowserHelperMotion; import java.util.ArrayList; public class App extends Application { private final String TAG = App.class.getSimpleName(); public static final String CHANNEL_1 = "channel_1"; public static MediaBrowserHelperMotion mediaBrowserHelper; //CURRENTLY PLAYING public static Handler playingHandler = new Handler(); public ImageView currentSong; public ImageView previousSong; public static int currentlyPlaying = 1; public static int currentState; public static int repeat; public static int shuffle; //LOADERS public static final int READ_STORAGE_LOADER = 0; public static final int PLAYLIST_MEDIA_LOADER = 1; public static final int BROWSER_MEDIA_LOADER = 2; public static final int DIALOG_MEDIA_LOADER = 3; public static final int ALBUM_MEDIA_LOADER = 4; public static final int LIBRARY_MEDIA_LOADER = 5; public static final int ARTIST_MEDIA_LOADER = 6; //GET MEDIA public static final int GET_ALBUM_SONGS = 1; public static final int GET_ARTIST_SONGS = 2; public static final int GET_PLAYLIST_SONGS = 3; public static final int GET_RECENT_SONGS = 4; public static final int GET_ARTIST_ALBUMS = 5; //LIBRARY public static ArrayList<Songs> songs = new ArrayList<>(); public static ArrayList<Albums> albums = new ArrayList<>(); public static ArrayList<AlbumsSections> albumsSections = new ArrayList<>(); public static ArrayList<Artists> artists = new ArrayList<>(); public static ArrayList<Playlists> playlists = new ArrayList<>(); //QUEUE CONTENTS public static ArrayList<Songs> librarySongs = new ArrayList<>(); public static ArrayList<Songs> artistSongs = new ArrayList<>(); public static ArrayList<Songs> albumSongs = new ArrayList<>(); public static ArrayList<Songs> playlistSongs = new ArrayList<>(); public static ArrayList<Songs> searchSong = new ArrayList<>(); public static ArrayList<Songs> addToQueue = new ArrayList<>(); //SAVING AND RESTORING UI STATE public static ArrayList<Songs> savedSongs; public static ArrayList<SavedStateDetails> savedState; //UP NEXT public static ArrayList<Songs> queueDisplay = new ArrayList<>(); public static QueueAdapter queueAdapter; public static String nowPlayingFrom; public static ArrayList<Songs> deleteFromQueue = new ArrayList<>(); //FAST SCROLLING public static ArrayList<Integer> sectionsSongs = new ArrayList<>(); public static ArrayList<String> lettersSongs = new ArrayList<>(); public static ArrayList<Integer> sectionsArtists = new ArrayList<>(); public static ArrayList<String> lettersArtists = new ArrayList<>(); public static ArrayList<Integer> sectionsAlbums = new ArrayList<>(); public static ArrayList<String> lettersAlbums = new ArrayList<>(); //CONSTANTS public static final int SKIP_NEXT = 1; public static final int SKIP_PREVIOUS = 2; public static final int QUEUE_NEXT = 3; public static final int QUEUE_END = 4; public static final int FROM_LIBRARY = 5; public static final int FROM_ARTIST = 6; public static final int FROM_ALBUM = 7; public static final int FROM_SEARCH = 8; public static final int FROM_PLAYLIST = 9; public static final int TO_ARTIST = 10; public static final int TO_ALBUM = 11; public static final int ARTIST_DETAIL = 12; public static final int SEARCH = 13; public static final int RECENTLY_ADDED = 14; //COMMANDS AND RESULT CODES public static final String GET_CURRENT_POSITION = "1"; public static final int RECEIVE_CURRENT_POSITION = 1; public static final String GET_ARTIST_ALBUM = "2"; public static final int RECEIVE_ARTIST_ALBUM = 2; public static final String GET_QUEUE_POSITION = "3"; public static final int RECEIVE_QUEUE_POSITION = 3; public static final String GET_PLAYBACKSTATE = "4"; public static final int RECEIVE_PLAYBACKSTATE = 4; //CUSTOM ACTIONS public static final String ADD_SONG = "1"; public static final String ADD_ALBUM_ARTIST_PLAYLIST = "2"; public static final String SET_POSITION = "3"; public static final String CLEAR = "4"; public static final String ACTIVITY_RESTORE = "5"; public static final String SET_QUEUE_LIBRARY = "6"; public static final String SET_QUEUE_LIBRARY_SONGS = "7"; public static final String SET_QUEUE_ARTIST = "8"; public static final String SET_QUEUE_ALBUM = "9"; public static final String SET_QUEUE_SEARCH = "10"; public static final String SET_QUEUE_PLAYLIST = "11"; public static final String SET_UP_NEXT = "12"; public static final String QUEUE_CLICK = "13"; public static final String SHUFFLE_QUEUE = "14"; public static final String SAVE_QUEUE = "15"; public static final String RESTORE_SAVED_QUEUE = "16"; public static final String INITIALIZE_QUEUE_CHANGE = "17"; public static final String SET_ELAPSED_TIME = "18"; public static final String SET_FROM = "19"; public static final String PLAY_BUTTON_START = "20"; public static final String MEDIA_DELETED = "21"; @Override public void onCreate() { super.onCreate(); createNotificationChannels(); } private void createNotificationChannels() { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel_1 = new NotificationChannel(CHANNEL_1, "Now Playing", NotificationManager.IMPORTANCE_LOW); NotificationManager notificationManager = getSystemService(NotificationManager.class); if(notificationManager != null) notificationManager.createNotificationChannel(channel_1); } } public static int calculateSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int width = options.outWidth; final int height = options.outHeight; int sampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / sampleSize) >= reqHeight && (halfWidth / sampleSize) >= reqWidth) sampleSize *= 2; } return sampleSize; } public static class DetailsTransition extends TransitionSet { public DetailsTransition() { setOrdering(ORDERING_TOGETHER); addTransition(new ChangeBounds()) .addTransition(new ChangeTransform()) .addTransition(new ChangeClipBounds()); //.addTransition(new ChangeImageTransform()); } } public static ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() { @Override public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) { int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN; int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT; return makeMovementFlags(dragFlags, swipeFlags); } @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { return queueAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition()); } @Override public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { queueAdapter.onItemDismiss(viewHolder.getAdapterPosition()); } @Override public boolean isLongPressDragEnabled() { return super.isLongPressDragEnabled(); } @Override public boolean isItemViewSwipeEnabled() { return super.isItemViewSwipeEnabled(); } }); } <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/adapters/QueueAdapter.java package com.rookieandroid.rookiemusicplayer.adapters; import android.content.Context; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.rookieandroid.rookiemusicplayer.R; import static com.rookieandroid.rookiemusicplayer.App.queueDisplay; public class QueueAdapter extends RecyclerView.Adapter<QueueAdapter.QueueViewHolder> { private static String TAG = QueueAdapter.class.getSimpleName(); private QueueAdapter.ListItemClickListener listener; private QueueChange queueChange; private Context context; public interface ListItemClickListener { void QueueListItemClick(int position); } //Keeps the queue updated on drags and swipes public interface QueueChange { void updateQueueOrder(int from, int to); void updateQueueDismiss(int index); } public QueueAdapter(QueueAdapter.ListItemClickListener listener) { this.listener = listener; setHasStableIds(true); } public void initializeQueueChange(QueueChange queueChange) { this.queueChange = queueChange; } @NonNull @Override public QueueAdapter.QueueViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.queue_list, parent, false); QueueAdapter.QueueViewHolder viewHolder = new QueueAdapter.QueueViewHolder(view); return viewHolder; } @Override public long getItemId(int position) { return Integer.parseInt(queueDisplay.get(position).getId()); } @Override public int getItemViewType(int position) { return Integer.parseInt(queueDisplay.get(position).getId()); } @Override public void onBindViewHolder(@NonNull QueueAdapter.QueueViewHolder holder, int position) { holder.bind(position); } @Override public int getItemCount() { return queueDisplay.size(); } public boolean onItemMove(int fromPosition, int toPosition) { queueChange.updateQueueOrder(fromPosition, toPosition); return true; } public void onItemDismiss(int position) { queueChange.updateQueueDismiss(position); } class QueueViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private ImageView albumArt; private TextView songName; private TextView songArtist; private ImageView order; public QueueViewHolder(@NonNull View itemView) { super(itemView); albumArt = itemView.findViewById(R.id.songArt); songName = itemView.findViewById(R.id.songName); songArtist = itemView.findViewById(R.id.songArtist); order = itemView.findViewById(R.id.order); itemView.setOnClickListener(this); } public void bind(int position) { Uri uri = Uri.parse(queueDisplay.get(position).getArt()); Glide.with(context).load(uri).placeholder(R.drawable.noalbumart).fallback(R.drawable.noalbumart).error(R.drawable.noalbumart).into(albumArt); songName.setText(queueDisplay.get(position).getTitle()); songArtist.setText(queueDisplay.get(position).getArtist()); } @Override public void onClick(View view) { int clickedPosition = getAdapterPosition(); listener.QueueListItemClick(clickedPosition); } } } <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/adapters/PlaylistDialogAdapter.java package com.rookieandroid.rookiemusicplayer.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.rookieandroid.rookiemusicplayer.Playlists; import com.rookieandroid.rookiemusicplayer.R; import java.util.ArrayList; public class PlaylistDialogAdapter extends RecyclerView.Adapter<PlaylistDialogAdapter.PlaylistDialogViewHolder> { private ArrayList<Playlists> playlists; private ListItemClickListener listener; private Context context; public interface ListItemClickListener { void onListItemClick(Playlists playlist); } public PlaylistDialogAdapter(ArrayList<Playlists> playlists, ListItemClickListener listener) { this.playlists = playlists; this.listener = listener; } @NonNull @Override public PlaylistDialogViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.playlists_list, parent, false); PlaylistDialogViewHolder viewHolder = new PlaylistDialogViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(@NonNull PlaylistDialogViewHolder holder, int position) { holder.bind(position); } @Override public int getItemCount() { return playlists.size(); } class PlaylistDialogViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView playlistName; public PlaylistDialogViewHolder(@NonNull View itemView) { super(itemView); playlistName = itemView.findViewById(R.id.playlist); itemView.setOnClickListener(this); } public void bind(int position) { playlistName.setText(playlists.get(position).getPlaylist()); } @Override public void onClick(View view) { int clickedPosition = getAdapterPosition(); listener.onListItemClick(playlists.get(clickedPosition)); } } } <file_sep>/README.md # RookMusicPlayer <img src="screenshots/rookscreenshot1.png" width="275"> <img src="screenshots/rookscreenshot2.png" width="275"> <img src="screenshots/rookscreenshot3.png" width="275"> <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/architecture/StateDatabase.java package com.rookieandroid.rookiemusicplayer.architecture; import android.content.Context; import androidx.annotation.NonNull; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.sqlite.db.SupportSQLiteDatabase; import com.rookieandroid.rookiemusicplayer.Songs; @Database(entities = {Songs.class, SavedDetails.class}, version = 1, exportSchema = false) public abstract class StateDatabase extends RoomDatabase { private static StateDatabase instance; public abstract SavedQueueDao savedQueueDao(); public abstract SavedDetailsDao savedDetailsDao(); public static synchronized StateDatabase getInstance(Context context) { if(instance == null) { instance = Room.databaseBuilder(context.getApplicationContext(), StateDatabase.class, "state_database") .fallbackToDestructiveMigration().addCallback(roomCallBack).build(); } return instance; } private static RoomDatabase.Callback roomCallBack = new RoomDatabase.Callback() { @Override public void onCreate(@NonNull SupportSQLiteDatabase db) { super.onCreate(db); } @Override public void onOpen(@NonNull SupportSQLiteDatabase db) { super.onOpen(db); } }; } <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/helpers/GoToDialog.java package com.rookieandroid.rookiemusicplayer.helpers; import android.app.Dialog; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.InsetDrawable; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.appcompat.app.AlertDialog; import com.rookieandroid.rookiemusicplayer.R; import com.rookieandroid.rookiemusicplayer.Songs; import static com.rookieandroid.rookiemusicplayer.App.TO_ALBUM; import static com.rookieandroid.rookiemusicplayer.App.TO_ARTIST; public class GoToDialog extends AlertDialog { private Context context; private Songs artist_album; private TextView artistName; private TextView albumName; private RelativeLayout goArtist; private RelativeLayout goAlbum; private GoTo goTo; public interface GoTo { void goTo(Songs artist_album, int to); } public GoToDialog(Context context, Songs artist_album) { super(context); this.context = context; this.artist_album = artist_album; goTo = (GoTo) context; } public void OpenDialog() { final AlertDialog alertDialog = new AlertDialog.Builder(context).create(); final View alertLayout = getLayoutInflater().inflate(R.layout.dialog_goto,null); goArtist = alertLayout.findViewById(R.id.goToArtist); artistName = alertLayout.findViewById(R.id.artist); artistName.setText(artist_album.getArtist()); goAlbum = alertLayout.findViewById(R.id.goToAlbum); albumName = alertLayout.findViewById(R.id.album); albumName.setText(artist_album.getAlbum()); setClickListeners(alertDialog); alertDialog.setView(alertLayout); new Dialog(context); alertDialog.show(); ColorDrawable back = new ColorDrawable(Color.TRANSPARENT); InsetDrawable inset = new InsetDrawable(back, 20); alertDialog.getWindow().setBackgroundDrawable(inset); alertDialog.getWindow().setElevation(20.0f); } private void setClickListeners(AlertDialog alertDialog) { goArtist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goTo.goTo(artist_album, TO_ARTIST); alertDialog.dismiss(); } }); goAlbum.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goTo.goTo(artist_album, TO_ALBUM); alertDialog.dismiss(); } }); } } <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/helpers/SectionIndexFixer.java package com.rookieandroid.rookiemusicplayer.helpers; import java.util.ArrayList; public class SectionIndexFixer { public SectionIndexFixer(){} public void fixIndex(ArrayList<String> letters, ArrayList<Integer> sections) { if(!letters.contains("#")) { letters.add(0, "!"); sections.add(0, -1); } if(!letters.contains("A")) { letters.add(1, "!"); sections.add(1, -1); } if(!letters.contains("B")) { letters.add(2, "!"); sections.add(2, -1); } if(!letters.contains("C")) { letters.add(3, "!"); sections.add(3, -1); } if(!letters.contains("D")) { letters.add(4, "!"); sections.add(4, -1); } if(!letters.contains("E")) { letters.add(5, "!"); sections.add(5, -1); } if(!letters.contains("F")) { letters.add(6, "!"); sections.add(6, -1); } if(!letters.contains("G")) { letters.add(7, "!"); sections.add(7, -1); } if(!letters.contains("H")) { letters.add(8, "!"); sections.add(8, -1); } if(!letters.contains("I")) { letters.add(9, "!"); sections.add(9, -1); } if(!letters.contains("J")) { letters.add(10, "!"); sections.add(10, -1); } if(!letters.contains("K")) { letters.add(11, "!"); sections.add(11, -1); } if(!letters.contains("L")) { letters.add(12, "!"); sections.add(12, -1); } if(!letters.contains("M")) { letters.add(13, "!"); sections.add(13, -1); } if(!letters.contains("N")) { letters.add(14, "!"); sections.add(14, -1); } if(!letters.contains("O")) { letters.add(15, "!"); sections.add(15, -1); } if(!letters.contains("P")) { letters.add(16, "!"); sections.add(16, -1); } if(!letters.contains("Q")) { letters.add(17, "!"); sections.add(17, -1); } if(!letters.contains("R")) { letters.add(18, "!"); sections.add(18, -1); } if(!letters.contains("S")) { letters.add(19, "!"); sections.add(19, -1); } if(!letters.contains("T")) { letters.add(20, "!"); sections.add(20, -1); } if(!letters.contains("U")) { letters.add(21, "!"); sections.add(21, -1); } if(!letters.contains("V")) { letters.add(22, "!"); sections.add(22, -1); } if(!letters.contains("W")) { letters.add(23, "!"); sections.add(23, -1); } if(!letters.contains("X")) { letters.add(24, "!"); sections.add(24, -1); } if(!letters.contains("Y")) { letters.add(25, "!"); sections.add(25, -1); } if(!letters.contains("Z")) { letters.add(26, "!"); sections.add(26, -1); } } } <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/helpers/MediaControlDialog.java package com.rookieandroid.rookiemusicplayer.helpers; import android.app.Dialog; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.InsetDrawable; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.loader.app.LoaderManager; import androidx.loader.content.Loader; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.rookieandroid.rookiemusicplayer.Albums; import com.rookieandroid.rookiemusicplayer.Artists; import com.rookieandroid.rookiemusicplayer.MainActivity; import com.rookieandroid.rookiemusicplayer.Playlists; import com.rookieandroid.rookiemusicplayer.R; import com.rookieandroid.rookiemusicplayer.Songs; import com.rookieandroid.rookiemusicplayer.adapters.AlbumDetailsAdapter; import com.rookieandroid.rookiemusicplayer.adapters.AlbumsAdapter; import com.rookieandroid.rookiemusicplayer.adapters.ArtistsAdapter; import com.rookieandroid.rookiemusicplayer.adapters.PlaylistDialogAdapter; import com.rookieandroid.rookiemusicplayer.adapters.PlaylistsAdapter; import com.rookieandroid.rookiemusicplayer.adapters.SongsAdapter; import com.google.android.material.textfield.TextInputEditText; import java.util.ArrayList; import static com.rookieandroid.rookiemusicplayer.App.DIALOG_MEDIA_LOADER; import static com.rookieandroid.rookiemusicplayer.App.FROM_ALBUM; import static com.rookieandroid.rookiemusicplayer.App.FROM_ARTIST; import static com.rookieandroid.rookiemusicplayer.App.FROM_LIBRARY; import static com.rookieandroid.rookiemusicplayer.App.FROM_PLAYLIST; import static com.rookieandroid.rookiemusicplayer.App.GET_ALBUM_SONGS; import static com.rookieandroid.rookiemusicplayer.App.GET_ARTIST_SONGS; import static com.rookieandroid.rookiemusicplayer.App.mediaBrowserHelper; import static com.rookieandroid.rookiemusicplayer.App.playlists; public class MediaControlDialog extends AlertDialog implements PlaylistDialogAdapter.ListItemClickListener { private final String TAG = MediaControlDialog.class.getSimpleName(); private static final int SONG = 1; private static final int ALBUM = 2; private static final int ARTIST = 3; private static final int PLAYLIST = 4; private static final int PLAYLIST_SONG = 5; ContentResolver contentResolver; private int removePosition; private ArrayList<Songs> albumSongs; private ArrayList<Songs> artistSongs; private Songs song; private Songs playlistSong; private Albums album; private Artists artist; private Playlists playlist; private ArrayList<Songs> librarySongs; private SongsAdapter librarySongsAdapter; private ArrayList<Albums> libraryAlbums; private AlbumsAdapter libraryAlbumsAdapter; private AlbumDetailsAdapter albumSongsAdapter; private ArrayList<Artists> libraryArtists; private ArtistsAdapter libraryArtistsAdapter; private ArrayList<Playlists> currentPlaylists; private PlaylistsAdapter playlistsAdapter; private ArrayList<Songs> playlistSongs; private SongsAdapter playlistSongsAdapter; private AlertDialog alertDialog; private AlertDialog alertDialogPlaylist; private AlertDialog alertDialogNewPlaylist; private int media; private int code; private int ID; private Context context; private MediaControlDialog.UpdateLibrary updateLibrary; private MediaControlDialog.UpdatePlaylist updatePlaylist; //MEDIA CONTROL private ImageView mediaArt; private TextView mediaName; private TextView mediaArtist; private TextView mediaType; private TextView deleteText; private RelativeLayout delete; private RelativeLayout playlistAction; private RelativeLayout next; private RelativeLayout last; //PLAYLIST CONTROL private RecyclerView recyclerView; private Button cancelPlaylist; private Button createNewPlaylist; //NEW PLAYLIST CONTROL private TextInputEditText newPlaylistName; private TextInputEditText newPlaylistDescription; private Button newPlaylistCancel; private Button newPlaylistCreate; public interface UpdateLibrary { void updateSongsLibrary(Songs song); void updateAlbumsLibrary(Albums album, ArrayList<Songs> albumSongs, int from); void updateArtistsLibrary(Artists artist, ArrayList<Songs> artistSongs); } public interface UpdatePlaylist { void updatePlaylistCount(); } //DIALOG FOR SONG public MediaControlDialog(Context context, Songs song, ArrayList<Songs> librarySongs, SongsAdapter librarySongsAdapter, MediaControlDialog.UpdateLibrary updateLibrary, int code) { super(context); this.song = song; this.librarySongs = librarySongs; this.librarySongsAdapter = librarySongsAdapter; this.context = context; this.updateLibrary = updateLibrary; this.code = code; media = SONG; contentResolver = context.getContentResolver(); } //DIALOG FOR ALBUM SONG public MediaControlDialog(Context context, Songs song, ArrayList<Songs> librarySongs, AlbumDetailsAdapter albumSongsAdapter, MediaControlDialog.UpdateLibrary updateLibrary, int code) { super(context); this.song = song; this.librarySongs = librarySongs; this.albumSongsAdapter = albumSongsAdapter; this.context = context; this.updateLibrary = updateLibrary; this.code = code; media = SONG; contentResolver = context.getContentResolver(); } //DIALOG FOR ALBUM public MediaControlDialog(Context context, Albums album, ArrayList<Albums> libraryAlbums, AlbumsAdapter libraryAlbumsAdapter, MediaControlDialog.UpdateLibrary updateLibrary, int code) { super(context); this.album = album; this.libraryAlbums = libraryAlbums; this.libraryAlbumsAdapter = libraryAlbumsAdapter; this.context = context; this.updateLibrary = updateLibrary; this.code = code; media = ALBUM; contentResolver = context.getContentResolver(); } //DIALOG FOR ARTIST public MediaControlDialog(Context context, Artists artist, ArrayList<Artists> libraryArtists, ArtistsAdapter libraryArtistsAdapter, MediaControlDialog.UpdateLibrary updateLibrary, int code) { super(context); this.artist = artist; this.libraryArtists = libraryArtists; this.libraryArtistsAdapter = libraryArtistsAdapter; this.context = context; this.updateLibrary = updateLibrary; this.code = code; media = ARTIST; contentResolver = context.getContentResolver(); } //DIALOG FOR PLAYLIST public MediaControlDialog(Context context, Playlists playlist, ArrayList<Playlists> currentPlaylists, PlaylistsAdapter playlistsAdapter, int code) { super(context); this.playlist = playlist; this.context = context; this.currentPlaylists = currentPlaylists; this.playlistsAdapter = playlistsAdapter; this.code = code; media = PLAYLIST; contentResolver = context.getContentResolver(); } //DIALOG FOR PLAYLIST SONG public MediaControlDialog(Context context, Songs playlistSong, Playlists playlist, ArrayList<Songs> playlistSongs, SongsAdapter playlistSongsAdapter, MediaControlDialog.UpdatePlaylist updatePlaylist, int code) { super(context); this.playlistSong = playlistSong; this.playlist = playlist; this.context = context; this.playlistSongs = playlistSongs; this.playlistSongsAdapter = playlistSongsAdapter; this.code = code; this.updatePlaylist = updatePlaylist; media = PLAYLIST_SONG; contentResolver = context.getContentResolver(); } public void OpenDialog() { alertDialog = new AlertDialog.Builder(context).create(); final View alertLayout = getLayoutInflater().inflate(R.layout.dialog_media,null); mediaArt = alertLayout.findViewById(R.id.mediaArt); mediaName = alertLayout.findViewById(R.id.mediaName); mediaArtist = alertLayout.findViewById(R.id.mediaArtist); mediaType = alertLayout.findViewById(R.id.mediaType); delete = alertLayout.findViewById(R.id.mediaDelete); playlistAction = alertLayout.findViewById(R.id.mediaPlaylist); deleteText = alertLayout.findViewById(R.id.mediaDeleteText); next = alertLayout.findViewById(R.id.mediaPlayNext); last = alertLayout.findViewById(R.id.mediaPlayLast); setDialogClickListeners(alertDialog); switch (media) { case SONG: setSongArt(song); deleteText.setText(context.getString(R.string.deleteSongFromLibrary)); mediaName.setText(song.getTitle()); mediaArtist.setText(song.getArtist()); mediaType.setText(song.getAlbum()); break; case ALBUM: setAlbumArt(album); deleteText.setText(context.getString(R.string.deleteAlbumFromLibrary)); mediaName.setText(album.getAlbum()); mediaArtist.setText(album.getArtist()); mediaType.setVisibility(View.GONE); break; case ARTIST: deleteText.setText(context.getString(R.string.deleteArtistFromLibrary)); mediaArt.setImageDrawable(context.getDrawable(R.drawable.ic_noartistart)); mediaName.setText(artist.getArtist()); mediaArtist.setVisibility(View.GONE); mediaType.setVisibility(View.GONE); break; case PLAYLIST: setPlaylistArt(); if(currentPlaylists == null && playlistsAdapter == null) delete.setVisibility(View.GONE); else deleteText.setText(context.getString(R.string.deletePlaylist)); mediaName.setText(playlist.getPlaylist()); mediaArtist.setVisibility(View.GONE); mediaType.setVisibility(View.GONE); break; case PLAYLIST_SONG: setSongArt(playlistSong); deleteText.setText(context.getString(R.string.deleteSongFromPlaylist)); mediaName.setText(playlistSong.getTitle()); mediaArtist.setText(playlistSong.getArtist()); mediaType.setText(playlistSong.getAlbum()); break; } /*switch (code) { case FROM_LIBRARY: //Log.i(TAG, "DIALOG FROM LIBRARY"); break; case FROM_ARTIST: //Log.i(TAG, "DIALOG FROM ARTIST"); break; case FROM_ALBUM: //Log.i(TAG, "DIALOG FROM ALBUM"); break; case FROM_PLAYLIST: //Log.i(TAG, "DIALOG FROM PLAYLIST"); break; }*/ alertDialog.setView(alertLayout); new Dialog(context); alertDialog.show(); ColorDrawable back = new ColorDrawable(Color.TRANSPARENT); InsetDrawable inset = new InsetDrawable(back, 20); alertDialog.getWindow().setBackgroundDrawable(inset); alertDialog.getWindow().setElevation(20.0f); } private void OpenPlaylistDialog() { alertDialogPlaylist = new AlertDialog.Builder(context).create(); final View alertLayoutPlaylist = getLayoutInflater().inflate(R.layout.dialog_playlist,null); cancelPlaylist = alertLayoutPlaylist.findViewById(R.id.cancelPlaylist); createNewPlaylist = alertLayoutPlaylist.findViewById(R.id.createPlaylist); setPlaylistDialogClickListeners(alertDialogPlaylist); recyclerView = alertLayoutPlaylist.findViewById(R.id.createdPlaylists); LinearLayoutManager layoutManager = new LinearLayoutManager(context); PlaylistDialogAdapter dialogAdapter = new PlaylistDialogAdapter(playlists, this); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(dialogAdapter); alertDialogPlaylist.setView(alertLayoutPlaylist); new Dialog(context); alertDialogPlaylist.show(); ColorDrawable back = new ColorDrawable(Color.TRANSPARENT); InsetDrawable inset = new InsetDrawable(back, 100); alertDialogPlaylist.getWindow().setBackgroundDrawable(inset); alertDialogPlaylist.getWindow().setElevation(20.0f); } public void OpenNewPlaylistDialog() { alertDialogNewPlaylist = new AlertDialog.Builder(context).create(); final View alertLayoutNewPlaylist = getLayoutInflater().inflate(R.layout.dialog_new_playlist,null); newPlaylistCancel = alertLayoutNewPlaylist.findViewById(R.id.cancelNewPlaylist); newPlaylistCreate = alertLayoutNewPlaylist.findViewById(R.id.createNewPlaylist); newPlaylistName = alertLayoutNewPlaylist.findViewById(R.id.newPlaylistName); newPlaylistDescription = alertLayoutNewPlaylist.findViewById(R.id.newPlaylistDescription); setNewPlaylistDialogClickListeners(alertDialogNewPlaylist); alertDialogNewPlaylist.setView(alertLayoutNewPlaylist); new Dialog(context); alertDialogNewPlaylist.show(); ColorDrawable back = new ColorDrawable(Color.TRANSPARENT); InsetDrawable inset = new InsetDrawable(back, 100); alertDialogNewPlaylist.getWindow().setBackgroundDrawable(inset); alertDialogNewPlaylist.getWindow().setElevation(20.0f); } private void setSongArt(Songs song) { Uri uri = Uri.parse(song.getArt()); Glide.with(context).load(uri).placeholder(R.drawable.noalbumart).fallback(R.drawable.noalbumart).error(R.drawable.noalbumart).into(mediaArt); } private void setAlbumArt(Albums album) { Uri uri = Uri.parse(album.getArt()); Glide.with(context).load(uri).placeholder(R.drawable.noalbumart).fallback(R.drawable.noalbumart).error(R.drawable.noalbumart).into(mediaArt); } private void setPlaylistArt() { Glide.with(context).load(R.drawable.playlistart).into(mediaArt); } @Override public void onListItemClick(Playlists playlist) { switch (media) { case SONG: mediaBrowserHelper.addToPlaylist(playlist, song); Toast.makeText(context, song.getTitle().toUpperCase() + " ADDED TO " + playlist.getPlaylist().toUpperCase(), Toast.LENGTH_SHORT).show(); break; case ARTIST: mediaBrowserHelper.addToPlaylist(playlist, artist); Toast.makeText(context, artist.getArtist().toUpperCase() + " ADDED TO " + playlist.getPlaylist().toUpperCase(), Toast.LENGTH_SHORT).show(); //Log.i(TAG, artist.getArtist().toUpperCase() + " ADDED TO " + playlist.getPlaylist().toUpperCase()); break; case ALBUM: mediaBrowserHelper.addToPlaylist(playlist, album); Toast.makeText(context, album.getAlbum().toUpperCase() + " ADDED TO " + playlist.getPlaylist().toUpperCase(), Toast.LENGTH_SHORT).show(); //Log.i(TAG, album.getAlbum().toUpperCase() + " ADDED TO " + playlist.getPlaylist().toUpperCase()); break; case PLAYLIST: mediaBrowserHelper.addToPlaylist(playlist, this.playlist); Toast.makeText(context, this.playlist.getPlaylist().toUpperCase() + " ADDED TO " + playlist.getPlaylist().toUpperCase(), Toast.LENGTH_SHORT).show(); //Log.i(TAG, this.playlist.getPlaylist().toUpperCase() + " ADDED TO " + playlist.getPlaylist().toUpperCase()); break; } alertDialogPlaylist.dismiss(); } private void setDialogClickListeners(AlertDialog alertDialog) { delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { switch (media) { case SONG: alertDialog.dismiss(); /*if(code == FROM_ALBUM || code == FROM_ARTIST) { updateLibrary.updateSongsLibrary(song); }*/ updateLibrary.updateSongsLibrary(song); removePosition = librarySongs.indexOf(song); librarySongs.remove(song); if(code == FROM_LIBRARY || code == FROM_ARTIST) librarySongsAdapter.notifyItemRemoved(removePosition); else if(code == FROM_ALBUM) albumSongsAdapter.notifyItemRemoved(removePosition); /*long songId = Long.parseLong(song.getId()); Uri songUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, songId); String selectionSong = MediaStore.Audio.Media._ID + "=?"; String[] selectionArgsSong = {song.getId()}; contentResolver.delete(songUri, selectionSong, selectionArgsSong);*/ //Toast.makeText(context, song.getTitle() + " DELETED", Toast.LENGTH_SHORT).show(); //Log.i(TAG, song.getTitle().toUpperCase() + " DELETED FROM LIBRARY"); break; case ALBUM: alertDialog.dismiss(); LoaderManager.getInstance((MainActivity) context).initLoader(DIALOG_MEDIA_LOADER, null, songsCallbacks); break; case ARTIST: alertDialog.dismiss(); LoaderManager.getInstance((MainActivity) context).initLoader(DIALOG_MEDIA_LOADER, null, songsCallbacks); break; case PLAYLIST: alertDialog.dismiss(); removePosition = currentPlaylists.indexOf(playlist); currentPlaylists.remove(playlist); playlistsAdapter.notifyItemRemoved(removePosition); playlists.remove(playlist); Uri playlistUri = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI; String selectionPlaylist = MediaStore.Audio.Playlists.NAME + "=?"; String[] selectionArgPlaylist = {playlist.getPlaylist() + "SPLITHERE" + playlist.getDescription()}; contentResolver.delete(playlistUri, selectionPlaylist, selectionArgPlaylist); Uri playlistSongsUri = MediaStore.Audio.Playlists.Members.getContentUri("external", Long.parseLong(playlist.getId())); contentResolver.delete(playlistSongsUri, null, null); Toast.makeText(context, playlist.getPlaylist() + " DELETED", Toast.LENGTH_SHORT).show(); //Log.i(TAG, playlist.getPlaylist().toUpperCase() + " DELETED FROM PLAYLISTS"); break; case PLAYLIST_SONG: alertDialog.dismiss(); removePosition = playlistSongs.indexOf(playlistSong); playlistSongs.remove(playlistSong); playlistSongsAdapter.notifyItemRemoved(removePosition); Uri playlistSongUri = MediaStore.Audio.Playlists.Members.getContentUri("external", Long.parseLong(playlist.getId())); String selectionPlaylistSong = MediaStore.Audio.Playlists.Members.AUDIO_ID + "=?"; String[] selectionArgPlaylistSong = {playlistSong.getId()}; contentResolver.delete(playlistSongUri, selectionPlaylistSong, selectionArgPlaylistSong); updatePlaylist.updatePlaylistCount(); Toast.makeText(context, playlistSong.getTitle() + " DELETED", Toast.LENGTH_SHORT).show(); //Log.i(TAG, playlistSong.getTitle().toUpperCase() + " DELETED FROM PLAYLIST"); break; } } }); playlistAction.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { alertDialog.dismiss(); OpenPlaylistDialog(); } }); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { switch (media) { case SONG: mediaBrowserHelper.addNext(song); alertDialog.dismiss(); break; case PLAYLIST_SONG: mediaBrowserHelper.addNext(playlistSong); alertDialog.dismiss(); break; case ALBUM: mediaBrowserHelper.addNext(album); alertDialog.dismiss(); break; case ARTIST: mediaBrowserHelper.addNext(artist); alertDialog.dismiss(); break; case PLAYLIST: mediaBrowserHelper.addNext(playlist); alertDialog.dismiss(); break; } } }); last.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { switch (media) { case SONG: mediaBrowserHelper.addLast(song); alertDialog.dismiss(); break; case PLAYLIST_SONG: mediaBrowserHelper.addLast(playlistSong); alertDialog.dismiss(); break; case ALBUM: mediaBrowserHelper.addLast(album); alertDialog.dismiss(); break; case ARTIST: mediaBrowserHelper.addLast(artist); alertDialog.dismiss(); break; case PLAYLIST: mediaBrowserHelper.addLast(playlist); alertDialog.dismiss(); break; } } }); } private void setPlaylistDialogClickListeners(AlertDialog alertDialog) { cancelPlaylist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { alertDialog.dismiss(); } }); createNewPlaylist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { alertDialog.dismiss(); OpenNewPlaylistDialog(); } }); } private void setNewPlaylistDialogClickListeners(AlertDialog alertDialog) { newPlaylistCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { alertDialog.dismiss(); } }); newPlaylistCreate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String newName = newPlaylistName.getText().toString(); String newDescription = newPlaylistDescription.getText().toString(); if(!TextUtils.isEmpty(newName)) { ContentResolver contentResolver = context.getContentResolver(); Uri playlistUri = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI; ContentValues values = new ContentValues(); String split = "SPLITHERE"; values.put(MediaStore.Audio.Playlists.NAME, newName + split + newDescription); Uri newPlaylistUri = contentResolver.insert(playlistUri, values); if(newPlaylistUri != null) { String[] projection = {MediaStore.Audio.Playlists.NAME ,MediaStore.Audio.Playlists._ID}; Cursor cursor = contentResolver.query(newPlaylistUri ,projection, null, null, null); if(cursor != null && cursor.moveToFirst()) { int playlistDetails = cursor.getColumnIndex(MediaStore.Audio.Playlists.NAME); int id = cursor.getColumnIndex(MediaStore.Audio.Playlists._ID); String NameDescription = cursor.getString(playlistDetails); String[] parts = NameDescription.split(split); String playlistName = parts[0]; String playlistDescription = parts[1]; String playlistID = cursor.getString(id); //Log.i(TAG, "PLAYLIST " + playlistName.toUpperCase() + " CREATED WITH ID " + playlistID); playlists.add(new Playlists(playlistName, playlistID, playlistDescription)); cursor.close(); } } alertDialog.dismiss(); if(playlist != null) OpenPlaylistDialog(); } else newPlaylistName.setError("MUST INPUT NAME"); } }); } private LoaderManager.LoaderCallbacks<ArrayList> songsCallbacks = new LoaderManager.LoaderCallbacks<ArrayList>() { @NonNull @Override public Loader<ArrayList> onCreateLoader(int id, @Nullable Bundle args) { if(media == ALBUM) return new GetMedia(context, GET_ALBUM_SONGS, -1, album); return new GetMedia(context, GET_ARTIST_SONGS, -1, artist); } @Override public void onLoadFinished(@NonNull Loader<ArrayList> loader, ArrayList data) { if(media == ALBUM) { albumSongs = data; updateLibrary.updateAlbumsLibrary(album, albumSongs, code); if(code == FROM_LIBRARY || code == FROM_ARTIST) { removePosition = libraryAlbums.indexOf(album); libraryAlbums.remove(album); libraryAlbumsAdapter.notifyItemRemoved(removePosition); } } else { artistSongs = data; updateLibrary.updateArtistsLibrary(artist, artistSongs); removePosition = libraryArtists.indexOf(artist); libraryArtists.remove(artist); libraryArtistsAdapter.notifyItemRemoved(removePosition); } } @Override public void onLoaderReset(@NonNull Loader<ArrayList> loader) {} }; } <file_sep>/app/src/main/java/com/rookieandroid/rookiemusicplayer/architecture/StateViewModel.java package com.rookieandroid.rookiemusicplayer.architecture; import android.app.Application; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LiveData; import com.rookieandroid.rookiemusicplayer.SavedStateDetails; import com.rookieandroid.rookiemusicplayer.Songs; import java.util.List; public class StateViewModel extends AndroidViewModel { private StateRepository stateRepository; private LiveData<List<Songs>> savedQueue; private LiveData<List<SavedStateDetails>> savedStateDetails; public StateViewModel(@NonNull Application application) { super(application); stateRepository = new StateRepository(application); savedQueue = stateRepository.getSavedQueue(); savedStateDetails = stateRepository.getSavedStateDetails(); } public void insertAll(List<Songs> savedQueue) { stateRepository.insertAll(savedQueue); } public void insert(SavedDetails savedDetails) { stateRepository.insert(savedDetails); } public void update(SavedDetails savedDetails) { stateRepository.update(savedDetails); } public void delete(SavedDetails savedDetails) { stateRepository.delete(savedDetails); } public void deleteSavedQueue() { stateRepository.deleteSavedQueue(); } public void deleteSavedDetails() { stateRepository.deleteSavedDetails(); } public LiveData<List<Songs>> getSavedQueue() { return savedQueue; } public LiveData<List<SavedStateDetails>> getSavedStateDetails() { return savedStateDetails; } }
43e15301058f7fcd6c37337450b3e5a0c82980ff
[ "Markdown", "Java" ]
19
Java
dariushooks/RookMusicPlayer
f59cfdd7bfa623e5bd7767b6a8fd57ca9dfae982
305ec63b51bed3113e26b006c7f166cf9f829983
refs/heads/master
<repo_name>FlorianVeys/BluetoothSender<file_sep>/BluetoothSender-Windows/BluetoothSender-Windows/ViewModel/Converters/BooleanToColorConverter.cs using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using System.Windows.Media; namespace BluetoothSender_Windows.ViewModel.Converters { public class BooleanToColorConverter : IValueConverter { private readonly String _colorBackgroundDefault = "DarkSlateGray"; private readonly String _colorBackgroundUserControl = "#FF436060"; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { try { bool active = value != null && (bool) value; return active ? _colorBackgroundUserControl : _colorBackgroundDefault; } catch (Exception) { return _colorBackgroundDefault; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } } <file_sep>/BluetoothSender-Windows/BluetoothSender-Windows/ViewModel/ReceiverViewModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GalaSoft.MvvmLight; namespace BluetoothSender_Windows.ViewModel { public class ReceiverViewModel : ViewModelBase { private bool _bluetoothServiceIsActive; public bool BluetoothServiceActive { get => _bluetoothServiceIsActive; set { if (_bluetoothServiceIsActive != value) { _bluetoothServiceIsActive = value; if (value) { BluetoothServiceStart(); } else { BluetoothServiceStop(); } RaisePropertyChanged(nameof(BluetoothServiceActive)); } } } public ReceiverViewModel() { //TODO } private void BluetoothServiceStart() { //TODO } private void BluetoothServiceStop() { //TODO } } } <file_sep>/BluetoothSender-Windows/BluetoothSender-Windows/ViewModel/EmitterViewModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.CommandWpf; namespace BluetoothSender_Windows.ViewModel { public class EmitterViewModel : ViewModelBase { public ICommand RefreshDevicesList { get; } public EmitterViewModel() { RefreshDevicesList = new RelayCommand(RefreshList); } private void RefreshList() { //TODO } } } <file_sep>/BluetoothSender-Windows/BluetoothSender-Windows/ViewModel/Converters/VisibilityConverter.cs using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace BluetoothSender_Windows.ViewModel.Converters { public class VisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Boolean val = value != null && (Boolean)value; return val ? "Visible" : "Collapsed"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { String val = (String)value; return val != null && val.Equals("Visible"); } } } <file_sep>/BluetoothSender-Windows/BluetoothSender-Windows/ViewModel/MainViewModel.cs using System; using System.ComponentModel; using System.Windows; using System.Windows.Input; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.CommandWpf; namespace BluetoothSender_Windows.ViewModel { public class MainViewModel : ViewModelBase { public ICommand CloseApplication { get; } public ICommand MinimizeApplication { get; } public ICommand MenuControl { get; } public bool VisibilityHistory { get; set; } public bool VisibilityEmitter { get; set; } public bool VisibilityReceiver { get; set; } public MainViewModel() { CloseApplication = new RelayCommand(CloseAppli); MinimizeApplication = new RelayCommand(MinimizeAppli); MenuControl = new RelayCommand<string>(changeView); DisplayEmitterView(); } private void changeView(string parameter) { switch (parameter) { case "History": DisplayHistoryView(); break; case "Emitter": DisplayEmitterView(); break; case "Receiver": DisplayReceiverView(); break; } NotifyChange(); } private void DisplayHistoryView() { VisibilityEmitter = false; VisibilityReceiver = false; VisibilityHistory = true; } private void DisplayEmitterView() { VisibilityEmitter = true; VisibilityReceiver = false; VisibilityHistory = false; } private void DisplayReceiverView() { VisibilityEmitter = false; VisibilityReceiver = true; VisibilityHistory = false; } private void CloseAppli() { App.Current.Shutdown(); } private void MinimizeAppli() { App.Current.MainWindow.WindowState = WindowState.Minimized; } private void NotifyChange() { RaisePropertyChanged(nameof(VisibilityEmitter)); RaisePropertyChanged(nameof(VisibilityReceiver)); RaisePropertyChanged(nameof(VisibilityHistory)); } } }<file_sep>/BluetoothSender-Windows/BluetoothSender-Windows/ViewModel/Converters/BooleanToMessageConverter.cs using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace BluetoothSender_Windows.ViewModel.Converters { public class BooleanToMessageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { bool active = (bool) value; return active ? "Service activé" : "Service désactivé"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } }
8c88c16db8dc592618cb0644baec98c6a3f8f72f
[ "C#" ]
6
C#
FlorianVeys/BluetoothSender
86f70cdf44e896c7bd6a64292a9acaa42bfb7750
d5c4adf10b873884cc715efe5da293326f1a63ef
refs/heads/master
<file_sep>package com.company.proj.Topic; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class TopicService { private List<Topic> topics = new ArrayList<Topic>(); public TopicService() { this.topics.add(new Topic(1,"maths")); this.topics.add(new Topic(2,"maths")); this.topics.add(new Topic(3,"maths")); this.topics.add(new Topic(4,"maths")); } public List<Topic> getAllTopics() { return topics; } public Topic getTopic(String id) { return topics.get(Integer.parseInt(id)-1); } public List<Topic> addTopic(Topic topic) { this.topics.add(topic); return topics; } public List<Topic> updateTopic(Topic topic, String id) { topics.remove(Integer.parseInt(id)-1); this.topics.add(Integer.parseInt(id)-1,topic) ; return topics; } }
44ba823ddcd11510c0d52aa5d3b8d3a64e0dd1df
[ "Java" ]
1
Java
kumararunesh/sbproj
ff4ab265a1b6e8fbc10db5e87dbe7a9bbf190d9a
c820f3b47c252aa162632e094142f1011da226bb
refs/heads/master
<file_sep># Villain Mail A villains-only messages application. ## Installation 1. Clone source code from url https://github.com/trenshaw88/Villain-Mail.git 2. Create a database 3. Create .env and add database credentials 4. Run migrations # Heroku 1. Open browser, navigate to url https://villian-mail.herokuapp.com/ <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\DB; class Sent extends Model { public function messages() { return $this->hasMany('App\Message')->orderBy('recipient_id', 'desc'); } public static function sent_messages() { // $condition = \App\Condition::find(2); $sent_messages = DB::table('messages') ->orderBy('created_at', 'desc') ->get(); return $sent_messages; } public function recipient() { return $this->belongsTo('App\Message', 'recipient_id'); } }
6f480c4cd68c170adee2ea24539e444f32bbfa2b
[ "Markdown", "PHP" ]
2
Markdown
trenshaw88/Villain-Mail
62b624cbb9477ed56a60eb520f8a0cf6a6d2866e
1b2961e07045ca23f24265751ef600792db0eb60
refs/heads/master
<repo_name>zawa-works/EmoTip<file_sep>/settings.js const ids = ['very_satisfied', 'satisfied', 'neither', 'dissatisfied', 'very_dissatisfied'] document.addEventListener('touchmove', function (e) { e.preventDefault(); }, { passive: false }); function drawSelectedBorder(ele) { let id_value = ele.id ids.forEach(function (id) { let obj = document.getElementById(id) if (id === id_value) obj.style.border = 'solid 1px yellow'; else obj.style.borderWidth = '0px'; }) }
2f3c222dea09a6e66a94283a8265dcf5e871a0e2
[ "JavaScript" ]
1
JavaScript
zawa-works/EmoTip
ab0e85c13407691a777be964de98350328683dad
3e6da745cf6850accfc05f0d558b7ac7ecfc8b9e
refs/heads/master
<file_sep># import asyncio # import websockets # async def hello(): # async with websockets.connect('ws://localhost:8080') as websocket: # name = input("What's your name??") # await websocket.send(name) # print(websocket) # print("> {}".format(name)) # greeting = await websocket.recv() # print("> {}".format(greeting)) # asyncio.get_event_loop().run_until_complete(hello()) from websocket import create_connection import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(module)s - %(asctime)s - %(levelname)s - %(message)s')) logger.addHandler(handler) ws = create_connection("ws://127.0.0.1:12345") logger.info("Open") send = "11 23" logger.info("Sending '{}'...".format(send)) ws.send(send) logger.info("sent") logger.info("Receiving...") result = ws.recv() logger.info("Received '{}".format(result)) ws.close() logger.info("Close") # import websocket # import thread # import time # import logging # logger = logging.getLogger(__name__) <file_sep># import asyncio # import websockets # async def hello(websocket, path): # name = await websocket.recv() # print("< {}".format(name)) # greeting = "Hello {}!!".format(name) # await websocket.send(greeting) # print("> {}".format(greeting)) # start_server = websockets.serve(hello, 'localhost', 8080) # asyncio.get_event_loop().run_until_complete(start_server) # asyncio.get_event_loop().run_forever() import logging from websocket_server import WebsocketServer logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(module)s - %(asctime)s - %(levelname)s - %(message)s')) logger.addHandler(handler) def new_client(client, server): logger.info('New Client {}:{} has joined'.format(client['address'][0], client['address'][1])) def client_left(client, server): logger.info('New Client {}:{} has left'.format(client['address'][0], client['address'][1])) def message_received(client, server, message): logger.info('Message "{}" has been received from {}:{}'.format(message, client['address'][0], client['address'][1])) # reply_message = 'Hi!!' + message result = message_processing(message) server.send_message(client, str(result)) logger.info('Message "{}" has been received from {}:{}'.format(result, client['address'][0], client['address'][1])) def message_processing(message): content = message.split(' ') return int(content[0]) + int(content[1]) if __name__ == '__main__': server = WebsocketServer(port=12345, host='127.0.0.1', loglevel=logging.INFO) server.set_fn_new_client(new_client) server.set_fn_client_left(client_left) server.set_fn_message_received(message_received) server.run_forever()<file_sep>## Introduction This is an experimental implementation of WebSocket in Python. ## Version Python: 3.6 ## Prerequisites pip install websocket_server, logging ## Usage ```console $ git clone https://github.com/Rowing0914/WebSocket_python.git $ cd WebSocket_python $ python server.py ## Open another terminal or CMD and execute the command below. $ python client.py ```
dcd29b8fe99ef486d8665f907ae6ddd923cf452e
[ "Markdown", "Python" ]
3
Python
Rowing0914/WebSocket_python
dd8b1c17a3768e1cc1a606eb03a99e19a06f4889
584458ca7114477fb0e81e0da01707f9be4fb1b3
refs/heads/master
<file_sep>import helloWorld from './hello-world'; import addImage from './adding-image'; import HelloButton from './components/Hello-button/Hello-button'; import CustomButton from './components/Custom-button/CustomButton'; helloWorld(); addImage(); const helloButton = new HelloButton(); helloButton.render(); const customButton = new CustomButton(); customButton.render(); <file_sep>npm install sass-loader node-sass webpack --save-dev <file_sep>import lionImg from '../images/lion.jpg'; export default function addImage() { const img = document.createElement('img'); img.alt = 'lion image'; img.title = 'title image'; img.src = lionImg; img.width = 300; const body = document.querySelector('body'); body.appendChild(img); } <file_sep>import './CustomButton.scss'; class CustomButton { buttonCssClass = 'custom-button'; render() { const button = document.createElement('button'); const body = document.querySelector('body'); button.innerHTML = 'Custom Button'; button.onclick = function() { const p = document.createElement('p'); p.innerHTML = 'Custom Text'; p.classList.add('custom-text'); body.appendChild(p); }; // button.classList.add('custom-button'); button.classList.add(this.buttonCssClass); //this will work after setting up babel loader to support ES6 features body.appendChild(button); } } export default CustomButton;
a2cca13c2a4365472a5deaf2a0bb349e49bf8edb
[ "JavaScript", "Markdown" ]
4
JavaScript
jaintanya1128/learning-webpack
42bf9b729fb141d101c6603ad9ac146be69ffa90
3e98b763d120029650c1a15c2a8e49797c31b80b
refs/heads/master
<file_sep>package ui; /** * * @author DEGUZMAN */ public final class Constants { public static final String DONT_EXIST = "dont exist"; public static final String EXIST = "exist"; public static final String ERROR = "error"; public static final String HOST = "127.0.0.1"; public static final int PORT = 8888; public static final String VERIFY_ADMIN_REQUEST = "verify admin"; public static final String GENERATE_ACCOUNT_REQUEST = "generate account"; public static final String ADD_CUSTOMER_REQUEST = "add customer"; public static final String VERIFY_CUSTOMER_REQUEST = "verify customer"; public static final String CHECK_FINGERPRINT_REQUEST = "check if fingerprint exist"; public static final String ADD_ACCOUNT_REQUEST = "add account"; public static final String GET_ID_REQUEST = "get id"; public static final String GET_ACCOUNTS_REQUEST = "get accounts"; public static final String GET_ACCOUNT_BALANCES_REQUEST = "get account balances"; public static final String GET_NAMES_REQUEST = "get names"; public static final String ACTION_SUCCESSFUL = "successful"; public static final String ACTION_UNSUCCESSFUL = "unsuccessful"; public static final String FIRST_NAME = "first_name"; public static final String LAST_NAME = "last_name"; public static final String ID_NUMBER = "id_number"; public static final String ACCOUNT_NUMBER = "account_number"; public static final String PASSWORD = "<PASSWORD>"; public static final String PRINT = "print"; public static final String USERNAME = "username"; private Constants() { //this prevents even the native class from calling this ctor as well : throw new AssertionError(); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ui; import java.awt.Cursor; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.Document; /** * * @author DEGUZMAN */ public class LoginPanel extends javax.swing.JPanel { DocumentListener listener = new MyDocumentListener(); /** * Creates new form LoginPanel */ public LoginPanel() { initComponents(); usernameField.getDocument().addDocumentListener(listener); passwordField.getDocument().addDocumentListener(listener); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); usernameField = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); passwordField = new javax.swing.JPasswordField(); loginButton = new javax.swing.JButton(); exitButton = new javax.swing.JButton(); jLabel1.setText("Login"); jLabel2.setText("User - name :"); jLabel3.setText("Password:"); loginButton.setText("Log in"); loginButton.setEnabled(false); loginButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loginButtonActionPerformed(evt); } }); exitButton.setText("Exit"); exitButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(exitButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(loginButton)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(passwordField)))) .addContainerGap(30, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(loginButton) .addComponent(exitButton)) .addContainerGap(42, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed new Thread(this::verifyAdmin).start(); }//GEN-LAST:event_loginButtonActionPerformed private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed AdminFrame.getHomePanel().showPanel(HomePanelController.WELCOME_PANEL); }//GEN-LAST:event_exitButtonActionPerformed public void verifyAdmin() { String username = usernameField.getText(); String password = <PASSWORD>.valueOf(<PASSWORD>()); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); loginButton.setEnabled(false); try { String response = Connector.verifyAdmin(username, password); if (response.equalsIgnoreCase("EXIST")) { AdminFrame.getHomePanel().getWelcomePanel().setLoginButton(false); AdminFrame.getHomePanel().getWelcomePanel().setLogoutButton(true); AdminFrame.getHomePanel().showPanel(HomePanelController.WELCOME_PANEL); AdminFrame.setButtonsStatus(true); } else if (response.equalsIgnoreCase("NOT FOUND")) { JOptionPane.showMessageDialog(this, "Not Authorised", "Info", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this, response, "Info", JOptionPane.INFORMATION_MESSAGE); } } catch (IOException ex) { //Logger.getLogger(LoginPanel.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } setCursor(null); loginButton.setEnabled(true); } public static void main(String[] arf) { JFrame frame = new JFrame("Loging in"); frame.add(new LoginPanel()); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton exitButton; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JButton loginButton; private javax.swing.JPasswordField passwordField; private javax.swing.JTextField usernameField; // End of variables declaration//GEN-END:variables class MyDocumentListener implements DocumentListener { @Override public void insertUpdate(DocumentEvent e) { loginButton.setEnabled(!usernameField.getText().equals("") && passwordField.getPassword().length > 0); } @Override public void removeUpdate(DocumentEvent e) { loginButton.setEnabled(!usernameField.getText().equals("") && passwordField.getPassword().length > 0); } @Override public void changedUpdate(DocumentEvent e) { loginButton.setEnabled(!usernameField.getText().equals("") && passwordField.getPassword().length > 0); } } } <file_sep>package ui; import java.awt.Cursor; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; public class DetailsForm extends javax.swing.JPanel { MyDocumentListener listener = new MyDocumentListener(); /** * Creates new form DetailsForm */ public DetailsForm() { initComponents(); firstNameField.getDocument().addDocumentListener(listener); lastNameField.getDocument().addDocumentListener(listener); idField.getDocument().addDocumentListener(listener); passwordField.getDocument().addDocumentListener(listener); confirmPasswordField.getDocument().addDocumentListener(listener); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); firstNameField = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); lastNameField = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); idField = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); passwordField = new javax.swing.JPasswordField(); confirmPasswordField = new javax.swing.JPasswordField(); generateAccountButton = new javax.swing.JButton(); accountLabel = new javax.swing.JLabel(); okButton = new javax.swing.JButton(); exitButton = new javax.swing.JButton(); confirmationLabel = new javax.swing.JLabel(); passwordSizeLabel = new javax.swing.JLabel(); jLabel1.setText("Customers Details"); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel2.setText("First name"); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel3.setText("Last name"); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel4.setText("Id number"); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel5.setText("Password"); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel6.setText("Confirm"); generateAccountButton.setText("Generate account number."); generateAccountButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { generateAccountButtonActionPerformed(evt); } }); accountLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); accountLabel.setText("_"); okButton.setText("Ok"); okButton.setEnabled(false); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); exitButton.setText("Exit"); exitButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitButtonActionPerformed(evt); } }); confirmationLabel.setForeground(new java.awt.Color(255, 0, 0)); confirmationLabel.setText(" "); passwordSizeLabel.setForeground(new java.awt.Color(255, 0, 0)); passwordSizeLabel.setText(" "); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(exitButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(okButton)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(firstNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(lastNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(idField, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(generateAccountButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(accountLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(confirmationLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(confirmPasswordField))) .addGroup(layout.createSequentialGroup() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(passwordSizeLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(passwordField))))) .addContainerGap(159, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(firstNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(lastNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(idField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(passwordSizeLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 21, Short.MAX_VALUE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(confirmPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(confirmationLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(generateAccountButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(accountLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(okButton) .addComponent(exitButton)) .addGap(27, 27, 27)) ); }// </editor-fold>//GEN-END:initComponents private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed AdminFrame.getAddPanel().showPanel(AddPanelController.SCANNING_PANEL); }//GEN-LAST:event_exitButtonActionPerformed private void generateAccountButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generateAccountButtonActionPerformed new Thread(this::getAndSetAccount).start(); }//GEN-LAST:event_generateAccountButtonActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed if (!Arrays.equals(passwordField.getPassword(), confirmPasswordField.getPassword())) { JOptionPane.showMessageDialog(this, "Confirmed password should be equal to the password", "Info", JOptionPane.ERROR_MESSAGE); return; } if (confirmDetails()) { BufferedImage print = AdminFrame.getAddPanel().getScanningPanel().getPrint(); new Thread(() -> addCustomer(getDetails(), print)).start(); } }//GEN-LAST:event_okButtonActionPerformed public Map<String, String> getDetails() { Map<String, String> details = new HashMap<>(); details.put(Constants.FIRST_NAME, firstNameField.getText()); details.put(Constants.LAST_NAME, lastNameField.getText()); details.put(Constants.ID_NUMBER, idField.getText()); details.put(Constants.ACCOUNT_NUMBER, accountLabel.getText()); details.put(Constants.PASSWORD, String.valueOf(passwordField.getPassword())); return details; } public boolean confirmDetails() { String message = String.format("%13s : %-15s %n%13s : %-15s %n%13s : %-15s %n%13s : %-15s", "First name", firstNameField.getText(), "Last name", lastNameField.getText(), "ID number", idField.getText(), "Account", accountLabel.getText() ); int choice = JOptionPane.showConfirmDialog(this, message, "Confirm", JOptionPane.OK_CANCEL_OPTION); return (choice == JOptionPane.OK_OPTION); } private void processResponse(String response) { JOptionPane.showMessageDialog(this, response); if (response.equalsIgnoreCase("SUCCESS")) { AdminFrame.getAddPanel().showPanel(AddPanelController.SCANNING_PANEL); } } public void addCustomer(Map<String, String> details, BufferedImage image) { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); okButton.setEnabled(false); try { String response = Connector.addCustomer(details, image); processResponse(response); } catch (IOException ex) { ex.printStackTrace(); } setCursor(null); resetFields(); okButton.setEnabled(true); } public void setOkButton() { boolean status = !"_".equals(accountLabel.getText()) && confirmPasswordField.getPassword().length > 0 && !"".equals(firstNameField.getText()) && !"".equals(idField.getText()) && !"".equals(lastNameField.getText()) && passwordField.getPassword().length > 0; okButton.setEnabled(status); } public void getAndSetAccount() { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); generateAccountButton.setEnabled(false); try { String account = Connector.generateAccountNumber(); SwingUtilities.invokeLater(() -> { accountLabel.setText(account); setOkButton(); }); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(this, ex.getMessage(), "Info", JOptionPane.ERROR_MESSAGE); } setCursor(null); generateAccountButton.setEnabled(true); } public void resetFields() { accountLabel.setText("_"); confirmPasswordField.setText(""); passwordField.setText(""); firstNameField.setText(""); lastNameField.setText(""); idField.setText(""); } class MyDocumentListener implements DocumentListener { @Override public void insertUpdate(DocumentEvent e) { set(); } @Override public void removeUpdate(DocumentEvent e) { set(); } @Override public void changedUpdate(DocumentEvent e) { set(); } public void set() { int passwordSize = passwordField.getPassword().length; boolean passwordSizeOk = passwordSize > 0 && passwordSize >= 6; String s = (passwordSize > 0 && passwordSize < 6) ? ("Password length must be greater than 6 characters"): (" "); passwordSizeLabel.setText(s); boolean passwordEqual = Arrays.equals(passwordField.getPassword(), confirmPasswordField.getPassword()); s = (confirmPasswordField.getPassword().length > 0 && !passwordEqual) ? ("Password should be the same") : (" "); confirmationLabel.setText(s); boolean status = !"_".equals(accountLabel.getText()) && passwordEqual && !"".equals(firstNameField.getText()) && !"".equals(idField.getText()) && !"".equals(lastNameField.getText()) && passwordSizeOk; okButton.setEnabled(status); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel accountLabel; private javax.swing.JPasswordField confirmPasswordField; private javax.swing.JLabel confirmationLabel; private javax.swing.JButton exitButton; private javax.swing.JTextField firstNameField; private javax.swing.JButton generateAccountButton; private javax.swing.JTextField idField; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JTextField lastNameField; private javax.swing.JButton okButton; private javax.swing.JPasswordField passwordField; private javax.swing.JLabel passwordSizeLabel; // End of variables declaration//GEN-END:variables public static void main(String[] args) { JFrame frame = new JFrame("Details form"); frame.add(new DetailsForm()); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }//334 <file_sep>package ui; import java.awt.Cursor; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; public class ScanningPanel extends javax.swing.JPanel { GUITimer timer = new GUITimer(); /** * Creates new form scanningPanel */ public ScanningPanel() { initComponents(); addMouseListener(timer); timer.start(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); printLabel = new javax.swing.JLabel(); jLabel1.setText("Scan fingerprint"); printLabel.setBackground(new java.awt.Color(255, 255, 255)); printLabel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true)); printLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { printLabelMouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(printLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 362, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(28, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(printLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(33, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void printLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_printLabelMouseClicked String filePath = getPath(); setIcon(new ImageIcon(filePath)); try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); String id = getIdForPrint(ImageIO.read(new File(filePath))); setCursor(null); processResponse(id); } catch (IOException ex) { JOptionPane.showMessageDialog(this.getParent(), ex.getMessage()); ex.printStackTrace(); } finally { setCursor(null); reset(); } }//GEN-LAST:event_printLabelMouseClicked private void processResponse(String response) { if (response.equals("")) { JOptionPane.showMessageDialog(this.getParent(), "Print not found"); return; } else if (response.startsWith("ERROR")) { JOptionPane.showMessageDialog(this.getParent(), response, "Error", JOptionPane.INFORMATION_MESSAGE); CustomerFrame.showPanel(CustomerFrame.WELCOME_PANEL); return; } authenticate(response); } private String getPassword() { JPasswordField passwordField = new JPasswordField(); JOptionPane pane = new JOptionPane(); pane.setMessage(passwordField); JDialog dialog = pane.createDialog(this.getParent(), "Enter password"); dialog.setModal(true); dialog.setVisible(true); dialog.dispose(); String password = String.valueOf(passwordField.getPassword()); return password; } public void authenticate(String id) { for (int trials = 0; trials < 3; trials++) { String password = getPassword(); String result = verifyCustomer(id, password); if (result.equalsIgnoreCase("EXIST")) { CustomerFrame.showPanel(CustomerFrame.ACTION_PANEL); CustomerFrame.setCustomerId(id); break; } else if (result.equalsIgnoreCase("NOT FOUND")) { } else { JOptionPane.showMessageDialog(this.getParent(), result, "Error", JOptionPane.INFORMATION_MESSAGE); CustomerFrame.showPanel(CustomerFrame.WELCOME_PANEL); } } } private String verifyCustomer(String id, String password) { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); String result; try { result = ClientConnector.verifyCustomer(id, password); } catch (IOException ex) { CustomerFrame.showPanel(CustomerFrame.WELCOME_PANEL); result = "ERROR:" + ex.getMessage(); ex.printStackTrace(); } setCursor(null); return result; } /** * prompts for the path of the print * * @return the path of the selected print */ private String getPath() { JFileChooser fileChooser = new PictureChooser(); int result = fileChooser.showOpenDialog(null); if (result == JFileChooser.CANCEL_OPTION) { return null; } File fileName = fileChooser.getSelectedFile(); //get file //display error if invalid if ((fileName == null) || (fileName.getName().equals(""))) { JOptionPane.showMessageDialog(this, "Invalid Name", "error", JOptionPane.ERROR_MESSAGE); return null; } return fileName.getPath(); } private void setIcon(ImageIcon img) { SwingUtilities.invokeLater(() -> { Image image = img.getImage().getScaledInstance(printLabel.getWidth(), printLabel.getHeight(), Image.SCALE_SMOOTH); printLabel.setIcon(new ImageIcon(image)); }); } private String getIdForPrint(BufferedImage image) throws IOException { return ClientConnector.getIdForPrint(image); } /** * sets the print label to null */ public void reset() { printLabel.setIcon(null); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; public javax.swing.JLabel printLabel; // End of variables declaration//GEN-END:variables public static void main(String[] s) { JFrame frame = new JFrame("Scanning panel"); frame.add(new ScanningPanel()); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } //200 <file_sep>package adminserver; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.imageio.ImageIO; import sourcefiles.FingerprintMatcher; import sourcefiles.FingerprintTemplate; /** *An implementation of finding the location of a fingerprint image from the provided * @author DEGUZMAN */ public class FingerprintFinder { String[] printsLocation; FingerprintMatcher matcher; String location = ""; ExecutorService executor ; /** * Takes the prints location * @param prints */ public FingerprintFinder(String[] prints) { printsLocation = prints; } String find(BufferedImage image) { FingerprintTemplate probe = new FingerprintTemplate().create(loadImage(image)); matcher = new FingerprintMatcher().index(probe); executor = Executors.newCachedThreadPool(); MatchingThread [] threads = new MatchingThread[printsLocation.length]; for(int i = 0; i < printsLocation.length; i++){ threads[i] = new MatchingThread(printsLocation[i]); executor.execute(threads[i]); } executor.shutdown(); // shut down worker threads when their tasks complete return getLocation(); } synchronized private String getLocation(){ while("".equals(location) && !executor.isTerminated()) try { wait(); } catch (InterruptedException ex) { } return location; } synchronized private void setLocation(String location){ this.location = location; executor.shutdownNow(); notifyAll(); } private byte[] loadImage(BufferedImage bImage) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(bImage, "jpg", bos); byte[] data = bos.toByteArray(); return data; } catch (Exception e) { } return new byte[0]; } class MatchingThread implements Runnable{ String printToMatch; public MatchingThread(String print) { this.printToMatch = print; } @Override public void run() { try { BufferedImage image = ImageIO.read(new File(printToMatch)); FingerprintTemplate matching = new FingerprintTemplate().create(loadImage(image)); if (matcher.match(matching) > 40 ) setLocation(printToMatch); } catch (IOException ex) { ex.printStackTrace(); } } } } <file_sep>package ui; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; /** * * @author DEGUZMAN */ public class TimeThread extends MouseAdapter implements Runnable { int loadingtime = 30000; int time = loadingtime; //30 seconds ThreadAction action; //what to do when time elapses public TimeThread(ThreadAction action) { this.action = action; } @Override public void run() { while (true) { try { Thread.sleep(1000); setTime(time -= 1000); if (time <= 0) { action.action(); setTime(loadingtime); } } catch (InterruptedException e) { e.printStackTrace(); } } } synchronized void setTime(int value) { time = value; } @Override public void mouseMoved(MouseEvent e) { setTime(loadingtime); } @Override public void mouseReleased(MouseEvent e) { setTime(loadingtime); } @Override public void mouseEntered(MouseEvent e) { setTime(loadingtime); } } <file_sep>//make sure to make it a must to pass credentials for each request package clientserver; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; public class SocketHandler implements Runnable { Socket socket; ObjectInputStream inputStream; ObjectOutputStream outputStream; /** * initializes the SocketHandler * * @param socket the socket to process */ public SocketHandler(Socket socket) { this.socket = socket; setStreams(); } private void setStreams() { try { inputStream = new ObjectInputStream(socket.getInputStream()); outputStream = new ObjectOutputStream(socket.getOutputStream()); } catch (IOException ex) { ex.printStackTrace(); } } /** * reads the request and call the appropriate method to process the request */ @Override public void run() { try (IOClosable closer = socket::close) { String request = inputStream.readUTF(); switch (request.toLowerCase()) { case Constants.GET_ID_REQUEST: readPrintReturnId(); break; case Constants.GET_ACCOUNT_REQUEST: getAccounts(); break; case Constants.VERIFY_PASSWORD_REQUEST: verifyPassword(); break; case Constants.GET_ACCOUNT_BALANCES_REQUEST: getAccountBalances(); break; case Constants.WITHDRAW_REQUEST: withdraw(); break; default: //do nothing } } catch (Exception ex) { ex.printStackTrace(); } } /** * perform the withdraw action */ private void withdraw() throws Exception { String response = ""; try { Map<String, String> data = (Map<String, String>) inputStream.readObject(); response = Database.withdraw(data.get(Constants.ID_NUMBER), data.get(Constants.ACCOUNT_NUMBER), Double.parseDouble(data.get("amount"))); } catch (IOException | ClassNotFoundException | NumberFormatException | SQLException ex) { response = "Error withdrawing cash. Try again later"; throw ex; } finally { sendString(response); } } /** * process getting of customers accounts and balances in the accounts */ private void getAccountBalances() { String response = ""; try { String id = inputStream.readUTF(); Map<String, String> result; try { result = Database.getAccountBalances(id); } catch (Exception ex) { result = new HashMap<>(); result.put("Error", ex.getMessage()); } outputStream.writeObject(result); return; } catch (IOException ex) { ex.printStackTrace(); response = ex.getMessage(); } } /** * used to verify customer credentials */ private void verifyPassword() { String result; try { Map<String, String> map = (Map<String, String>) inputStream.readObject(); result = (verifyCustomer(map.get("id_number"), map.get("password"))) ? Constants.ACCOUNT_NUMBER : "NOT FOUND"; } catch (Exception ex) { //Logger.getLogger(SocketHandler.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); result = ex.getMessage(); } try { sendString(result); } catch (IOException ex) { //Logger.getLogger(SocketHandler.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } } /** * verify if a customer with the given id_number and password exist * * @param id_number the id number of the customer * @param password the password of the customer * @return true if the customer exist otherwise false * @throws SQLException */ private boolean verifyCustomer(String id_number, String password) throws SQLException { return Database.customerExist(id_number, password); } /** * gets the accounts of particular id read from sockets. sends result back * as a string array */ private void getAccounts() throws SQLException, IOException { String[] accounts = new String[1]; try { String id = inputStream.readUTF(); accounts = Database.getAccounts(id); } catch (IOException ex) { accounts[0] = "An error occured getting the accounts. Try again later or check with the bank"; throw ex; } finally{ outputStream.writeObject(accounts); } } /** * reads a print from the socket and sends back the id number of the print * stored in the database */ private void readPrintReturnId() throws Exception { String result = ""; try { String minutiae = inputStream.readUTF(); result = getIDForMinutiae(minutiae); } catch (IOException | SQLException ex) { result = "Error processing print. Try again later or check with the bank"; throw ex; } finally { sendString(result); } } /** * used to retrieve the ID of the customer with the given finger-print * minutiae * * @param minutiae the minutiae of the customer * @return id number * @throws SQLException */ private String getIDForMinutiae(String minutiae) throws SQLException { return Database.getMinutiaeID(minutiae); } /** * used to send a string across the socket * * @param value the string to send * @throws IOException throws an exception if an error occurs during sending */ private void sendString(String value) throws IOException { outputStream.writeUTF(value); outputStream.flush(); } } //201 <file_sep>package ui; import java.awt.Cursor; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.table.AbstractTableModel; /** * * @author DEGUZMAN */ public class SearchPanel extends javax.swing.JPanel { /** * Creates new form SearchPanel */ public SearchPanel() { initComponents(); idField.getDocument().addDocumentListener(new FieldListener()); } /** * Retrieve names of a customer using {@link Connector} class * * @param id the id number of the person to retrieve names * @return the names of the customer */ public Map<String, String> getNames(String id) throws IOException { return Connector.getNames(id); } /** * Retrieve accounts and balances using {@link Connector} class * * @param id the id number of the person to retrieve accounts and balances * @return the balances mapped to the accounts */ public Map<String, String> getAccountsAndBalances(String id) throws IOException{ return Connector.getAccountBalances(id); } /** * Clear the name textfields */ public void clear() { firstNameField.setText(" "); lastNameField.setText(" "); } public void search() { tableModel.clear(); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if (Connector.connectionExist()) { try { String id = idField.getText(); Map<String, String> names = getNames(id); firstNameField.setText(names.get("first_name")); lastNameField.setText(names.get("last_name")); tableModel.updateTable(id); } catch (IOException ex) { JOptionPane.showMessageDialog(this, ex.getMessage()); } }else { JOptionPane.showMessageDialog(this.getParent(), "There is no connetion with the Server", "Connection Error", JOptionPane.ERROR_MESSAGE); } setCursor(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); idField = new javax.swing.JTextField(); searchButton = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); firstNameField = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); lastNameField = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); accountTable = new javax.swing.JTable(); jLabel1.setText("Search customer"); jLabel2.setText("ID:"); idField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { idFieldActionPerformed(evt); } }); searchButton.setText("Search"); searchButton.setEnabled(false); searchButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchButtonActionPerformed(evt); } }); jLabel3.setText("First name:"); firstNameField.setEditable(false); firstNameField.setBackground(new java.awt.Color(255, 255, 255)); firstNameField.setDisabledTextColor(new java.awt.Color(0, 0, 0)); jLabel4.setText("Last name:"); lastNameField.setEditable(false); lastNameField.setBackground(new java.awt.Color(255, 255, 255)); lastNameField.setDisabledTextColor(new java.awt.Color(0, 0, 0)); jScrollPane1.setBackground(new java.awt.Color(255, 255, 255)); jScrollPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jScrollPane1.setToolTipText("accounts"); accountTable.setModel(tableModel); accountTable.setColumnSelectionAllowed(true); accountTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); accountTable.setShowVerticalLines(false); jScrollPane1.setViewportView(accountTable); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(firstNameField)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(idField, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lastNameField))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(searchButton)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(45, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(idField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(searchButton)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(firstNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lastNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(31, 31, 31) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(27, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed new Thread(this::search).start(); }//GEN-LAST:event_searchButtonActionPerformed private void idFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_idFieldActionPerformed new Thread(this::search).start(); }//GEN-LAST:event_idFieldActionPerformed public static void main(String [] args){ JFrame frame = new JFrame("Search Panel"); frame.add(new SearchPanel()); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } class AccountsTableModel extends AbstractTableModel { Map<String, String> data = new HashMap<>(); String[] keys = {}; @Override public int getRowCount() { return data.size(); } @Override public int getColumnCount() { return 2; } @Override public String getValueAt(int rowIndex, int columnIndex) { return columnIndex == 0 ? keys[rowIndex] : data.get(keys[rowIndex]); } //get name of a particular column in ResultSet @Override public String getColumnName(int column) { return column == 0 ? "Account" : "Balance"; } /** * update the data in the table * * @param id the id number of the individual whose data will fill the * table */ public void updateTable(String id) throws IOException { data = SearchPanel.this.getAccountsAndBalances(id); //refresh the data of the table keys = data.keySet().toArray(new String[data.size()]); fireTableDataChanged(); } public void clear() { data.clear(); fireTableDataChanged(); } } class FieldListener implements DocumentListener { @Override public void insertUpdate(DocumentEvent e) { setSearchButton(); } @Override public void removeUpdate(DocumentEvent e) { setSearchButton(); } @Override public void changedUpdate(DocumentEvent e) { setSearchButton(); } private void setSearchButton() { searchButton.setEnabled(!idField.getText().equals("")); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTable accountTable; private javax.swing.JTextField firstNameField; private javax.swing.JTextField idField; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField lastNameField; private javax.swing.JButton searchButton; // End of variables declaration//GEN-END:variables AccountsTableModel tableModel = new AccountsTableModel(); } <file_sep>package ui; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Timer; public class GUITimer extends MouseAdapter { private final int loadingtime = 120000; //2 minutes private final Timer timer ; boolean actionOccured = false; public GUITimer() { timer = new Timer(loadingtime, (ActionEvent e) -> { GUITimer.this.run(); }); } public void start(){ timer.start(); } public void stop(){ timer.stop(); } public void run() { if (actionOccured) { setActionOccurred(false); } else { CustomerFrame.showPanel(CustomerFrame.WELCOME_PANEL); } } synchronized void setActionOccurred(boolean value) { actionOccured = value; } @Override public void mouseMoved(MouseEvent e) { System.out.println("mouse moved"); setActionOccurred(true); } @Override public void mouseReleased(MouseEvent e) { System.out.println("mouse released"); setActionOccurred(true); } @Override public void mouseEntered(MouseEvent e) { System.out.println("mouse entered"); setActionOccurred(true); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ui; import java.awt.CardLayout; /** * * @author DEGUZMAN */ public final class CustomerFrame extends javax.swing.JFrame { private static String customerId; private static final CardLayout card = new CardLayout(); private static final WelcomePanel welcomePanel = new WelcomePanel(); private static final ScanningPanel scanningPanel = new ScanningPanel(); private static final ActionPanel actionPanel = new ActionPanel(); private static final WithdrawPanel withdrawPanel = new WithdrawPanel(); TimeThread timeThread = new TimeThread(()-> {showPanel(WELCOME_PANEL);} ); Thread thread = new Thread(timeThread); GUITimer timer = new GUITimer(); public static final String WELCOME_PANEL = "welcome_panel"; public static final String SCANNING_PANEL = "scanning_panel"; public static final String ACTION_PANEL = "action_panel"; public static final String WITHDRAW_PANEL = "withdraw_panel"; public CustomerFrame() { initComponents(); card.addLayoutComponent(welcomePanel, WELCOME_PANEL); card.addLayoutComponent(scanningPanel, SCANNING_PANEL); card.addLayoutComponent(actionPanel, ACTION_PANEL); card.addLayoutComponent(withdrawPanel, WITHDRAW_PANEL); mainPanel.setLayout(card); mainPanel.add(welcomePanel); mainPanel.add(scanningPanel); mainPanel.add(actionPanel); mainPanel.add(withdrawPanel); //thread.start(); addMouseListener(timer); timer.start(); } public static String getCustomerId() { return customerId; } public static void setCustomerId(String Id) { customerId = Id; } public static void showPanel(String panelName) { if (panelName.equalsIgnoreCase(SCANNING_PANEL)) scanningPanel.reset(); else if (panelName.equalsIgnoreCase(WELCOME_PANEL)) setCustomerId(""); else if (panelName.equalsIgnoreCase(WITHDRAW_PANEL)) withdrawPanel.reset(); card.show(mainPanel, panelName); } public static WelcomePanel getWelcomePanel() { return welcomePanel; } public static ScanningPanel getScanningPanel() { return scanningPanel; } public static ActionPanel getActionPanel() { return actionPanel; } public static WithdrawPanel getWithdrawPanel() { return withdrawPanel; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { mainPanel = new java.awt.Panel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); setPreferredSize(new java.awt.Dimension(400, 300)); setResizable(false); javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel); mainPanel.setLayout(mainPanelLayout); mainPanelLayout.setHorizontalGroup( mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 400, Short.MAX_VALUE) ); mainPanelLayout.setVerticalGroup( mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 400, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 306, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) ); setSize(new java.awt.Dimension(400, 306)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(CustomerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CustomerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CustomerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CustomerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { new CustomerFrame().setVisible(true); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private static java.awt.Panel mainPanel; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package adminserver; import java.awt.Cursor; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.text.DateFormat; import java.util.Date; import java.util.Scanner; import java.util.logging.Level; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; /** * * @author DEGUZMAN */ public class ServerApp extends javax.swing.JFrame { /** * Creates new form ServerApp */ public ServerApp() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { controlPanel = new javax.swing.JPanel(); startButton = new javax.swing.JButton(); stopButton = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); infoArea = new javax.swing.JTextArea(); jMenuBar1 = new javax.swing.JMenuBar(); viewMenu = new javax.swing.JMenu(); serverInfoMenuItem = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); connectionsMenuItem = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JPopupMenu.Separator(); clearLogsMenuItem = new javax.swing.JMenuItem(); helpMenu = new javax.swing.JMenu(); aboutMenuItem = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Admin Server"); addWindowStateListener(new java.awt.event.WindowStateListener() { public void windowStateChanged(java.awt.event.WindowEvent evt) { formWindowStateChanged(evt); } }); controlPanel.setBackground(new java.awt.Color(102, 102, 102)); startButton.setText("Start"); startButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { startButtonActionPerformed(evt); } }); stopButton.setText("Stop"); stopButton.setEnabled(false); stopButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { stopButtonActionPerformed(evt); } }); infoArea.setColumns(20); infoArea.setFont(new java.awt.Font("Lucida Console", 0, 12)); // NOI18N infoArea.setLineWrap(true); infoArea.setRows(5); infoArea.setToolTipText("information area"); infoArea.setWrapStyleWord(true); infoArea.setDisabledTextColor(new java.awt.Color(0, 0, 0)); infoArea.setEnabled(false); infoArea.setSelectionColor(new java.awt.Color(255, 255, 255)); jScrollPane1.setViewportView(infoArea); javax.swing.GroupLayout controlPanelLayout = new javax.swing.GroupLayout(controlPanel); controlPanel.setLayout(controlPanelLayout); controlPanelLayout.setHorizontalGroup( controlPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(controlPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(controlPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE) .addGroup(controlPanelLayout.createSequentialGroup() .addComponent(startButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(stopButton) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); controlPanelLayout.setVerticalGroup( controlPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(controlPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(controlPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(startButton) .addComponent(stopButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE) .addContainerGap()) ); getContentPane().add(controlPanel, java.awt.BorderLayout.CENTER); viewMenu.setText("View"); serverInfoMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK)); serverInfoMenuItem.setText("Server info"); serverInfoMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { serverInfoMenuItemActionPerformed(evt); } }); viewMenu.add(serverInfoMenuItem); jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem2.setText("Logs"); viewMenu.add(jMenuItem2); connectionsMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK)); connectionsMenuItem.setText("Connections"); connectionsMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { connectionsMenuItemActionPerformed(evt); } }); viewMenu.add(connectionsMenuItem); viewMenu.add(jSeparator1); clearLogsMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.SHIFT_MASK)); clearLogsMenuItem.setText("Clear logs"); clearLogsMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clearLogsMenuItemActionPerformed(evt); } }); viewMenu.add(clearLogsMenuItem); jMenuBar1.add(viewMenu); helpMenu.setText("Help"); aboutMenuItem.setText("About"); helpMenu.add(aboutMenuItem); jMenuBar1.add(helpMenu); setJMenuBar(jMenuBar1); setBounds(0, 0, 366, 270); }// </editor-fold>//GEN-END:initComponents private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed new Thread(this::startServer).start(); }//GEN-LAST:event_startButtonActionPerformed private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopButtonActionPerformed new Thread(this::stopServer).start(); }//GEN-LAST:event_stopButtonActionPerformed private void formWindowStateChanged(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowStateChanged // TODO add your handling code here: }//GEN-LAST:event_formWindowStateChanged private void connectionsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectionsMenuItemActionPerformed // TODO add your handling code here: }//GEN-LAST:event_connectionsMenuItemActionPerformed private void clearLogsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearLogsMenuItemActionPerformed SwingUtilities.invokeLater(() -> infoArea.setText("")); }//GEN-LAST:event_clearLogsMenuItemActionPerformed private void serverInfoMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_serverInfoMenuItemActionPerformed JTextArea display = new JTextArea(); new Thread(() -> readFile("server_info_log.txt", display)).start(); JOptionPane.showMessageDialog(this, new JScrollPane(display), "Server info", WIDTH); JOptionPane pane = new JOptionPane(); }//GEN-LAST:event_serverInfoMenuItemActionPerformed private void readFile(String file_name, JTextArea displayArea) { try { FileInputStream inputStream = new FileInputStream(new File("server_info_log.txt")); Scanner scanner = new Scanner(new File("server_info_log.txt")); while(scanner.hasNext()) displayArea.append(scanner.next()); } catch (FileNotFoundException ex) { displayArea.append(ex.getMessage() + "\n"); } } private void startServer() { display("Starting server"); startButton.setEnabled(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { Server.start(); display("Server started " + Server.isRunning()); log(Level.INFO, "Server started " + Server.isRunning()); stopButton.setEnabled(Server.isRunning()); startButton.setEnabled(!Server.isRunning()); if (Server.isRunning()) new Thread(this::notifier).start(); display("Database connection exist: " + Database.checkConnection()); log(Level.INFO, "Database connection exist: " + Database.checkConnection()); } catch (IOException ex) { log(Level.SEVERE, ex.getMessage()); display("Error while starting server " + ex.getMessage()); ex.printStackTrace(); } setCursor(null); } private void stopServer() { display("Stopping server"); stopButton.setEnabled(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { Server.stop(); display("Server stopped\nServer running: " + Server.isRunning()); log(Level.INFO, "Server stopped: " ); startButton.setEnabled(!Server.isRunning()); stopButton.setEnabled(Server.isRunning()); display("Database connected: " + Database.checkConnection()); log(Level.INFO, "Database connected: " + Database.checkConnection() ); } catch (IOException ex) { log(Level.SEVERE, ex.getMessage()); display("Error while stopping server " + ex.getMessage()); } setCursor(null); } /** * displays a message on the infoArea at Event dispatch thread * * @param message the message to be displayed */ private void display(String message) { SwingUtilities.invokeLater(() -> infoArea.append(message + " ( " + DateFormat.getDateTimeInstance().format(new Date()) + " )\n")); } /** * used to log a message into the logger file * * @param level the level of the message * @param message the message to be logged */ private void log(Level level, String message){ ServerInfoLog.log(Level.INFO, "Server started " + Server.isRunning()); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ServerApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ServerApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ServerApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ServerApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ServerApp().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenuItem aboutMenuItem; private javax.swing.JMenuItem clearLogsMenuItem; private javax.swing.JMenuItem connectionsMenuItem; private javax.swing.JPanel controlPanel; private javax.swing.JMenu helpMenu; private javax.swing.JTextArea infoArea; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JPopupMenu.Separator jSeparator1; private javax.swing.JMenuItem serverInfoMenuItem; private javax.swing.JButton startButton; private javax.swing.JButton stopButton; private javax.swing.JMenu viewMenu; // End of variables declaration//GEN-END:variables public void notifier() { while (Server.isRunning()) { display("Server running \nDatabase connected " + Database.checkConnection()); try { Thread.sleep(10000); } catch (InterruptedException ex) { } } } class WindowChecker extends WindowAdapter { @Override public void windowClosing(WindowEvent e) { ServerApp.this.stopServer(); } @Override public void windowClosed(WindowEvent e) { if (!Server.isRunning()) { JOptionPane.showMessageDialog(null, "Server could not stop running", "Error", JOptionPane.ERROR); } } } } <file_sep>package clientserver; //throw illigelState if db not connected //add logging import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; public class Database { private static Connection connection; static { //executedd once to setup the database connect(); } Database() { connect(); } /** * setup connection to the database */ public static void connect() { try { connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "root", ""); } catch (SQLException ex) { //Logger.getLogger(Database.class.getName()).log(Level.SEVERE, "Could not connect to database", ex); System.err.println("Could not connect to database"); } } /** * closes connection to the database */ public static void disconnect() { try { connection.close(); } catch (SQLException ex) { //Logger.getLogger(Database.class.getName()).log(Level.SEVERE, "Could not connect to database", ex); System.err.println("Could not close to database"); } } /** * checks if there is a connection with the database and tries to connect if there is no connection * @return true if a connection exist */ public static boolean checkConnection() { if (!connectionExist()) connect(); return connectionExist(); } /** * Checks if a connection to the database exist * * @return true if there is a connection otherwise false */ public static boolean connectionExist() { try { return connection != null && connection.isValid(100); } catch (SQLException ex) { Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); return false; } } /** * checks if a customer exists in a database. NB. Checks only customers who have set passwords * * @param id_number * @param password * @return return true if a customer with the given id_number exist otherwise false * @throws java.sql.SQLException if an error occurred while reading the database */ public static boolean customerExist(String id_number, String password) throws SQLException{ String query = "SELECT id_number FROM passwords WHERE id_number = '" + id_number + "' AND password = '" + password + "'"; try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query)) { return resultSet.next(); //true if data exist } } //id not needed here /** * used to get the balance in a specified account of a customer * * @param id_number the id number of the customer * @param account_number the account number of the customer * @return the balance of the customer in the account number * @throws java.sql.SQLException if there is an error reading the database */ public static double getBalance(String id_number, String account_number) throws SQLException { String query = "SELECT balance FROM accounts WHERE id_number = '" + id_number + "' AND account_number = '" + account_number + "'"; try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query)) { if (resultSet.next()) { return resultSet.getFloat(1); } throw new SQLException("Account not found"); } } /** * used to fetch all the accounts of a given customer * * @param id_number the id number of the customer * @return all the accounts of a customer in form of a String array * @throws java.sql.SQLException if there was an error reading the accounts */ public static String[] getAccounts(String id_number) throws SQLException { String query = "SELECT account_number FROM accounts WHERE id_number = '" + id_number + "'"; ArrayList<String> accountNumbers = new ArrayList<>(1); try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query)) { while (resultSet.next()) { accountNumbers.add(resultSet.getString(1)); } } return accountNumbers.toArray(new String[accountNumbers.size()]); } /** * locates the id number for the minutiae * * @param minutiae the minutiae of the print * @return the id_number of the fingerprint * @throws java.sql.SQLException if there is an error reading the prints from the database */ public static String getMinutiaeID(String minutiae) throws SQLException { return new MinutiaeFinder(getMinutiae()).find(minutiae); } /** * used to get the balances of all the accounts registered on a given id * number * * @param idNumber the id number of the customer * @return the accounts and their balances * @throws Exception */ public static Map<String, String> getAccountBalances(String idNumber) throws Exception { String query = "SELECT account_number, balance FROM accounts WHERE id_number = '" + idNumber + "'"; Map<String, String> accounts = new HashMap<>(); try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query)) { while (resultSet.next()) { accounts.put(resultSet.getString("account_number"), resultSet.getString("balance")); } } return accounts; } /** * get all the print locations stored in the database * * @return returns locations stored as a String array * @throws SQLException throws SQLException if there is an error reading the * database */ private static Map<String,String> getMinutiae() throws SQLException { Map<String,String> minutiae = new HashMap<>(); String query = "SELECT * FROM fingerprints"; try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query)) { while (resultSet.next()) { //iterate the result set minutiae.put(resultSet.getString(1), resultSet.getString(2)); } } return minutiae; } /** * Deducts the amount of money from the account * * @param idNumber the id number of the customer * @param account the account number of the customer * @param amount the amount to withdraw * @return response which can be either {@link Constants.ACTION_SUCCESSFUL} if withdraw was successful or {@link Constants.ACTION_UNSUCCESSFUL} if withdraw was unsuccessful * or a message if the balance is less * @throws java.sql.SQLException if an error occurred when deducting cash */ public static String withdraw(String idNumber, String account, double amount) throws SQLException { if( getBalance(idNumber, account) < amount){ return "Your account is low on cash"; } String query = "update accounts set balance = balance - '" + amount + "' where id_number = '" + idNumber + "' and account_number = '" + account + "'"; try (Statement statement = connection.createStatement()) { int result = statement.executeUpdate(query); return result > 0 ? Constants.ACTION_SUCCESSFUL : Constants.ACTION_UNSUCCESSFUL; } } /** * deposits money to the given account of a id number * * @param idNumber the id number of the customer * @param account the account number of the customer * @param amount the amount to deposit * @return either {@link Constants.ACTION_SUCCESSFUL} if deposit was successful or {@link Constants.ACTION_SUCCESSFUL} if deposit was unsuccessful * @throws java.sql.SQLException when an error is encountered */ public static String deposit(String idNumber, String account, float amount) throws SQLException{ String query = "update accounts set balance = balance + '" + amount + "' where id_number = '" + idNumber + "' and account_number = '" + account + "'"; try (Statement statement = connection.createStatement()) { int result = statement.executeUpdate(query); return result > 0 ? Constants.ACTION_SUCCESSFUL : Constants.ACTION_UNSUCCESSFUL ; } } }//241 <file_sep>package ui; import java.awt.CardLayout; import javax.swing.*; public final class AddPanelController extends JPanel { private CardLayout card = new CardLayout(); private final ScanningPanel scanningPanel = new ScanningPanel(); private final AddAccountPanel addAccountPanel = new AddAccountPanel(); private final DetailsForm detailsForm = new DetailsForm(); public static final String SCANNING_PANEL = "scanning_panel"; public static final String ADD_ACCOUNT_PANEL = "add_account_panel"; public static final String DETAILS_PANEL = "details_panel"; public AddPanelController() { card.addLayoutComponent(scanningPanel, SCANNING_PANEL); card.addLayoutComponent(addAccountPanel, ADD_ACCOUNT_PANEL); card.addLayoutComponent(detailsForm, DETAILS_PANEL); this.setLayout(card); add(scanningPanel); add(addAccountPanel); add(detailsForm); } public AddAccountPanel getAddAccountPanel() { return addAccountPanel; } public ScanningPanel getScanningPanel() { return scanningPanel; } public AddAccountPanel getPasswordPanel() { return addAccountPanel; } public DetailsForm getDetailsForm() { return detailsForm; } public void showPanel(String panelName) { if (panelName.equalsIgnoreCase(SCANNING_PANEL)) { scanningPanel.getSubmitButton().setEnabled(false); scanningPanel.getFingerprintLabel().setIcon(null); } else if (panelName.equalsIgnoreCase(ADD_ACCOUNT_PANEL)) { addAccountPanel.reset(); } card.show(this, panelName); } }//49
40f8853cff0557fe5665e795d2c9880a7b7dd3b5
[ "Java" ]
13
Java
Jinamizi/Project
05762cdcca2aadbd4daec38bebebb22fc0e4dae5
3199be465e33d6c69210a66f76cbab224cb8f6c7
refs/heads/master
<repo_name>giss-ignacio/imdbdownloader<file_sep>/README.md # imdbdownloader Download movies database to csv for further data science analysis. ## Movies database processing: <p align="center"> <a href="http://www.youtube.com/watch?feature=player_embedded&v=lsX6UijPygM " target="_blank"><img src="http://img.youtube.com/vi/lsX6UijPygM/0.jpg" alt="Movies database processing " width="240" height="180" border="10" /></a></p> ## Movies database conversion to csv: <p align="center"> <a href="http://www.youtube.com/watch?feature=player_embedded&v=AiNXFbdqpHI " target="_blank"><img src="http://img.youtube.com/vi/AiNXFbdqpHI/0.jpg" alt="Movies database csv" width="240" height="180" border="10" /></a></p> ![alt tag](https://s4.postimg.org/kil22muyl/8257_10208296303390974_3322366975959709238_n.jpg)<file_sep>/download.rb require 'net/ftp' require 'rubygems/package' require 'zlib' FTP_SITE = "ftp.fu-berlin.de" FTP_DIR = "/pub/misc/movies/database" DLD_DIR = "data" def download_files ftp = Net::FTP::new(FTP_SITE) ftp.passive = true ftp.login("ftp", "guest") ftp.chdir(FTP_DIR) fileList = ftp.list('*.gz') fileList.each do |file| filename = file.split.last puts "Downloading " + filename filesize = ftp.size(filename) filesizemb = filesize/1048576 puts "File size: #{filesizemb} MB" progressbar = ProgressBar.create progressbar.total = filesize ftp.getbinaryfile(filename, "#{DLD_DIR}/#{filename}", 1024) { |data| progressbar.progress += data.size } end ftp.close end def extract_files Dir.glob("#{DLD_DIR}/*.gz") do |gz_file| Zlib::GzipReader.open(gz_file) do | input_stream | puts "Extracting #{gz_file} " File.open(gz_file.chomp('.gz'), "w") do |output_stream| IO.copy_stream(input_stream, output_stream) end end end end def download_and_extract download_files extract_files end<file_sep>/db_handle.rb require 'sqlite3' DBNAME = "im_db.sqlite" def create_db File.delete(DBNAME) if File.exists?DBNAME db = SQLite3::Database.new( DBNAME ) db.execute("CREATE TABLE Movies ( id INTEGER PRIMARY KEY, title varchar(250), year integer, budgeting integer, running_times integer, ratings float, votes integer, rating_votes varchar(10), mpaa_ratings varchar(5), is_series numeric )") db.execute("CREATE TABLE Ratings (id INTEGER PRIMARY KEY, movie_id integer, score varchar(10), outof10 float, votes integer)") db.execute("CREATE TABLE Genres (id INTEGER PRIMARY KEY , movie_id integer, genre varchar(50))") db.execute("CREATE INDEX title on Movies (title)") db.execute("CREATE INDEX year on Movies (year)") db.execute("CREATE INDEX titleyear on Movies (title, year)") db.execute("CREATE INDEX id on Movies (id)") db.execute("CREATE INDEX rid on Ratings (id)") db.execute("CREATE INDEX rmid on Ratings (movie_id)") db.execute("CREATE INDEX gid on Genres (id)") db.execute("CREATE INDEX gmid on Genres (movie_id)") return db end <file_sep>/db_to_csv.rb require "rubygems" require "arrayfields" require "sqlite3" require "set" require "ruby-progressbar" DB_CSV_NAME = "im_db.csv" $genres_nm = ["Action", "Adventure", "Animation", "Comedy", "Drama", "Documentary", "Horror", "Mystery", "Romance", "Short", "Thriller", "Sci-Fi"] $maprat = {"." => 0, "0" => 4.5, "1" => 14.5, "2" => 24.5, "3" => 34.5, "4" => 44.5, "5" => 45.5, "6" => 64.5, "7" => 74.5, "8" => 84.5, "9" => 94.5, "*" => 100} def ratings_numeric(ratings) ratings[0..ratings.length].to_s.split(//).map{|s| $maprat[s]} end def set_genres(id, data) genres = data.execute("SELECT genre FROM Genres where movie_id = #{id};").flatten.to_set $genres_nm.map { |genre| (genres.include? genre) ? 1 : 0} end def db_to_csv(data) db_com = "SELECT Movies.* FROM Movies ORDER BY title" db_com_count = "SELECT COUNT(*) FROM Movies;" tot_count = data.execute(db_com_count) total_fl = tot_count.first.first progressbar = ProgressBar.create progressbar.total = total_fl File.open("im_db.csv", "w") do |out| out << [ 'title', 'year', 'length', 'budget', 'rating', 'votes', (1..10).map{|i| "r" + i.to_s}, 'mpaa', $genres_nm , 'is_series' ].flatten.join(",") + "\n" data.execute(db_com) do |row| out << [ row[1], row[2], row[4], row[3], row[5], row[6], ratings_numeric(row[7]), row[8], set_genres(row[0], data), row[9] ].flatten.join(",") + "\n" rescue nil progressbar.increment end end tot_count = IO.readlines( DB_CSV_NAME ).size - 1 puts "Total csv entries: #{tot_count} " end<file_sep>/main.rb require 'rubygems' require "highline/import" require_relative 'download' require_relative 'db_handle' require_relative 'db_to_csv' MOVIES = "movies" RUNNING_TIMES = "running-times" BUDGETING = "budgeting" TITLE = "title" HYPHENS = /(-{79})/i MPAA_RAT = "mpaa-ratings-reasons" RATINGS = "ratings" GENRES = "genres" def regex_form(category) reg_form = /(.*?)/i case category when MOVIES reg_form = /^(.+) \s+ \([0-9]+\) \s? (\{.+\})? (\(.+\))? \s+ ([0-9]+(-[0-9\?]+)?)$/ix when TITLE reg_form = /MV:\s+(.+)? \s \(([0-9]+)\)/ix when RUNNING_TIMES reg_form = /^(.+) \s+ \(([0-9]+)\) \s+ (?:[a-z]+:)?([0-9]+)/ix when BUDGETING reg_form = /BT:\s+USD\s+([0-9,.]+)/ix when MPAA_RAT reg_form = /RE: Rated (.*?) /i when RATINGS reg_form = /([0-9.\*]+) \s+ ([0-9]+) \s+ ([0-9.]+) \s+ (.+)? \s+ \(([0-9]+)\)/ix when GENRES reg_form = /^(.+)? \s+ \(([0-9]+)\) (?:\s*[({].*[})])* \s+(.*?)$/ix end return reg_form end def add_movies(data) movies_reg = regex_form(MOVIES) match_prev = ['', '', '', '', ''] series = "" datacom = data.prepare("INSERT INTO Movies (title, year, is_series) VALUES (?, ?, ?);") i = 0 data.transaction do data.execute "DELETE FROM Movies;" filename = "#{DLD_DIR}/#{MOVIES}.list" tot_count = IO.readlines(filename).size progressbar = ProgressBar.create progressbar.total = tot_count File.open(filename, "r:Windows-1252").each_line do |l| progressbar.increment if match = movies_reg.match(l) unless match[match.length - 1].nil? series = match[1] datacom.execute!(match[1].tr(',".',''), match[match.length - 2][0..3].to_i, 1) else if ((match[1] != match_prev[1]) || (match[match.length - 2] != match_prev[match_prev.length - 2])) && (match[1] != series) datacom.execute!(match[1].tr(',".',''), match[match.length - 2][0..3].to_i, 0) end end end end end end def add_running_times(data) running_times_reg = regex_form(RUNNING_TIMES) datacom = data.prepare("UPDATE Movies set running_times=? WHERE title=? AND year=?;") i = 0 data.transaction do filename = "#{DLD_DIR}/#{RUNNING_TIMES}.list" tot_count = IO.readlines(filename).size progressbar = ProgressBar.create progressbar.total = tot_count File.open(filename, "r:Windows-1252").each_line do |l| progressbar.increment if match = running_times_reg.match(l) datacom.execute!(match[3].to_i, match[1].tr(',".',''), match[2].to_i) end end end end def add_budgeting(data) budgeting_reg = regex_form(BUDGETING) title_reg = regex_form(TITLE) datacom = data.prepare("UPDATE Movies set budgeting=? WHERE title=? AND year=?;") filename = "#{DLD_DIR}/business.list" business = File.open(filename, "r:Windows-1252").read.split(HYPHENS) tot_count = business.map.size progressbar = ProgressBar.create progressbar.total = tot_count data.transaction do business.map do |l| progressbar.increment if match = title_reg.match(l.to_s) and bt = budgeting_reg.match(l.to_s) datacom.execute!(bt[1].gsub!(",","").to_i, match[1].tr(',".',''), match[2].to_i) end end end end def add_mpaa_ratings_reasons(data) mpaa_reg = regex_form(MPAA_RAT) title_reg = regex_form(TITLE) datacom = data.prepare("UPDATE Movies set mpaa_ratings=? WHERE title=? AND year=?;") filename = "#{DLD_DIR}/#{MPAA_RAT}.list" mpaa_ratings = File.open(filename, "r:Windows-1252").read.split(HYPHENS) tot_count = mpaa_ratings.map.size progressbar = ProgressBar.create progressbar.total = tot_count data.transaction do mpaa_ratings.map do |l| progressbar.increment if match = title_reg.match(l.to_s) and rt = mpaa_reg.match(l.to_s) datacom.execute!(rt[1], match[1].tr(',".',''), match[2].to_i) end end end end def add_genres(data) genres_reg = regex_form(GENRES) datacom = data.prepare("INSERT INTO Genres (genre, movie_id) VALUES (?, (SELECT id FROM Movies WHERE title=? AND year=?));") data.transaction do filename = "#{DLD_DIR}/#{GENRES}.list" tot_count = IO.readlines(filename).size progressbar = ProgressBar.create progressbar.total = tot_count data.execute "DELETE FROM Genres;" File.open(filename, "r:Windows-1252").each_line do |l| progressbar.increment if match = genres_reg.match(l) datacom.execute!(match[3], match[1].tr(',".',''), match[2].to_i) end end puts end end def add_ratings(data) ratings_reg = regex_form(RATINGS) datacom = data.prepare("UPDATE Movies set votes=?, ratings=?, rating_votes=? WHERE title=? AND year=?;") data.transaction filename = "#{DLD_DIR}/#{RATINGS}.list" tot_count = IO.readlines(filename).size progressbar = ProgressBar.create progressbar.total = tot_count File.open(filename, "r:Windows-1252").each_line do |l| progressbar.increment if match = ratings_reg.match(l) rating, votes, outof10, title, year = match[1], match[2], match[3], match[4], match[5] datacom.execute!(votes, outof10, rating, title.tr(',".',''), year) end end data.commit end def add_all data = create_db puts "Processing movies database" puts "Adding movies" add_movies(data) puts "Adding running times" add_running_times(data) puts "Adding budgeting" add_budgeting(data) puts "Adding mpaa ratings reasons" add_mpaa_ratings_reasons(data) puts "Adding ratings" add_ratings(data) puts "Adding genres" add_genres(data) end def database_to_csv database = SQLite3::Database.new( DBNAME ) db_to_csv(database) end def do_everything download_and_extract add_all database_to_csv end def show_menu Gem.win_platform? ? (system "cls") : (system "clear") puts loop do choose do |menu| puts "\n\nImdbDownloader \n\n" menu.prompt = "Select an option: " menu.choice(:'Do everything') { do_everything } menu.choice(:'Download files') { download_and_extract } menu.choice(:'Add all movies to database') { add_all } menu.choice(:'Export database to csv') { database_to_csv } menu.choice(:Quit, "Exit program.") { exit } end end end if __FILE__ == $0 # Main Menu # show_menu #data = SQLite3::Database.new( DBNAME ) end
201da79dda80843ff58b11c33bab60f60873d6ae
[ "Markdown", "Ruby" ]
5
Markdown
giss-ignacio/imdbdownloader
e1f11f51bfbfaa22605f56bdfe774deb54a8c27d
b8b86642fc24eae0c6e1099eef0ab279f7a7190a
refs/heads/master
<file_sep><!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <title>practica 5</title> <link rel="stylesheet" type="text/css" href="estilo.css"> </head> <body> <div id="contenedor"> <div id="cabecera"><h1>PRACTICA 5 DE PHP</h1> <div>Nombre: <NAME></div> <div>Fecha de entrega: 07 de septiembre de 2016</div> </div> <div id="menu"> <UL> <li><a href="eje1.php">Ejercicio 1</a></li> <li><a href="eje2.php">Ejercicio 2</a></li> <li><a href="eje3.php">Ejercicio 3</a></li> <li><a href="eje4.php">Ejercicio 4</a></li> <li><a href="eje5.php">Ejercicio 5</a></li> <li><a href="eje6.php">Ejercicio 6</a></li> <li><a href="eje7.php">Ejercicio 7</a></li> <li><span class="elegido"><a href="eje8.php">Ejercicio 8</a></span></li> <li><a href="eje9.php">Ejercicio 9</a></li> <li><a href="eje10.php">Ejercicio 10</a></li> <li><a href="eje11.php">Ejercicio 11</a></li> <li><a href="eje12.php">Ejercicio 12</a></li> </UL> </div> <div id="contenido"><p class="enunciado">Realizar un programa que reciba una fecha en formato numérico y lo convierta a texto. (Ejemplo: 31/08/2016 => 31 de agosto de 2016</p> <div class="cleare"> <form action="" method="POST"> <table > <tr> <td colspan="2"> <strong>Mostrar fecha larga</strong></h2></td> </tr> <tr> <td><strong>Fecha:</strong></td> <td><input type="date" name="fecha" style="width:150px;"></td> </tr> <tr> <td><input type="submit" name="enviar" value="enviar"></td> </tr> </table> </form> <?php $meses = array('01'=>'Enero','02'=>'Febrero','03'=>'Marzo','04'=>'Abril','05'=>'Mayo','06'=>'Junio','07'=>'Julio','08'=>'Agosto','09'=>'Septiembre','10'=>'Octubre','11'=>'Noviembre','12'=>'Diciembre'); if (isset($_POST["fecha"])) { $fecha= strtotime($_POST["fecha"]); //echo $fecha; echo "<h3>".date("d",$fecha)." de ".$meses[date("m",$fecha)]." de ". date("Y",$fecha)."</h3>"; } ?> </div> </div> <div id="pie">&copy; derechos reservados 2016 </div> </div> </body> </html><file_sep><!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <title>practica 5</title> <link rel="stylesheet" type="text/css" href="estilo.css"> </head> <body> <div id="contenedor"> <div id="cabecera"><h1>PRACTICA 5 DE PHP</h1> <div>Nombre: <NAME></div> <div>Fecha de entrega: 07 de septiembre de 2016</div> </div> <div id="menu"> <UL> <li><a href="eje1.php">Ejercicio 1</a></li> <li><a href="eje2.php">Ejercicio 2</a></li> <li><a href="eje3.php">Ejercicio 3</a></li> <li><a href="eje4.php">Ejercicio 4</a></li> <li><a href="eje5.php">Ejercicio 5</a></li> <li><a href="eje6.php">Ejercicio 6</a></li> <li><span class="elegido"><a href="eje7.php">Ejercicio 7</a></span></li> <li><a href="eje8.php">Ejercicio 8</a></li> <li><a href="eje9.php">Ejercicio 9</a></li> <li><a href="eje10.php">Ejercicio 10</a></li> <li><a href="eje11.php">Ejercicio 11</a></li> <li><a href="eje12.php">Ejercicio 12</a></li> </UL> </div> <div id="contenido"><p class="enunciado">Programar un formulario que reciba tres números y determine cuál es el mayor, el del medio y el menor.</p> <div class="cleare"> <form action="" method="POST"> <table > <tr> <td colspan="2"> <strong>Ordenacion de numeros</strong></h2></td> </tr> <tr> <td><strong>Primer Numero:</strong></td> <td><input type="number" name="pn" placeholder="1er #" style="width:40px;"></td> </tr> <tr> <td><strong>Segundo Numero:</strong></td> <td><input type="number" name="sn" placeholder="2do #" style="width:40px;"></td> </tr> <tr> <td><strong>Tercer Numero:</strong></td> <td><input type="number" name="tn" placeholder="3er #" style="width:40px;"></td> </tr> <tr> <td><input type="submit" name="enviar" value="enviar"></td> </tr> </table> </form> <?php if (isset($_POST["pn"]) && isset($_POST["sn"]) && isset($_POST["tn"]) ) { $a=$_POST["pn"]; $b=$_POST["sn"]; $c=$_POST["tn"]; if ($a > $b && $a > $c) { if ($b > $c) { echo "<strong>mayor: $a<br></strong>"; echo "<strong>medio: $b<br></strong>"; echo "<strong>menor: $c<br></strong>"; } else{ echo "<strong>mayor: $a<br></strong>"; echo "<strong>medio: $c<br></strong>"; echo "<strong>menor: $b<br></strong>"; } } else { if ($b > $a && $b > $c) { if ($a > $c) { echo "<strong>mayor: $b<br></strong>"; echo "<strong>medio: $a<br></strong>"; echo "<strong>menor: $c<br></strong>"; } else{ echo "<strong>mayor: $b<br></strong>"; echo "<strong>medio: $c<br></strong>"; echo "<strong>menor: $a<br></strong>"; } } else{ if ($c > $a && $c > $b) { if ($a > $b) { echo "<strong>mayor: $c<br></strong>"; echo "<strong>medio: $a<br></strong>"; echo "<strong>menor: $b<br></strong>"; } else{ echo "<strong>mayor: $c<br></strong>"; echo "<strong>medio: $b<br></strong>"; echo "<strong>menor: $a<br></strong>"; } } else{ echo "<strong>dos o mas numeros son iguales<br></strong>"; } } } } ?> </div> </div> <div id="pie">&copy; derechos reservados 2016 </div> </div> </body> </html><file_sep><!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <title>practica 5</title> <link rel="stylesheet" type="text/css" href="estilo.css"> </head> <body> <div id="contenedor"> <div id="cabecera"><h1>PRACTICA 5 DE PHP</h1> <div>Nombre: <NAME></div> <div>Fecha de entrega: 07 de septiembre de 2016</div> </div> <div id="menu"> <UL> <li><a href="eje1.php">Ejercicio 1</a></li> <li><a href="eje2.php">Ejercicio 2</a></li> <li><a href="eje3.php">Ejercicio 3</a></li> <li><a href="eje4.php">Ejercicio 4</a></li> <li><a href="eje5.php">Ejercicio 5</a></li> <li><a href="eje6.php">Ejercicio 6</a></li> <li><a href="eje7.php">Ejercicio 7</a></li> <li><a href="eje8.php">Ejercicio 8</a></li> <li><a href="eje9.php">Ejercicio 9</a></li> <li><a href="eje10.php">Ejercicio 10</a></li> <li><span class="elegido"><a href="eje11.php">Ejercicio 11</a></span></li> <li><a href="eje12.php">Ejercicio 12</a></li> </UL> </div> <div id="contenido"><p class="enunciado">Crear un formulario que reciba los nombres de seis (6) equipos y un botón que al pulsar genere un fixture de partidos.</p> <div class="cleare"> <form action="" method="POST"> <table > <tr> <td colspan="2"> <strong>Fixture de equipos</strong></h2></td> </tr> <tr> <td><strong>Equipo 1:</strong></td> <td><input type="text" name="pe" placeholder="1er equipo" required="" style="width:100px;"></td> </tr> <tr> <td><strong>Equipo 2:</strong></td> <td><input type="text" name="se" placeholder="2do equipo" required="" style="width:100px;"></td> </tr> <tr> <td><strong>Equipo 3:</strong></td> <td><input type="text" name="te" placeholder="3er equipo" required="" style="width:100px;"></td> </tr> <tr> <td><strong>Equipo 4:</strong></td> <td><input type="text" name="ce" placeholder="4to equipo" required="" style="width:100px;"></td> </tr> <tr> <td><strong>Equipo 5:</strong></td> <td><input type="text" name="qe" placeholder="5to equipo" required="" style="width:100px;"></td> </tr> <tr> <td><strong>Equipo 6:</strong></td> <td><input type="text" name="sxe" placeholder="6to equipo" required="" style="width:100px;"></td> </tr> <tr> <td><input type="submit" name="enviar" value="enviar"></td> </tr> </table> </form> <?php function llenararray($max) { $switch=0; $numero=0; $arr = array(-1,-1,-1,-1,-1,-1); for ($i=0; $i <=$max-1 ; $i++) { $c=0; $numero=rand(0,5); while ($c<=$i) { if ($numero==$arr[$c]) { $c=0; $numero=rand(0,5); } else{ $c++; } } $arr[$i]=$numero; } return $arr; } if (isset($_POST["pe"]) && isset($_POST["se"]) && isset($_POST["te"]) && isset($_POST["ce"]) && isset($_POST["qe"]) && isset($_POST["sxe"])) { echo "<h2>Fixture de Partidos</h2>"; $arr= llenararray(6); $arreq = array($_POST["pe"],$_POST["se"],$_POST["te"],$_POST["ce"],$_POST["qe"],$_POST["sxe"]); echo "<h5>-".strtoupper($arreq[$arr[0]])."- vs -".strtoupper($arreq[$arr[1]])."-<h5>"; echo "<h5>-".strtoupper($arreq[$arr[2]])."- vs -".strtoupper($arreq[$arr[3]])."-<h5>"; echo "<h5>-".strtoupper($arreq[$arr[4]])."- vs -".strtoupper($arreq[$arr[5]])."-<h5>"; } ?> </div> <div id="pie">&copy; derechos reservados 2016 </div> </div> </body> </html><file_sep><!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <title>practica 5</title> <link rel="stylesheet" type="text/css" href="estilo.css"> </head> <body> <div id="contenedor"> <div id="cabecera"><h1>PRACTICA 5 DE PHP</h1> <div>Nombre: <NAME></div> <div>Fecha de entrega: 07 de septiembre de 2016</div> </div> <div id="menu"> <UL> <li><a href="eje1.php">Ejercicio 1</a></li> <li><a href="eje2.php">Ejercicio 2</a></li> <li><span class="elegido"><a href="eje3.php">Ejercicio 3</a></span></li> <li><a href="eje4.php">Ejercicio 4</a></li> <li><a href="eje5.php">Ejercicio 5</a></li> <li><a href="eje6.php">Ejercicio 6</a></li> <li><a href="eje7.php">Ejercicio 7</a></li> <li><a href="eje8.php">Ejercicio 8</a></li> <li><a href="eje9.php">Ejercicio 9</a></li> <li><a href="eje10.php">Ejercicio 10</a></li> <li><a href="eje11.php">Ejercicio 11</a></li> <li><a href="eje12.php">Ejercicio 12</a></li> </UL> </div> <div id="contenido"><p class="enunciado"> Generar un tablero de ajedrez alternando colores de cada casilla y como contenido mostrar un número </p> <?php define("tam",8); $c=1; ?> <div class="cleare"> <table border="0"> <?php for ($i=1; $i <= tam ; $i++) { echo "<tr class='fila'>"; if ($i%2==0) { $c=2; } else{ $c=1; } for ($j=1; $j <=tam ; $j++) { if($c%2==0) { echo "<td class='casilla-negra'>".tam."</td>"; } else { echo "<td class='casilla'>".tam."</td>";# code... } $c++; } echo "</tr>"; } ?> </table> </div> </div> <div id="pie">&copy; derechos reservados 2016 </div> </div> </body> </html><file_sep><!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <title>practica 5</title> <link rel="stylesheet" type="text/css" href="estilo.css"> </head> <body> <div id="contenedor"> <div id="cabecera"><h1>PRACTICA 5 DE PHP</h1> <div>Nombre: <NAME></div> <div>Fecha de entrega: 07 de septiembre de 2016</div> </div> <div id="menu"> <UL> <li><a href="eje1.php">Ejercicio 1</a></li> <li><a href="eje2.php">Ejercicio 2</a></li> <li><a href="eje3.php">Ejercicio 3</a></li> <li><a href="eje4.php">Ejercicio 4</a></li> <li><a href="eje5.php">Ejercicio 5</a></li> <li><a href="eje6.php">Ejercicio 6</a></li> <li><a href="eje7.php">Ejercicio 7</a></li> <li><a href="eje8.php">Ejercicio 8</a></li> <li><span class="elegido"><a href="eje9.php">Ejercicio 9</a></span></li> <li><a href="eje10.php">Ejercicio 10</a></li> <li><a href="eje11.php">Ejercicio 11</a></li> <li><a href="eje12.php">Ejercicio 12</a></li> </UL> </div> <div id="contenido"><p class="enunciado">Crear un formulario de contacto que reciba los siguientes campos: nombre, apellidos, correo y comentario. Una vez que se pulse el botón enviar debe mostrar los datos recibidos.</p> <div class="cleare"> <form action="" method="POST"> <table > <tr> <td colspan="2"> <strong>Formulario de contacto</strong></h2></td> </tr> <tr> <td><strong>Nombre:</strong></td> <td><input type="text" name="nombre" placeholder="Nombre" required="" style="width:150px;"></td> </tr> <tr> <td><strong>Apellidos:</strong></td> <td><input type="text" name="apellidos" placeholder="Apellidos" required="" style="width:150px;"></td> </tr> <tr> <td><strong>Correo:</strong></td> <td><input type="email" name="correo" placeholder="Correo electronico" required="" style="width:150px;"></td> </tr> <tr> <td><strong>Cometario:</strong></td> <td><textarea name="comentario" placeholder="Tu comentario nos interesa" required="" style="width:100%; height:100%px"></textarea></td> </tr> <tr> <td><input type="submit" name="enviar" value="enviar"></td> </tr> </table> </form> <?php if (isset($_POST["nombre"])) { echo "<p><strong>Nombre : </strong>".strtoupper($_POST['nombre'])." ".strtoupper($_POST['apellidos'])."</p>"; echo "<p><strong>Email : </strong>".$_POST['correo']."</p>"; echo "<p><strong>Comentario : </strong>".$_POST['comentario']."</p>"; } ?> </div> </div> <div id="pie">&copy; derechos reservados 2016 </div> </div> </body> </html><file_sep><!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <title>practica 5</title> <link rel="stylesheet" type="text/css" href="estilo.css"> </head> <body> <div id="contenedor"> <div id="cabecera"><h1>PRACTICA 5 DE PHP</h1> <div>Nombre: <NAME></div> <div>Fecha de entrega: 07 de septiembre de 2016</div> </div> <div id="menu"> <UL> <li><a href="eje1.php">Ejercicio 1</a></li> <li><a href="eje2.php">Ejercicio 2</a></li> <li><a href="eje3.php">Ejercicio 3</a></li> <li><a href="eje4.php">Ejercicio 4</a></li> <li><span class="elegido"><a href="eje5.php">Ejercicio 5</a></span></li> <li><a href="eje6.php">Ejercicio 6</a></li> <li><a href="eje7.php">Ejercicio 7</a></li> <li><a href="eje8.php">Ejercicio 8</a></li> <li><a href="eje9.php">Ejercicio 9</a></li> <li><a href="eje10.php">Ejercicio 10</a></li> <li><a href="eje11.php">Ejercicio 11</a></li> <li><a href="eje12.php">Ejercicio 12</a></li> </UL> </div> <div id="contenido"><p class="enunciado">Crear un programa que muestre las imágenes que contiene un directorio en cuatro columnas, además al pulsar sobre cualquier imagen debe mostrar la imagen en tamaño real (En la carpeta puede existir cualquier número de imágenes)</p> <p>Carpeta "img"</p> <div class="cleare"> <?php if (is_dir("img")) { if ($dir=opendir("img")) { while (($archivo= readdir($dir))!=false) { if ($archivo != '.' && $archivo != '..' && $archivo != '.htaccess') { echo '<div class="casillaimg">'; echo '<a href="img/'.$archivo.'" target="_blank"><img src="img/'.$archivo.'" width=70 height=70></a>'; echo "</div>"; //echo "$archivo <br>"; } } } } ?> </div> </div> <div id="pie">&copy; derechos reservados 2016 </div> </div> </body> </html><file_sep><!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <title>practica 5</title> <link rel="stylesheet" type="text/css" href="estilo.css"> </head> <body> <div id="contenedor"> <div id="cabecera"><h1>PRACTICA 5 DE PHP</h1> <div>Nombre: <NAME></div> <div>Fecha de entrega: 07 de septiembre de 2016</div> </div> <div id="menu"> <UL> <li><a href="eje1.php">Ejercicio 1</a></li> <li><a href="eje2.php">Ejercicio 2</a></li> <li><a href="eje3.php">Ejercicio 3</a></li> <li><a href="eje4.php">Ejercicio 4</a></li> <li><a href="eje5.php">Ejercicio 5</a></li> <li><span class="elegido"><a href="eje6.php">Ejercicio 6</a></span></li> <li><a href="eje7.php">Ejercicio 7</a></li> <li><a href="eje8.php">Ejercicio 8</a></li> <li><a href="eje9.php">Ejercicio 9</a></li> <li><a href="eje10.php">Ejercicio 10</a></li> <li><a href="eje11.php">Ejercicio 11</a></li> <li><a href="eje12.php">Ejercicio 12</a></li> </UL> </div> <div id="contenido"><p class="enunciado">Imprima los valores de un arreglo asociativo usando la instrucción foreach<br> <strong>Las monedas</strong></p> <div class="cleare"> <?php $arreglo= array('Bolivia' =>'Peso boliviano' ,'Peru'=>'Nuevo Sol','Argentina'=>'Peso argetino','Brasil'=>'Real','Venezuela'=>'Bolivar','EEUU'=> 'dolar','Europa'=>'euro','India'=>'Rupia'); foreach ($arreglo as $indice =>$valor) { ?> <strong><?=$indice.': '?></strong> <?=$valor?><br> <?php }?> </div> </div> <div id="pie">&copy; derechos reservados 2016 </div> </div> </body> </html><file_sep><!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <title>practica 5</title> <link rel="stylesheet" type="text/css" href="estilo.css"> </head> <body> <div id="contenedor"> <div id="cabecera"> <?php session_start(); if(md5($_POST['tmptxt']) != $_SESSION['key']) { //echo("Error: Nos has introducido el codigo correcto"); header('Location: eje10.php'); }else{ echo '<h1>BIENVENIDO '.strtoupper($_POST["usuario"]).' ¡¡¡Felicidades no eres un Robot o no lo pareces!!!</h1>'; } ?> </div> <div id="contenido"><p class="enunciado">Práctica de manejo del lenguaje php de la <br>materia <i>Tecnologias emergentes I </i></p></div> <div id="pie">&copy; derechos reservados 2016 </div> </div> </body> </html> <?php /*session_start(); // Configuracion $conf['mailDestinatario'] = '<EMAIL>'; $conf['mailAsunto'] = 'Buzon'; $conf['url_error'] = 'eje10.php'; $conf['url_ok'] = 'http://www.dominio.es/---cambiar por la página de ok---'; ###################################################################### # codigo de verificacion ###################################################################### // Validar argumentos y captcha if(!$_POST) { header('Location: '.$conf['url_error']); exit; } if ($_SESSION['tmptxt'] != $_POST['tmptxt']) { header('Location: '.$conf['url_error']); exit; } // Limpiar input de usuario foreach($_POST as $id=>$value) { $var[$id] = strip_tags(trim($value)); } // Definir cuerpo del email foreach($var as $id=>$value) { $mailCuerpo .= "$id : $value\r\n"; } // Enviar correo if(mail($conf['mailDestinatario'], $conf['mailAsunto'], $mailCuerpo)) { header('Location: '.$conf['url_ok']); } else { header('Location: '.$conf['url_error']); } */ ?><file_sep><!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <title>practica 5</title> <link rel="stylesheet" type="text/css" href="estilo.css"> </head> <body> <div id="contenedor"> <div id="cabecera"><h1>PRACTICA 5 DE PHP</h1> <div>Nombre: <NAME></div> <div>Fecha de entrega: 07 de septiembre de 2016</div> </div> <div id="menu"> <UL> <li><a href="eje1.php">Ejercicio 1</a></li> <li><a href="eje2.php">Ejercicio 2</a></li> <li><a href="eje3.php">Ejercicio 3</a></li> <li><a href="eje4.php">Ejercicio 4</a></li> <li><a href="eje5.php">Ejercicio 5</a></li> <li><a href="eje6.php">Ejercicio 6</a></li> <li><a href="eje7.php">Ejercicio 7</a></li> <li><a href="eje8.php">Ejercicio 8</a></li> <li><a href="eje9.php">Ejercicio 9</a></li> <li><a href="eje10.php">Ejercicio 10</a></li> <li><a href="eje11.php">Ejercicio 11</a></li> <li><span class="elegido"><a href="eje12.php">Ejercicio 12</a></span></li> </UL> </div> <div id="contenido"><p class="enunciado">Crear un simulador de lanzamiento de dos (2) y cinco (5) dados.</p> <div class="cleare"> <table cellspacing="20"> <tr> <td style="background-color: black; color:white;"> <form action="" method="POST"> <h3>Lanzar 2 dados</h3> <input type="hidden" name="lanza" value="2"> <input type="submit" name="enviar"> </form></td> <td style="background-color: green;color:white;"><form action="" method="POST"> <h3>Lanzar 5 dados</h3> <input type="hidden" name="lanza" value="5"> <input type="submit" name="enviar"> </form></td> </tr> </table> <?php if (isset($_POST["lanza"])) { if ($_POST["lanza"]==2) $dados= array("img/dg1.png","img/dg2.png","img/dg3.png","img/dg4.png","img/dg5.png","img/dg6.png"); else $dados= array("img/dv1.png","img/dv2.png","img/dv3.png","img/dv4.png","img/dv5.png","img/dv6.png"); for ($i=1 ; $i <= $_POST["lanza"] ; $i++) { echo '<div class="casillaimg">'; echo '<img src="'.$dados[rand(0,5)].'" width=70 height=70>'; echo "</div>"; } /*} */ } ?> </div> </div> <div id="pie">&copy; derechos reservados 2016 </div> </div> </body> </html>
7620112f54b1323ab4e98123660366f0a7e6218a
[ "PHP" ]
9
PHP
severocruz/practica5PHP
fff0f6d58839613c0d717a0a529a040d9e2b146e
1717d1e9a3e679a8c302482c7876ac14e2763e2b
refs/heads/master
<file_sep>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //var KafkaUtils = function() {} var JavaKakfaUtils = Java.type("org.apache.spark.streaming.kafka.KafkaUtils") var KafkaUtils = {} KafkaUtils.createStream = function(ssc, zkQuorum, group, topic) { var integer = new java.lang.Integer(1); var m = new java.util.HashMap(); m.put(topic, integer); return new DStream(JavaKakfaUtils.createStream(ssc.getJavaObject(), zkQuorum, group, m), ssc); }; <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JSDoc: Source: sql/DataFrame.js</title> <script src="scripts/prettify/prettify.js"> </script> <script src="scripts/prettify/lang-css.js"> </script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <div id="main"> <h1 class="page-title">Source: sql/DataFrame.js</h1> <section> <article> <pre class="prettyprint source"><code>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @constructor * @classdesc A distributed collection of data organized into named columns. A DataFrame is equivalent to a relational table in Spark SQL. * @example * var people = sqlContext.read.parquet("...") * @example * // Once created, it can be manipulated using the various domain-specific-language (DSL) functions defined in: * // DataFrame (this class), Column, and functions. * // To select a column from the data frame: * var ageCol = people("age") */ var DataFrame = function(jvmDataFrame) { JavaWrapper.call(this, jvmDataFrame); // Initialize our Row-specific properties this.logger = Logger.getLogger("sql.DataFrame_js"); }; DataFrame.prototype = Object.create(JavaWrapper.prototype); //Set the "constructor" property to refer to DataFrame DataFrame.prototype.constructor = DataFrame; /** * aggregates on the entire DataFrame without groups. * @example * // df.agg(...) is a shorthand for df.groupBy().agg(...) * var map = {}; * map["age"] = "max"; * map["salary"] = "avg"; * df.agg(map) * df.groupBy().agg(map) * @param {hashMap} - hashMap&lt;String,String> exprs * @returns {DataFrame} */ DataFrame.prototype.agg = function(hashMap) { return new DataFrame(this.getJavaObject().agg(hashMap)); }; /** * Returns a new DataFrame with an alias set. * @param {string} alias * @returns {DataFrame} */ DataFrame.prototype.as = function(alias) { return new DataFrame(this.getJavaObject().as(alias)); }; /** * Selects column based on the column name and return it as a Column. * Note that the column name can also reference to a nested column like a.b. * @param {string} colName * @returns {Column} */ DataFrame.prototype.apply = function(colName) { return new Column(this.getJavaObject().apply(colName)); }; /** * Persist this DataFrame with the default storage level (`MEMORY_ONLY`). * @returns {DataFrame} */ DataFrame.prototype.cache = function() { return new DataFrame(this.getJavaObject().cache()); }; /** * Returns a new DataFrame that has exactly numPartitions partitions. * Similar to coalesce defined on an RDD, this operation results in a narrow dependency, * e.g. if you go from 1000 partitions to 100 partitions, there will not be a shuffle, * instead each of the 100 new partitions will claim 10 of the current partitions. * @param {integer} numPartitions * @returns {DataFrame} */ DataFrame.prototype.coalesce = function(numPartitions) { return new DataFrame(this.getJavaObject().coalesce()); }; /** * Selects column based on the column name and return it as a Column. * @param {string} name * @returns {Column} */ DataFrame.prototype.col = function(name) { return new Column(this.getJavaObject().col(name)); }; /** * Returns an array that contains all of Rows in this DataFrame. * @returns {Row[]} */ DataFrame.prototype.collect = function() { var jRows = this.getJavaObject().collect(); var rows = []; for (var i = 0; i &lt; jRows.length; i++) { rows.push(new Row(jRows[i])); } return rows; }; /** * Returns all column names as an array. * @returns {string[]} */ DataFrame.prototype.columns = function() { var x = this.getJavaObject().columns(); var s = []; for (var i = 0; i &lt; x.length; i++) { s.push(x[i]); } return s; }; /** * Returns the number of rows in the DataFrame. * @returns {integer} */ DataFrame.prototype.count = function() { return this.getJavaObject().count(); }; /** * Create a multi-dimensional cube for the current DataFrame using the specified columns, so we can run aggregation on them. * @param {string| Column} cols... * @example * var df = peopleDataFrame.cube("age", "expense"); * @returns {GroupedData} */ DataFrame.prototype.cube = function() { var args = Array.prototype.slice.call(arguments); if(typeof args[0] !== 'object') args = args.map(function(v) { return this.col(v); }.bind(this)); var jCols = args.map(function(v) { return Utils.unwrapObject(v); }); return new GroupedData(this.getJavaObject().cube(jCols)); }; /** * Computes statistics for numeric columns, including count, mean, stddev, min, and max. * If no columns are given, this function computes statistics for all numerical columns. * This function is meant for exploratory data analysis, as we make no guarantee about the backward * compatibility of the schema of the resulting DataFrame. If you want to programmatically compute * summary statistics, use the agg function instead. * @param {string} cols.... * @example * var df = peopleDataFrame.describe("age", "expense"); * @returns {DataFrame} */ DataFrame.prototype.describe = function() { var args = Array.prototype.slice.call(arguments); return new DataFrame(this.getJavaObject().describe(args)); }; /** * Returns a new DataFrame that contains only the unique rows from this DataFrame. This is an alias for dropDuplicates. */ DataFrame.prototype.distinct = function() { return this.dropDuplicates(); }; /** * Returns a new DataFrame with a column dropped. * @param {string | Column} col * @returns {DataFrame} */ DataFrame.prototype.drop = function(col) { return new DataFrame(this.getJavaObject().drop(Utils.unwrapObject(col))); }; /** * Returns a new DataFrame that contains only the unique rows from this DataFrame, if colNames then considering only the subset of columns. * @param {string[]} colNames * @returns {DataFrame} */ DataFrame.prototype.dropDuplicates = function(colNames) { if (!colNames) { return new DataFrame(this.getJavaObject().dropDuplicates()); } else { return new DataFrame(this.getJavaObject().dropDuplicates(colNames)); } }; /** * Returns all column names and their data types as an array of arrays. ex. [["name","StringType"],["age","IntegerType"],["expense","IntegerType"]] * @returns {Array} Array of Array[2] */ DataFrame.prototype.dtypes = function() { var d = this.getJavaObject().dtypes(); var arrayOfTuple2 = []; for (var i = 0; i &lt; d.length; i++) { var tuple2 = Utils.javaToJs(d[i]); // convert Tuple2 to array[o1, o2] arrayOfTuple2.push(tuple2); } return arrayOfTuple2; }; /** * Returns a new DataFrame containing rows in this frame but not in another frame. This is equivalent to EXCEPT in SQL. * @param {DataFrame} otherDataFrame to compare to this DataFrame * @returns {DataFrame} */ DataFrame.prototype.except = function(otherDataFrame) { return new DataFrame(this.getJavaObject().except(Utils.unwrapObject(otherDataFrame))); }; /** * Prints the plans (logical and physical) to the console for debugging purposes. * @parma {boolean} if false prints the physical plans only. */ DataFrame.prototype.explain = function(extended) { var b = (extended) ? true : false; this.getJavaObject().explain(b); }; /** * Filters rows using the given SQL expression string or Filters rows using the given Column.. * @param {string | Column} * @returns {DataFrame} */ DataFrame.prototype.filter = function(arg) { if(typeof arg === 'object') return this.filterWithColumn(arguments[0]); else return this.filterWithString(arguments[0]); }; /** * Filters rows using the given Column * @param {Column} col * @returns {DataFrame} * @private */ DataFrame.prototype.filterWithColumn = function(col) { return new DataFrame(this.getJavaObject().filter(Utils.unwrapObject(col))); }; /** * Filters rows using the given SQL expression string * @param {string} columnExpr * @returns {DataFrame} * @private */ DataFrame.prototype.filterWithString = function(columnExpr) { return new DataFrame(this.getJavaObject().filter(columnExpr)); }; /** * Returns the first row. Alias for head(). * returns {Row} */ DataFrame.prototype.first = function() { return this.head(); }; /** * Returns a new RDD by first applying a function to all rows of this DataFrame, and then flattening the results. * @param {function} func * @returns {RDD} */ DataFrame.prototype.flatMap = function(func) { return this.toRDD().flatMap(func); }; /** * Applies a function to all elements of this DataFrame. * @example * rdd3.foreach(function(record) { * var connection = createNewConnection() * connection.send(record); * connection.close() * }); * @param {function} Function with one parameter * @returns {void} */ DataFrame.prototype.foreach = function(func) { return this.toRDD().foreach(func); }; /** * Applies a function to each partition of this DataFrame. * @example * df.foreachPartition(function(partitionOfRecords) { * var connection = createNewConnection() * partitionOfRecords.forEach(function(record){ * connection.send(record); * }); * connection.close() * }); * @param {function} Function with one Array parameter * @returns {void} */ DataFrame.prototype.foreachPartition = function(func) { return this.toRDD().foreachPartition(func); }; /** * Groups the DataFrame using the specified columns, so we can run aggregation on them * @param {string[] | Column[]} - Array of Column objects of column name strings * @returns {GroupedData} */ DataFrame.prototype.groupBy = function() { var args = Array.prototype.slice.call(arguments); if(typeof args[0] === 'object') return this.groupByWithColumns(args); else return this.groupByWithStrings(args); }; /** * Groups the DataFrame using the specified columns, so we can run aggregation on them * @param {Columns[]} * @returns {GroupedData} * @private */ DataFrame.prototype.groupByWithColumns = function(args) { var jCols = args.map(function(v) { return Utils.unwrapObject(v); }); var jGroupedData = this.getJavaObject().groupBy(jCols); var gd = new GroupedData(jGroupedData); return gd; }; /** * Groups the DataFrame using the specified columns, so we can run aggregation on them * @param {string[]} columnNames * @returns {GroupedData} * @private */ DataFrame.prototype.groupByWithStrings = function(args) { var jCols = args.map(function(v) { return this.col(v); }.bind(this)); return this.groupByWithColumns(jCols); }; /** * Returns the first row. * @returns {Row} */ DataFrame.prototype.head = function() { return new Row(this.getJavaObject().head()); }; /** * Returns a best-effort snapshot of the files that compose this DataFrame. This method simply asks each constituent * BaseRelation for its respective files and takes the union of all results. Depending on the source relations, * this may not find all input files. Duplicates are removed. * @returns {string[]} files */ DataFrame.prototype.inputFiles = function() { var files= this.getJavaObject().inputFiles(); var retFiles = []; for (var i = 0; i &lt; files.length; i++ ) { retFiles.push(files[i]); } return retFiles; }; /** * Returns a new DataFrame containing rows only in both this frame and another frame. This is equivalent to INTERSECT in SQL * @param {DataFrame} other * @returns {DataFrame} */ DataFrame.prototype.intersect = function(other) { return new DataFrame(this.getJavaObject().intersect(Utils.unwrapObject(other))); }; /** * Returns true if the collect and take methods can be run locally (without any Spark executors). * @returns {boolean} */ DataFrame.prototype.isLocal = function() { return this.getJavaObject().isLocal(); }; /** * Cartesian join with another DataFrame. Note that cartesian joins are very expensive without an extra filter that can be pushed down. * @param {DataFrame} Right side of the join operation. * @param {string | string[] | Column} columnNamesOrJoinExpr Optional: If string or array of strings column names, inner equi-join with another DataFrame using the given columns. * Different from other join functions, the join columns will only appear once in the output, i.e. similar to SQL's JOIN USING syntax. * If Column object, joinExprs inner join with another DataFrame, using the given join expression. * @param {string} joinType Optional, only valid if using Column joinExprs. * @returns {DataFrame} * @example * var joinedDf = df1.join(df2); * // or * var joinedDf = df1.join(df2,"age"); * // or * var joinedDf = df1.join(df2, ["age", "DOB"]); * // or Column joinExpr * var joinedDf = df1.join(df2, df1.col("name").equalTo(df2.col("name"))); * // or Column joinExpr * var joinedDf = df1.join(df2, df1.col("name").equalTo(df2.col("name")), "outer"); */ DataFrame.prototype.join = function(right, usingColumns, joinType) { var result; if (usingColumns) { if (Array.isArray(usingColumns)) { var scalaSeq = org.eclairjs.nashorn.Utils.toScalaSeq(usingColumns); result = this.getJavaObject().join(Utils.unwrapObject(right), scalaSeq); } else if (usingColumns instanceof Column) { var jType = !joinType ? "inner" : joinType; result = this.getJavaObject().join(Utils.unwrapObject(right), Utils.unwrapObject(usingColumns), jType); } else { result = this.getJavaObject().join(Utils.unwrapObject(right), usingColumns); } } else { result = this.getJavaObject().join(Utils.unwrapObject(right)); } return new DataFrame(result); }; /** * Returns a new DataFrame by taking the first n rows. The difference between this function and head is that head * returns an array while limit returns a new DataFrame. * @param {integer} number * @returns {DataFrame} */ DataFrame.prototype.limit = function(number) { return new DataFrame(this.getJavaObject().limit(number)); }; /** * Returns a new RDD by applying a function to all rows of this DataFrame. * @param {function} func * @returns {RDD} */ DataFrame.prototype.map = function(func) { return this.toRDD().map(func); }; /** * Return a new RDD by applying a function to each partition of this DataFrame. * Similar to map, but runs separately on each partition (block) of the DataFrame, so func must accept an Array. * func should return a array rather than a single item. * @param {function} * @returns {RDD} */ DataFrame.prototype.mapPartitions = function(func) { return this.toRDD().mapPartitions(func); }; /** * Returns a DataFrameNaFunctions for working with missing data. * @returns {DataFrameNaFunctions} */ DataFrame.prototype.na = function() { return new DataFrameNaFunctions(this.getJavaObject().na()); }; /** * Returns a new DataFrame sorted by the specified columns, if columnName is used sorted in ascending order. * This is an alias of the sort function. * @param {string | Column} columnName,...columnName or sortExprs,... sortExprs * @returns {DataFrame} */ DataFrame.prototype.orderBy = function() { return this.sort.apply(this, arguments); }; /** * @param {StorageLevel} newLevel * @returns {DataFrame} */ DataFrame.prototype.persist = function(newLevel) { var arg = newLevel ? Utils.unwrapObject(newLevel) : null; return new DataFrame(this.getJavaObject().persist(arg)); }; /** * Prints the schema to the console in a nice tree format. */ DataFrame.prototype.printSchema = function() { this.getJavaObject().printSchema(); }; /** * @returns {SQLContextQueryExecution} */ DataFrame.prototype.queryExecution = function() { return new SQLContext.QueryExecution(this.getJavaObject().queryExecution()); }; /** * Randomly splits this DataFrame with the provided weights. * @param {float[]} weights - weights for splits, will be normalized if they don't sum to 1. * @param {int} seed - Seed for sampling. * @returns {DataFrame[]} */ DataFrame.prototype.randomSplit = function(weights, seed) { var dfs = this.getJavaObject().randomSplit(weights, seed); var retDfs = []; for (var i = 0; i &lt; dfs.length; i++) { retDfs.push(new DataFrame(dfs[i])); } return retDfs; }; /** * Represents the content of the DataFrame as an RDD of Rows. * @returns {RDD} */ DataFrame.prototype.rdd = function() { return this.toRDD(); }; /** * Registers this DataFrame as a temporary table using the given name. * @param {string} tableName */ DataFrame.prototype.registerTempTable = function(tableName) { this.getJavaObject().registerTempTable(tableName); }; /** * Returns a new DataFrame that has exactly numPartitions partitions. * @param {integer} numPartitions * @returns {DataFrame} */ DataFrame.prototype.repartition = function(numPartitions) { return new DataFrame(this.getJavaObject().repartition(numPartitions)); }; /** * Create a multi-dimensional rollup for the current DataFrame using the specified columns, * so we can run aggregation on them. See GroupedData for all the available aggregate functions. * @param {string | Column} columnName, .....columnName or sortExprs,... sortExprs * @returns {GroupedData} * @example * var result = peopleDataFrame.rollup("age", "networth").count(); * // or * var col = peopleDataFrame.col("age"); * var result = peopleDataFrame.rollup(col).count(); */ DataFrame.prototype.rollup = function() { var columns = []; for (var i = 0; i &lt; arguments.length; i++) { var o = arguments[i]; if (typeof o === 'string' || o instanceof String) { o = this.col(o); } columns.push(Utils.unwrapObject(o)); } return new GroupedData(this.getJavaObject().rollup(columns)); }; /** * Returns a new DataFrame by sampling a fraction of rows, using a random seed. * @param {boolean} withReplacement * @param {float} fraction * @param {integer} seed Optional * @returns {DataFrame} */ DataFrame.prototype.sample = function(withReplacement, fraction, seed) { return new DataFrame(this.getJavaObject().sample(withReplacement, fraction, seed)); }; /** * Returns the schema of this DataFrame. * @returns {StructType} */ DataFrame.prototype.schema = function() { return new StructType(this.getJavaObject().schema()); }; /** * Selects a set of column based expressions. * @param {Column[] | string[]} * @returns {DataFrame} */ DataFrame.prototype.select = function() { var args = Array.prototype.slice.call(arguments); if(typeof args[0] === 'object') return this.selectWithColumns(args); else return this.selectWithStrings(args); }; /** * Selects a set of SQL expressions. This is a variant of select that accepts SQL expressions. * @param {string} exprs,...exprs * @returns {DataFrame} * @example * var result = peopleDataFrame.selectExpr("name", "age > 19"); */ DataFrame.prototype.selectExpr = function() { var args = Array.prototype.slice.call(arguments); return new DataFrame(this.getJavaObject().selectExpr(args)); }; /** * Selects a set of column based expressions. * @param {Column[]} * @returns {DataFrame} * @private */ DataFrame.prototype.selectWithColumns = function(args) { var jCols = args.map(function(v) { return Utils.unwrapObject(v); }); var jdf = this.getJavaObject().select(jCols); var df = new DataFrame(jdf); return df; }; /** * Selects a set of column based expressions. * @param {string[]} * @returns {DataFrame} * @private */ DataFrame.prototype.selectWithStrings = function(args) { var jCols = args.map(function(v) { return this.col(v); }.bind(this)); return this.selectWithColumns(jCols); }; /** * Displays the DataFrame rows in a tabular form. * @param {interger} numberOfRows Optional, defaults to 20. * @param {boolean] truncate Optional defaults to false, Whether truncate long strings. If true, strings more than 20 characters will be * truncated and all cells will be aligned right */ DataFrame.prototype.show = function(numberOfRows, truncate) { var numRow = numberOfRows ? numberOfRows : 20; var trunk = truncate ? true : false; this.getJavaObject().show(numRow, trunk); }; /** * Returns a new DataFrame sorted by the specified columns, if columnName is used sorted in ascending order. * @param {string | Column} columnName,...columnName or sortExprs,... sortExprs * @returns {DataFrame} * @example * var result = peopleDataFrame.sort("age", "name"); * // or * var col = peopleDataFrame.col("age"); * var colExpr = col.desc(); * var result = peopleDataFrame.sort(colExpr); */ DataFrame.prototype.sort = function() { var sortExprs = []; for (var i = 0; i &lt; arguments.length; i++) { var o = arguments[i]; if (typeof o === 'string' || o instanceof String) { o = this.col(o).asc(); } sortExprs.push(Utils.unwrapObject(o)); } return new DataFrame(this.getJavaObject().sort(Utils.unwrapObject(sortExprs))); }; /** * Returns SQLContext * @returns {SQLContext} */ DataFrame.prototype.sqlContext = function() { return new SQLContext(this.getJavaObject().sqlContext()); }; /** * Returns a DataFrameStatFunctions for working statistic functions support. * @example * var stat = peopleDataFrame.stat().cov("income", "networth"); * * @returns {DataFrameStatFunctions} */ DataFrame.prototype.stat = function() { return new DataFrameStatFunctions(this.getJavaObject().stat()); }; /** * Returns the first n rows in the DataFrame. * @param {integer} num * @returns {Row[]} */ DataFrame.prototype.take = function(num) { var rows = this.getJavaObject().take(num); var r = []; for (var i = 0; i &lt; rows.length; i++) { r.push(new Row(rows[i])); } return r; }; /** * Returns a new DataFrame with columns renamed. This can be quite convenient in conversion from a * RDD of tuples into a DataFrame with meaningful names. For example: * @param {string} colNames,...colNames * @return {DataFrame} * @example * var result = nameAgeDF.toDF("newName", "newAge"); */ DataFrame.prototype.toDF = function() { var args = Array.prototype.slice.call(arguments); return new DataFrame(this.getJavaObject().toDF(args)); }; /** * Returns the content of the DataFrame as a RDD of JSON strings. * @returns {RDD} */ DataFrame.prototype.toJSON = function() { return new RDD(this.getJavaObject().toJSON()); }; /** * Represents the content of the DataFrame as an RDD of Rows. * @returns {RDD} */ DataFrame.prototype.toRDD = function() { return new RDD(this.getJavaObject().javaRDD()); }; /** * Returns a new DataFrame containing union of rows in this frame and another frame. This is equivalent to UNION ALL in SQL. * @param {DataFrame} other * @returns {DataFrame} */ DataFrame.prototype.unionAll = function(other) { return new DataFrame(this.getJavaObject().unionAll(Utils.unwrapObject(other))); }; /** * @param {boolean} blocking */ DataFrame.prototype.unpersist = function(blocking) { this.getJavaObject().unpersist(blocking); }; /** * Filters rows using the given Column or SQL expression. * @param {Column | string} condition - . * @returns {DataFrame} */ DataFrame.prototype.where = function(condition) { return this.filter(condition); }; /** * Returns a new DataFrame by adding a column or replacing the existing column that has the same name. * @param {string} name * @param {Column} col * @returns {DataFrame} * @example * var col = peopleDataFrame.col("age"); * var df1 = peopleDataFrame.withColumn("newCol", col); */ DataFrame.prototype.withColumn = function(name, col) { return new DataFrame(this.getJavaObject().withColumn(name, Utils.unwrapObject(col))); }; /** * Returns a new DataFrame with a column renamed. This is a no-op if schema doesn't contain existingName. * @param {string} existingName * @param {string} newName * @returns {DataFrame} */ DataFrame.prototype.withColumnRenamed = function(existingName, newName) { return new DataFrame(this.getJavaObject().withColumnRenamed(existingName, newName)); }; /** * Interface for saving the content of the DataFrame out into external storage. * @returns {DataFrameWriter} */ DataFrame.prototype.write = function() { return new DataFrameWriter(this.getJavaObject().write()); }; </code></pre> </article> </section> </div> <nav> <h2><a href="index.html">Index</a></h2><h3>Classes</h3><ul><li><a href="Accumulable.html">Accumulable</a></li><li><a href="AccumulableParam.html">AccumulableParam</a></li><li><a href="Accumulator.html">Accumulator</a></li><li><a href="ALS.html">ALS</a></li><li><a href="ArrayType.html">ArrayType</a></li><li><a href="AssociationRules.html">AssociationRules</a></li><li><a href="BinaryType.html">BinaryType</a></li><li><a href="BisectingKMeans.html">BisectingKMeans</a></li><li><a href="BisectingKMeansModel.html">BisectingKMeansModel</a></li><li><a href="BooleanType.html">BooleanType</a></li><li><a href="CalendarIntervalType.html">CalendarIntervalType</a></li><li><a href="Column.html">Column</a></li><li><a href="DataFrame.html">DataFrame</a></li><li><a href="DataFrameNaFunctions.html">DataFrameNaFunctions</a></li><li><a href="DataFrameReader.html">DataFrameReader</a></li><li><a href="DataFrameStatFunctions.html">DataFrameStatFunctions</a></li><li><a href="DataFrameWriter.html">DataFrameWriter</a></li><li><a href="DataType.html">DataType</a></li><li><a href="DataTypes.html">DataTypes</a></li><li><a href="DateType.html">DateType</a></li><li><a href="DenseVector.html">DenseVector</a></li><li><a href="DoubleType.html">DoubleType</a></li><li><a href="DStream.html">DStream</a></li><li><a href="Duration.html">Duration</a></li><li><a href="FloatAccumulatorParam.html">FloatAccumulatorParam</a></li><li><a href="FloatType.html">FloatType</a></li><li><a href="FPGrowth.html">FPGrowth</a></li><li><a href="FPGrowthModel.html">FPGrowthModel</a></li><li><a href="FreqItemset.html">FreqItemset</a></li><li><a href="functions.html">functions</a></li><li><a href="FutureAction.html">FutureAction</a></li><li><a href="GroupedData.html">GroupedData</a></li><li><a href="HashPartitioner.html">HashPartitioner</a></li><li><a href="IntAccumulatorParam.html">IntAccumulatorParam</a></li><li><a href="IntegerType.html">IntegerType</a></li><li><a href="LabeledPoint.html">LabeledPoint</a></li><li><a href="LinearRegressionModel.html">LinearRegressionModel</a></li><li><a href="LinearRegressionWithSGD.html">LinearRegressionWithSGD</a></li><li><a href="List.html">List</a></li><li><a href="MapType.html">MapType</a></li><li><a href="MatrixFactorizationModel.html">MatrixFactorizationModel</a></li><li><a href="Metadata.html">Metadata</a></li><li><a href="MLWord2Vec.html">MLWord2Vec</a></li><li><a href="MLWord2VecModel.html">MLWord2VecModel</a></li><li><a href="NullType.html">NullType</a></li><li><a href="NumericType.html">NumericType</a></li><li><a href="PartialResult.html">PartialResult</a></li><li><a href="Partitioner.html">Partitioner</a></li><li><a href="RangePartitioner.html">RangePartitioner</a></li><li><a href="Rating.html">Rating</a></li><li><a href="RDD.html">RDD</a></li><li><a href="Row.html">Row</a></li><li><a href="RowFactory.html">RowFactory</a></li><li><a href="Rule.html">Rule</a></li><li><a href="SparkConf.html">SparkConf</a></li><li><a href="SparkContext.html">SparkContext</a></li><li><a href="SparkFiles.html">SparkFiles</a></li><li><a href="SparkStatusTracker.html">SparkStatusTracker</a></li><li><a href="SparseVector.html">SparseVector</a></li><li><a href="SQLContext.html">SQLContext</a></li><li><a href="SQLContext.QueryExecution.html">QueryExecution</a></li><li><a href="SQLContext.SparkPlanner.html">SparkPlanner</a></li><li><a href="SQLContext.SQLSession.html">SQLSession</a></li><li><a href="SqlDate.html">SqlDate</a></li><li><a href="SqlTimestamp.html">SqlTimestamp</a></li><li><a href="StorageLevel.html">StorageLevel</a></li><li><a href="StreamingContext.html">StreamingContext</a></li><li><a href="StringType.html">StringType</a></li><li><a href="StructField.html">StructField</a></li><li><a href="StructType.html">StructType</a></li><li><a href="Time.html">Time</a></li><li><a href="TimestampType.html">TimestampType</a></li><li><a href="Vectors.html">Vectors</a></li><li><a href="VectorUDT.html">VectorUDT</a></li><li><a href="Word2Vec.html">Word2Vec</a></li><li><a href="Word2VecModel.html">Word2VecModel</a></li></ul><h3>Global</h3><ul><li><a href="global.html#Vector">Vector</a></li></ul> </nav> <br clear="both"> <footer> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.2.3-dev</a> on Thu Feb 18 2016 17:00:52 GMT-0500 (EST) </footer> <script> prettyPrint(); </script> <script src="scripts/linenumber.js"> </script> </body> </html> <file_sep>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * :: Experimental :: * Word2Vec trains a model of `Map(String, Vector)`, i.e. transforms a word into a code for further * natural language processing or machine learning process. * @classdesc * @param {string} * @class */ MLWord2Vec = function (obj) { this.logger = Logger.getLogger("Word2Vec_js"); var jvmObject; if (obj instanceof org.apache.spark.ml.feature.Word2Vec) { jvmObject = obj; } else if ((typeof obj) == 'string') { jvmObject = new org.apache.spark.ml.feature.Word2Vec(obj); } else { jvmObject = new org.apache.spark.ml.feature.Word2Vec(); } JavaWrapper.call(this, jvmObject); }; MLWord2Vec.prototype = Object.create(JavaWrapper.prototype); MLWord2Vec.prototype.constructor = MLWord2Vec; /** * @param {string} * @returns {MLWord2Vec} */ MLWord2Vec.prototype.setInputCol = function (value) { return new MLWord2Vec(this.getJavaObject().setInputCol(value)); } /** * @param {string} * @returns {MLWord2Vec} */ MLWord2Vec.prototype.setOutputCol = function (value) { return new MLWord2Vec(this.getJavaObject().setOutputCol(value)); } /** * @param {integer} * @returns {MLWord2Vec} */ MLWord2Vec.prototype.setVectorSize = function (value) { return new MLWord2Vec(this.getJavaObject().setVectorSize(value)); } /** * @param {integer} value * @returns {MLWord2Vec} */ MLWord2Vec.prototype.setWindowSize = function (value) { return new MLWord2Vec(this.getJavaObject().setWindowSize(value)); } /** * @param {float} value * @returns {MLWord2Vec} */ MLWord2Vec.prototype.setStepSize = function (value) { return new MLWord2Vec(this.getJavaObject().setStepSize(value)); } /** * @param {integer} value * @returns {MLWord2Vec} */ MLWord2Vec.prototype.setNumPartitions = function (value) { return new MLWord2Vec(this.getJavaObject().setNumPartitions(value)); } /** * @param {integer} value * @returns {MLWord2Vec} */ MLWord2Vec.prototype.setMaxIter = function (value) { return new MLWord2Vec(this.getJavaObject().setMaxIter(value)); } /** * @param {integer} value * @returns {MLWord2Vec} */ MLWord2Vec.prototype.setSeed = function (value) { return new MLWord2Vec(this.getJavaObject().setSeed(value)); } /** * @param {integer} value * @returns {MLWord2Vec} */ MLWord2Vec.prototype.setMinCount = function (value) { return new MLWord2Vec(this.getJavaObject().setMinCount(value)); } /** * @param {DataFrame} dataset * @returns {MLWord2VecModel} */ MLWord2Vec.prototype.fit = function (dataset) { var dataset_uw = Utils.unwrapObject(dataset); return new MLWord2VecModel(this.getJavaObject().fit(dataset_uw)); } /** * @param {StructType} schema * @returns {StructType} */ MLWord2Vec.prototype.transformSchema = function (schema) { var schema_uw = Utils.unwrapObject(schema); return new StructType(this.getJavaObject().transformSchema(schema_uw)); } /** * @param {ParamMap} * @returns {MLWord2Vec} * @private */ MLWord2Vec.prototype.copy = function (extra) { throw "not implemented by ElairJS"; // var extra_uw = Utils.unwrapObject(extra); // return this.getJavaObject().copy(extra_uw); } /** * :: Experimental :: * Model fitted by {@link MLWord2Vec}. * @classdesc * @constructor */ MLWord2VecModel = function (jvmObject) { this.logger = Logger.getLogger("MLWord2VecModel_js"); JavaWrapper.call(this, jvmObject); }; MLWord2VecModel.prototype = Object.create(JavaWrapper.prototype); MLWord2VecModel.prototype.constructor = MLWord2VecModel; /** * Find "num" number of words closest in similarity to the given word. * Returns a dataframe with the words and the cosine similarities between the * synonyms and the given word. * @param {string} * @param {number} * @returns {DataFrame} * @private * */ MLWord2VecModel.prototype.findSynonymswithnumber = function (word, num) { throw "not implemented by ElairJS"; // return this.getJavaObject().findSynonyms(word,num); } /** * Find "num" number of words closest to similarity to the given vector representation * of the word. Returns a dataframe with the words and the cosine similarities between the * synonyms and the given word vector. * @param {Vector} * @param {number} * @returns {DataFrame} * @private * */ MLWord2VecModel.prototype.findSynonymswithnumber = function (word, num) { throw "not implemented by ElairJS"; // var word_uw = Utils.unwrapObject(word); // return this.getJavaObject().findSynonyms(word_uw,num); } /** * @param {string} * @returns {string} * @private * */ MLWord2VecModel.prototype.setInputCol = function (value) { throw "not implemented by ElairJS"; // return this.getJavaObject().setInputCol(value); } /** * @param {string} * @returns {string} * @private * */ MLWord2VecModel.prototype.setOutputCol = function (value) { throw "not implemented by ElairJS"; // return this.getJavaObject().setOutputCol(value); } /** * Transform a sentence column to a vector column to represent the whole sentence. The transform * is performed by averaging all word vectors it contains. * @param {DataFrame} * @returns {DataFrame} * @private * */ MLWord2VecModel.prototype.transform = function (dataset) { var dataset_uw = Utils.unwrapObject(dataset); return new DataFrame(this.getJavaObject().transform(dataset_uw)); } /** * @param {StructType} * @returns {StructType} * @private * */ MLWord2VecModel.prototype.transformSchema = function (schema) { throw "not implemented by ElairJS"; // var schema_uw = Utils.unwrapObject(schema); // return this.getJavaObject().transformSchema(schema_uw); } /** * @param {ParamMap} * @returns {MLWord2VecModel} * @private * */ MLWord2VecModel.prototype.copy = function (extra) { throw "not implemented by ElairJS"; // var extra_uw = Utils.unwrapObject(extra); // return this.getJavaObject().copy(extra_uw); } /** * @returns {MLWriter} * @private * */ MLWord2VecModel.prototype.write = function () { throw "not implemented by ElairJS"; // return this.getJavaObject().write(); } // // static methods // /** * @param {string} * @returns {MLWord2Vec} * @private * */ MLWord2Vec.load = function (path) { throw "not implemented by ElairJS"; // return org.apache.spark.ml.feature.MLWord2Vec.load(path); } /** * @returns {MLReader} * @private * */ MLWord2VecModel.read = function () { throw "not implemented by ElairJS"; // return org.apache.spark.ml.feature.MLWord2VecModel.read(); } /** * @param {string} * @returns {MLWord2VecModel} * @private * */ MLWord2VecModel.load = function (path) { throw "not implemented by ElairJS"; // return org.apache.spark.ml.feature.Word2VecModel.load(path); } <file_sep>package org.eclairjs.nashorn; import jdk.nashorn.api.scripting.ScriptObjectMirror; import org.apache.commons.lang.ArrayUtils; import org.apache.spark.api.java.function.PairFlatMapFunction; import scala.Tuple2; import javax.script.Invocable; import javax.script.ScriptEngine; import java.util.ArrayList; public class JSPairFlatMapFunction implements PairFlatMapFunction { private String func = null; private Object args[] = null; private String functionName = null; public JSPairFlatMapFunction(String func, Object[] o) { this.functionName = Utils.getUniqeFunctionName(); this.func = "var " + this.functionName +" = " + func; this.args = o; } @Override public Iterable<Tuple2> call(Object o) throws Exception { ScriptEngine e = NashornEngineSingleton.getEngine(); e.eval(this.func); Invocable invocable = (Invocable) e; Object arg0 = Utils.javaToJs(o, e); Object params[] = {arg0}; params = ArrayUtils.addAll(params, this.args); ScriptObjectMirror ret = (ScriptObjectMirror)invocable.invokeFunction(this.functionName, params); ArrayList l = new ArrayList(ret.values()); ArrayList<Tuple2> l2 = new ArrayList<Tuple2>(ret.size()); for(Object t : l) { ArrayList al = new ArrayList(((ScriptObjectMirror)t).values()); Object t1 = Utils.jsToJava(al.get(0)); Object t2 = Utils.jsToJava(al.get(1)); Tuple2 tuple = new Tuple2(t1, t2); l2.add(tuple); } return l2; } } <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JSDoc: Source: streaming/StreamingContext.js</title> <script src="scripts/prettify/prettify.js"> </script> <script src="scripts/prettify/lang-css.js"> </script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <div id="main"> <h1 class="page-title">Source: streaming/StreamingContext.js</h1> <section> <article> <pre class="prettyprint source"><code>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var JavaStreamingContext = Java.type('org.apache.spark.streaming.api.java.JavaStreamingContext'); /** * @constructor * @classdesc Main entry point for Spark Streaming functionality. It provides methods used to create DStreams from various input sources. * It can be either created by providing a Spark master URL and an appName, or from a org.apache.spark.SparkConf configuration * (see core Spark documentation), or from an existing org.apache.spark.SparkContext. The associated SparkContext can be accessed * using context.sparkContext. After creating and transforming DStreams, the streaming computation can be started and stopped using * context.start() and context.stop(), respectively. context.awaitTermination() allows the current thread to wait for the termination * of the context by stop() or by an exception. * @param {SparkContex} sparkContext * @param {Duration} duration */ var StreamingContext = function(sparkContext, duration) { var jvmObj = new JavaStreamingContext(Utils.unwrapObject(sparkContext), Utils.unwrapObject(duration) ); this.logger = Logger.getLogger("streaming.Duration_js"); JavaWrapper.call(this, jvmObj); }; StreamingContext.prototype = Object.create(JavaWrapper.prototype); StreamingContext.prototype.constructor = StreamingContext; /** * Wait for the execution to stop */ StreamingContext.prototype.awaitTermination = function() { this.getJavaObject().awaitTermination(); }; /** * Wait for the execution to stop, or timeout * @param {long} millis * @returns {boolean} */ StreamingContext.prototype.awaitTerminationOrTimeout = function(millis) { return this.getJavaObject().awaitTerminationOrTimeout(millis); }; /** * Start the execution of the streams. */ StreamingContext.prototype.start = function() { this.getJavaObject().start(); }; /** * Stops the execution of the streams. */ StreamingContext.prototype.stop = function() { if(arguments.length == 1) { this.getJavaObject().stop(arguments[0]); } else { this.getJavaObject().stop(); } }; StreamingContext.prototype.close = function() { this.getJavaObject().close(); }; /** * Create a input stream from TCP source hostname:port. * @param {string} host * @param {string} port * @returns {DStream} */ StreamingContext.prototype.socketTextStream = function(host, port) { var jDStream = this.getJavaObject().socketTextStream(host, port); return new DStream(jDStream, this); }; </code></pre> </article> </section> </div> <nav> <h2><a href="index.html">Index</a></h2><h3>Classes</h3><ul><li><a href="Accumulable.html">Accumulable</a></li><li><a href="AccumulableParam.html">AccumulableParam</a></li><li><a href="Accumulator.html">Accumulator</a></li><li><a href="ALS.html">ALS</a></li><li><a href="ArrayType.html">ArrayType</a></li><li><a href="AssociationRules.html">AssociationRules</a></li><li><a href="BinaryType.html">BinaryType</a></li><li><a href="BisectingKMeans.html">BisectingKMeans</a></li><li><a href="BisectingKMeansModel.html">BisectingKMeansModel</a></li><li><a href="BooleanType.html">BooleanType</a></li><li><a href="CalendarIntervalType.html">CalendarIntervalType</a></li><li><a href="Column.html">Column</a></li><li><a href="DataFrame.html">DataFrame</a></li><li><a href="DataFrameNaFunctions.html">DataFrameNaFunctions</a></li><li><a href="DataFrameReader.html">DataFrameReader</a></li><li><a href="DataFrameStatFunctions.html">DataFrameStatFunctions</a></li><li><a href="DataFrameWriter.html">DataFrameWriter</a></li><li><a href="DataType.html">DataType</a></li><li><a href="DataTypes.html">DataTypes</a></li><li><a href="DateType.html">DateType</a></li><li><a href="DenseVector.html">DenseVector</a></li><li><a href="DoubleType.html">DoubleType</a></li><li><a href="DStream.html">DStream</a></li><li><a href="Duration.html">Duration</a></li><li><a href="FloatAccumulatorParam.html">FloatAccumulatorParam</a></li><li><a href="FloatType.html">FloatType</a></li><li><a href="FPGrowth.html">FPGrowth</a></li><li><a href="FPGrowthModel.html">FPGrowthModel</a></li><li><a href="FreqItemset.html">FreqItemset</a></li><li><a href="functions.html">functions</a></li><li><a href="FutureAction.html">FutureAction</a></li><li><a href="GroupedData.html">GroupedData</a></li><li><a href="HashPartitioner.html">HashPartitioner</a></li><li><a href="IntAccumulatorParam.html">IntAccumulatorParam</a></li><li><a href="IntegerType.html">IntegerType</a></li><li><a href="LabeledPoint.html">LabeledPoint</a></li><li><a href="LinearRegressionModel.html">LinearRegressionModel</a></li><li><a href="LinearRegressionWithSGD.html">LinearRegressionWithSGD</a></li><li><a href="List.html">List</a></li><li><a href="MapType.html">MapType</a></li><li><a href="MatrixFactorizationModel.html">MatrixFactorizationModel</a></li><li><a href="Metadata.html">Metadata</a></li><li><a href="MLWord2Vec.html">MLWord2Vec</a></li><li><a href="MLWord2VecModel.html">MLWord2VecModel</a></li><li><a href="NullType.html">NullType</a></li><li><a href="NumericType.html">NumericType</a></li><li><a href="PartialResult.html">PartialResult</a></li><li><a href="Partitioner.html">Partitioner</a></li><li><a href="RangePartitioner.html">RangePartitioner</a></li><li><a href="Rating.html">Rating</a></li><li><a href="RDD.html">RDD</a></li><li><a href="Row.html">Row</a></li><li><a href="RowFactory.html">RowFactory</a></li><li><a href="Rule.html">Rule</a></li><li><a href="SparkConf.html">SparkConf</a></li><li><a href="SparkContext.html">SparkContext</a></li><li><a href="SparkFiles.html">SparkFiles</a></li><li><a href="SparkStatusTracker.html">SparkStatusTracker</a></li><li><a href="SparseVector.html">SparseVector</a></li><li><a href="SQLContext.html">SQLContext</a></li><li><a href="SQLContext.QueryExecution.html">QueryExecution</a></li><li><a href="SQLContext.SparkPlanner.html">SparkPlanner</a></li><li><a href="SQLContext.SQLSession.html">SQLSession</a></li><li><a href="SqlDate.html">SqlDate</a></li><li><a href="SqlTimestamp.html">SqlTimestamp</a></li><li><a href="StorageLevel.html">StorageLevel</a></li><li><a href="StreamingContext.html">StreamingContext</a></li><li><a href="StringType.html">StringType</a></li><li><a href="StructField.html">StructField</a></li><li><a href="StructType.html">StructType</a></li><li><a href="Time.html">Time</a></li><li><a href="TimestampType.html">TimestampType</a></li><li><a href="Vectors.html">Vectors</a></li><li><a href="VectorUDT.html">VectorUDT</a></li><li><a href="Word2Vec.html">Word2Vec</a></li><li><a href="Word2VecModel.html">Word2VecModel</a></li></ul><h3>Global</h3><ul><li><a href="global.html#Vector">Vector</a></li></ul> </nav> <br clear="both"> <footer> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.2.3-dev</a> on Thu Feb 18 2016 17:00:52 GMT-0500 (EST) </footer> <script> prettyPrint(); </script> <script src="scripts/linenumber.js"> </script> </body> </html> <file_sep>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var sparkConf = new SparkConf() .setAppName("Binary Classification Metrics Test") .setMaster("local[*]"); var sc = new SparkContext(sparkConf); var data = MLUtils.loadLibSVMFile(sc, "examples/data/mllib/sample_binary_classification_data.txt"); //Split data into training (60%) and test (40%) var split = data.randomSplit([0.6, 0.4], 11) var training = split[0].cache(); var test = split[1]; var model = new LogisticRegressionWithLBFGS() .setNumClasses(2) .run(training); var predictionAndLabels = test.mapToPair(function(lp, model) { return [model.predict(lp.getFeatures()), lp.getLabel()]; }); var metrics = new BinaryClassificationMetrics(predictionAndLabels); // Precision by threshold var precision = metrics.precisionByThreshold(); print("Precision by threshold: " + precision.collect()); // Recall by threshold var recall = metrics.recallByThreshold(); print("Recall by threshold: " + recall.collect()); // F Score by threshold var f1Score = metrics.fMeasureByThreshold(); print("F1 Score by threshold: " + f1Score.collect()); var f2Score = metrics.fMeasureByThreshold(2.0); print("F2 Score by threshold: " + f2Score.collect()); // Precision-recall curve var prc = metrics.pr(); print("Precision-recall curve: " + prc.collect()); <file_sep>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.eclairjs.nashorn; import jdk.nashorn.api.scripting.JSObject; import jdk.nashorn.api.scripting.ScriptObjectMirror; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptException; import org.apache.log4j.Logger; import org.apache.spark.SparkFiles; import org.apache.spark.mllib.regression.LinearRegressionModel; import org.apache.spark.mllib.regression.LabeledPoint; import org.apache.spark.rdd.RDD; import org.apache.spark.sql.Row; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import scala.Tuple2; import scala.collection.Seq; import scala.collection.convert.Wrappers.IteratorWrapper; import scala.collection.convert.Wrappers.IterableWrapper; import java.io.FileReader; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.*; /** * Created by bburns on 9/18/15. */ public class Utils { /* public static Object javaToJs(Object o) { if(o instanceof Tuple2) { Tuple2 t = (Tuple2)o; ArrayList l = new ArrayList(); l.add(t._1()); l.add(t._2()); return l.toArray(); } else return o; } */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static Object javaToJs(Object o, ScriptEngine engine) { Logger logger = Logger.getLogger(Utils.class); String packageName = null; if(o != null) { logger.debug("javaToJs className " + o.getClass().getName()); Package pack = o.getClass().getPackage(); if (pack != null) { packageName = pack.getName(); } } /* * Any object that belongs to Spark we will wrapper it with a JavaScript object * If we don't have a JavaScript wrapper for it then we will catch the * exception and just use the wrapObject method. */ if ((packageName != null) && (packageName.indexOf("org.apache.spark") > -1)) { logger.debug("spark object"); String className = o.getClass().getSimpleName(); try { Invocable invocable = (Invocable) engine; if (className.endsWith("$")) { //anonymous class logger.debug("getSuperClass for " + className); className = o.getClass().getSuperclass().getSimpleName(); } if ( className.equals("JavaRDD")) { /* * Map JavaRDD to RDD for JavaScript */ className = "RDD"; //o.getClass().getSimpleName(); } else if (className.equals("Word2Vec") || className.equals("Word2VecModel")) { if (packageName.indexOf("org.apache.spark.ml") > -1) { /* ML */ className = "ML" + o.getClass().getSimpleName(); } } logger.debug("create " + className); Object params[] = {className, o}; Object parm = invocable.invokeFunction("createJavaWrapperObject", params); logger.debug(parm); return parm; } catch (Exception e) { logger.warn(className + " convertion error, will just wrapObject " + e); logger.debug(className + " javaToJs instanceof " + o.getClass()); return wrapObject(o); } } else if (o instanceof Tuple2) { Tuple2 t = (Tuple2)o; logger.info("Tupple2 - " + t.toString()); Object er = null; Object o1 = javaToJs(t._1(),engine); Object o2 = javaToJs(t._2(), engine); logger.debug("o1 = " + o1); try { Invocable invocable = (Invocable) engine; Object params[] = {o1, o2}; er = invocable.invokeFunction("convertJavaTuple2",params); } catch (ScriptException | NoSuchMethodException e) { logger.error(" Tuple2 convertion " + e); } return er; } else if (o instanceof IteratorWrapper) { logger.debug("Iterator " + o.toString()); ArrayList alist = new ArrayList(); while(((IteratorWrapper) o).hasMoreElements()) { alist.add(javaToJs(((IteratorWrapper) o).nextElement(),engine)); } return wrapObject(alist); } else if (o instanceof IterableWrapper) { logger.debug("Iterable " + o.toString()); ArrayList alist = new ArrayList(); Iterator iter=((IterableWrapper) o).iterator(); while(iter.hasNext()) { alist.add(javaToJs(iter.next(),engine)); } return wrapObject(alist); } else if (o instanceof JSONObject) { Object er = null; try { logger.debug("JSONObject " + o.toString()); Invocable invocable = (Invocable) engine; Object params[] = {o.toString()}; er = invocable.invokeFunction("convertJavaJSONObject",params); } catch (ScriptException | NoSuchMethodException e) { logger.error(" JSONObject convertion " + e); } return er; } else { logger.debug(" jsToJava wrapObject " + o); return wrapObject(o); } } public static Object jsToJava(Object o) { Logger logger = Logger.getLogger(Utils.class); if(o != null) logger.debug("jsToJava" + o.getClass().getName()); if ( (o instanceof ScriptObjectMirror) && ((ScriptObjectMirror) o).hasMember("getJavaObject") ) { Object r = ((ScriptObjectMirror) o).callMember("getJavaObject"); logger.debug("getJavaObject" + r.getClass().getName()); return r; } else if(o instanceof JSObject) { Object obj = ScriptObjectMirror.wrapAsJSONCompatible(o, null); String j = JSONValue.toJSONString(obj); return JSONValue.parse(j); } return o; } public static String getUniqeFunctionName() { return "EXPORTEDFUNCTION" + java.util.UUID.randomUUID().toString().replace("-", "_"); } public static ScriptEngine addScopeVarsToEngine(HashMap scopeVars, ScriptEngine engine) { Logger logger = Logger.getLogger(Utils.class); logger.debug("addScopeVarsToEngine"); if (scopeVars != null) { Iterator it = scopeVars.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); logger.debug("adding " + pair.getKey() + " value " + pair.getValue()); engine.put((String)pair.getKey(), pair.getValue()); } } return engine; } private static Object wrapObject(Object o) { Logger logger = Logger.getLogger(Utils.class); if(o instanceof String || o instanceof Number) { return o; } logger.debug("wrapAsJSONCompatible " + o); return ScriptObjectMirror.wrapAsJSONCompatible(o,null); } public static String jarLoc() { Logger logger = Logger.getLogger(Utils.class); String jarPath = null; Map<String, String> env = System.getenv(); jarPath = env.get("ECLAIR_JAR_LOC"); if (jarPath == null) { String path = Utils.class.getProtectionDomain().getCodeSource().getLocation().getPath(); logger.info("jar path = " + path); String decodedPath = null; try { decodedPath = URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } jarPath = decodedPath; } logger.info("env = "+ jarPath); return jarPath; } /** * Takes an array of objects and returns a scala Seq * @param {Object[]} o * @return {scala.collection.Seq} */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static Seq toScalaSeq(Object[] o) { ArrayList list = new ArrayList(); for (int i = 0; i < o.length; i++) { list.add(o[i]); } return scala.collection.JavaConversions.asScalaBuffer(list).toList(); } } <file_sep>/* * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * :: Experimental :: * * Generates association rules from a [[RDD[FreqItemset[Item]]]. This method only generates * association rules which have a single item as the consequent. * * @classdesc */ /** * Constructs a default instance with default parameters {minConfidence = 0.8}. * @class */ var AssociationRules = function() { this.logger = Logger.getLogger("AssociationRules_js"); var jvmObject; if (arguments.length < 1) { jvmObject = new org.apache.spark.mllib.fpm.AssociationRules(); } else { jvmObject = arguments[0]; } JavaWrapper.call(this, jvmObject); }; AssociationRules.prototype = Object.create(JavaWrapper.prototype); AssociationRules.prototype.constructor = AssociationRules; /** * Sets the minimal confidence (default: `0.8`). * @param {float} minConfidence * @returns {AssociationRules} */ AssociationRules.prototype.setMinConfidence = function(minConfidence) { var javaObject = this.getJavaObject().setMinConfidence(minConfidence); return new AssociationRules(javaObject); }; /** * Computes the association rules with confidence above {@link minConfidence}. * @param {RDD} freqItemsets frequent itemset model obtained from {@link FPGrowth} * * @returns {RDD} a [[Set[Rule[Item]]] containing the assocation rules. */ AssociationRules.prototype.run = function(freqItemsets) { var freqItemsets_uw = Utils.unwrapObject(freqItemsets); var javaObject = this.getJavaObject().run(freqItemsets_uw); return new RDD(javaObject); }; /** * An association rule between sets of items. * * @classdesc * @class */ var Rule = function(jvmObject) { this.logger = Logger.getLogger("Rule_js"); this.logger.debug("constructor"); JavaWrapper.call(this, jvmObject); }; Rule.prototype = Object.create(JavaWrapper.prototype); Rule.prototype.constructor = Rule; /** * Returns antecedent * @returns {object} */ Rule.prototype.antecedent = function() { /* public java.util.List<Item> javaAntecedent() Returns antecedent in a Java List. */ return this.getJavaObject().javaAntecedent(); }; /** * Returns consequent * @returns {object} */ Rule.prototype.consequent = function() { /* public java.util.List<Item> javaConsequent() Returns consequent in a Java List. */ return this.getJavaObject().javaConsequent(); }; /** * Returns the confidence of the rule. * @returns {float} */ Rule.prototype.confidence = function() { /* public double confidence() Returns the confidence of the rule. */ return this.getJavaObject().confidence(); }; /** * * @returns {string} */ Rule.prototype.toString = function() { return this.getJavaObject().toString(); };<file_sep>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var sparkConf = new SparkConf().setAppName("JavaScriptSparkSQL").setMaster("local[*]"); var ctx = new SparkContext(sparkConf); var sqlContext = new SQLContext(ctx); // Load a text file and convert each line to a JavaScript Object. var people = ctx.textFile("examples/data/people.txt").map(function(line) { var parts = line.split(","); return person = { name: parts[0], age: parseInt(parts[1].trim()) }; }); //Generate the schema var fields = []; fields.push(DataTypes.createStructField("name", DataTypes.StringType, true)); fields.push(DataTypes.createStructField("age", DataTypes.IntegerType, true)); var schema = DataTypes.createStructType(fields); // Convert records of the RDD (people) to Rows. var rowRDD = people.map(function(person){ return RowFactory.create([person.name, person.age]); }); //Apply the schema to the RDD. var peopleDataFrame = sqlContext.createDataFrame(rowRDD, schema); // Register the DataFrame as a table. peopleDataFrame.registerTempTable("people"); // SQL can be run over RDDs that have been registered as tables. var results = sqlContext.sql("SELECT name FROM people"); //The results of SQL queries are DataFrames and support all the normal RDD operations. //The columns of a row in the result can be accessed by ordinal. var names = results.toRDD().map(function(row) { return "Name: " + row.getString(0); }); print("names = " + names.take(10)); var dataFrame = sqlContext.read().json("examples/data/test.json"); var gd = dataFrame.groupBy(dataFrame.col("first")); var df2 = gd.count(); df2.show(); df2.count(); <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JSDoc: Source: sql/Column.js</title> <script src="scripts/prettify/prettify.js"> </script> <script src="scripts/prettify/lang-css.js"> </script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <div id="main"> <h1 class="page-title">Source: sql/Column.js</h1> <section> <article> <pre class="prettyprint source"><code>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * * @constructor * @classdesc A column in a DataFrame. * @param {string} column name of the column */ var Column = function(column) { var jvmObj; if (typeof column === 'string' || column instanceof String) { jvmObj = new org.apache.spark.sql.Column(column); } else { jvmObj = column; } this.logger = Logger.getLogger("sql.Column_js"); JavaWrapper.call(this, jvmObj); }; Column.prototype = Object.create(JavaWrapper.prototype); //Set the "constructor" property to refer to Column Column.prototype.constructor = Column; /** * Gives the column an alias. Same as as. * @param {string} alias * @returns {Column} * @example * // Renames colA to colB in select output. * df.select(df.col("colA").alias("colB")) */ Column.prototype.alias = function(a) { return new Column(this.getJavaObject().alias(a)); } /** * Boolean AND. * @param {Column} other * @returns {Column} * @example * people.select( people.col("inSchool").and(people.col("isEmployed"))); */ Column.prototype.and = function(other) { return new Column(this.getJavaObject().and(Utils.unwrapObject(other))); } /** * Extracts a value or values from a complex type. * The following types of extraction are supported: * - Given an Array, an integer ordinal can be used to retrieve a single value. * - Given a Map, a key of the correct type can be used to retrieve an individual value. * - Given a Struct, a string fieldName can be used to extract that field. * - Given an Array of Structs, a string fieldName can be used to extract filed * of every struct in that array, and return an Array of fields * @param {string} * @returns {Column} * @private */ Column.prototype.apply = function(extraction) { throw "not implemented by ElairJS"; //return new Column(this.getJavaObject().apply(extraction)); } /** * Gives the column an alias. * @param {string | string[]} aliases, if array of strings assigns the given aliases to the results of a table generating function. * @param {Metadata} metadata Optional, not valid with string array * @returns {Column} */ Column.prototype.as = function(aliases, metadata) { var c; if (!Array.isArray(aliases) && metadata) { c = this.getJavaObject().as(aliases, metadata); } else { c = this.getJavaObject().as(aliases); } return new Column(c); } /** * Returns an ordering used in sorting. * @returns {Column} * @example * df.sort(df.col("age").asc()); */ Column.prototype.asc = function() { return new Column(this.getJavaObject().asc()); }; /** * True if the current column is between the lower bound and upper bound, inclusive. * @param {object} lowerBound * @param {object} upperBound * @returns {Column} * @example * var col = new Column("age"); * var testCol = col.between(10, 29); * var results = peopleDataFrame.select(testCol); */ Column.prototype.between = function(lowerBound, upperBound) { this.logger.debug("between"); return new Column(this.getJavaObject().between(lowerBound, upperBound)); }; /** * Compute bitwise AND of this expression with another expression. * @example * df.select(df.col("colA").bitwiseAND(df.col("colB"))); * * @since EclairJS 0.1 Spark 1.4.0 * @param {Column} other * @returns {Column} */ Column.prototype.bitwiseAND = function(other) { var javaObject = this.getJavaObject().bitwiseAND(Utils.unwrapObject(other)); return new Column(javaObject); }; /** * Compute bitwise OR of this expression with another expression. * @example * df.select(df.col("colA").bitwiseOR(df.col("colB"))); * * @since EclairJS 0.1 Spark 1.4.0 * @param {Column} other * @returns {Column} */ Column.prototype.bitwiseOR = function(other) { var javaObject = this.getJavaObject().bitwiseOR(Utils.unwrapObject(other)); return new Column(javaObject); }; /** * Compute bitwise XOR of this expression with another expression. * @example * df.select(df.col("colA").bitwiseXOR(df.col("colB"))); * * @since EclairJS 0.1 Spark 1.4.0 * @param {Column} other * @returns {Column} */ Column.prototype.bitwiseXOR = function(other) { var javaObject = this.getJavaObject().bitwiseXOR(Utils.unwrapObject(other)); return new Column(javaObject); }; /** * Casts the column to a different data type. * @example * // Casts colA to IntegerType. * df.select(df("colA").cast(DataTpes.IntegerType)) * * // equivalent to * df.select(df.col("colA").cast("int")) * * @since EclairJS 0.1 Spark 1.3.0 * @param {DataType | string} to If string supported types are: `string`, `boolean`, `int`, * `float`, `double`, `date`, `timestamp`. * @returns {Column} */ Column.prototype.cast = function(to) { var javaObject = this.getJavaObject().cast(Utils.unwrapObject(to)); return new Column(javaObject); }; /** * Contains the other element. * * @since EclairJS 0.1 Spark 1.3.0 * @param {object} * @returns {Column} */ Column.prototype.contains = function(other) { var javaObject = this.getJavaObject().contains(other); return new Column(javaObject); } /** * Returns an ordering used in sorting. * @returns {Column} * @example * df.sort(df.col("age").desc()); */ Column.prototype.desc = function() { return new Column(this.getJavaObject().desc()); }; /** * Division this expression by another expression. * @example * people.select( people.col("height").divide(people.col("weight")) ); * * @since EclairJS 0.1 Spark 1.3.0 * @param {Column} other * @returns {Column} */ Column.prototype.divide = function(other) { var javaObject = this.getJavaObject().divide(Utils.unwrapObject(other)); return new Column(javaObject); } /** * String ends with. * with another string literal * @since EclairJS 0.1 Spark 1.3.0 * @param {string | Column} other, if string ends with another string literal. * @returns {Column} */ Column.prototype.endsWith = function(other) { var javaObject = this.getJavaObject().endsWith(Utils.unwrapObject(other)); return new Column(javaObject); } /** * Equality test that is safe for null values. * * @since EclairJS 0.1 Spark 1.3.0 * @param {object} other * @returns {Column} */ Column.prototype.eqNullSafe = function(other) { var javaObject = this.getJavaObject().eqNullSafe(Utils.unwrapObject(other)); return new Column(javaObject); } /** * Equality test * @param {object} * @returns {boolean} */ Column.prototype.equals = function(that) { return this.getJavaObject().equals(Utils.unwrapObject(that)); }; /** * Equality test * @param {object} * @returns {Column} */ Column.prototype.equalTo = function(obj) { return new Column(this.getJavaObject().equalTo(Utils.unwrapObject(obj))); }; /** * Prints the expression to the console for debugging purpose. * @parma {boolean} extended * @since EclairJS 0.1 Spark 1.3.0 */ Column.prototype.explain = function(extended) { var ex = extended ? true : false; this.getJavaObject().explain(extended); }; /** * Greater than or equal to an expression. * @example * people.select( people.col("age").geq(21) ) * @param {object} * @returns {Column} */ Column.prototype.geq = function(obj) { return new Column(this.getJavaObject().geq(Utils.unwrapObject(obj))); }; /** * An expression that gets a field by name in a {@link StructType}. * * @since EclairJS 0.1 Spark 1.3.0 * @param {string} fieldName * @returns {Column} */ Column.prototype.getField = function(fieldName) { var javaObject = this.getJavaObject().getField(fieldName); return new Column(javaObject); }; /** * An expression that gets an item at position `ordinal` out of an array, * or gets a value by key `key` in a {@link MapType}. * * @since EclairJS 0.1 Spark 1.3.0 * @param {object} key * @returns {Column} */ Column.prototype.getItem = function(key) { var javaObject = this.getJavaObject().getItem(Utils.unwrapObject(key)); return new Column(javaObject); }; /** * Greater than. * @example * people.select( people.col("age").gt(21) ); * @param {object} * @returns {Column} */ Column.prototype.gt = function(obj) { return new Column(this.getJavaObject().gt(Utils.unwrapObject(obj))); }; /** * @returns {integer} */ Column.prototype.hashCode = function() { return this.getJavaObject().hashCode(); }; /** * A boolean expression that is evaluated to true if the value of this expression is contained * by the evaluated values of the arguments. * @example * var col = peopleDataFrame.col("age"); * var testCol = col.in([20, 19]); * var results = peopleDataFrame.select(testCol); * * @since EclairJS 0.1 Spark 1.3.0 * @param {array} * @returns {Column} */ Column.prototype.in = function(list) { var javaObject = this.getJavaObject().in(list); return new Column(javaObject); }; /** * A boolean expression that is evaluated to true if the value of this expression is contained * by the evaluated values of the arguments. * * @since EclairJS 0.1 Spark 1.3.0 * @param {array} * @returns {Column} */ Column.prototype.isin = function(list) { var javaObject = this.getJavaObject().isin(list); return new Column(javaObject); }; /** * True if the current expression is NaN. * * @since EclairJS 0.1 Spark 1.5.0 * @returns {Column} */ Column.prototype.isNaN = function() { var javaObject = this.getJavaObject().isNaN(); return new Column(javaObject); }; /** * True if the current expression is null. * * @since EclairJS 0.1 Spark 1.3.0 * @returns {Column} */ Column.prototype.isNull = function() { var javaObject = this.getJavaObject().isNull(); return new Column(javaObject); }; /** * True if the current expression is NOT null. * * @since EclairJS 0.1 Spark 1.3.0 * @returns {Column} */ Column.prototype.isNotNull = function() { var javaObject = this.getJavaObject().isNotNull(); return new Column(javaObject); }; /** * Less than or equal to. * @example * people.select( people.col("age").leq(21) ); * * @since EclairJS 0.1 Spark 1.3.0 * @param {object} other * @returns {Column} */ Column.prototype.leq = function(other) { var javaObject = this.getJavaObject().leq(Utils.unwrapObject(other)); return new Column(javaObject); }; /** * SQL like expression. * * @since EclairJS 0.1 Spark 1.3.0 * @param {string} literal * @returns {Column} */ Column.prototype.like = function(literal) { var javaObject = this.getJavaObject().like(literal); return new Column(javaObject); }; /** * Less than. * @example * people.select( people.col("age").lt(21) ); * * @since EclairJS 0.1 Spark 1.3.0 * @param {object} other * @returns {Column} */ Column.prototype.lt = function(other) { var javaObject = this.getJavaObject().lt(Utils.unwrapObject(other)); return new Column(javaObject); }; /** * Subtraction. Subtract the other expression from this expression. * @example * people.select( people.col("height").minus(people.col("weight")) ); * * @since EclairJS 0.1 Spark 1.3.0 * @param {Column} other * @returns {Column} */ Column.prototype.minus = function(other) { var javaObject = this.getJavaObject().minus(Utils.unwrapObject(other)); return new Column(javaObject); }; /** * Modulo (a.k.a. remainder) expression. * * @since EclairJS 0.1 Spark 1.3.0 * @param {object} other * @returns {Column} */ Column.prototype.mod = function(other) { var javaObject = this.getJavaObject().mod(Utils.unwrapObject(other)); return new Column(javaObject); }; /** * Multiplication of this expression and another expression. * @example * people.select( people.col("height").multiply(people.col("weight")) ); * * @since EclairJS 0.1 Spark 1.3.0 * @param {Column} other * @returns {Column} */ Column.prototype.multiply = function(other) { var javaObject = this.getJavaObject().multiply(Utils.unwrapObject(other)); return new Column(javaObject); }; /** * Inequality test. * @example * df.filter( df.col("colA").notEqual(df.col("colB")) ); * * @since EclairJS 0.1 Spark 1.3.0 * @param {Column} other * @returns {Column} */ Column.prototype.notEqual = function(other) { var javaObject = this.getJavaObject().notEqual(Utils.unwrapObject(other)); return new Column(javaObject); }; /** * Boolean OR. * @example * people.filter( people.col("inSchool").or(people.col("isEmployed")) ); * * @since EclairJS 0.1 Spark 1.3.0 * @param {Column} other * @returns {Column} */ Column.prototype.or = function(other) { var other_uw = Utils.unwrapObject(other); var javaObject = this.getJavaObject().or(other_uw); return new Column(javaObject); }; /** * Evaluates a list of conditions and returns one of multiple possible result expressions. * If otherwise is not defined at the end, null is returned for unmatched conditions. * * @example * people.select(functions.when(people.col("gender").equalTo("male"), 0) * .when(people.col("gender").equalTo("female"), 1) * .otherwise(2)) * * @since EclairJS 0.1 Spark 1.4.0 * @param {object} value * @returns {Column} */ Column.prototype.otherwise = function(value) { var javaObject = this.getJavaObject().otherwise(value); return new Column(javaObject); }; /** * Evaluates a list of conditions and returns one of multiple possible result expressions. * If otherwise is not defined at the end, null is returned for unmatched conditions. * * @example * people.select(functions.when(people.col("gender").equalTo("male"), 0) * .when(people.col("gender").equalTo("female"), 1) * .otherwise(2)) * * @since EclairJS 0.1 Spark 1.4.0 * @returns {Column} */ Column.prototype.when = function(condition,value) { var condition_uw = Utils.unwrapObject(condition); var javaObject = this.getJavaObject().when(condition_uw,value); return new Column(javaObject); } </code></pre> </article> </section> </div> <nav> <h2><a href="index.html">Index</a></h2><h3>Classes</h3><ul><li><a href="Accumulable.html">Accumulable</a></li><li><a href="AccumulableParam.html">AccumulableParam</a></li><li><a href="Accumulator.html">Accumulator</a></li><li><a href="ALS.html">ALS</a></li><li><a href="ArrayType.html">ArrayType</a></li><li><a href="AssociationRules.html">AssociationRules</a></li><li><a href="BinaryType.html">BinaryType</a></li><li><a href="BisectingKMeans.html">BisectingKMeans</a></li><li><a href="BisectingKMeansModel.html">BisectingKMeansModel</a></li><li><a href="BooleanType.html">BooleanType</a></li><li><a href="CalendarIntervalType.html">CalendarIntervalType</a></li><li><a href="Column.html">Column</a></li><li><a href="DataFrame.html">DataFrame</a></li><li><a href="DataFrameNaFunctions.html">DataFrameNaFunctions</a></li><li><a href="DataFrameReader.html">DataFrameReader</a></li><li><a href="DataFrameStatFunctions.html">DataFrameStatFunctions</a></li><li><a href="DataFrameWriter.html">DataFrameWriter</a></li><li><a href="DataType.html">DataType</a></li><li><a href="DataTypes.html">DataTypes</a></li><li><a href="DateType.html">DateType</a></li><li><a href="DenseVector.html">DenseVector</a></li><li><a href="DoubleType.html">DoubleType</a></li><li><a href="DStream.html">DStream</a></li><li><a href="Duration.html">Duration</a></li><li><a href="FloatAccumulatorParam.html">FloatAccumulatorParam</a></li><li><a href="FloatType.html">FloatType</a></li><li><a href="FPGrowth.html">FPGrowth</a></li><li><a href="FPGrowthModel.html">FPGrowthModel</a></li><li><a href="FreqItemset.html">FreqItemset</a></li><li><a href="functions.html">functions</a></li><li><a href="FutureAction.html">FutureAction</a></li><li><a href="GroupedData.html">GroupedData</a></li><li><a href="HashPartitioner.html">HashPartitioner</a></li><li><a href="IntAccumulatorParam.html">IntAccumulatorParam</a></li><li><a href="IntegerType.html">IntegerType</a></li><li><a href="LabeledPoint.html">LabeledPoint</a></li><li><a href="LinearRegressionModel.html">LinearRegressionModel</a></li><li><a href="LinearRegressionWithSGD.html">LinearRegressionWithSGD</a></li><li><a href="List.html">List</a></li><li><a href="MapType.html">MapType</a></li><li><a href="MatrixFactorizationModel.html">MatrixFactorizationModel</a></li><li><a href="Metadata.html">Metadata</a></li><li><a href="MLWord2Vec.html">MLWord2Vec</a></li><li><a href="MLWord2VecModel.html">MLWord2VecModel</a></li><li><a href="NullType.html">NullType</a></li><li><a href="NumericType.html">NumericType</a></li><li><a href="PartialResult.html">PartialResult</a></li><li><a href="Partitioner.html">Partitioner</a></li><li><a href="RangePartitioner.html">RangePartitioner</a></li><li><a href="Rating.html">Rating</a></li><li><a href="RDD.html">RDD</a></li><li><a href="Row.html">Row</a></li><li><a href="RowFactory.html">RowFactory</a></li><li><a href="Rule.html">Rule</a></li><li><a href="SparkConf.html">SparkConf</a></li><li><a href="SparkContext.html">SparkContext</a></li><li><a href="SparkFiles.html">SparkFiles</a></li><li><a href="SparkStatusTracker.html">SparkStatusTracker</a></li><li><a href="SparseVector.html">SparseVector</a></li><li><a href="SQLContext.html">SQLContext</a></li><li><a href="SQLContext.QueryExecution.html">QueryExecution</a></li><li><a href="SQLContext.SparkPlanner.html">SparkPlanner</a></li><li><a href="SQLContext.SQLSession.html">SQLSession</a></li><li><a href="SqlDate.html">SqlDate</a></li><li><a href="SqlTimestamp.html">SqlTimestamp</a></li><li><a href="StorageLevel.html">StorageLevel</a></li><li><a href="StreamingContext.html">StreamingContext</a></li><li><a href="StringType.html">StringType</a></li><li><a href="StructField.html">StructField</a></li><li><a href="StructType.html">StructType</a></li><li><a href="Time.html">Time</a></li><li><a href="TimestampType.html">TimestampType</a></li><li><a href="Vectors.html">Vectors</a></li><li><a href="VectorUDT.html">VectorUDT</a></li><li><a href="Word2Vec.html">Word2Vec</a></li><li><a href="Word2VecModel.html">Word2VecModel</a></li></ul><h3>Global</h3><ul><li><a href="global.html#Vector">Vector</a></li></ul> </nav> <br clear="both"> <footer> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.2.3-dev</a> on Thu Feb 18 2016 17:00:52 GMT-0500 (EST) </footer> <script> prettyPrint(); </script> <script src="scripts/linenumber.js"> </script> </body> </html> <file_sep>/* * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var BinaryClassificationMetrics = function(rdd) { var javaRdd = rdd.getJavaObject(); this.classTag = javaRdd.classTag() var r = rdd.getJavaObject().rdd(); JavaWrapper.call(this, new org.apache.spark.mllib.evaluation.BinaryClassificationMetrics(r)); }; BinaryClassificationMetrics.prototype = Object.create(JavaWrapper.prototype); /** * Returns the (threshold, precision) curve. */ BinaryClassificationMetrics.prototype.precisionByThreshold = function() { var rdd = this.getJavaObject().precisionByThreshold(); return new RDD(org.apache.spark.api.java.JavaRDD.fromRDD(rdd, this.classTag)); }; /** * Returns the (threshold, recall) curve. */ BinaryClassificationMetrics.prototype.recallByThreshold = function() { var rdd = this.getJavaObject().recallByThreshold(); return new RDD(org.apache.spark.api.java.JavaRDD.fromRDD(rdd, this.classTag)); }; /** * Returns the (threshold, F-Measure) curve with beta = 1.0. */ BinaryClassificationMetrics.prototype.fMeasureByThreshold = function(t) { if(arguments.length == 0) { var rdd = this.getJavaObject().fMeasureByThreshold(); return new RDD(org.apache.spark.api.java.JavaRDD.fromRDD(rdd, this.classTag)); } else { var rdd = this.getJavaObject().fMeasureByThreshold(t); return new RDD(org.apache.spark.api.java.JavaRDD.fromRDD(rdd, this.classTag)); } }; /** * Returns the precision-recall curve, which is an RDD of (recall, precision), * NOT (precision, recall), with (0.0, 1.0) prepended to it. * @see http://en.wikipedia.org/wiki/Precision_and_recall */ BinaryClassificationMetrics.prototype.pr = function() { var rdd = this.getJavaObject().pr(); return new RDD(org.apache.spark.api.java.JavaRDD.fromRDD(rdd, this.classTag)); }; var RegressionMetrics = function(rdd) { var javaRdd = rdd.getJavaObject(); this.classTag = javaRdd.classTag() JavaWrapper.call(this, new org.apache.spark.mllib.evaluation.RegressionMetrics(javaRdd.rdd())); }; RegressionMetrics.prototype = Object.create(JavaWrapper.prototype); /** * Returns the mean squared error, which is a risk function corresponding to the * expected value of the squared error loss or quadratic loss. */ RegressionMetrics.prototype.meanSquaredError = function() { return this.getJavaObject().meanSquaredError(); }; /** * Returns the root mean squared error, which is defined as the square root of * the mean squared error. */ RegressionMetrics.prototype.rootMeanSquaredError = function() { return this.getJavaObject().rootMeanSquaredError(); }; /** * Returns R^2^, the unadjusted coefficient of determination. * @see [[http://en.wikipedia.org/wiki/Coefficient_of_determination]] * In case of regression through the origin, the definition of R^2^ is to be modified. * @see <NAME>, Regression through the Origin. Teaching Statistics 25, 76-80 (2003) * [[https://online.stat.psu.edu/~ajw13/stat501/SpecialTopics/Reg_thru_origin.pdf]] */ RegressionMetrics.prototype.r2 = function() { return this.getJavaObject().r2(); }; /** * Returns the mean absolute error, which is a risk function corresponding to the * expected value of the absolute error loss or l1-norm loss. */ RegressionMetrics.prototype.meanAbsoluteError = function() { return this.getJavaObject().meanAbsoluteError(); }; /** * Returns the variance explained by regression. * explainedVariance = \sum_i (\hat{y_i} - \bar{y})^2 / n * @see [[https://en.wikipedia.org/wiki/Fraction_of_variance_unexplained]] */ RegressionMetrics.prototype.explainedVariance = function() { return this.getJavaObject().explainedVariance(); }; <file_sep> /* * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Represents a numeric vector, whose index type is Int and value type is Double. * * Note: Users should not implement this interface. * @classdesc */ var Vector = function(jvmObject) { this.logger = Logger.getLogger("Vector_js"); JavaWrapper.call(this, jvmObject); }; Vector.prototype = Object.create(JavaWrapper.prototype); Vector.prototype.constructor = Vector; /** * @returns {??} */ Vector.prototype.$init$ = function() { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().$init$(); // return new ??(javaObject); }; /** * Size of the vector. * @returns {number} */ Vector.prototype.size = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().size(); }; /** * Converts the instance to a double array. * @returns {number[]} */ Vector.prototype.toArray = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().toArray(); }; /** * @param {object} other * @returns {boolean} */ Vector.prototype.equals = function(other) { throw "not implemented by ElairJS"; // var other_uw = Utils.unwrapObject(other); // return this.getJavaObject().equals(other_uw); }; /** * Returns a hash code value for the vector. The hash code is based on its size and its first 128 * nonzero entries, using a hash algorithm similar to {@link hashCode}. * @returns {number} */ Vector.prototype.hashCode = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().hashCode(); }; /** * Gets the value of the ith element. * @param {number} i index * @returns {number} */ Vector.prototype.apply = function(i) { throw "not implemented by ElairJS"; // return this.getJavaObject().apply(i); }; /** * Makes a deep copy of this vector. * @returns {Vector} */ Vector.prototype.copy = function() { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().copy(); // return Utils.javaToJs(javaObject); }; /** * Applies a function `f` to all the active elements of dense and sparse vector. * * @param {func} f the function takes two parameters where the first parameter is the index of * the vector with type `Int`, and the second parameter is the corresponding value * with type `Double`. */ Vector.prototype.foreachActive = function(f) { throw "not implemented by ElairJS"; // var sv = Utils.createJavaParams(f); // var fn = new org.eclairjs.nashorn.JSFunction2(sv.funcStr, sv.scopeVars); // this.getJavaObject().foreachActive(fn); }; /** * Number of active entries. An "active entry" is an element which is explicitly stored, * regardless of its value. Note that inactive entries have value 0. * @returns {number} */ Vector.prototype.numActives = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().numActives(); }; /** * Number of nonzero elements. This scans all active values and count nonzeros. * @returns {number} */ Vector.prototype.numNonzeros = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().numNonzeros(); }; /** * Converts this vector to a sparse vector with all explicit zeros removed. * @returns {SparseVector} */ Vector.prototype.toSparse = function() { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().toSparse(); // return new SparseVector(javaObject); }; /** * Converts this vector to a dense vector. * @returns {DenseVector} */ Vector.prototype.toDense = function() { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().toDense(); // return new DenseVector(javaObject); }; /** * Returns a vector in either dense or sparse format, whichever uses less storage. * @returns {Vector} */ Vector.prototype.compressed = function() { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().compressed(); // return Utils.javaToJs(javaObject); }; /** * Find the index of a maximal element. Returns the first maximal element in case of a tie. * Returns -1 if vector has length 0. * @returns {number} */ Vector.prototype.argmax = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().argmax(); }; /** * Converts the vector to a JSON string. * @returns {string} */ Vector.prototype.toJson = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().toJson(); }; /** * :: AlphaComponent :: * * User-defined type for {@link Vector} which allows easy interaction with SQL * via {@link DataFrame}. * @classdesc */ /** * @returns {??} * @class */ var VectorUDT = function(jvmObject) { this.logger = Logger.getLogger("VectorUDT_js"); JavaWrapper.call(this, jvmObject); }; VectorUDT.prototype = Object.create(JavaWrapper.prototype); VectorUDT.prototype.constructor = VectorUDT; /** * @returns {StructType} */ VectorUDT.prototype.sqlType = function() { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().sqlType(); // return new StructType(javaObject); }; /** * @param {object} obj * @returns {InternalRow} */ VectorUDT.prototype.serialize = function(obj) { throw "not implemented by ElairJS"; // var obj_uw = Utils.unwrapObject(obj); // return this.getJavaObject().serialize(obj_uw); }; /** * @param {object} datum * @returns {Vector} */ VectorUDT.prototype.deserialize = function(datum) { throw "not implemented by ElairJS"; // var datum_uw = Utils.unwrapObject(datum); // var javaObject = this.getJavaObject().deserialize(datum_uw); // return Utils.javaToJs(javaObject); }; /** * @returns {string} */ VectorUDT.prototype.pyUDT = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().pyUDT(); }; /** * @returns {Class} */ VectorUDT.prototype.userClass = function() { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().userClass(); // return new Class(javaObject); }; /** * @param {object} o * @returns {boolean} */ VectorUDT.prototype.equals = function(o) { throw "not implemented by ElairJS"; // var o_uw = Utils.unwrapObject(o); // return this.getJavaObject().equals(o_uw); }; /** * @returns {number} */ VectorUDT.prototype.hashCode = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().hashCode(); }; /** * @returns {string} */ VectorUDT.prototype.typeName = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().typeName(); }; /** * A dense vector represented by a value array. * @classdesc */ /** * @param {number[]} values * @returns {??} * @class */ var DenseVector = function(arg) { this.logger = Logger.getLogger("DenseVector_js"); var jvmObj; if (Array.isArray(arg)) { jvmObj = new org.apache.spark.mllib.linalg.DenseVector(arg); } else { jvmObj = arg; } Vector.call(this, jvmObj); }; DenseVector.prototype = Object.create(Vector.prototype); DenseVector.prototype.constructor = DenseVector; /** * @returns {number} */ DenseVector.prototype.size = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().size(); }; /** * @returns {string} */ DenseVector.prototype.toString = function() { return this.getJavaObject().toString(); }; /** * @returns {float[]} */ DenseVector.prototype.toArray = function() { return this.getJavaObject().toArray(); }; /** * @param {number} i * @returns {number} */ DenseVector.prototype.apply = function(i) { throw "not implemented by ElairJS"; // return this.getJavaObject().apply(i); }; /** * @returns {DenseVector} */ DenseVector.prototype.copy = function() { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().copy(); // return new DenseVector(javaObject); }; /** * @param {func} f */ DenseVector.prototype.foreachActive = function(f) { throw "not implemented by ElairJS"; // var sv = Utils.createJavaParams(f); // var fn = new org.eclairjs.nashorn.JSFunction2(sv.funcStr, sv.scopeVars); // this.getJavaObject().foreachActive(fn); }; /** * @returns {number} */ DenseVector.prototype.hashCode = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().hashCode(); }; /** * @returns {number} */ DenseVector.prototype.numActives = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().numActives(); }; /** * @returns {number} */ DenseVector.prototype.numNonzeros = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().numNonzeros(); }; /** * @returns {SparseVector} */ DenseVector.prototype.toSparse = function() { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().toSparse(); // return new SparseVector(javaObject); }; /** * @returns {number} */ DenseVector.prototype.argmax = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().argmax(); }; /** * @returns {string} */ DenseVector.prototype.toJson = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().toJson(); }; /** * A sparse vector represented by an index array and an value array. * * @param size size of the vector. * @param indices index array, assume to be strictly increasing. * @param values value array, must have the same length as the index array. * @classdesc */ /** * @param {number} size * @param {number[]} indices * @param {number[]} values * @returns {??} * @class */ var SparseVector = function(size,indices,values) { var jvmObject = new org.apache.spark.mllib.linalg.SparseVector(size,indices,values); this.logger = Logger.getLogger("SparseVector_js"); Vector.call(this, jvmObject); }; SparseVector.prototype = Object.create(Vector.prototype); SparseVector.prototype.constructor = SparseVector; /** * @returns {string} */ SparseVector.prototype.toString = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().toString(); }; /** * @returns {number[]} */ SparseVector.prototype.toArray = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().toArray(); }; /** * @returns {SparseVector} */ SparseVector.prototype.copy = function() { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().copy(); // return new SparseVector(javaObject); }; /** * @param {func} f */ SparseVector.prototype.foreachActive = function(f) { throw "not implemented by ElairJS"; // var sv = Utils.createJavaParams(f); // var fn = new org.eclairjs.nashorn.JSFunction2(sv.funcStr, sv.scopeVars); // this.getJavaObject().foreachActive(fn); }; /** * @returns {number} */ SparseVector.prototype.hashCode = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().hashCode(); }; /** * @returns {number} */ SparseVector.prototype.numActives = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().numActives(); }; /** * @returns {number} */ SparseVector.prototype.numNonzeros = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().numNonzeros(); }; /** * @returns {SparseVector} */ SparseVector.prototype.toSparse = function() { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().toSparse(); // return new SparseVector(javaObject); }; /** * @returns {number} */ SparseVector.prototype.argmax = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().argmax(); }; /** * @returns {string} */ SparseVector.prototype.toJson = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().toJson(); }; /** * * @constructor */ var Vectors = function() { //var jvmObject = new org.apache.spark.mllib.linalg.SparseVector(size,indices,values); this.logger = Logger.getLogger("Vectors_js"); //Vector.call(this, jvmObject); }; // // static methods // /** * Creates a dense vector from its values. * @param {number} firstValue * @param {...number} otherValues * @returns {Vector} */ Vectors.densewithOtherValues = function(firstValue,otherValues) { throw "not implemented by ElairJS"; // // TODO: handle repeated parm 'otherValues' // var javaObject = org.apache.spark.mllib.linalg.Vectors.dense(firstValue,otherValues); // return Utils.javaToJs(javaObject); }; /** * Creates a dense vector from a double array. * @param {float[]} values * @returns {Vector} */ Vectors.dense = function(values) { var javaObject = org.apache.spark.mllib.linalg.Vectors.dense(values); return Utils.javaToJs(javaObject); }; /** * Creates a sparse vector providing its index array and value array. * * @param {number} size vector size. * @param {number[]} indices index array, must be strictly increasing. * @param {number[]} values value array, must have the same length as indices. * @returns {Vector} */ Vectors.sparse0 = function(size,indices,values) { throw "not implemented by ElairJS"; // var javaObject = org.apache.spark.mllib.linalg.Vectors.sparse(size,indices,values); // return Utils.javaToJs(javaObject); }; /** * Creates a sparse vector using unordered (index, value) pairs. * * @param {number} size vector size. * @param {Tuple2[]} elements vector elements in (index, value) pairs. * @returns {Vector} */ Vectors.sparse1 = function(size,elements) { throw "not implemented by ElairJS"; // // TODO: handle Tuple conversion for 'elements' // var elements_uw = Utils.unwrapObject(elements); // var javaObject = org.apache.spark.mllib.linalg.Vectors.sparse(size,elements_uw); // return Utils.javaToJs(javaObject); }; /** * Creates a sparse vector using unordered (index, value) pairs in a Java friendly way. * * @param {number} size vector size. * @param {JavaIterable} elements vector elements in (index, value) pairs. * @returns {Vector} */ Vectors.sparse2 = function(size,elements) { throw "not implemented by ElairJS"; // // TODO: handle Tuple conversion for 'elements' // var elements_uw = Utils.unwrapObject(elements); // var javaObject = org.apache.spark.mllib.linalg.Vectors.sparse(size,elements_uw); // return Utils.javaToJs(javaObject); }; /** * Creates a vector of all zeros. * * @param {number} size vector size * @returns {Vector} a zero vector */ Vectors.zeros = function(size) { throw "not implemented by ElairJS"; // var javaObject = org.apache.spark.mllib.linalg.Vectors.zeros(size); // return Utils.javaToJs(javaObject); }; /** * Parses a string resulted from [[Vector.toString]] into a {@link Vector}. * @param {string} s * @returns {Vector} */ Vectors.parse = function(s) { throw "not implemented by ElairJS"; // var javaObject = org.apache.spark.mllib.linalg.Vectors.parse(s); // return Utils.javaToJs(javaObject); }; /** * Parses the JSON representation of a vector into a {@link Vector}. * @param {string} json * @returns {Vector} */ Vectors.fromJson = function(json) { throw "not implemented by ElairJS"; // var javaObject = org.apache.spark.mllib.linalg.Vectors.fromJson(json); // return Utils.javaToJs(javaObject); }; /** * Returns the p-norm of this vector. * @param {Vector} vector input vector. * @param {number} p norm. * @returns {number} norm in L^p^ space. */ Vectors.norm = function(vector,p) { throw "not implemented by ElairJS"; // var vector_uw = Utils.unwrapObject(vector); // return org.apache.spark.mllib.linalg.Vectors.norm(vector_uw,p); }; /** * Returns the squared distance between two Vectors. * @param {Vector} v1 first Vector. * @param {Vector} v2 second Vector. * @returns {number} squared distance between two Vectors. */ Vectors.sqdist = function(v1,v2) { throw "not implemented by ElairJS"; // var v1_uw = Utils.unwrapObject(v1); // var v2_uw = Utils.unwrapObject(v2); // return org.apache.spark.mllib.linalg.Vectors.sqdist(v1_uw,v2_uw); }; /** * @param {DenseVector} dv * @returns {Array} */ DenseVector.unapply = function(dv) { throw "not implemented by ElairJS"; // var dv_uw = Utils.unwrapObject(dv); // return org.apache.spark.mllib.linalg.DenseVector.unapply(dv_uw); }; /** * @param {SparseVector} sv * @returns {Tuple3} */ SparseVector.unapply = function(sv) { throw "not implemented by ElairJS"; // var sv_uw = Utils.unwrapObject(sv); // var javaObject = org.apache.spark.mllib.linalg.SparseVector.unapply(sv_uw); // return new Tuple3(javaObject); }; <file_sep>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @constructor * @classdec A set of methods for aggregations on a DataFrame, created by DataFrame.groupBy. */ var GroupedData = function(jvmGroupedData) { JavaWrapper.call(this, jvmGroupedData); // Initialize our Row-specific properties this.logger = Logger.getLogger("sql.GroupData_js"); } GroupedData.prototype = Object.create(JavaWrapper.prototype); //Set the "constructor" property to refer to GroupedData GroupedData.prototype.constructor = GroupedData; /** * Compute aggregates by specifying a series of aggregate columns. Note that this function by default retains the grouping columns in its output. * To not retain grouping columns, set spark.sql.retainGroupColumns to false. * The available aggregate methods are defined in {@link functions}. * @example * // Java: * df.groupBy("department").agg(max("age"), sum("expense")); * @since EclairJS 0.1 Spark 1.3.0 * @param {Column | string} columnExpr,...columnExpr or columnName, ...columnName * @returns {DataFrame} */ GroupedData.prototype.agg = function() { /* * First convert any strings to Columns */ var args = Utils.createJavaObjectArguments(arguments, Column); /* * Create a argument list we can send to Java */ var str = "this.getJavaObject().agg(" for (var i = 0; i < args.length; i++) { var spacer = i < 1 ? "" : ","; str += spacer + "args[" + i + "]"; } str += ");"; var javaObject = eval(str); return new DataFrame(javaObject); }; /** * Compute the avg value for each numeric columns for each group. * @param {string[]} cols * @returns {DataFrame} */ GroupedData.prototype.avg = function(cols) { return new DataFrame(this.getJavaObject().avg(cols)); }; GroupedData.prototype.apply = function(cols) { throw "not implemented by ElairJS"; }; /** * Count the number of rows for each group. * @returns {DataFrame} */ GroupedData.prototype.count = function() { var jdf = this.getJavaObject().count(); var df = new DataFrame(jdf); return df; }; /** * Compute the max value for each numeric columns for each group. * @param {string[]} cols * @returns {DataFrame} */ GroupedData.prototype.max = function(cols) { return new DataFrame(this.getJavaObject().max(cols)); }; /** * Compute the mean value for each numeric columns for each group. * @param {string[]} cols * @returns {DataFrame} */ GroupedData.prototype.mean = function(cols) { return new DataFrame(this.getJavaObject().mean(cols)); }; /** * Compute the min value for each numeric columns for each group. * @param {string[]} cols * @returns {DataFrame} */ GroupedData.prototype.min = function(cols) { return new DataFrame(this.getJavaObject().min(cols)); }; /** * Compute the sum value for each numeric columns for each group. * @param {string[]} cols * @returns {DataFrame} */ GroupedData.prototype.sum = function(cols) { return new DataFrame(this.getJavaObject().sum(cols)); }; <file_sep>/* * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Word2Vec creates vector representation of words in a text corpus. * The algorithm first constructs a vocabulary from the corpus * and then learns vector representation of words in the vocabulary. * The vector representation can be used as features in * natural language processing and machine learning algorithms. * * We used skip-gram model in our implementation and hierarchical softmax * method to train the model. The variable names in the implementation * matches the original C implementation. * * For original C implementation, see https://code.google.com/p/word2vec/ * For research papers, see * Efficient Estimation of Word Representations in Vector Space * and * Distributed Representations of Words and Phrases and their Compositionality. * @classdesc * @class */ var Word2Vec = function(jvmObject) { this.logger = Logger.getLogger("Word2Vec_js"); if (!jvmObject) { jvmObject = new org.apache.spark.mllib.feature.Word2Vec(); } JavaWrapper.call(this, jvmObject); }; Word2Vec.prototype = Object.create(JavaWrapper.prototype); Word2Vec.prototype.constructor = Word2Vec; /** * Sets vector size (default: 100). * @param {number} vectorSize * @returns {} */ Word2Vec.prototype.setVectorSize = function(vectorSize) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().setVectorSize(vectorSize); // return new (javaObject); }; /** * Sets initial learning rate (default: 0.025). * @param {number} learningRate * @returns {} */ Word2Vec.prototype.setLearningRate = function(learningRate) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().setLearningRate(learningRate); // return new (javaObject); }; /** * Sets number of partitions (default: 1). Use a small number for accuracy. * @param {number} numPartitions * @returns {} */ Word2Vec.prototype.setNumPartitions = function(numPartitions) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().setNumPartitions(numPartitions); // return new (javaObject); }; /** * Sets number of iterations (default: 1), which should be smaller than or equal to number of * partitions. * @param {number} numIterations * @returns {} */ Word2Vec.prototype.setNumIterations = function(numIterations) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().setNumIterations(numIterations); // return new (javaObject); }; /** * Sets random seed (default: a random long integer). * @param {number} seed * @returns {} */ Word2Vec.prototype.setSeed = function(seed) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().setSeed(seed); // return new (javaObject); }; /** * Sets the window of words (default: 5) * @param {number} window * @returns {} */ Word2Vec.prototype.setWindowSize = function(window) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().setWindowSize(window); // return new (javaObject); }; /** * Sets minCount, the minimum number of times a token must appear to be included in the word2vec * model's vocabulary (default: 5). * @param {number} minCount * @returns {} */ Word2Vec.prototype.setMinCount = function(minCount) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().setMinCount(minCount); // return new (javaObject); }; /** * Computes the vector representation of each word in vocabulary. * @param {RDD} dataset an RDD of words * @returns {Word2VecModel} a Word2VecModel */ Word2Vec.prototype.fit = function(dataset) { var dataset_uw = Utils.unwrapObject(dataset); var javaObject = this.getJavaObject().fit(dataset_uw); return new Word2VecModel(javaObject); }; /** * Word2Vec model * @param wordIndex maps each word to an index, which can retrieve the corresponding * vector from wordVectors * @param wordVectors array of length numWords * vectorSize, vector corresponding * to the word mapped with index i can be retrieved by the slice * (i * vectorSize, i * vectorSize + vectorSize) * @classdesc */ /** * @param {Map} model * @returns {??} * @class */ var Word2VecModel = function(jvmObject) { //var jvmObject = new org.apache.spark.mllib.feature.Word2VecModel(model); this.logger = Logger.getLogger("Word2VecModel_js"); JavaWrapper.call(this, jvmObject); }; Word2VecModel.prototype = Object.create(JavaWrapper.prototype); Word2VecModel.prototype.constructor = Word2VecModel; /** * @param {SparkContext} sc * @param {string} path */ Word2VecModel.prototype.save = function(sc,path) { throw "not implemented by ElairJS"; // var sc_uw = Utils.unwrapObject(sc); // this.getJavaObject().save(sc_uw,path); }; /** * Transforms a word to its vector representation * @param {string} word a word * @returns {Vector} vector representation of word */ Word2VecModel.prototype.transform = function(word) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().transform(word); // return Utils.javaToJs(javaObject); }; /** * Find synonyms of a word * @param {string} word a word * @param {number} num number of synonyms to find * @returns {Tuple2[]} array of (word, cosineSimilarity) */ Word2VecModel.prototype.findSynonyms = function(word,num) { var javaObject = this.getJavaObject().findSynonyms(word,num); return Utils.javaToJs(javaObject); }; /** * Find synonyms of the vector representation of a word * @param {Vector} vector vector representation of a word * @param {number} num number of synonyms to find * @returns {Tuple2[]} array of (word, cosineSimilarity) */ Word2VecModel.prototype.findSynonymswithnumber = function(vector,num) { throw "not implemented by ElairJS"; // var vector_uw = Utils.unwrapObject(vector); // var javaObject = this.getJavaObject().findSynonyms(vector_uw,num); // return Utils.javaToJs(javaObject); }; /** * Returns a map of words to their vector representations. * @returns {Map} */ Word2VecModel.prototype.getVectors = function() { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().getVectors(); // return new Map(javaObject); }; // // static methods // /** * @param {SparkContext} sc * @param {string} path * @returns {Word2VecModel} */ Word2VecModel.load = function(sc,path) { throw "not implemented by ElairJS"; // var sc_uw = Utils.unwrapObject(sc); // var javaObject = org.apache.spark.mllib.feature.Word2VecModel.load(sc_uw,path); // return new Word2VecModel(javaObject); }; <file_sep>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * We need to load SparkContext.js and SparkConf.js in order to create SparkContext * The SparkContext will load the rest of sparkJS files. So these are the oly two * the user has to explicitly load. */ var sparkContext = new SparkContext("local[*]", "mllib Unit test"); var LinearRegressionWithSGDTest = function(file) { var sc = sparkContext; var data = sc.textFile(file).cache(); var scopeVars = {}; var parsedData = data.map( function(s) { var parts = s.split(","); var features = parts[1].split(" "); return new LabeledPoint(parts[0], new DenseVector(features)); }); //var t = parsedData.take(5); //print("take 5 = " + JSON.stringify(parsedData.take(5))); var numIterations = 3; /* var */ linearRegressionModel = LinearRegressionWithSGD.train(parsedData, numIterations); // Due to JUNIT scoping these need to be global /* var */ delta = 17; // Due to JUNIT scoping these need to be global var valuesAndPreds = parsedData.mapToPair(function(lp, linearRegressionModel, delta) { var label = lp.getLabel(); var f = lp.getFeatures(); var prediction = linearRegressionModel.predict(f) + delta; return [prediction, label]; }, [linearRegressionModel, delta]); // end MapToPair //print("valuesAndPreds: " + valuesAndPreds.take(10).toString()); return valuesAndPreds.take(10).toString(); } var AssociationRulesTest = function() { load("examples/mllib/association_rules_example.js"); return run(sparkContext); } var BisectingKMeansExample = function() { load("examples/mllib/bisecting_k_means_example.js"); return JSON.stringify(run(sparkContext)); } <file_sep>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * We need to load SparkContext.js and SparkConf.js in order to create SparkContext * The SparkContext will load the rest of sparkJS files. So these are the oly two * the user has to explicitly load. */ var sparkConf = new SparkConf() .setAppName("Linear Regression Test") .setMaster("local[*]"); //.setMaster("spark://MacBook-Pro.local:7077"); var sc = new SparkContext(sparkConf); var data = sc.textFile("examples/data/lpsa.data").cache(); var scopeVars = {}; var parsedData = data.map( function(s) { var parts = s.split(","); var features = parts[1].split(" "); return new LabeledPoint(parts[0], new DenseVector(features)); }); var t = parsedData.take(5); print("take 5 = " + JSON.stringify(parsedData.take(5))); var numIterations = 3; var linearRegressionModel = LinearRegressionWithSGD.train(parsedData, numIterations); var delta = 17; var valuesAndPreds = parsedData.mapToPair(function(lp, linearRegressionModel, delta) { // FIXME var label = lp.getLabel(); var f = lp.getFeatures(); var prediction = linearRegressionModel.predict(f) + delta; return [prediction, label]; }, [linearRegressionModel, delta]); // end MapToPair print("valuesAndPreds: " + valuesAndPreds.take(10).toString()); <file_sep>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @constructor * @classdesc PartialResult */ var PartialResult = function(initialVal,isFinal) { var jvmObject = new org.apache.spark.partial.PartialResult(initialVal,isFinal); this.logger = Logger.getLogger("PartialResult_js"); JavaWrapper.call(this, jvmObject); }; PartialResult.prototype = Object.create(JavaWrapper.prototype); PartialResult.prototype.constructor = PartialResult; PartialResult.prototype.initialValue = function() { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().initialValue(); // return new object(javaObject); } PartialResult.prototype.isInitialValueFinal = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().isInitialValueFinal(); } /** * Blocking method to wait for and return the final value. * @returns {object} */ PartialResult.prototype.getFinalValue = function() { //throw "not implemented by ElairJS"; var javaObject = this.getJavaObject().getFinalValue(); return new object(javaObject); } /** * Set a handler to be called when this PartialResult completes. Only one completion handler * is supported per PartialResult. * @returns {PartialResult} */ PartialResult.prototype.onComplete = function(handler, bindArgs) { //throw "not implemented by ElairJS"; var fn = Utils.createLambdaFunction(handler, org.eclairjs.nashorn.JSFunction, bindArgs); var javaObject = this.getJavaObject().onComplete(fn); return new PartialResult(javaObject); } /** * Set a handler to be called if this PartialResult's job fails. Only one failure handler * is supported per PartialResult. */ PartialResult.prototype.onFail = function(handler, bindArgs) { throw "not implemented by ElairJS"; // var fn = Utils.createLambdaFunction(handler, org.eclairjs.nashorn.JSFunction, bindArgs); // this.getJavaObject().onFail(fn); } /** * Transform this PartialResult into a PartialResult of type T. * @returns {PartialResult} */ PartialResult.prototype.map = function(func, bindArgs) { throw "not implemented by ElairJS"; // var fn = Utils.createLambdaFunction(func, org.eclairjs.nashorn.JSFunction, bindArgs); // var javaObject = this.getJavaObject().map(fn); // return new PartialResult(javaObject); } PartialResult.prototype.toString = function() { throw "not implemented by ElairJS"; return this.getJavaObject().toString(); } <file_sep>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Construct a LinearRegression object with default parameters: {stepSize: 1.0, numIterations: 100, miniBatchFraction: 1.0}. * @constructor * @classdesc Train a linear regression model with no regularization using Stochastic Gradient Descent. * This solves the least squares regression formulation f(weights) = 1/n ||A weights-y||^2^ (which is the mean squared error). * Here the data matrix has n rows, and the input RDD holds the set of rows of A, each with its corresponding right hand side label y. * See also the documentation for the precise formulation. */ var LinearRegressionWithSGD = {} LinearRegressionWithSGD.DEFAULT_NUM_ITERATIONS = 100; /** * Train a LinearRegression model given an RDD of (label, features) pairs. * @param {RDD} rdd of LabeledPoints * @param {integer} numIterations * @returns {LinearRegressionModel} */ LinearRegressionWithSGD.train = function(rdd, numIterations) { var logger = Logger.getLogger("LinearRegressionWithSGD_js"); logger.debug("JavaRDD " + rdd); var jo = rdd.getJavaObject(); logger.debug("jo = " + jo); var lrdd = org.apache.spark.api.java.JavaRDD.toRDD(jo); logger.debug("calling train"); var model = org.apache.spark.mllib.regression.LinearRegressionWithSGD.train(lrdd, numIterations); logger.debug("return model"); return new LinearRegressionModel(model); }; <file_sep>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @constructor * @classdec Represents a Discretized Stream (DStream), the basic abstraction in Spark Streaming, * is a continuous sequence of RDDs (of the same type) representing a continuous stream of data. * @param {object} jDStream */ var DStream = function(jDStream, streamingContext) { var jvmObj = jDStream; this.streamingContext = streamingContext; this.logger = Logger.getLogger("streaming.dtream.DStream_js"); JavaWrapper.call(this, jvmObj); }; DStream.prototype = Object.create(JavaWrapper.prototype); DStream.prototype.constructor = DStream; /** * Persist RDDs of this DStream with the default storage level (MEMORY_ONLY_SER) * @returns {DStream} */ DStream.prototype.cache = function() { return new DStream(this.getJavaObject().cache(), this.streamingContext); }; /** * Generate an RDD for the given duration * @param {Time} validTime * @returns {RDD} */ DStream.prototype.compute = function(validTime) { return new DStream(this.getJavaObject().compute(validTime.getJavaObject()), this.streamingContext); }; /** * Return a new DStream containing only the elements that satisfy a predicate. * @param {function} func * @param {Object[]} bindArgs - Optional array whose values will be added to func's argument list. * @returns {DStream} */ DStream.prototype.filter = function(func, bindArgs) { var fn = Utils.createLambdaFunction(func, org.eclairjs.nashorn.JSFunction, bindArgs); return new DStream(this.getJavaObject().filter(fn), this.streamingContext); }; /** * Persist RDDs of this DStream with the storage level * @param {StorageLevel} Optional (MEMORY_ONLY_SER) by default * @return {DStream} */ DStream.prototype.persist = function() { if(arguments.length == 1) { return new DStream( this.getJavaObject().persist(arguments[0].getJavaObject()), this.streamingContext); } else { return new DStream(this.getJavaObject().perist(), this.streamingContext); } }; /** * Return a new DStream with an increased or decreased level of parallelism. * @param {int} numPartitions * @returns {DStream} */ DStream.prototype.repartition = function(numPartitions) { return new DStream(this.getJavaObject().repartition(numPartitions), this.streamingContext); }; /** * Return a new DStream by unifying data of another DStream with this DStream. * @param {DStream} that * @returns {DStream} */ DStream.prototype.union = function(that) { return new DStream(this.getJavaObject().union(Utils.unwrapObject(that)), this.streamingContext); } /** * Return a new DStream in which each RDD contains all the elements in seen in a sliding window of time over this DStream. * The new DStream generates RDDs with the same interval as this DStream. * @param duration - width of the window; must be a multiple of this DStream's interval. * @param slideInterval - Optional * @returns {DStream} */ DStream.prototype.window = function(duration) { if(arguments.length == 1) { return new DStream(this.getJavaObject().window( Utils.unwrapObject(arguments[0])), this.streamingContext); } else { return new DStream(this.getJavaObject().window( Utils.unwrapObject(arguments[0]), Utils.unwrapObject(arguments[1])), this.streamingContext); } }; /** * Enable periodic checkpointing of RDDs of this DStream. * @param {Duration} interval * @return {DStream} */ DStream.prototype.checkpoint = function(interval) { return new DStream(this.getJavaObject().checkpoint(interval.getJavaObject()), this.streamingContext); }; /** * Return the StreamingContext associated with this DStream * @returns {StreamingContext} */ DStream.prototype.context = function() { return this.streamingContext; }; /** * Return a new DStream in which each RDD has a single element generated by * counting each RDD of this DStream. * @returns {DStream} */ DStream.prototype.count = function() { return new DStream(this.getJavaObject().count(), this.streamingContext); }; /** * Return a new DStream in which each RDD contains the counts of each distinct * value in each RDD of this DStream. Hash partitioning is used to generate the * RDDs with Spark's default number of partitions if numPartions is not * specified. * @param {int} numPartitions * @returns {DStream} */ DStream.prototype.countByValue = function() { if(arguments.length > 0) { return new DStream(this.getJavaObject().countByValue(arguments[0]), this.stremaingContext); } else { return new DStream(this.getJavaObject().countByValue(), this.streamingContext); } }; /** * Return a new DStream in which each RDD contains the count of distinct * elements in RDDs in a sliding window over this DStream. Hash partitioning is * used to generate the RDDs with Spark's default number of partitions if * numPartitions is not specified. * @param {Duration} windowDuration * @param {Duration} slideDuration * @param {int} numPartitions * @returns {DStream} */ DStream.prototype.countByValueAndWindow = function() { if(arguments.length == 2) { return new DStream( this.getJavaObject().countByValueAndWindow( arguments[0].getJavaObject(), arguments[1].getJavaObject() ), this.streamingContext ) } else { return new DStream( this.getJavaObject().countByValueAndWindow( arguments[0].getJavaObject(), arguments[1].getJavaObject(), arguments[2] ), this.streamingContext ) } }; /** * Return a new DStream in which each RDD has a single element generated by * counting the number of elements in a window over this DStream. windowDuration * and slideDuration are as defined in the window() operation. This is * equivalent to window(windowDuration, slideDuration).count() * @param {Duration} windowDuration * @param {Duration} slideDuration * @returns {DStream} */ DStream.prototype.countByWindow = function(windowDuration, slideDuration) { return new DStream( this.getJavaObject().countByWindow( windowDuration.getJavaObject(), slideDuration.getJavaObject() ), this.streamingContext) }; /** * Return a new DStream by first applying a function to all elements of this * DStream, and then flattening the results. * @param func * @param {Object[]} bindArgs - Optional array whose values will be added to func's argument list. * @returns {DStream} */ DStream.prototype.flatMap = function(func, bindArgs) { var fn = Utils.createLambdaFunction(func, org.eclairjs.nashorn.JSFlatMapFunction, bindArgs); return new DStream(this.getJavaObject().flatMap(fn), this.streamingContext); }; /** * Return a new DStream by applying a function to all elements of this DStream, * and then flattening the results * @param func * @param {Object[]} bindArgs - Optional array whose values will be added to func's argument list. * @returns {DStream} */ DStream.prototype.flatMapToPair = function(func, bindArgs) { var fn = Utils.createLambdaFunction(func, org.eclairjs.nashorn.JSPairFlatMapFunction, bindArgs); return new DStream(this.getJavaObject().flatMapToPair(fn), this.streamingContext); }; /** * Return a new DStream in which each RDD is generated by applying glom() to * each RDD of this DStream. Applying glom() to an RDD coalesces all elements * within each partition into an array. */ DStream.prototype.glom = function() { return new DStream(this.getJavaObject().glom(), this.streamingContext); } /** * Return a new DStream by applying a function to all elements of this DStream. * @param func * @param {Object[]} bindArgs - Optional array whose values will be added to func's argument list. * @returns {DStream} */ DStream.prototype.map = function(func, bindArgs) { var fn = Utils.createLambdaFunction(func, org.eclairjs.nashorn.JSFunction, bindArgs); return new DStream(this.getJavaObject().map(fn), this.streamingContext); }; /** * Return a new DStream by applying a function to all elements of this DStream. * @param func * @param {Object[]} bindArgs - Optional array whose values will be added to func's argument list. * @returns {DStream} */ DStream.prototype.mapToPair = function(func, bindArgs) { var fn = Utils.createLambdaFunction(func, org.eclairjs.nashorn.JSPairFunction, bindArgs); return new DStream(this.getJavaObject().mapToPair(fn), this.streamingContext); }; /** * Return a new DStream in which each RDD is generated by applying * mapPartitions() to each RDDs of this DStream. Applying mapPartitions() to an * RDD applies a function to each partition of the RDD. * @param func * @param {Object[]} bindArgs - Optional array whose values will be added to func's argument list. * @returns {DStream} */ DStream.prototype.mapPartitions = function(func, bindArgs) { var fn = Utils.createLambdaFunction(func, org.eclairjs.nashorn.JSFlatMapFunction, bindArgs); return new DStream(this.getJavaObject().mapPartitions(fn), this.streamingContext); }; /** * Apply a function to each RDD in this DStream. This is an output operator, so 'this' DStream will be registered as an output * stream and therefore materialized. * @param func * @param {Object[]} bindArgs - Optional array whose values will be added to func's argument list. * @returns {void} */ DStream.prototype.foreachRDD = function(func, bindArgs) { var fn = Utils.createLambdaFunction(func, org.eclairjs.nashorn.JSFunction, bindArgs); this.getJavaObject().foreachRDD(fn); }; /** * Print the first ten elements of each RDD generated in this DStream. This is an output operator, so this DStream will be * registered as an output stream and there materialized. * @returns {void} */ DStream.prototype.print = function() { this.getJavaObject().print(); }; <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JSDoc: Source: HashPartitioner.js</title> <script src="scripts/prettify/prettify.js"> </script> <script src="scripts/prettify/lang-css.js"> </script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <div id="main"> <h1 class="page-title">Source: HashPartitioner.js</h1> <section> <article> <pre class="prettyprint source"><code>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @constructor * A {@link Partitioner} that implements hash-based partitioning using * Java's `Object.hashCode`. * * Java arrays have hashCodes that are based on the arrays' identities rather than their contents, * so attempting to partition an RDD[Array[_]] or RDD[(Array[_], _)] using a HashPartitioner will * produce an unexpected or incorrect result. * @classdesc * */ var HashPartitioner = function(partitions) { var jvmObject = new org.apache.spark.HashPartitioner(partitions); this.logger = Logger.getLogger("HashPartitioner_js"); JavaWrapper.call(this, jvmObject); }; HashPartitioner.prototype = Object.create(JavaWrapper.prototype); HashPartitioner.prototype.constructor = HashPartitioner; HashPartitioner.prototype.numPartitions = function() { return this.getJavaObject().numPartitions(); } HashPartitioner.prototype.getPartition = function(key) { return this.getJavaObject().getPartition(key); } HashPartitioner.prototype.equals = function(other) { var other_uw = Utils.unwrapObject(other); return this.getJavaObject().equals(other_uw); } HashPartitioner.prototype.hashCode = function() { return this.getJavaObject().hashCode(); } </code></pre> </article> </section> </div> <nav> <h2><a href="index.html">Index</a></h2><h3>Classes</h3><ul><li><a href="result..html">A {@link Partitioner} that implements hash-based partitioning using Java's `Object.hashCode`. Java arrays have hashCodes that are based on the arrays' identities rather than their contents, so attempting to partition an RDD[Array[_]] or RDD[(Array[_], _)] using a HashPartitioner will produce an unexpected or incorrect result.</a></li><li><a href="Accumulator.html">Accumulator</a></li><li><a href="ArrayType.html">ArrayType</a></li><li><a href="BinaryType.html">BinaryType</a></li><li><a href="BooleanType.html">BooleanType</a></li><li><a href="ByteType.html">ByteType</a></li><li><a href="CalendarIntervalType.html">CalendarIntervalType</a></li><li><a href="Column.html">Column</a></li><li><a href="DataFrame.html">DataFrame</a></li><li><a href="DataFrameNaFunctions.html">DataFrameNaFunctions</a></li><li><a href="DataFrameReader.html">DataFrameReader</a></li><li><a href="DataFrameStatFunctions.html">DataFrameStatFunctions</a></li><li><a href="DataFrameWriter.html">DataFrameWriter</a></li><li><a href="DataType.html">DataType</a></li><li><a href="DataTypes.html">DataTypes</a></li><li><a href="DateType.html">DateType</a></li><li><a href="DecimalType.html">DecimalType</a></li><li><a href="DenseVector.html">DenseVector</a></li><li><a href="DoubleType.html">DoubleType</a></li><li><a href="DStream.html">DStream</a></li><li><a href="Duration.html">Duration</a></li><li><a href="FloatType.html">FloatType</a></li><li><a href="functions.html">functions</a></li><li><a href="GroupedData.html">GroupedData</a></li><li><a href="IntegerType.html">IntegerType</a></li><li><a href="LabeledPoint.html">LabeledPoint</a></li><li><a href="LinearRegressionModel.html">LinearRegressionModel</a></li><li><a href="LinearRegressionWithSGD.html">LinearRegressionWithSGD</a></li><li><a href="LongType.html">LongType</a></li><li><a href="MapType.html">MapType</a></li><li><a href="Metadata.html">Metadata</a></li><li><a href="NullType.html">NullType</a></li><li><a href="NumericType.html">NumericType</a></li><li><a href="PartialResult.html">PartialResult</a></li><li><a href="Partitioner.html">Partitioner</a></li><li><a href="RangePartitioner.html">RangePartitioner</a></li><li><a href="RDD.html">RDD</a></li><li><a href="Row.html">Row</a></li><li><a href="RowFactory.html">RowFactory</a></li><li><a href="ShortType.html">ShortType</a></li><li><a href="SparkConf.html">SparkConf</a></li><li><a href="SparkContext.html">SparkContext</a></li><li><a href="SparkFiles.html">SparkFiles</a></li><li><a href="SQLContext.html">SQLContext</a></li><li><a href="SQLContext.QueryExecution.html">QueryExecution</a></li><li><a href="SQLContext.SparkPlanner.html">SparkPlanner</a></li><li><a href="SQLContext.SQLSession.html">SQLSession</a></li><li><a href="SqlDate.html">SqlDate</a></li><li><a href="SqlTimestamp.html">SqlTimestamp</a></li><li><a href="StorageLevel.html">StorageLevel</a></li><li><a href="StreamingContext.html">StreamingContext</a></li><li><a href="StringType.html">StringType</a></li><li><a href="StructField.html">StructField</a></li><li><a href="StructType.html">StructType</a></li><li><a href="Time.html">Time</a></li><li><a href="TimestampType.html">TimestampType</a></li><li><a href="Vector.html">Vector</a></li></ul> </nav> <br clear="both"> <footer> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.2.3-dev</a> on Tue Jan 19 2016 17:58:48 GMT-0500 (EST) </footer> <script> prettyPrint(); </script> <script src="scripts/linenumber.js"> </script> </body> </html> <file_sep>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var Utils = {}; Utils.logger = Logger.getLogger("Utils_js"); /** * This function needs to parse the arguments that are being passed to the LAMDA function * and get references to the arguments that will need to be added to the closer of the Nashorn * engine when the LAMDA function runs on the worker. A standard spark LAMDA would look like: * function(sparkArg){...}, but we need any variables declared outside the closer of the LAMDA * to be passed into the LAMDA so we can add them to the args when we call the LAMDA function from * a new Nashorn engine context. Are LAMDA function must include the out of closer variables ex. * function(sparkArg, scopeArg1, scopeArg2, .....) * @param {function} func LAMDA function that will be passed to spark. The functions * will have the format function(sparkArg, scopeArg1, scopeArg2, .....) * @param {sparkArgumentsPassed} the number of arguments passed to the LAMDA by spark defaults to 1 * * @return {Object} { * funcStr: stringified funciton that was passed in, * scopeVars: Array of references to the out of closer args * } */ Utils.createJavaParams = function(func, sparkArgumentsPassed) { Utils.logger.debug("createJavaParams func: " + func + " sparkArgumentsPassed: " + sparkArgumentsPassed); var scopeVarsStartingPosion = sparkArgumentsPassed ? sparkArgumentsPassed : 1; var parmas = {}; parmas.scopeVars = null; /* * First we stringify the function */ parmas.funcStr = func.toString(); /* * Start parsing the arguments passed to the function */ var start = parmas.funcStr.indexOf("("); var stop = parmas.funcStr.indexOf(")"); var agrsStr = parmas.funcStr.substring(start +1, stop); var args = agrsStr.split(","); // get all the arguments names parmas.scopeVars = []; for (var i = scopeVarsStartingPosion; i < args.length; i++) { // unwrapObjects or we can have serialization problems Utils.logger.debug("scopeVar = " + args[i]); var a = eval(args[i]); Utils.logger.debug("got a ref to = " + a); parmas.scopeVars.push(Utils.unwrapObject(eval(args[i]))); // eval the argument name to get a reference to the variable } return parmas; }; Utils.javaToJs = function(javaObj) { if (Array.isArray(javaObj) || javaObj.getClass().isArray() ) { var ret = []; for (var i=0;i<javaObj.length;i++) { ret.push(org.eclairjs.nashorn.Utils.javaToJs(javaObj[i], org.eclairjs.nashorn.NashornEngineSingleton.getEngine())); } return ret; } else return org.eclairjs.nashorn.Utils.javaToJs(javaObj,org.eclairjs.nashorn.NashornEngineSingleton.getEngine()); }; Utils.unwrapObject = function(obj) { if (Array.isArray(obj)) { var unObj = []; for (var i=0;i<obj.length;i++) { unObj.push(Utils.unwrapObject(obj[i])); } return unObj; } else return (obj && obj.getJavaObject) ? obj.getJavaObject() : obj; }; Utils.unwrapTuple = function(obj) { Utils.logger.debug("unwrapTuple = " + obj); if (Array.isArray(obj) && obj.length>1) { var Tuple2 = Java.type('scala.Tuple2'); return new Tuple2(Utils.unwrapObject(obj[0]),Utils.unwrapObject(obj[1])); } else throw "Expecting tuple, i.e. [1,2] "; }; /** * Creates a argument list of Spark Java objects that can be passed to a Spark Java method. * If the objects passed in the argument list are an instanceof "type" then the object will be * unwrapped else will will create an instanceof "type" for that object. * If the object * for example: * // Spark Java * GoupedData.agg(Column expr, Column... exprs) * @private * @param {object | string} object,...object * @param {function} type this is the constructor of the desired object type for example Column * @returns {object[]} array of Java spark objects */ Utils.createJavaObjectArguments = function(args, type) { /* * First convert any strings to Objects of type */ var a = Array.prototype.slice.call(args); for (var i = 0; i < a.length; i++) { var o = a[i]; if (!(o instanceof type)) { o = new type(o); } a[i] = Utils.unwrapObject(o); } return a; }; /** * Creates a Java HashMap from a JavaScript object. * @private * @param {object} obj hashMap * @returns {HashMap} java.util.HashMap */ Utils.createJavaHashMap = function(obj, javaMapObj) { var map = javaMapObj ? javaMapObj : new java.util.HashMap(); for(var colName in obj){ if (typeof obj[colName] === 'number') { map.put(new java.lang.Double(colName), new java.lang.Double(obj[colName])); } else { map.put(colName, obj[colName]); } } return map; }; function convertJavaTuple2(o1, o2) { return [o1 ,o2]; }; function convertJavaJSONObject(str) { return JSON.parse(str); }; function createJavaWrapperObject(className, obj) { return eval("new " + className + "(obj)"); }; Utils.createLambdaFunction = function(func, clazz, bindArgs) { return new clazz(func.toString(), bindArgs ? Utils.unwrapObject(bindArgs) : []) };<file_sep>/* * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Model representing the result of matrix factorization. * * Note: If you create the model directly using constructor, please be aware that fast prediction * requires cached user/product features and their associated partitioners. * * @param rank Rank for the features in this model. * @param userFeatures RDD of tuples where each tuple represents the userId and * the features computed for this user. * @param productFeatures RDD of tuples where each tuple represents the productId * and the features computed for this product. * @classdesc */ /** * @param {number} rank * @param {RDD} userFeatures * @param {RDD} productFeatures * @class */ var MatrixFactorizationModel = function() { this.logger = Logger.getLogger("MatrixFactorizationModel_js"); var jvmObject = arguments[0]; if (arguments.length > 1) { var userFeatures = Utils.unwrapObject(arguments[1]); var productFeatures = Utils.unwrapObject(arguments[2]); jvmObject = new org.apache.spark.mllib.recommendation.MatrixFactorizationModel(arguments[0],userFeatures,productFeatures); } JavaWrapper.call(this, jvmObject); }; MatrixFactorizationModel.prototype = Object.create(JavaWrapper.prototype); MatrixFactorizationModel.prototype.constructor = MatrixFactorizationModel; /** * @param {number} user * @param {number} product * @returns {number} */ MatrixFactorizationModel.prototype.predict0 = function(user,product) { throw "not implemented by ElairJS"; // return this.getJavaObject().predict(user,product); }; /** * Predict the rating of many users for many products. * The output RDD has an element per each element in the input RDD (including all duplicates) * unless a user or product is missing in the training set. * * @param {RDD} usersProducts RDD of (user, product) pairs. * @returns {RDD} RDD of Ratings. */ MatrixFactorizationModel.prototype.predict1 = function(usersProducts) { throw "not implemented by ElairJS"; // // TODO: handle Tuple conversion for 'usersProducts' // var usersProducts_uw = Utils.unwrapObject(usersProducts); // var javaObject = this.getJavaObject().predict(usersProducts_uw); // return new RDD(javaObject); }; /** * Java-friendly version of {@link predict}. * @param {JavaPairRDD} usersProducts * @returns {JavaRDD} */ MatrixFactorizationModel.prototype.predict2 = function(usersProducts) { throw "not implemented by ElairJS"; // var usersProducts_uw = Utils.unwrapObject(usersProducts); // var javaObject = this.getJavaObject().predict(usersProducts_uw); // return new JavaRDD(javaObject); }; /** * Recommends products to a user. * * @param {number} user the user to recommend products to * @param {number} num how many products to return. The number returned may be less than this. * "score" in the rating field. Each represents one recommended product, and they are sorted * by score, decreasing. The first returned is the one predicted to be most strongly * recommended to the user. The score is an opaque value that indicates how strongly * recommended the product is. * @returns {Rating[]} [[Rating]] objects, each of which contains the given user ID, a product ID, and a */ MatrixFactorizationModel.prototype.recommendProducts = function(user,num) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().recommendProducts(user,num); // return Utils.javaToJs(javaObject); }; /** * Recommends users to a product. That is, this returns users who are most likely to be * interested in a product. * * @param {number} product the product to recommend users to * @param {number} num how many users to return. The number returned may be less than this. * "score" in the rating field. Each represents one recommended user, and they are sorted * by score, decreasing. The first returned is the one predicted to be most strongly * recommended to the product. The score is an opaque value that indicates how strongly * recommended the user is. * @returns {Rating[]} [[Rating]] objects, each of which contains a user ID, the given product ID, and a */ MatrixFactorizationModel.prototype.recommendUsers = function(product,num) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().recommendUsers(product,num); // return Utils.javaToJs(javaObject); }; /** * Save this model to the given path. * * This saves: * - human-readable (JSON) model metadata to path/metadata/ * - Parquet formatted data to path/data/ * * The model may be loaded using {@link load}. * * @param {SparkContext} sc Spark context used to save model data. * @param {string} path Path specifying the directory in which to save this model. * If the directory already exists, this method throws an exception. */ MatrixFactorizationModel.prototype.save = function(sc,path) { throw "not implemented by ElairJS"; // var sc_uw = Utils.unwrapObject(sc); // this.getJavaObject().save(sc_uw,path); }; /** * Recommends topK products for all users. * * @param {number} num how many products to return for every user. * rating objects which contains the same userId, recommended productID and a "score" in the * rating field. Semantics of score is same as recommendProducts API * @returns {RDD} [(Int, Array[Rating])] objects, where every tuple contains a userID and an array of */ MatrixFactorizationModel.prototype.recommendProductsForUsers = function(num) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().recommendProductsForUsers(num); // return new RDD(javaObject); }; /** * Recommends topK users for all products. * * @param {number} num how many users to return for every product. * of rating objects which contains the recommended userId, same productID and a "score" in the * rating field. Semantics of score is same as recommendUsers API * @returns {RDD} [(Int, Array[Rating])] objects, where every tuple contains a productID and an array */ MatrixFactorizationModel.prototype.recommendUsersForProducts = function(num) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().recommendUsersForProducts(num); // return new RDD(javaObject); }; /** * * @returns {RDD} */ MatrixFactorizationModel.prototype.userFeatures = function() { var javaObject = this.getJavaObject().userFeatures(); return new RDD(javaObject.toJavaRDD()); }; /** * * @returns {RDD} */ MatrixFactorizationModel.prototype.productFeatures = function() { var javaObject = this.getJavaObject().productFeatures(); return new RDD(javaObject.toJavaRDD()); }; // // static methods // /** * Load a model from the given path. * * The model should have been saved by {@link save}. * * @param {SparkContext} sc Spark context used for loading model files. * @param {string} path Path specifying the directory to which the model was saved. * @returns {MatrixFactorizationModel} Model instance */ MatrixFactorizationModel.load = function(sc,path) { throw "not implemented by ElairJS"; // var sc_uw = Utils.unwrapObject(sc); // var javaObject = org.apache.spark.mllib.recommendation.MatrixFactorizationModel.load(sc_uw,path); // return new MatrixFactorizationModel(javaObject); }; <file_sep>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @constructor * @classdesc An object that defines how the elements in a key-value pair RDD are partitioned by key. * Maps each key to a partition ID, from 0 to `numPartitions - 1`. */ var Partitioner = function(jvmObject) { throw "con't do 'new' on abstract class 'Partitioner'" // this.logger = Logger.getLogger("Partitioner_js"); // JavaWrapper.call(this, jvmObject); }; Partitioner.prototype = Object.create(JavaWrapper.prototype); Partitioner.prototype.constructor = Partitioner; Partitioner.prototype.numPartitions = function() { throw "not implemented by ElairJS"; // return this.getJavaObject().numPartitions(); } Partitioner.prototype.getPartition = function(key) { throw "not implemented by ElairJS"; // return this.getJavaObject().getPartition(key); } /** * @constructor * @classdesc A {@link Partitioner} that implements hash-based partitioning using * Java's `Object.hashCode`. * * Java arrays have hashCodes that are based on the arrays' identities rather than their contents, * so attempting to partition an RDD[Array[_]] or RDD[(Array[_], _)] using a HashPartitioner will * produce an unexpected or incorrect result. * */ var HashPartitioner = function(partitions) { var jvmObject = new org.apache.spark.HashPartitioner(partitions); this.logger = Logger.getLogger("HashPartitioner_js"); JavaWrapper.call(this, jvmObject); }; HashPartitioner.prototype = Object.create(JavaWrapper.prototype); HashPartitioner.prototype.constructor = HashPartitioner; HashPartitioner.prototype.numPartitions = function() { return this.getJavaObject().numPartitions(); } HashPartitioner.prototype.getPartition = function(key) { return this.getJavaObject().getPartition(key); } HashPartitioner.prototype.equals = function(other) { var other_uw = Utils.unwrapObject(other); return this.getJavaObject().equals(other_uw); } HashPartitioner.prototype.hashCode = function() { return this.getJavaObject().hashCode(); } /** * @constructor * @classdesc A {@link Partitioner} that partitions sortable records by range into roughly * equal ranges. The ranges are determined by sampling the content of the RDD passed in. * * Note that the actual number of partitions created by the RangePartitioner might not be the same * as the `partitions` parameter, in the case where the number of sampled records is less than * the value of `partitions`. * */ var RangePartitioner = function(partitions,rdd,ascending) { var jvmObject = new org.apache.spark.RangePartitioner(partitions,rdd,ascending); this.logger = Logger.getLogger("RangePartitioner_js"); JavaWrapper.call(this, jvmObject); }; RangePartitioner.prototype = Object.create(JavaWrapper.prototype); RangePartitioner.prototype.constructor = RangePartitioner; RangePartitioner.prototype.numPartitions = function() { return this.getJavaObject().numPartitions(); } RangePartitioner.prototype.getPartition = function(key) { return this.getJavaObject().getPartition(key); } RangePartitioner.prototype.equals = function(other) { var other_uw = Utils.unwrapObject(other); return this.getJavaObject().equals(other_uw); } RangePartitioner.prototype.hashCode = function() { return this.getJavaObject().hashCode(); } // // static methods // /** * Choose a partitioner to use for a cogroup-like operation between a number of RDDs. * * If any of the RDDs already has a partitioner, choose that one. * * Otherwise, we use a default HashPartitioner. For the number of partitions, if * spark.default.parallelism is set, then we'll use the value from SparkContext * defaultParallelism, otherwise we'll use the max number of upstream partitions. * * Unless spark.default.parallelism is set, the number of partitions will be the * same as the number of partitions in the largest upstream RDD, as this should * be least likely to cause out-of-memory errors. * * We use two method parameters (rdd, others) to enforce callers passing at least 1 RDD. * @returns {Partitioner} */ Partitioner.defaultPartitioner = function(rdd,others) { var rdd_uw = Utils.unwrapObject(rdd); var others_uw = Utils.unwrapObject(others); var javaObject = org.apache.spark.HashPartitioner.defaultPartitioner(rdd_uw,others_uw); return Utils.javaToJs(javaObject); } <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JSDoc: Source: mllib/feature/Word2Vec.js</title> <script src="scripts/prettify/prettify.js"> </script> <script src="scripts/prettify/lang-css.js"> </script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <div id="main"> <h1 class="page-title">Source: mllib/feature/Word2Vec.js</h1> <section> <article> <pre class="prettyprint source"><code>/* * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Word2Vec creates vector representation of words in a text corpus. * The algorithm first constructs a vocabulary from the corpus * and then learns vector representation of words in the vocabulary. * The vector representation can be used as features in * natural language processing and machine learning algorithms. * * We used skip-gram model in our implementation and hierarchical softmax * method to train the model. The variable names in the implementation * matches the original C implementation. * * For original C implementation, see https://code.google.com/p/word2vec/ * For research papers, see * Efficient Estimation of Word Representations in Vector Space * and * Distributed Representations of Words and Phrases and their Compositionality. * @classdesc * @class */ var Word2Vec = function(jvmObject) { this.logger = Logger.getLogger("Word2Vec_js"); if (!jvmObject) { jvmObject = new org.apache.spark.mllib.feature.Word2Vec(); } JavaWrapper.call(this, jvmObject); }; Word2Vec.prototype = Object.create(JavaWrapper.prototype); Word2Vec.prototype.constructor = Word2Vec; /** * Sets vector size (default: 100). * @param {number} vectorSize * @returns {} */ Word2Vec.prototype.setVectorSize = function(vectorSize) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().setVectorSize(vectorSize); // return new (javaObject); }; /** * Sets initial learning rate (default: 0.025). * @param {number} learningRate * @returns {} */ Word2Vec.prototype.setLearningRate = function(learningRate) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().setLearningRate(learningRate); // return new (javaObject); }; /** * Sets number of partitions (default: 1). Use a small number for accuracy. * @param {number} numPartitions * @returns {} */ Word2Vec.prototype.setNumPartitions = function(numPartitions) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().setNumPartitions(numPartitions); // return new (javaObject); }; /** * Sets number of iterations (default: 1), which should be smaller than or equal to number of * partitions. * @param {number} numIterations * @returns {} */ Word2Vec.prototype.setNumIterations = function(numIterations) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().setNumIterations(numIterations); // return new (javaObject); }; /** * Sets random seed (default: a random long integer). * @param {number} seed * @returns {} */ Word2Vec.prototype.setSeed = function(seed) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().setSeed(seed); // return new (javaObject); }; /** * Sets the window of words (default: 5) * @param {number} window * @returns {} */ Word2Vec.prototype.setWindowSize = function(window) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().setWindowSize(window); // return new (javaObject); }; /** * Sets minCount, the minimum number of times a token must appear to be included in the word2vec * model's vocabulary (default: 5). * @param {number} minCount * @returns {} */ Word2Vec.prototype.setMinCount = function(minCount) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().setMinCount(minCount); // return new (javaObject); }; /** * Computes the vector representation of each word in vocabulary. * @param {RDD} dataset an RDD of words * @returns {Word2VecModel} a Word2VecModel */ Word2Vec.prototype.fit = function(dataset) { var dataset_uw = Utils.unwrapObject(dataset); var javaObject = this.getJavaObject().fit(dataset_uw); return new Word2VecModel(javaObject); }; /** * Word2Vec model * @param wordIndex maps each word to an index, which can retrieve the corresponding * vector from wordVectors * @param wordVectors array of length numWords * vectorSize, vector corresponding * to the word mapped with index i can be retrieved by the slice * (i * vectorSize, i * vectorSize + vectorSize) * @classdesc */ /** * @param {Map} model * @returns {??} * @class */ var Word2VecModel = function(jvmObject) { //var jvmObject = new org.apache.spark.mllib.feature.Word2VecModel(model); this.logger = Logger.getLogger("Word2VecModel_js"); JavaWrapper.call(this, jvmObject); }; Word2VecModel.prototype = Object.create(JavaWrapper.prototype); Word2VecModel.prototype.constructor = Word2VecModel; /** * @param {SparkContext} sc * @param {string} path */ Word2VecModel.prototype.save = function(sc,path) { throw "not implemented by ElairJS"; // var sc_uw = Utils.unwrapObject(sc); // this.getJavaObject().save(sc_uw,path); }; /** * Transforms a word to its vector representation * @param {string} word a word * @returns {Vector} vector representation of word */ Word2VecModel.prototype.transform = function(word) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().transform(word); // return Utils.javaToJs(javaObject); }; /** * Find synonyms of a word * @param {string} word a word * @param {number} num number of synonyms to find * @returns {Tuple2[]} array of (word, cosineSimilarity) */ Word2VecModel.prototype.findSynonyms = function(word,num) { var javaObject = this.getJavaObject().findSynonyms(word,num); return Utils.javaToJs(javaObject); }; /** * Find synonyms of the vector representation of a word * @param {Vector} vector vector representation of a word * @param {number} num number of synonyms to find * @returns {Tuple2[]} array of (word, cosineSimilarity) */ Word2VecModel.prototype.findSynonymswithnumber = function(vector,num) { throw "not implemented by ElairJS"; // var vector_uw = Utils.unwrapObject(vector); // var javaObject = this.getJavaObject().findSynonyms(vector_uw,num); // return Utils.javaToJs(javaObject); }; /** * Returns a map of words to their vector representations. * @returns {Map} */ Word2VecModel.prototype.getVectors = function() { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().getVectors(); // return new Map(javaObject); }; // // static methods // /** * @param {SparkContext} sc * @param {string} path * @returns {Word2VecModel} */ Word2VecModel.load = function(sc,path) { throw "not implemented by ElairJS"; // var sc_uw = Utils.unwrapObject(sc); // var javaObject = org.apache.spark.mllib.feature.Word2VecModel.load(sc_uw,path); // return new Word2VecModel(javaObject); }; </code></pre> </article> </section> </div> <nav> <h2><a href="index.html">Index</a></h2><h3>Classes</h3><ul><li><a href="Accumulable.html">Accumulable</a></li><li><a href="AccumulableParam.html">AccumulableParam</a></li><li><a href="Accumulator.html">Accumulator</a></li><li><a href="ALS.html">ALS</a></li><li><a href="ArrayType.html">ArrayType</a></li><li><a href="AssociationRules.html">AssociationRules</a></li><li><a href="BinaryType.html">BinaryType</a></li><li><a href="BisectingKMeans.html">BisectingKMeans</a></li><li><a href="BisectingKMeansModel.html">BisectingKMeansModel</a></li><li><a href="BooleanType.html">BooleanType</a></li><li><a href="CalendarIntervalType.html">CalendarIntervalType</a></li><li><a href="Column.html">Column</a></li><li><a href="DataFrame.html">DataFrame</a></li><li><a href="DataFrameNaFunctions.html">DataFrameNaFunctions</a></li><li><a href="DataFrameReader.html">DataFrameReader</a></li><li><a href="DataFrameStatFunctions.html">DataFrameStatFunctions</a></li><li><a href="DataFrameWriter.html">DataFrameWriter</a></li><li><a href="DataType.html">DataType</a></li><li><a href="DataTypes.html">DataTypes</a></li><li><a href="DateType.html">DateType</a></li><li><a href="DenseVector.html">DenseVector</a></li><li><a href="DoubleType.html">DoubleType</a></li><li><a href="DStream.html">DStream</a></li><li><a href="Duration.html">Duration</a></li><li><a href="FloatAccumulatorParam.html">FloatAccumulatorParam</a></li><li><a href="FloatType.html">FloatType</a></li><li><a href="FPGrowth.html">FPGrowth</a></li><li><a href="FPGrowthModel.html">FPGrowthModel</a></li><li><a href="FreqItemset.html">FreqItemset</a></li><li><a href="functions.html">functions</a></li><li><a href="FutureAction.html">FutureAction</a></li><li><a href="GroupedData.html">GroupedData</a></li><li><a href="HashPartitioner.html">HashPartitioner</a></li><li><a href="IntAccumulatorParam.html">IntAccumulatorParam</a></li><li><a href="IntegerType.html">IntegerType</a></li><li><a href="LabeledPoint.html">LabeledPoint</a></li><li><a href="LinearRegressionModel.html">LinearRegressionModel</a></li><li><a href="LinearRegressionWithSGD.html">LinearRegressionWithSGD</a></li><li><a href="List.html">List</a></li><li><a href="MapType.html">MapType</a></li><li><a href="MatrixFactorizationModel.html">MatrixFactorizationModel</a></li><li><a href="Metadata.html">Metadata</a></li><li><a href="MLWord2Vec.html">MLWord2Vec</a></li><li><a href="MLWord2VecModel.html">MLWord2VecModel</a></li><li><a href="NullType.html">NullType</a></li><li><a href="NumericType.html">NumericType</a></li><li><a href="PartialResult.html">PartialResult</a></li><li><a href="Partitioner.html">Partitioner</a></li><li><a href="RangePartitioner.html">RangePartitioner</a></li><li><a href="Rating.html">Rating</a></li><li><a href="RDD.html">RDD</a></li><li><a href="Row.html">Row</a></li><li><a href="RowFactory.html">RowFactory</a></li><li><a href="Rule.html">Rule</a></li><li><a href="SparkConf.html">SparkConf</a></li><li><a href="SparkContext.html">SparkContext</a></li><li><a href="SparkFiles.html">SparkFiles</a></li><li><a href="SparkStatusTracker.html">SparkStatusTracker</a></li><li><a href="SparseVector.html">SparseVector</a></li><li><a href="SQLContext.html">SQLContext</a></li><li><a href="SQLContext.QueryExecution.html">QueryExecution</a></li><li><a href="SQLContext.SparkPlanner.html">SparkPlanner</a></li><li><a href="SQLContext.SQLSession.html">SQLSession</a></li><li><a href="SqlDate.html">SqlDate</a></li><li><a href="SqlTimestamp.html">SqlTimestamp</a></li><li><a href="StorageLevel.html">StorageLevel</a></li><li><a href="StreamingContext.html">StreamingContext</a></li><li><a href="StringType.html">StringType</a></li><li><a href="StructField.html">StructField</a></li><li><a href="StructType.html">StructType</a></li><li><a href="Time.html">Time</a></li><li><a href="TimestampType.html">TimestampType</a></li><li><a href="Vectors.html">Vectors</a></li><li><a href="VectorUDT.html">VectorUDT</a></li><li><a href="Word2Vec.html">Word2Vec</a></li><li><a href="Word2VecModel.html">Word2VecModel</a></li></ul><h3>Global</h3><ul><li><a href="global.html#Vector">Vector</a></li></ul> </nav> <br clear="both"> <footer> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.2.3-dev</a> on Thu Feb 18 2016 17:00:52 GMT-0500 (EST) </footer> <script> prettyPrint(); </script> <script src="scripts/linenumber.js"> </script> </body> </html> <file_sep>/* * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var LogisticRegressionModel = function(jvmObj) { JavaWrapper.call(this, jvmObj); }; LogisticRegressionModel.prototype = Object.create(JavaWrapper.prototype); LogisticRegressionModel.prototype.constructor = LogisticRegressionModel; LogisticRegressionModel.prototype.clearThreshold = function() { this.getJavaObject().clearThreshold(); }; LogisticRegressionModel.prototype.predict = function(testData) { var p = this.getJavaObject().predict(Utils.unwrapObject(testData)); return p; } var LogisticRegressionWithLBFGS = function(jvmObj) { if(jvmObj == undefined) { jvmObj = new org.apache.spark.mllib.classification.LogisticRegressionWithLBFGS(); } JavaWrapper.call(this, jvmObj); }; LogisticRegressionWithLBFGS.prototype = Object.create(JavaWrapper.prototype); LogisticRegressionWithLBFGS.prototype.setNumClasses = function(n) { return new LogisticRegressionWithLBFGS( this.getJavaObject().setNumClasses(n)); }; LogisticRegressionWithLBFGS.prototype.run = function(input, initialWeights) { if(initialWeights == undefined) { return new LogisticRegressionModel( this.getJavaObject().run(input.getJavaObject().rdd())); } else { return new LogisticRegressionModel( this.getJavaObject().run(input.getJavaObject().rdd(), initialWeights.getJavaObject())); } }; <file_sep>/* * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var exampleApacheLogs = [ "10.10.10.10 - \"FRED\" [18/Jan/2013:17:56:07 +1100] \"GET http://images.com/2013/Generic.jpg " + "HTTP/1.1\" 304 315 \"http://referall.com/\" \"Mozilla/4.0 (compatible; MSIE 7.0; " + "Windows NT 5.1; GTB7.4; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; " + ".NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR " + "3.5.30729; Release=ARP)\" \"UD-1\" - \"image/jpeg\" \"whatever\" 0.350 \"-\" - \"\" 265 923 934 \"\" " + "192.168.3.11 images.com 1358492167 - Whatup", "10.10.10.10 - \"FRED\" [18/Jan/2013:18:02:37 +1100] \"GET http://images.com/2013/Generic.jpg " + "HTTP/1.1\" 304 306 \"http:/referall.com\" \"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; " + "GTB7.4; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR " + "3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR " + "3.5.30729; Release=ARP)\" \"UD-1\" - \"image/jpeg\" \"whatever\" 0.352 \"-\" - \"\" 256 977 988 \"\" " + "0 172.16.31.10 images.com 1358492557 - Whatup"]; var apacheLogRegex = /^([\d.]+) (\S+) (\S+) \[([\w\d:/]+\s[+\-]\d{4})\] "(.+?)" (\d{3}) ([\d\-]+) "([^"]+)" "([^"]+)"/; function extractStats(line) { var match = line.match(apacheLogRegex); if (match) { var bytes = 0+match[7]; return { count:1, bytes:bytes}; } else { return { count:1, bytes:0}; } } function extractKey(line) { var match = line.match(apacheLogRegex); if (match) { var ip = match[1]; var user = match[3]; var query = match[5]; if (user !='"-"') { return { ip:ip, user:user, query:query}; } } return {ip:null, user:null, query:null}; } var conf = new SparkConf().setAppName("JavaScript Log Query").setMaster("local[*]"); var sparkContext = new SparkContext(conf); var dataSet = (arguments.length == 1) ? sparkContext.textFile(arguments[0]) : sparkContext.parallelize(exampleApacheLogs); var extracted = dataSet.mapToPair(function(line){ return [extractKey(line),extractStats(line)]; }); var counts = extracted.reduceByKey(function(stats1,stats2){ return {count:stats1.count+stats2.count,bytes:stats1.bytes+stats2.bytes}; }); var output = counts.collect(); for (var i=0;i<output.length;i++) print("user="+JSON.stringify(output[i][0])+"\tbytes="+output[i][1].bytes+"\tn="+output[i][1].count); sparkContext.stop(); <file_sep>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.eclairjs.nashorn; import org.junit.Test; import static org.junit.Assert.*; import javax.script.Invocable; import javax.script.ScriptEngine; public class MlLibTest { @Test public void LinearRegressionTest() throws Exception { ScriptEngine engine = TestUtils.getEngine(); String file = TestUtils.resourceToFile("/data/mllib/lpsa.data"); TestUtils.evalJSResource(engine, "/mllib/mllibtest.js"); Object ret = ((Invocable)engine).invokeFunction("LinearRegressionWithSGDTest", file); String expected = "34.802055592544406,-0.4307829,32.26369105545771,-0.1625189,27.073768640300933,-0.1625189,32.956369807610656,-0.1625189,26.589176152816094,0.3715636,34.161678328568854,0.7654678,24.3647041765334,0.8544153,26.661937949806784,1.2669476,28.790597957841044,1.2669476,20.51350661135643,1.2669476"; assertEquals("failure - strings are not equal", expected, ret.toString()); } /* tests SparkContext.parallelize([FreqItemset]) FreqItemset() AssociationRules() AssociationRules.setMinConfidence() AssociationRules.run() Rule.antecedent() Rule.consequent() Rule.confidence() RDD.collect() */ @Test public void AssociationRulesTest() throws Exception { ScriptEngine engine = TestUtils.getEngine(); //String file = TestUtils.resourceToFile("/data/mllib/lpsa.data"); TestUtils.evalJSResource(engine, "/mllib/mllibtest.js"); Object ret = ((Invocable)engine).invokeFunction("AssociationRulesTest"); String expected = "[a] => [b], 0.8"; assertEquals("failure - strings are not equal", expected, ret.toString()); } @Test public void BisectingKMeansExample() throws Exception { ScriptEngine engine = TestUtils.getEngine(); //String file = TestUtils.resourceToFile("/data/mllib/lpsa.data"); TestUtils.evalJSResource(engine, "/mllib/mllibtest.js"); Object ret = ((Invocable)engine).invokeFunction("BisectingKMeansExample"); String expected = "{\"Compute_Cost\":0.07999999999994545," + "\"Cluster_Center_0\":\"[0.2]\",\"Cluster_Center_1\":\"[10.2]\"," + "\"Cluster_Center_2\":\"[20.200000000000003]\",\"Cluster_Center_3\":\"[30.200000000000003]\"}"; assertEquals("failure - strings are not equal", expected, ret.toString()); } } <file_sep>/* * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Computes the PageRank of URLs from an input file. Input file should * be in format of: * URL neighbor URL * URL neighbor URL * URL neighbor URL * ... * where URL and their neighbors are separated by space(s). * * This is an example implementation for learning how to use Spark. For more conventional use, * please refer to org.apache.spark.graphx.lib.PageRank * @class */ var conf = new SparkConf().setAppName("JavaScript Page Rank").setMaster("local[*]"); var sparkContext = new SparkContext(conf); var filename=(arguments.length > 0) ? arguments[1] : "examples/data/pagerank_data.txt"; var iters = (arguments.length > 1) ? 0+arguments[1] : 10; // Loads in input file. It should be in format of: // URL neighbor URL // URL neighbor URL // URL neighbor URL // ... var lines = sparkContext.textFile(filename, 1); // Loads all URLs from input file and initialize their neighbors. var links = lines.mapToPair(function(s) { var parts = s.split(/\s+/); return [parts[0], parts[1]]; }).distinct().groupByKey().cache(); // Loads all URLs with other URL(s) link to from input file and initialize ranks of them to one. var ranks = links.mapValues(function() { return 1.0; }); // Calculates and updates URL ranks continuously using PageRank algorithm. for (var current = 0; current < iters; current++) { // Calculates URL contributions to the rank of other URLs. var contribs = links.join(ranks).values() .flatMapToPair(function(tuple) { var urlCount = tuple[0].length; var results = []; for (var n=0;n<urlCount;n++) { results.push([tuple[0][n], tuple[1] / urlCount]); } return results; }); // Re-calculates URL ranks based on neighbor contributions. ranks = contribs.reduceByKey(function(a,b){return a+b;}). mapValues(function(sum) { return 0.15 + sum * 0.85; }); } // Collects all URL ranks and dump them to console. var output = ranks.collect(); for (var i=0;i<output.length;i++) { print(output[i][0] + " has rank: " + output[i][1] + "."); } sparkContext.stop(); <file_sep>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var conf = new SparkConf().setAppName("JavaScript streaming").setMaster("local[*]"); var sparkContext = new SparkContext(conf); var streamingContext = new StreamingContext(sparkContext, new Duration(2000)); //var dstream = streamingContext.socketTextStream("localhost", 9999); print("KafkaUtils"); print(KafkaUtils); print(KafkaUtils.createStream); var dstream = KafkaUtils .createStream(streamingContext, "192.168.127.12:2181", "floyd", "airline") //.window(new Duration(1000 * 60 * 15)) .flatMap(function(chunk) { return chunk[1].split('\n'); }) .map(function(line) { var lineArr = line.split(","); var str = JSON.stringify({ "origin": lineArr[16], "carrier": lineArr[8], "flight_num": lineArr[9], "destination": lineArr[17], "take_off_delay_mins": parseInt(lineArr[15]) }) return str; }) var sqlContext = new org.apache.spark.sql.hive.HiveContext(sparkContext.getJavaObject().sc()); sqlContext.sql("CREATE TABLE IF NOT EXISTS airline (origin STRING, carrier STRING, flight_num STRING, destination STRING, take_off_delay_mins INT)") dstream.foreachRDD(function(rdd) { var df = sqlContext.read().json(rdd) var writer = df.write().mode(org.apache.spark.sql.SaveMode.Append) //df.show() writer.saveAsTable("airline"); //print(rdd.collect()); }); streamingContext.start(); streamingContext.awaitTermination(); <file_sep><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.ibm</groupId> <artifactId>eclairjs-nashorn</artifactId> <version>0.1</version> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <executions> <execution> <phase>compile</phase> <goals> <goal>compile</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.4.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <filters> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> </filters> <artifactSet> <excludes> <exclude>classworlds:classworlds</exclude> <exclude>junit:junit</exclude> <exclude>jmock:*</exclude> <exclude>*:xml-apis</exclude> <exclude>org.scala-lang:*</exclude> <exclude>org.apache.maven:lib:tests</exclude> <exclude>log4j:log4j:jar:</exclude> <exclude>org.eclipse.jetty:*</exclude> </excludes> </artifactSet> </configuration> </execution> </executions> </plugin> </plugins> <pluginManagement> <plugins> <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.--> <plugin> <groupId>org.eclipse.m2e</groupId> <artifactId>lifecycle-mapping</artifactId> <version>1.0.0</version> <configuration> <lifecycleMappingMetadata> <pluginExecutions> <pluginExecution> <pluginExecutionFilter> <groupId> com.phasebash.jsdoc </groupId> <artifactId> jsdoc3-maven-plugin </artifactId> <versionRange> [1.1.0,) </versionRange> <goals> <goal>jsdoc3</goal> </goals> </pluginExecutionFilter> <action> <ignore></ignore> </action> </pluginExecution> </pluginExecutions> </lifecycleMappingMetadata> </configuration> </plugin> </plugins> </pluginManagement> </build> <properties> <spark.version>1.6.0</spark.version> </properties> <dependencies> <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-library</artifactId> <version>2.10.2</version> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-core_2.10</artifactId> <version>${spark.version}</version> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-sql_2.10</artifactId> <version>${spark.version}</version> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-catalyst_2.10</artifactId> <version>${spark.version}</version> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-hive_2.10</artifactId> <version>${spark.version}</version> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-streaming_2.10</artifactId> <version>${spark.version}</version> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-mllib_2.10</artifactId> <version>${spark.version}</version> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-streaming-kafka_2.10</artifactId> <version>${spark.version}</version> </dependency> <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> <scope>test</scope> </dependency> </dependencies> <profiles> <profile> <id>notebook</id> <dependencies> <dependency> <groupId>org.apache.toree</groupId> <artifactId>toree-kernel-api_2.10</artifactId> <version>0.0.0-dev-SNAPSHOT</version> <scope>provided</scope> <exclusions> <exclusion> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>net.alchim31.maven</groupId> <artifactId>scala-maven-plugin</artifactId> <executions> <execution> <id>scala-compile-first</id> <phase>process-resources</phase> <goals> <goal>add-source</goal> <goal>compile</goal> </goals> </execution> <execution> <id>scala-test-compile</id> <phase>process-test-resources</phase> <goals> <goal>testCompile</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>docs</id> <build> <plugins> <plugin> <groupId>com.phasebash.jsdoc</groupId> <artifactId>jsdoc3-maven-plugin</artifactId> <version>1.1.0</version> <executions> <execution> <phase>compile</phase> <goals> <goal>jsdoc3</goal> </goals> </execution> </executions> <configuration> <recursive>true</recursive> <directoryRoots> <directoryRoot>src/main/resources</directoryRoot> </directoryRoots> <outputDirectory>docs/jsdoc</outputDirectory> </configuration> </plugin> </plugins> </build> </profile> </profiles> </project> <file_sep>/* * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function showWarning() { var warning = "WARN: This is a naive implementation of Logistic Regression " + "and is given as an example!\n" + "Please use either org.apache.spark.mllib.classification.LogisticRegressionWithSGD " + "or org.apache.spark.mllib.classification.LogisticRegressionWithLBFGS " + "for more conventional use."; print(warning); } function printWeights( a) { print(a); } function dot( a, b) { var x = 0; for (var i = 0; i < D; i++) { x += a[i] * b[i]; } return x; } showWarning(); var D = 10; // Number of dimensions var file=(arguments.length>0) ? arguments[0] : "./examples/data/lr_data.txt"; var ITERATIONS = (arguments.length > 1) ? 0+arguments[1] : 10; var conf = new SparkConf().setAppName("JavaScript Logistic Regression ").setMaster("local[*]"); var sc = new SparkContext(conf); var lines = sc.textFile(file); var points = lines.map(function(line){ var tok = line.split(/\s+/); var y = tok[0]; var x = []; for (var i = 0; i < D; i++) { x[i] = tok[i + 1]; } return {x:x,y:y} ; }).cache(); // Initialize w to a random value var weights= []; for (var i = 0; i < D; i++) { weights[i] = 2 * Math.random() - 1; } print("Initial w: "); printWeights(weights); for (var i = 1; i <= ITERATIONS; i++) { print("On iteration " + i); var gradient = points.map( function (datapoint){ var gradient = []; for (var i = 0; i < D; i++) { var d = dot(weights, datapoint.x); gradient[i] = (1 / (1 + Math.exp(-datapoint.y * d)) - 1) * datapoint.y * datapoint.x[i]; } return gradient; }).reduce(function(a,b){ var result = []; for (var j = 0; j < D; j++) { result[j] = a[j] + b[j]; } return result; }); for (var j = 0; j < D; j++) { weights[j] -= gradient[j]; } } print("Final w: "); printWeights(weights); sc.stop(); <file_sep>/* * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var conf = new SparkConf().setAppName("JavaScript Spark Pi").setMaster("local[*]"); var sparkContext = new SparkContext(conf); /** * Computes an approximation to pi */ var slices = 10; var n = 100000 * slices; var l = []; for (var i = 0; i < n; i++) { l.push(i); } var dataSet = sparkContext.parallelize(l, slices); var count = dataSet.map(function(i) { var x = Math.random() * 2 - 1; var y = Math.random() * 2 - 1; return (x * x + y * y < 1) ? 1 : 0; }).reduce(function(int1,int2) { return int1 + int2; }); print("Pi is roughly " + (4.0 * count / n)); sparkContext.stop(); <file_sep>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var JavaStreamingContext = Java.type('org.apache.spark.streaming.api.java.JavaStreamingContext'); /** * @constructor * @classdesc Main entry point for Spark Streaming functionality. It provides methods used to create DStreams from various input sources. * It can be either created by providing a Spark master URL and an appName, or from a org.apache.spark.SparkConf configuration * (see core Spark documentation), or from an existing org.apache.spark.SparkContext. The associated SparkContext can be accessed * using context.sparkContext. After creating and transforming DStreams, the streaming computation can be started and stopped using * context.start() and context.stop(), respectively. context.awaitTermination() allows the current thread to wait for the termination * of the context by stop() or by an exception. * @param {SparkContex} sparkContext * @param {Duration} duration */ var StreamingContext = function(sparkContext, duration) { var jvmObj = new JavaStreamingContext(Utils.unwrapObject(sparkContext), Utils.unwrapObject(duration) ); this.logger = Logger.getLogger("streaming.Duration_js"); JavaWrapper.call(this, jvmObj); }; StreamingContext.prototype = Object.create(JavaWrapper.prototype); StreamingContext.prototype.constructor = StreamingContext; /** * Wait for the execution to stop */ StreamingContext.prototype.awaitTermination = function() { this.getJavaObject().awaitTermination(); }; /** * Wait for the execution to stop, or timeout * @param {long} millis * @returns {boolean} */ StreamingContext.prototype.awaitTerminationOrTimeout = function(millis) { return this.getJavaObject().awaitTerminationOrTimeout(millis); }; /** * Start the execution of the streams. */ StreamingContext.prototype.start = function() { this.getJavaObject().start(); }; /** * Stops the execution of the streams. */ StreamingContext.prototype.stop = function() { if(arguments.length == 1) { this.getJavaObject().stop(arguments[0]); } else { this.getJavaObject().stop(); } }; StreamingContext.prototype.close = function() { this.getJavaObject().close(); }; /** * Create a input stream from TCP source hostname:port. * @param {string} host * @param {string} port * @returns {DStream} */ StreamingContext.prototype.socketTextStream = function(host, port) { var jDStream = this.getJavaObject().socketTextStream(host, port); return new DStream(jDStream, this); }; <file_sep>/* * Copyright 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var sparkContext = new SparkContext("local[*]", "accumulators test"); var accum = sparkContext.accumulator([0]); var addInt = function(){ print("accum " + accum); sparkContext.parallelize([1, 2, 3, 4]).foreach(function(x, accum) { accum.add(x); }, [accum]); print( accum.value()); } addInt(); <file_sep>/* * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Model trained by {@link FPGrowth}, which holds frequent itemsets. * @param freqItemsets frequent itemset, which is an RDD of {@link FreqItemset} * @classdesc */ /** * @param {RDD} freqItemsets * @returns {??} * @class */ var FPGrowthModel = function(freqItemsets) { var jvmObject = new org.apache.spark.mllib.fpm.FPGrowthModel(freqItemsets); this.logger = Logger.getLogger("FPGrowthModel_js"); JavaWrapper.call(this, jvmObject); }; FPGrowthModel.prototype = Object.create(JavaWrapper.prototype); FPGrowthModel.prototype.constructor = FPGrowthModel; /** * Generates association rules for the [[Item]]s in {@link freqItemsets}. * @param {number} confidence minimal confidence of the rules produced * @returns {RDD} */ FPGrowthModel.prototype.generateAssociationRules = function(confidence) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().generateAssociationRules(confidence); // return new RDD(javaObject); }; /** * A parallel FP-growth algorithm to mine frequent itemsets. The algorithm is described in * [[http://dx.doi.org/10.1145/1454008.1454027 Li et al., PFP: Parallel FP-Growth for Query * Recommendation]]. PFP distributes computation in such a way that each worker executes an * independent group of mining tasks. The FP-Growth algorithm is described in * [[http://dx.doi.org/10.1145/335191.335372 Han et al., Mining frequent patterns without candidate * generation]]. * * @param minSupport the minimal support level of the frequent pattern, any pattern appears * more than (minSupport * size-of-the-dataset) times will be output * @param numPartitions number of partitions used by parallel FP-growth * * @see [[http://en.wikipedia.org/wiki/Association_rule_learning Association rule learning * (Wikipedia)]] * * @classdesc */ /** * Constructs a default instance with default parameters {minSupport: `0.3`, numPartitions: same * as the input data}. * * @returns {??} * @class */ var FPGrowth = function(jvmObject) { this.logger = Logger.getLogger("FPGrowth_js"); JavaWrapper.call(this, jvmObject); }; FPGrowth.prototype = Object.create(JavaWrapper.prototype); FPGrowth.prototype.constructor = FPGrowth; /** * Sets the minimal support level (default: `0.3`). * * @param {number} minSupport * @returns {} */ FPGrowth.prototype.setMinSupport = function(minSupport) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().setMinSupport(minSupport); // return new (javaObject); }; /** * Sets the number of partitions used by parallel FP-growth (default: same as input data). * * @param {number} numPartitions * @returns {} */ FPGrowth.prototype.setNumPartitions = function(numPartitions) { throw "not implemented by ElairJS"; // var javaObject = this.getJavaObject().setNumPartitions(numPartitions); // return new (javaObject); }; /** * Computes an FP-Growth model that contains frequent itemsets. * @param {RDD} data input data set, each element contains a transaction * * @returns {FPGrowthModel} an [[FPGrowthModel]] */ FPGrowth.prototype.runwithRDD = function(data) { throw "not implemented by ElairJS"; // var data_uw = Utils.unwrapObject(data); // var javaObject = this.getJavaObject().run(data_uw); // return new FPGrowthModel(javaObject); }; /** * @param {JavaRDD} data * @returns {FPGrowthModel} */ FPGrowth.prototype.runwithJavaRDD = function(data) { throw "not implemented by ElairJS"; // var data_uw = Utils.unwrapObject(data); // var javaObject = this.getJavaObject().run(data_uw); // return new FPGrowthModel(javaObject); }; /** * Frequent itemset. param: items items in this itemset. Java users should call javaItems() instead. param: freq frequency * @classdesc * @param {object} items * @param {integer} freq * @constructor */ var FreqItemset = function() { this.logger = Logger.getLogger("FreqItemset_js"); var jvmObject = arguments[0]; if (arguments.length > 1) { var items = Utils.unwrapObject(arguments[0]); if (Array.isArray(items)) { var list = new java.util.ArrayList(); items.forEach(function(item){ list.add(Utils.unwrapObject(item)); }); items = list.toArray(); } jvmObject = new org.apache.spark.mllib.fpm.FPGrowth.FreqItemset(items, arguments[1]); } JavaWrapper.call(this, jvmObject); }; FreqItemset.prototype = Object.create(JavaWrapper.prototype); FreqItemset.prototype.constructor = FreqItemset; FreqItemset.prototype.items = function() { var javaObject = this.getJavaObject().javaItems(); return javaObject; };
08bede0c9ff03e4c691998b47c39db8ac56bce17
[ "JavaScript", "Java", "Maven POM", "HTML" ]
35
JavaScript
codeaudit/eclairjs-nashorn
ce14f4b91c0a5786e095ec5b6836af6bf0b2b2c0
37c6b7407484563bdd857b916e1ef693c9fc5f8d
refs/heads/master
<repo_name>JMLuceroav/Automatizacion<file_sep>/automation/src/test/java/com/choucair/formacion/pageobjects/CategoriaPage.java package com.choucair.formacion.pageobjects; import net.serenitybdd.core.annotations.findby.FindBy; import net.serenitybdd.core.pages.PageObject; import net.serenitybdd.core.pages.WebElementFacade; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; public class CategoriaPage extends PageObject{ @FindBy(id="txtNombre") public WebElementFacade txtNombreCate; @FindBy(id="btnGuardar") public WebElementFacade btnSave; @FindBy(xpath="//*[@id='messages']/div/ul/li/span") public WebElementFacade lblVerifica; @FindBy(id="txtFiltro") public WebElementFacade txtFiltroCateg; @FindBy(id="btnFiltrar") public WebElementFacade btnFiltrar; @FindBy(xpath="//*[@id='tablaCategorias_data']/tr/td[1]") public WebElementFacade tbCateg; @FindBy(id="btnActualizar") public WebElementFacade btnUpdate; @FindBy(xpath="/html/body/section/div[2]/div/div/div/div/div/div[1]/div/div") public WebElementFacade lblValida; @FindBy(xpath="//*[@id='messages']/div/ul/li/span") public WebElementFacade lblValidaUpdate; @FindBy(id="btnEliminar") public WebElementFacade btnDelete; @FindBy(id="btnSi") public WebElementFacade btnSi; @FindBy(xpath="//*[@id='messages']/div/ul/li/span") public WebElementFacade lblValidaDelete; public void registrar_nueva_categoria(String categoria) { txtNombreCate.sendKeys(categoria); btnSave.click(); } public void verifica_registro_categoria() { String strMensaje =lblVerifica.getText(); String lblv ="Se guardó de manera correcta la Categoría"; assertThat(strMensaje, containsString(lblv)); } public void buscar_categoria(String updateCategoria) { txtFiltroCateg.sendKeys(updateCategoria); btnFiltrar.click(); } public void seleccionar_categoria_tabla() { System.out.println("traeee"+ tbCateg.getText()); tbCateg.click(); } public void seleccionar_opcion_editar() { btnUpdate.click(); String msg =lblValida.getText(); String lblv ="Actualizar Categoría"; assertThat(msg, containsString(lblv)); } public void actualizar_categoria(String newCategoria) { txtNombreCate.clear(); txtNombreCate.click(); txtNombreCate.sendKeys(newCategoria); btnSave.click(); } public void verificar_categoria_Actualizada() { String msg1 =lblValidaUpdate.getText(); String lblv ="Se actualizó de manera correcta la Categoría"; assertThat(msg1, containsString(lblv)); } public void eliminar_categoria() { btnDelete.click(); btnSi.click(); } public void verificar_categoria_eliminada() { String msg2 =lblValidaDelete.getText(); String lblv ="Se eliminó de manera correcta la Categoría"; assertThat(msg2, containsString(lblv)); } } <file_sep>/automation/src/test/java/com/choucair/formacion/steps/CategoriaSteps.java package com.choucair.formacion.steps; import java.util.List; import com.choucair.formacion.pageobjects.CategoriaPage; import net.thucydides.core.annotations.Step; public class CategoriaSteps { CategoriaPage categoriaPage; @Step public void diligenciar_Categorias_tabla(List<List<String>> data, int id) { categoriaPage.registrar_nueva_categoria(data.get(id).get(0).trim()); } @Step public void valida_registro_categoria() { categoriaPage.verifica_registro_categoria(); } @Step public void buscar_categoria(List<List<String>> data, int id) { categoriaPage.buscar_categoria(data.get(id).get(0).trim()); } @Step public void seleccionar_categoria() { categoriaPage.seleccionar_categoria_tabla(); } @Step public void seleccionar_categoria_editar() { categoriaPage.seleccionar_opcion_editar(); } @Step public void update_categoria(List<List<String>> data, int id) { categoriaPage.actualizar_categoria(data.get(id).get(0).trim()); } @Step public void validar_categoria_update() { categoriaPage.verificar_categoria_Actualizada(); } @Step public void delete_categoria() { categoriaPage.eliminar_categoria(); } @Step public void verificar_categoria_delete() { categoriaPage.verificar_categoria_eliminada(); } } <file_sep>/automation/src/test/java/com/choucair/formacion/pageobjects/LoginPage.java package com.choucair.formacion.pageobjects; import net.serenitybdd.core.annotations.findby.FindBy; import net.serenitybdd.core.pages.PageObject; import net.serenitybdd.core.pages.WebElementFacade; import net.thucydides.core.annotations.DefaultUrl; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @DefaultUrl("http://localhost:8080/VisorWeb/") public class LoginPage extends PageObject{ @FindBy(id="txtUsuario") public WebElementFacade txtUsername; @FindBy(id="txtClave") public WebElementFacade txtPassword; @FindBy(id="btnIniciarSesion") public WebElementFacade btnSignIn; @FindBy(xpath="/html/body/section/div[2]/div/div/div/div/div/div[1]/div/div/span") public WebElementFacade lblHomePpal; public void IngresarDatos(String strUsuario, String strPass){ txtUsername.sendKeys(strUsuario); txtPassword.sendKeys(str<PASSWORD>); btnSignIn.click(); } public void VerificaHome() { String labelv = "Visor de Almacén"; String strMensaje = lblHomePpal.getText(); System.out.println("------------"+strMensaje); assertThat(strMensaje, containsString(labelv)); } } <file_sep>/automation/src/test/java/com/choucair/formacion/pageobjects/MenuPage.java package com.choucair.formacion.pageobjects; import org.openqa.selenium.WebElement; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import net.serenitybdd.core.annotations.findby.FindBy; import net.serenitybdd.core.pages.PageObject; import net.serenitybdd.core.pages.WebElementFacade; public class MenuPage extends PageObject{ @FindBy(xpath="/html/body/section/div[1]/div") public WebElement mnuForm; @FindBy(xpath="/html/body/section/div[1]/nav/ul/li/span/i") public WebElement mnuAlmacen; @FindBy(xpath="/html/body/section/div[1]/nav/ul/li/ul/li[1]/a") public WebElement mnuCategoria; @FindBy(xpath="/html/body/section/div[2]/div/div/div/div/div/div[1]/div/div") public WebElement lblCategoria; @FindBy(id="btnNuevo") public WebElementFacade btnNuevo; @FindBy(xpath="/html/body/section/div[2]/div/div/div/div/div/div[1]/div/div") public WebElement lblMsg; public void menuFormValidation() { mnuForm.click(); mnuAlmacen.click(); mnuCategoria.click(); String strMensaje =lblCategoria.getText(); String lblv ="Mantenimiento de Categoría"; assertThat(strMensaje, containsString(lblv)); } public void presionar_nuevo() { btnNuevo.click(); String msg =lblMsg.getText(); String lblv ="Registrar Categoría"; assertThat(msg, containsString(lblv)); } }
34f11bca98265be40d6ac0c0815c84839164355c
[ "Java" ]
4
Java
JMLuceroav/Automatizacion
2d906d120bff77e4b532bec1871ca7636fca3c5b
1df1e5794be3f4f1c58114c0ffcf0fefd3b815ac
refs/heads/master
<file_sep>class Api::V1::ReviewsController < ApplicationController def index if params[:book_id] @reviews = Book.find(params[:book_id]).reviews render json: ReviewSerializer.new(@reviews) else render json: { error: "Must have a book to see reviews" } end end def show review_json = ReviewSerializer.new(@review).serialized_json render json:review_json end def create @review = Review.new(review_params) if @review.save render json: ReviewSerializer.new(@reviews), status: :created else error_resp = { error: @review.errors.full_messages.to_sentence } render json: error_resp, status: :unprocessable_entity end end def update if @review.update(review_params) render json: @review else render json: @review.errors, status: :unprocessable_entity end end def destroy @review.destroy end private def set_review @review = Review.find(params[:id]) end def review_params params.require(:review).permit(:content, :rating, :user_id, :book_id) end end <file_sep>import React from "react"; import { connect } from "react-redux"; import { updateLoginForm } from "../actions/loginForm.js"; import { login } from "../actions/currentUser.js"; const Login = ({ loginFormData, updateLoginForm, login }) => { const handleInputChange = event => { const { name, value } = event.target; const updatedFormInfo = { ...loginFormData, [name]: value }; updateLoginForm(updatedFormInfo); }; const handleSubmit = event => { event.preventDefault(); login(loginFormData); }; return ( <form onSubmit={handleSubmit}> <input placeholder="username" value={loginFormData.username} name="username" type="text" onChange={handleInputChange} /> <input placeholder="<PASSWORD>" value={loginFormData.password} name="<PASSWORD>" type="text" onChange={handleInputChange} /> <input type="submit" value="Log In" /> </form> ); }; const mapStateToProps = state => { return { loginFormData: state.loginForm }; }; export default connect( mapStateToProps, { updateLoginForm, login } )(Login); <file_sep>import React from "react"; import MyBooks from "./MyBooks.js"; const MainContainer = () => { return ( <div className="MainContainer"> <MyBooks /> </div> ); }; export default MainContainer; <file_sep>class UserSerializer include FastJsonapi::ObjectSerializer attributes :username, :name attribute :books do |user| { books: user.books } end end <file_sep>import React from "react"; import "./App.css"; import { connect } from "react-redux"; import { getCurrentUser } from "./actions/currentUser.js"; import NavBar from "./components/NavBar.js"; import Login from "./components/Login.js"; import MyBooks from "./components/MyBooks.js"; import BookCard from "./components/BookCard.js"; import NewBookFormWrapper from "./components/NewBookFormWrapper.js"; import EditBookFormWrapper from "./components/EditBookFormWrapper"; import { Route, Switch, withRouter } from "react-router-dom"; import { deleteBook } from "./actions/myBooks"; class App extends React.Component { componentDidMount() { this.props.getCurrentUser(); } render() { const { loggedIn, books } = this.props; return ( <div className="App"> {loggedIn ? <NavBar /> : <Login />} <Switch> <Route exact path="/login" component={Login} /> <Route exact path="/books" component={MyBooks} /> <Route exact path="/books/new" component={NewBookFormWrapper} /> <Route exact path="/books/:id" render={props => { const book = books.find( book => book.id === props.match.params.id ); return ( <BookCard book={book} deleteBook={this.props.deleteBook} {...props} /> ); }} /> <Route exact path="/books/:id/edit" render={props => { const book = books.find( book => book.id === props.match.params.id ); return <EditBookFormWrapper book={book} {...props} />; }} /> </Switch> </div> ); } } const mapStateToProps = state => { return { loggedIn: !!state.currentUser, books: state.myBooks }; }; export default withRouter( connect( mapStateToProps, { getCurrentUser, deleteBook } )(App) ); <file_sep>class ReviewSerializer include FastJsonapi::ObjectSerializer attributes :content, :rating belongs_to :user belongs_to :book end <file_sep>import React from "react"; import { connect } from "react-redux"; import { Link } from "react-router-dom"; import Card from "react-bootstrap/Card"; class MyBooks extends React.Component { render() { const bookCards = this.props.books.map((b) => ( <> <Card key={b.id} b={b} style={{ width: "16rem" }} > <Card.Body> <Card.Title>"{b.attributes.name}"</Card.Title> <Card.Text>By: {b.attributes.author}</Card.Text><Link to={`/books/${b.id}`}>...more</Link> </Card.Body> </Card> <br /> </> )); return ( <div> <h1 align="center">All Books:</h1> <div style={{ display: "flex", flexWrap: "wrap", justifyContent: "space-between" }} > {bookCards} </div> </div> ); } } const mapStateToProps = state => { return { books: state.myBooks }; }; export default connect( mapStateToProps )(MyBooks); <file_sep>class Book < ApplicationRecord has_many :reviews has_one :user validates :name, presence: true end <file_sep>class Api::V1::BooksController < ApplicationController before_action :set_book, only: [:show, :update, :destroy] def index if logged_in? @books = current_user.books render json: BookSerializer.new(@books) else render json: { error: "Must be logged in to see books" } end end def show render json: @book end def create @book = current_user.books.build(book_params) if @book.save render json: BookSerializer.new(@book), status: :created else error_resp = { error: @book.errors.full_messages.to_sentence } render json: error_resp, status: :unprocessable_entity end end def update if @book.update(book_params) render json: BookSerializer.new(@book), status: :ok else error_resp = { error: @book.errors.full_messages.to_sentence } render json: error_resp, status: :unprocessable_entity end end def destroy if @book.destroy render json: { data: "Book successfully destroyed" }, status: :ok else error_resp = { error: "Book not found and not destroyed" } render json: error_resp, status: :unprocessable_entity end end private def set_book @book = Book.find(params[:id]) end def book_params params.require(:book).permit( :name, :author, :description, :user_id ) end end <file_sep># Book Fellow [ NOTE ]: I will return to this app to clean up the code and add more features. ## Background Book social application is for children's books and beginner readers, user can CRUD and recommend books for other parents/kids. Also user can read other's book suggestions. This application is using React, Redux, Ruby on Rails, HTML, Javascript and Materialize CSS framework. ## Installation Instructions ### Setup Rails API backend: Clone this repo, and navigate to the repo directory in your terminal Change directories into backend folder: cd book-fellow-backend Run bundle install to install all gem dependencies Also run all rake migrations with rake db:migrate Then load rails s to start If you want to see this app in the browser, open your browser and navigate to `http://localhost:3000` (press ctrl-C or control-C while in the terminal to exit). ### Setup React server client side: Change directories into client folder: cd book-fellow-frontend Run npm install to install all package dependencies Run npm install es6-promise Run Rake Start to start up both servers Open your browser and navigate to `http://localhost:3001` (press ctrl-C or control-C while in the terminal to exit) ## Contributing Bug reports and pull requests are welcome on GitHub at https://github.com/yanchanllin/book-fellow.git. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct. ## License The gem is available as open source under the terms of the MIT License. <file_sep>import React from "react"; import BookForm from "./BookForm"; import { createBook } from "../actions/bookForm"; import { connect } from "react-redux"; const NewBookFormWrapper = ({ history, createBook }) => { const handleSubmit = (formData, userId) => { createBook( { ...formData, userId }, history ); }; return <BookForm history={history} handleSubmit={handleSubmit} />; }; export default connect( null, { createBook } )(NewBookFormWrapper); <file_sep>import { resetLoginForm } from "./loginForm.js"; import { getMyBooks, clearBooks } from "./myBooks.js"; //synchronous action creators export const setCurrentUser = user => { return { type: "SET_CURRENT_USER", user }; }; export const clearCurrentUser = () => { return { type: "CLEAR_CURRENT_USER" }; }; //asynchronous action creators export const login = credentials => { // console.log("credentials are", credentials); return dispatch => { return fetch("https://murmuring-atoll-04944.herokuapp.com/api/v1/login", { credentials: "include", method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(credentials) }) .then(r => r.json()) .then(response => { if (response.error) { alert(response.error); } else { dispatch(setCurrentUser(response.data)); dispatch(getMyBooks()); dispatch(resetLoginForm()); } }) .catch(console.log); }; }; export const logout = event => { return dispatch => { dispatch(clearCurrentUser()); dispatch(clearBooks()); return fetch("https://murmuring-atoll-04944.herokuapp.com/api/v1/logout", { credentials: "include", method: "DELETE" }); }; }; export const getCurrentUser = () => { return dispatch => { return fetch("https://murmuring-atoll-04944.herokuapp.com/api/v1/get_current_user", { credentials: "include", method: "GET", headers: { "Content-Type": "application/json" } }) .then(r => r.json()) .then(response => { if (response.error) { alert(response.error); } else { dispatch(setCurrentUser(response.data)); dispatch(getMyBooks()); } }) .catch(console.log); }; }; <file_sep># 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) # lili = User.first User.create(name:"lilil", username:"lilil", password:"<PASSWORD>") # amy = User.second # amy.books.create(name: "Blue", author:"<NAME>", description:"It's good for age 4 & up") # lili.books.create(name: "The Tiny Seed", author:"<NAME>", description:"age 4 & up,Its journey is perilous, and the reader learns the fate of fellow seeds") # lili.reviews.create(content:"good for beginnner reading", rating:"4/5", user_id:1,book_id:1) # amy.reviews.create(content:"Each page is packed with intriguing facts, future places, and lots more!", rating:"4/5",user_id:1,book_id:2)<file_sep>class BookSerializer include FastJsonapi::ObjectSerializer attributes :name, :author, :description, :user_id attribute :reviews do |book| book.reviews.map do |rev| { content: rev.content, rating: rev.rating } end end end <file_sep>BOOK SOCIAL APP (for children's books-educational, beginner readings) A REACT APP WITH A RAILS API BACKEND 2019-06 \*USER name username password_digest has_many :books has_many :reviews \*BOOK name,author,description has_many :reviews has_many :users \*REVIEW content,rating belongs_to :user belongs_to :book rails new book-fellow --api rails g scaffold user name username password_digest Domain ideas: bank app house sale apps review Overview It's mostly for children's books-educational, beginner readings. User can list many books and review on them, recommend for other parents/kids. User can also read other's book suggestions. <file_sep>import React from "react"; import BookForm from "./BookForm"; import { updateBook } from "../actions/bookForm"; import { setFormDataForEdit, resetNewBookForm } from "../actions/bookForm"; import { connect } from "react-redux"; class EditBookFormWrapper extends React.Component { componentDidMount() { this.props.book && this.props.setFormDataForEdit(this.props.book); } componentDidUpdate(prevProps) { this.props.book && !prevProps.book && this.props.setFormDataForEdit(this.props.book); } componentWillUnmount() { this.props.resetNewBookForm(); } handleSubmit = (formData, userId) => { const { updateBook, book, history } = this.props; updateBook( { ...formData, bookId: book.id, userId }, history ); }; render() { return <BookForm editMode handleSubmit={this.handleSubmit} />; } } export default connect( null, { updateBook, setFormDataForEdit, resetNewBookForm } )(EditBookFormWrapper);
60c0a2aa7fe37cd6e45a62843421b5cd168a1ada
[ "JavaScript", "Ruby", "Markdown" ]
16
Ruby
yanchanllin/book-fellow
fd6509786ec19c0522f0b9b4ab29f87e5dc78158
57aeabc6f6a4f8c71af882afdee8e6d41988f545
refs/heads/master
<file_sep>apturl==0.5.2 beautifulsoup4==4.4.1 blinker==1.3 Brlapi==0.6.4 chardet==2.3.0 checkbox-support==0.22 command-not-found==0.3 cryptography==1.2.3 defer==1.0.6 Django==1.11.5 django-bootstrap-form==3.3 django-bootstrap-toolkit==2.15.0 django-bootstrap3==9.1.0 django-widget-tweaks==1.4.1 feedparser==5.1.3 guacamole==0.9.2 html5lib==0.999 httplib2==0.9.1 idna==2.0 Jinja2==2.8 language-selector==0.1 louis==2.6.4 lxml==3.5.0 Mako==1.0.3 MarkupSafe==0.23 mysqlclient==1.3.12 oauthlib==1.0.3 onboard==1.2.0 padme==1.1.1 pexpect==4.0.1 Pillow==3.1.2 plainbox==0.25 ptyprocess==0.5 pyasn1==0.1.9 pycups==1.9.73 pycurl==7.43.0 pygobject==3.20.0 PyJWT==1.3.0 PyMySQL==0.7.11 pyparsing==2.0.3 python-apt==1.1.0b1 python-debian==0.1.27 python-systemd==231 pytz==2017.2 pyxdg==0.25 reportlab==3.3.0 requests==2.9.1 sessioninstaller==0.0.0 six==1.10.0 system-service==0.3 ubuntu-drivers-common==0.0.0 ufw==0.35 unattended-upgrades==0.1 unity-scope-calculator==0.1 unity-scope-chromiumbookmarks==0.1 unity-scope-colourlovers==0.1 unity-scope-devhelp==0.1 unity-scope-firefoxbookmarks==0.1 unity-scope-gdrive==0.7 unity-scope-manpages==0.1 unity-scope-openclipart==0.1 unity-scope-texdoc==0.1 unity-scope-tomboy==0.1 unity-scope-virtualbox==0.1 unity-scope-yelp==0.1 unity-scope-zotero==0.1 unity-tweak-tool==0.0.7 urllib3==1.13.1 usb-creator==0.3.0 virtualenv==15.1.0 xdiagnose==3.8.4.1 xkit==0.0.0 XlsxWriter==0.7.3 <file_sep>from __future__ import unicode_literals from django.views.generic import ListView, CreateView, UpdateView, View, DetailView from django.shortcuts import render, get_object_or_404, reverse, HttpResponseRedirect, HttpResponse from .models import Blog, Post, Category, Like from django.template import RequestContext, loader, Context from django import forms from comment.models import Comment class BlogForm(forms.ModelForm): search = forms.CharField(required=False) order_by = forms.ChoiceField(choices=( ('name', 'A->Z'), ('-name', 'Z->A'), ('-createdata', 'Last created'), ('createdata', 'First created'), ), required=False) class Meta: model = Blog fields = 'name', class BlogList(ListView): template_name = "blog/blogpage.html" context_object_name = 'blog' model = Blog def get_queryset(self): q = super(BlogList, self).get_queryset() self.form = BlogForm(self.request.GET) if self.form.is_valid(): if self.form.cleaned_data['order_by']: q = q.order_by(self.form.cleaned_data['order_by']) if self.form.cleaned_data['search']: q = q.filter(name=self.form.cleaned_data['search']) return q def get_context_data(self, **kwargs): context = super(BlogList, self).get_context_data(**kwargs) context['customform1'] = self.form context['category'] = Blog.category bdict = dict(self.request.GET) bdict.pop('page', None) #from urllib.parse import urlencode # from urlparse import urlparse try: from urllib.parse import urlencode except ImportError: from urllib import urlencode context['querypart'] = urlencode(bdict) for blogs in context['blog']: blogs.form = BlogForm(instance=blogs) return context class NewBlogForm(forms.ModelForm): class Meta: model = Blog fields = 'name', 'category', class NewBlog(CreateView): form_class = NewBlogForm template_name = 'blog/new_blog.html' def get_success_url(self): return reverse('blog:listOfBlogs') def get_context_data(self, **kwargs): context = super(NewBlog, self).get_context_data(**kwargs) context['category_list'] = Category.objects.all() return context def form_valid(self, form): form.instance.author = self.request.user return super(NewBlog, self).form_valid(form) class BlogUpdate(UpdateView): template_name = 'blog/edit_blog.html' model = Blog fields = 'name', 'category' def form_valid(self, form): if self.object.author == self.request.user: super(BlogUpdate, self).form_valid(form) template=loader.get_template('blog/blogpage.html') return HttpResponseRedirect('http://127.0.0.1:8080/blog/') else: return HttpResponseRedirect(404) def get_queryset(self): return super(BlogUpdate, self).get_queryset().filter(author=self.request.user) def get_success_url(self): return reverse('blog:listOfBlogs') #------------------------------------------------------------------------# #------------------------------------------------------------------------# #------------------------------------------------------------------------# #------------------------------------------------------------------------# class PostList(ListView): template_name = "blog/posts_list.html" context_object_name = 'posts' model = Post paginate_by = 10 def dispatch(self, request, *args, **kwargs): self.blog = get_object_or_404(Blog, id=self.kwargs['ident']) return super(PostList, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(PostList, self).get_context_data(**kwargs) context['blog'] = self.blog return context class NewPostForm(forms.ModelForm): class Meta: model = Post fields = 'postname', 'text' class NewPost(CreateView): form_class = NewPostForm template_name = 'blog/new_post.html' def dispatch(self, request, *args, **kwargs): self.blog = get_object_or_404(Blog, id=self.kwargs['ident'], author=request.user) return super(NewPost, self).dispatch(request, *args, **kwargs) def get_success_url(self): return reverse('blog:concretePost', kwargs={'ident': self.object.id}) def form_valid(self, form): form.instance.blog_id = self.kwargs['ident'] form.instance.author = self.request.user return super(NewPost, self).form_valid(form) def get_context_data(self, **kwargs): context = super(NewPost, self).get_context_data(**kwargs) context['blog'] = self.blog return context class PostUpdate(UpdateView): template_name = 'blog/edit_post.html' model = Post fields = 'postname', 'text' def form_valid(self, form): if self.object.author == self.request.user: return super(PostUpdate, self).form_valid(form) else: return HttpResponseRedirect(404) def get_queryset(self): return super(PostUpdate, self).get_queryset().filter(author=self.request.user) def get_success_url(self): return reverse('blog:concretePost', kwargs={'ident': self.object.id}) class PostPage(CreateView): template_name = "blog/post_page.html" context_object_name = 'post' model = Comment fields = ('text', ) def dispatch(self, request, *args, **kwargs): self.postobject = get_object_or_404(Post, id=self.kwargs['ident']) return super(PostPage, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(PostPage, self).get_context_data(**kwargs) context['post'] = self.postobject context['blog'] = self.postobject.blog context['likes'] = Like.objects.filter(post=self.postobject).count() context['comment_list'] = Comment.objects.filter(post=self.postobject) return context def get_success_url(self): return reverse('blog:concretePost', kwargs={'ident': self.object.post.id}) def form_valid(self, form): if self.request.user.is_authenticated(): form.instance.post_id = self.kwargs['ident'] form.instance.author = self.request.user return super(PostPage, self).form_valid(form) else: return HttpResponseRedirect(reverse('core:login')) class PostComments(CreateView): template_name = "blog/comments.html" context_object_name = 'post' model = Comment fields = ('text',) def get_context_data(self, **kwargs): self.postobject = get_object_or_404(Post, id=self.kwargs['ident']) context = super(PostComments, self).get_context_data(**kwargs) context['post'] = self.postobject return context class PostLikeAjaxView(View): def dispatch(self, request, *args, **kwargs): self.post_object = get_object_or_404(Post, id=self.kwargs['ident']) return super(PostLikeAjaxView, self).dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): if not self.request.user.is_authenticated() or not self.post_object.likes.filter(author=self.request.user).exists(): b2 = Like(author=self.request.user, post=self.post_object) b2.save() return HttpResponse(Like.objects.filter(post=self.post_object).count())<file_sep>from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .models import User class UserAdmin(BaseUserAdmin): admin.site.register(User) <file_sep>{% extends "core/base.html" %} {% load bootstrap3 %} {% load static %} {% block content %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="{% static "edit_blog.js" %}"> </script> <form data-formtype="ajaxForm" action="{% url "blog:edit_blog" pk=blog.id %}" method="post"> {% bootstrap_form form show_label=False %} {% csrf_token %} <input type="button" class="btn btn-default" onclick="history.back();" value="Back"> <input type="submit" class="btn btn-primary" onclick="winOpen();" value="Edit blog"> <script type="text/javascript"> function winOpen(){ alert('Success!'); }; </script> </form> {% endblock %}
343af2f3addd079adcfe2b63eb2db5fb8c9ed6b2
[ "Python", "Text", "HTML" ]
4
Text
manwithhonor/technotrack-web1-autumn-2017
bb2bbcbfaf9547e3713eb2a44f7359bdf978d1e3
ad6898343df618d7c95b0c4839290ab7fe8b6736
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Character : MonoBehaviour { <<<<<<< HEAD // 나도 모른다!! ======= // 머꼬!! >>>>>>> f37fabdef3ccee5d05679ad2bc927fb826e2e94e public int _hp; // 체력 public int _damage; // 공격력 public int _defence; // 방어력 public int _evasion; // 회피율 public int _accuracy; // 적중률 // 회피 여부 public virtual bool AttackSuccess(int accuracy, int evasion) { if ((accuracy - evasion) < 100) { int attackNumber = Random.Range(0, 100); if (attackNumber >= (accuracy - evasion)) { return true; } else { return false; } } else { return true; } } // 데미지 계산 public virtual int OnDamage(bool attackSuccess, int damage, int defence) { if (attackSuccess) { // 계산한 데미지값이 0보다 클경우 if ((damage - defence) > 0) { return damage - defence; } // 작거나 같을 경우 else { return 1; } } // 회피일 때 else { return 0; } } public virtual void Die() { if (_hp <= 0) { Destroy(this.gameObject); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Goblin : Character { // Start is called before the first frame update void Start() { _hp = 30; _damage = 5; _defence = 1; _accuracy = 100; _evasion = 0; } // Update is called once per frame void Update() { Die(); } public override bool AttackSuccess(int accuracy, int evasion) { return base.AttackSuccess(accuracy, evasion); } public override int OnDamage(bool attackSuccess, int damage, int defence) { return base.OnDamage(attackSuccess, damage, defence); } public override void Die() { base.Die(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class ItemManager : MonoBehaviour { public List<GameObject> _Item; public PlayerController playerController; // 무기 활성화 public void WeaponOpen(int itemNumber) { WeaponClose(); _Item[itemNumber].gameObject.SetActive(true); Debug.Log(_Item[itemNumber]); playerController._weapon = _Item[itemNumber]; } public void WeaponClose() { for (int x = 0; x < _Item.Count; x++) { _Item[x].gameObject.SetActive(false); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { internal GameObject _weapon; private Rigidbody2D _playerRigidbody; private Animator _playerAnimator; private float _moveSpeed = 300f; private float _jumpForce = 500f; private float _xInput; private float Timer = 0f; private int _jumpCount; private bool _death; private bool _jumpping; private bool _weaponUp; private bool _dashing; // Start is called before the first frame update void Start() { _playerRigidbody = GetComponent<Rigidbody2D>(); _playerAnimator = GetComponent<Animator>(); _jumpCount = 0; _death = false; _jumpping = false; _weaponUp = true; _dashing = false; } // Update is called once per frame void Update() { Move(); Jump(); PlayerAnimation(); Attack(); if (!_jumpping) { Dash(); Timer += Time.deltaTime; if (Timer > 5f) { _dashing = false; Timer = 0f; } } } // 이동 public void Move() { _xInput = Input.GetAxis("Horizontal"); float _playerSpeed = _xInput * _moveSpeed * Time.deltaTime; Vector2 NewVector = new Vector2(_playerSpeed, _playerRigidbody.velocity.y); _playerRigidbody.velocity = NewVector; if (_xInput < 0) // 왼쪽 { transform.rotation = Quaternion.Euler(0, 180, 0); } else if (_xInput > 0) // 오른쪽 { transform.rotation = Quaternion.Euler(0, 0, 0); } else { _playerSpeed = 0; } } // 점프 public void Jump() { if (Input.GetKeyDown(KeyCode.Space) && _jumpCount < 2) { _jumpCount++; _playerRigidbody.velocity = Vector2.zero; _playerRigidbody.AddForce(Vector2.up * _jumpForce); } } public void PlayerAnimation() { if (_xInput != 0 && _jumpping == false) { _playerAnimator.SetBool("SetMove", true); _playerAnimator.SetBool("SetJump", false); _playerAnimator.SetBool("SetIdle", false); } else if (_xInput == 0 && _jumpping == false) { _playerAnimator.SetBool("SetMove", false); _playerAnimator.SetBool("SetJump", false); _playerAnimator.SetBool("SetIdle", true); } else if (_jumpping || (_xInput == 0 && _jumpping)) { _playerAnimator.SetBool("SetMove", false); _playerAnimator.SetBool("SetJump", true); _playerAnimator.SetBool("SetIdle", false); } } public void Dash() { if (Input.GetKeyDown(KeyCode.X) && !_dashing ) { _moveSpeed = 900f; _dashing = true; Invoke("DashOff", 1f); } } public void DashOff() { _moveSpeed = 300f; } public void Attack() { if (Input.GetKeyDown(KeyCode.Z)) { if (_weaponUp) { _weapon.GetComponent<SpriteRenderer>().flipY = true; _weaponUp = false; } else { _weapon.GetComponent<SpriteRenderer>().flipY = false; _weaponUp = true; } } } public void Defense() { if (Input.GetKeyDown(KeyCode.C)) { } } private void OnCollisionEnter2D(Collision2D other) { if (other.gameObject.tag == "Floor") { _jumpCount = 0; _jumpping = false; } } private void OnCollisionExit2D(Collision2D other) { if (other.gameObject.tag == "Floor") { _jumpping = true; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : Character { bool canAttack = true; // Start is called before the first frame update void Start() { _hp = 80; _damage = 10; _defence = 1; _evasion = 0; _accuracy = 100; } // Update is called once per frame void FixedUpdate() { } public override bool AttackSuccess(int accuracy, int evasion) { return base.AttackSuccess(accuracy, evasion); } public override int OnDamage(bool attackSuccess, int damage, int defence) { return base.OnDamage(attackSuccess, damage, defence); } private void OnTriggerStay2D(Collider2D other) { if (other.tag == "Monster") { if (Input.GetKeyDown(KeyCode.Z) && canAttack) { Collider2D[] hitColliders = Physics2D.OverlapCircleAll(other.gameObject.transform.position, 0); int i = 0; while (i < hitColliders.Length) { Character monster = hitColliders[i].gameObject.GetComponent<Character>(); int damage = OnDamage(AttackSuccess(_accuracy, monster._evasion), _damage, monster._defence); monster._hp -= damage; i++; } canAttack = false; } if (Input.GetKeyUp(KeyCode.Z)) { canAttack = true; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { int[] _itemKind = new int[8]; // 0 = 장검, 1 = 양손도끼, 2 = 창, 3 = 해머, 4 = 양손방패, 5 = 한손검, 6 = 한손도끼, 7 = 한손방패 internal ItemManager IM; void Start() { for (int weaponNumber = 0 ; weaponNumber < _itemKind.Length ; weaponNumber++) { _itemKind[weaponNumber] = weaponNumber; } IM = gameObject.GetComponent<ItemManager>(); IM.WeaponClose(); } void Update() { } public void LongSword() { IM.WeaponOpen(_itemKind[0]); Debug.Log("LongSword"); } public void LongAxe() { IM.WeaponOpen(_itemKind[1]); Debug.Log("LongAxe"); } public void Spear() { IM.WeaponOpen(_itemKind[2]); Debug.Log("Spear"); } public void Hammer() { IM.WeaponOpen(_itemKind[3]); Debug.Log("Hammer"); } public void BigShilder() { IM.WeaponOpen(_itemKind[4]); Debug.Log("BigShilder"); } public void ShortSword() { IM.WeaponOpen(_itemKind[5]); Debug.Log("ShortSword"); } public void ShortAxe() { IM.WeaponOpen(_itemKind[6]); Debug.Log("ShortAxe"); } public void SmallShilder() { IM.WeaponOpen(_itemKind[7]); Debug.Log("SmallShilder"); } }
db7944f5a730da91962734fb5e00baaf6dd41b1c
[ "C#" ]
6
C#
SongDoRame/Top-of-Abyss
4c2219338f9a9803b8b79689294cb5fa95caa37e
3269cde63d3e987f524ffc5b8e1b25e529ab2543
refs/heads/master
<repo_name>Zverik/ansible-tile<file_sep>/roles/get_veloroad/files/expandjson.py #!/usr/bin/python import sys, os, cgi, json import psycopg2 import cgitb def query_geometry(osm_type, osm_id, coord, by_coord=False): if (not by_coord or not coord) and osm_id and (osm_type == 'way' or osm_type == 'relation'): # query db for an enclosing object for way/rel cur.execute('SELECT ST_AsGeoJSON(ST_Transform(way, 4326)) FROM planet_osm_polygon WHERE osm_id = %s', (osm_id if osm_type == 'way' else '-{}'.format(osm_id),)) result = cur.fetchone() return json.loads(result[0]) if result else None elif len(coord) >= 2: # query by smallest building enclosing coord cur.execute('SELECT ST_AsGeoJSON(ST_Transform(way, 4326)), ST_Area(way) as area FROM planet_osm_polygon WHERE ST_Transform(ST_SetSRID(ST_Point(%s, %s), 4326), 900913) && way ORDER BY area', (coord[0], coord[1])) result = cur.fetchone() return json.loads(result[0]) if result else None cgitb.enable() conn = psycopg2.connect('dbname=gis user=osm') cur = conn.cursor() form = cgi.FieldStorage() if 'jsont' in form and len(form.getfirst('jsont')): data = json.loads(form.getfirst('jsont')) elif 'json' in form and form['json'].file: data = json.load(form['json'].file) else: sys.exit(1) by_coord = form.getfirst('bycoord') == '1' if 'type' in data and data['type'] == 'FeatureCollection': for f in data['features']: osm_type = None osm_id = None coord = None if 'osm_type' in f['properties'] and 'osm_id' in f['properties']: osm_type = f['properties']['osm_type'] osm_id = f['properties']['osm_id'] if f['geometry']['type'] == 'Point': coord = f['geometry']['coordinates'] geom = query_geometry(osm_type, osm_id, coord, by_coord) if geom: f['geometry'] = geom cur.close() conn.close() print 'Content-Type: application/json\n' print json.dumps(data) <file_sep>/roles/schedules/files/oddmsk20.ini title = Open Data Day Moscow 2020 slug = oddmsk20 url = https://opendataday.ru/msk timezone = +03 <file_sep>/roles/stats/files/du_layer #!/bin/sh # # Plugin to monitor the rendering throughput of Renderd # # Parameters: # # config (required) # autoconf (optional - used by munin-config) # if [ "$1" = "config" ]; then echo 'graph_title Tile disk usage by layer' echo 'graph_args --base 1024' echo 'graph_vlabel Tile layer disk usage' echo 'graph_category renderd' echo 'v.label veloroad' echo 'v.info Veloroad' echo 'r.label veloroad hr' echo 'r.info Veloroad HiDPI' exit 0 fi du --max-depth 1 /var/lib/mod_tile > /tmp/du-layers.txt veloroad=`grep \/veloroad /tmp/du-layers.txt | cut -f1` veloroadhr=`grep \/veloroadhr /tmp/du-layers.txt | cut -f1` rm /tmp/du-layers.txt echo "v.value $veloroad" echo "r.value $veloroadhr" <file_sep>/roles/schedules/files/sotmus2019.ini title = State of the Map US 2019 slug = sotmus2019 url = https://2019.stateofthemap.us/ timezone = -05 <file_sep>/roles/get_veloroad/files/findbuildings.py #!/usr/bin/python # Script for converting coordinates to enclosing buildings, for visgeocode.html import sys, os, cgi, json import psycopg2 conn = psycopg2.connect('dbname=gis user=osm') cur = conn.cursor() form = cgi.FieldStorage() if 'json' in form and len(form.getfirst('json')): data = json.loads(form.getfirst('json')) else: data = [] ids = set() if data and len(data) > 0: for f in data: if 'lat' in f and 'lon' in f: cur.execute('SELECT osm_id, ST_AsGeoJSON(ST_Transform(way, 4326)), ST_Area(way) as area FROM planet_osm_polygon WHERE building is not null AND ST_Contains(way, ST_Transform(ST_SetSRID(ST_Point(%s, %s), 4326), 900913)) ORDER BY area LIMIT 1', (f['lon'], f['lat'])) result = cur.fetchone() if result and not result[0] in ids: ids.add(result[0]) f['geometry'] = json.loads(result[1]) cur.close() conn.close() print 'Content-Type: application/json' print 'Access-Control-Allow-Origin: *' print print json.dumps(data) <file_sep>/roles/queryat/files/queryat_config.py PYTHON = 'python3.5' <file_sep>/roles/schedules/files/sotm2020.ini title = State of the Map 2020 slug = sotm2020 url = https://2020.stateofthemap.org/ timezone = +00 <file_sep>/roles/mark_spam_bot/templates/backup_mark_spam.j2 #!/bin/bash set -u -e BORG=/usr/local/bin/borg export BORG_REPO={{ borg_repo }} export BORG_PASSPHRASE='{{ borg_pass }}' export BORG_REMOTE_PATH=borg1 export BORG_RSH='ssh -i /root/.ssh/borg -oBatchMode=yes' systemctl stop mark_spam_bot $BORG create --compression zstd,5 ::'MarkSpam_{now:%Y-%m-%d_%H%M}' \ /opt/src/mark_spam_bot/markspam.sqlite $BORG prune --prefix 'MarkSpam_' --keep-daily=3 --keep-weekly=1 --keep-monthly=1 systemctl start mark_spam_bot <file_sep>/roles/get_veloroad/files/trim_osc.py #!/usr/bin/python # Trim osmChange file to a bounding polygon and database contents # Written by <NAME>, licensed WTFPL import sys, os, argparse, getpass, gzip import psycopg2 from lxml import etree from shapely.geometry import Polygon, Point def poly_parse(fp): result = None poly = [] data = False for l in fp: l = l.strip() if l == 'END' and data: if len(poly) > 0: if hole and result: result = result.difference(Polygon(poly)) elif not hole and result: result = result.union(Polygon(poly)) elif not hole: result = Polygon(poly) poly = [] data = False elif l == 'END' and not data: break elif len(l) > 0 and ' ' not in l and '\t' not in l: data = True hole = l[0] == '!' elif l and data: poly.append(map(lambda x: float(x.strip()), l.split()[:2])) return result def box(x1,y1,x2,y2): return Polygon([(x1,y1), (x2,y1), (x2,y2), (x1,y2)]) default_user = getpass.getuser() parser = argparse.ArgumentParser(description='Trim osmChange file to a polygon and a database data') parser.add_argument('osc', type=argparse.FileType('r'), help='input osc file, "-" for stdin') parser.add_argument('output', help='output osc file, "-" for stdout') parser.add_argument('-d', dest='dbname', help='database name') parser.add_argument('--host', help='database host') parser.add_argument('--port', type=int, help='database port') parser.add_argument('--user', help='user name for db (default: {0})'.format(default_user), default=default_user) parser.add_argument('--password', action='store_true', help='ask for password', default=False) parser.add_argument('-p', '--poly', type=argparse.FileType('r'), help='osmosis polygon file') parser.add_argument('-b', '--bbox', nargs=4, type=float, metavar=('Xmin', 'Ymin', 'Xmax', 'Ymax'), help='Bounding box') parser.add_argument('-z', '--gzip', action='store_true', help='source and output files are gzipped') parser.add_argument('-v', dest='verbose', action='store_true', help='display debug information') options = parser.parse_args() # read poly poly = None if options.bbox: b = options.bbox poly = box(b[0], b[1], b[2], b[3]) if options.poly: tpoly = poly_parse(options.poly) poly = tpoly if not poly else poly.intersection(tpoly) if poly == None or not options.dbname: parser.print_help() sys.exit() # connect to database passwd = "" if options.password: passwd = getpass.getpass("Please enter your password: ") try: db = psycopg2.connect(database=options.dbname, user=options.user, password=passwd, host=options.host, port=options.port) except Exception, e: print "Error connecting to database: ", e sys.exit(1) cur = db.cursor() # read the entire osc into memory tree = etree.parse(options.osc if not options.gzip else gzip.GzipFile(fileobj=options.osc)) options.osc.close() root = tree.getroot() # NODES nodes = {} # True for nodes inside poly or referenced by good ways nodesM = [] # List of modified nodes outside poly (temporary) for node in root.iter('node'): if node.getparent().tag not in ['modify', 'create']: continue if 'lat' in node.keys() and 'lon' in node.keys(): inside = poly.intersects(Point(float(node.get('lon')), float(node.get('lat')))) nodes[node.get('id')] = inside if node.getparent().tag == 'modify' and not inside: nodesM.append(long(node.get('id'))) # Save modified nodes that are already in the database cur.execute('select id from planet_osm_nodes where id = ANY(%s);', (nodesM,)) for row in cur: nodes[str(row[0])] = True # WAYS ways = [] # List of ways (int id) with nodes inside poly or no known nodes waysM = [] # List of modified ways with no nodes inside poly (temporary) for way in root.iter('way'): if way.getparent().tag not in ['modify', 'create']: continue foundInside = False foundKnown = False for nd in way.iterchildren('nd'): if nd.get('ref') in nodes: foundKnown = True if nodes[nd.get('ref')] == True: foundInside = True break if foundInside: for nd in way.iterchildren('nd'): nodes[nd.get('ref')] = True else: wayId = int(way.get('id')) if foundKnown: ways.append(wayId) if way.getparent().tag == 'modify': waysM.append(wayId) cur.execute('select id from planet_osm_ways where id = ANY(%s);', (waysM,)) for row in cur: ways.remove(row[0]) # iterate over osmChange/<mode>/way[id=<id>]/nd and set nodes[ref] to True for nd in root.xpath('//way[@id={}]/nd'.format(row[0])): nodes[nd.get('ref')] = True # RELATIONS relations = [] # List of modified relations that are not in the database for rel in root.iter('relation'): if rel.getparent().tag == 'modify': relations.append(int(rel.get('id'))) cur.execute('select id from planet_osm_rels where id = ANY(%s);', (relations,)) for row in cur: relations.remove(row[0]) cur.close() db.close() # filter tree # 1. remove objects out of bounds cnt = [0, 0, 0] total = [0, 0, 0] types = ['node', 'way', 'relation'] for obj in root.iter('node', 'way', 'relation'): idx = types.index(obj.tag) ident = obj.get('id') if obj.getparent().tag in ['modify', 'create']: total[idx] = total[idx] + 1 if (obj.tag == 'node' and ident in nodes and not nodes[ident]) or (obj.tag == 'way' and int(ident) in ways) or (obj.tag == 'relation' and int(ident) in relations): obj.getparent().remove(obj) else: cnt[idx] = cnt[idx] + 1 if options.verbose: print '{} -> {}'.format('+'.join(map(str, total)), '+'.join(map(str, cnt))) # 2. remove empty sections for sec in root: if len(sec) == 0: root.remove(sec) # save modified osc of = sys.stdout if options.output == '-' else open(options.output, 'wb') if options.gzip: of = gzip.GzipFile(fileobj=of) of.write(etree.tostring(tree)) <file_sep>/roles/stats/files/du_zoom #!/bin/sh # # Plugin to monitor the rendering throughput of Renderd # # Parameters: # # config (required) # autoconf (optional - used by munin-config) # if [ "$1" = "config" ]; then echo 'graph_title Tile disk usage by zoom' echo 'graph_args --base 1024 -l 0' echo 'graph_vlabel Tile disk usage' echo 'graph_category renderd' echo 'z1.label zoom 6-8' echo 'z1.draw AREASTACK' echo 'z1.info Disk usage for z6-z8' echo 'z2.label zoom 9' echo 'z2.draw AREASTACK' echo 'z2.info Disk usage for z9' echo 'z3.label zoom 10' echo 'z3.draw AREASTACK' echo 'z3.info Disk usage for z10' echo 'z4.label zoom 11' echo 'z4.draw AREASTACK' echo 'z4.info Disk usage for z11' echo 'z5.label zoom 12' echo 'z5.draw AREASTACK' echo 'z5.info Disk usage for z12' echo 'z6.label zoom 13-15' echo 'z6.draw AREASTACK' echo 'z6.info Disk usage for z13-15' exit 0 fi du --max-depth 1 /var/lib/mod_tile/veloroad > /tmp/du-veloroad.txt zoom6=`(grep \/6 /tmp/du-veloroad.txt || echo 0) | cut -f1` zoom7=`(grep \/7 /tmp/du-veloroad.txt || echo 0) | cut -f1` zoom8=`(grep \/8 /tmp/du-veloroad.txt || echo 0) | cut -f1` zoom9=`(grep \/9 /tmp/du-veloroad.txt || echo 0) | cut -f1` zoom10=`(grep \/10 /tmp/du-veloroad.txt || echo 0) | cut -f1` zoom11=`(grep \/11 /tmp/du-veloroad.txt || echo 0) | cut -f1` zoom12=`(grep \/12 /tmp/du-veloroad.txt || echo 0) | cut -f1` zoom13=`(grep \/13 /tmp/du-veloroad.txt || echo 0) | cut -f1` zoom14=`(grep \/14 /tmp/du-veloroad.txt || echo 0) | cut -f1` zoom15=`(grep \/15 /tmp/du-veloroad.txt || echo 0) | cut -f1` rm /tmp/du-veloroad.txt echo "z1.value" `expr $zoom6 + $zoom7 + $zoom8` echo "z2.value $zoom9" echo "z3.value $zoom10" echo "z4.value $zoom11" echo "z5.value $zoom12" echo "z6.value" `expr $zoom13 + $zoom14 + $zoom15` <file_sep>/roles/schedules/files/balticgit20.ini title = Baltic GIT 2020 slug = balticgit2020 url = https://www.balticgitconf.eu/ timezone = +02 <file_sep>/roles/schedules/files/sotm2021.ini title = State of the Map 2021 slug = sotm2021 url = https://2021.stateofthemap.org/ timezone = +00 <file_sep>/roles/mayak_nav_bot/templates/backup_mayak.j2 #!/bin/bash set -u -e BORG=/usr/local/bin/borg export BORG_REPO={{ borg_repo }} export BORG_PASSPHRASE='{{ borg_pass }}' export BORG_REMOTE_PATH=borg1 export BORG_RSH='ssh -i /root/.ssh/borg -oBatchMode=yes' systemctl stop mayak_nav_bot $BORG create --compression zstd,5 ::'Mayak_{now:%Y-%m-%d_%H%M}' \ /opt/src/mayak_nav/config/photo \ /opt/src/mayak_nav/config/raybot.sqlite $BORG prune --prefix 'Mayak_' --keep-daily=7 --keep-weekly=2 --keep-monthly=3 systemctl start mayak_nav_bot <file_sep>/roles/teleput/templates/backup_teleput.j2 #!/bin/bash set -u -e BORG=/usr/local/bin/borg export BORG_REPO={{ borg_repo }} export BORG_PASSPHRASE='{{ borg_pass }}' export BORG_REMOTE_PATH=borg1 export BORG_RSH='ssh -i /root/.ssh/borg -oBatchMode=yes' systemctl stop teleput $BORG create --compression zstd,5 ::'Teleput_{now:%Y-%m-%d_%H%M}' \ /opt/src/teleput/teleput.sqlite $BORG prune --prefix 'Teleput_' --keep-daily=3 --keep-weekly=1 --keep-monthly=1 systemctl start teleput <file_sep>/roles/stats/files/make_stat.sh #!/bin/sh df -h / echo du --max-depth 1 -h /var/lib/mod_tile | grep 'lonely\|dhr\|smoot\|sur\|osm\|old' du --max-depth 1 -h /var/lib/mod_tile/veloroad/ | sort -k 2 echo top -n 1 -b |head -n 15 <file_sep>/roles/tile_server/files/openstreetmap-tiles-update-expire #!/bin/sh set -e #************************************************************************* #************************************************************************* OSMOSIS_BIN=osmosis OSM2PGSQL_BIN=osm2pgsql OSM2PGSQL_OPTIONS="-S /opt/styles/veloroad/veloroad.style" #OSM2PGSQL_OPTIONS="--flat-nodes /path/to/flatnodes --hstore" REPLAG=/opt/src/mod_tile/osmosis-db_replag TRIM_OSC=/opt/src/regional/trim_osc.py BOUNDS_POLY=/opt/styles/bounds.json BASE_DIR=/var/lib/mod_tile LOG_DIR=/var/log/tiles WORKOSM_DIR=$BASE_DIR/.osmosis LOCK_FILE=/tmp/openstreetmap-update-expire-lock.txt CHANGE_FILE=$BASE_DIR/changes.osc.gz EXPIRY_FILE=$BASE_DIR/dirty_tiles STOP_FILE=$BASE_DIR/stop.txt OSMOSISLOG=$LOG_DIR/osmosis.log PGSQLLOG=$LOG_DIR/osm2pgsql.log EXPIRYLOG=$LOG_DIR/expiry.log RUNLOG=$LOG_DIR/run.log EXPIRY_MINZOOM=10 EXPIRY_MAXZOOM=15 MIN_DISK_SPACE_MB=500 #************************************************************************* #************************************************************************* m_info() { echo "[`date +"%Y-%m-%d %H:%M:%S"`] $$ $1" >> "$RUNLOG" } m_error() { echo "[`date +"%Y-%m-%d %H:%M:%S"`] $$ [error] $1" >> "$RUNLOG" m_info "resetting state" /bin/cp $WORKOSM_DIR/last.state.txt $WORKOSM_DIR/state.txt || true rm "$CHANGE_FILE" || true rm "$EXPIRY_FILE.$$" || true rm "$LOCK_FILE" exit } m_ok() { echo "[`date +"%Y-%m-%d %H:%M:%S"`] $$ $1" >> "$RUNLOG" } getlock() { if [ -s $1 ]; then if [ "$(ps -p `cat $1` | wc -l)" -gt 1 ]; then return 1 #false fi fi echo $$ >"$1" return 0 #true } freelock() { rm "$1" rm "$CHANGE_FILE" } if [ $# -eq 1 ] ; then m_info "Initialising Osmosis replication system to $1" mkdir $WORKOSM_DIR $OSMOSIS_BIN --read-replication-interval-init workingDirectory=$WORKOSM_DIR 1>&2 2> "$OSMOSISLOG" wget "http://osm.personalwerk.de/replicate-sequences/?"$1"T00:00:00Z" -O $WORKOSM_DIR/state.txt else # make sure the lockfile is removed when we exit and then claim it if ! getlock "$LOCK_FILE"; then m_info "pid `cat $LOCK_FILE` still running" exit 3 fi if [ -e $STOP_FILE ]; then m_info "stopped" exit 2 fi #if (( `stat -f --format="%a*%S" $BASE_DIR` < 1024*1024*$MIN_DISK_SPACE_MB )); then if which python > /dev/null; then if python -c "import os, sys; st=os.statvfs('$BASE_DIR'); sys.exit(1 if st.f_bavail*st.f_frsize/1024/1024 > $MIN_DISK_SPACE_MB else 0)"; then m_info "there is less than $MIN_DISK_SPACE_MB MB left" exit 4 fi fi seq=`cat $WORKOSM_DIR/state.txt | grep sequenceNumber | cut -d= -f2` m_ok "start import from seq-nr $seq, replag is `$REPLAG -h`" /bin/cp $WORKOSM_DIR/state.txt $WORKOSM_DIR/last.state.txt m_ok "downloading diff" if ! $OSMOSIS_BIN --read-replication-interval workingDirectory=$WORKOSM_DIR --simplify-change --write-xml-change $CHANGE_FILE 1>&2 2> "$OSMOSISLOG"; then m_error "Osmosis error" fi if [ -e "$BOUNDS_POLY" ]; then m_ok "filtering diff" if ! python3 "$TRIM_OSC" -v -d gis -p "$BOUNDS_POLY" -z $CHANGE_FILE $CHANGE_FILE 1>&2 2>> "$RUNLOG"; then m_error "Trim_osc error" fi fi m_ok "importing diff" EXPIRY_METAZOOM=`expr $EXPIRY_MAXZOOM - 3` if ! $OSM2PGSQL_BIN -a --slim -e$EXPIRY_METAZOOM:$EXPIRY_METAZOOM $OSM2PGSQL_OPTIONS -o "$EXPIRY_FILE.$$" $CHANGE_FILE 1>&2 2> "$PGSQLLOG"; then m_error "osm2pgsql error" fi freelock "$LOCK_FILE" m_ok "expiring tiles" if ! render_expired --min-zoom=$EXPIRY_MINZOOM --max-zoom=$EXPIRY_MAXZOOM --touch-from=$EXPIRY_MINZOOM -s /var/run/renderd.sock < "$EXPIRY_FILE.$$" 2>&1 | tail -8 >> "$EXPIRYLOG"; then m_info "Expiry failed" fi rm "$EXPIRY_FILE.$$" m_ok "Done with import" fi <file_sep>/roles/schedules/files/sotm2019.ini title = State of the Map 2019 slug = sotm2019 url = https://2019.stateofthemap.org/ timezone = +02 <file_sep>/roles/schedules/files/update_schedules.sh #!/bin/bash set -e -u -x WWW=/var/www/sotm HERE="$(cd "$(dirname "$0")"; pwd)" DATA="$HERE/sotm_schedules" VENV="$HERE/sc_venv" BASEURL="https://sotm.osmz.ru" mkdir -p "$DATA" wget -q -r -O "$DATA/f2022.xml" "https://talks.osgeo.org/foss4g-2022/schedule/export/schedule.xml" wget -q -r -O "$DATA/f2022-at.xml" "https://talks.osgeo.org/foss4g-2022-academic-track/schedule/export/schedule.xml" # wget -q -r -O "$DATA/sotm2020-add.csv" 'https://docs.google.com/spreadsheets/d/1EO3aC3vF9dvb1wopT_cUHaDXqdGIrid_Kj59PZyzR_g/export?format=csv&id=0' #sed -i -e 's/Academic Track | Track 2 - Sunday, July 5/Track 2/' "$DATA/sotm2020-at.xml" SC="$VENV/bin/schedule_convert" $SC $DATA/foss4g2022.ini $DATA/f2022.xml $DATA/f2022-at.xml -l "$WWW" "$BASEURL/f2022" <file_sep>/roles/sotm_intro_bot/templates/config.py import os DATABASE = os.path.join(os.path.dirname(__file__), 'intros.sqlite') API_TOKEN = '{{ sotm_intro_bot_token }}' ADMIN_ID = {{ sotm_intro_admin_id }} <file_sep>/roles/sotm_intro_bot/templates/backup_intros.j2 #!/bin/bash set -u -e BORG=/usr/local/bin/borg export BORG_REPO={{ borg_repo }} export BORG_PASSPHRASE='{{ borg_pass }}' export BORG_REMOTE_PATH=borg1 export BORG_RSH='ssh -i /root/.ssh/borg -oBatchMode=yes' systemctl stop sotm_intro_bot $BORG create --compression zstd,5 ::'SotmIntro_{now:%Y-%m-%d_%H%M}' \ /opt/src/sotm_intro_bot/intros.sqlite $BORG prune --prefix 'SotmIntro_' --keep-daily=7 --keep-weekly=2 --keep-monthly=3 systemctl start sotm_intro_bot <file_sep>/roles/schedules/files/hot2019.ini title = HOT Summit 2019 slug = hotosm2019 url = https://summit2019.hotosm.org/ timezone = +02 <file_sep>/roles/hitrye/templates/backup_hitrye.j2 #!/bin/bash set -u -e BORG=/usr/local/bin/borg export BORG_REPO={{ borg_repo }} export BORG_PASSPHRASE='{{ borg_pass }}' export BORG_REMOTE_PATH=borg1 export BORG_RSH='ssh -i /root/.ssh/borg -oBatchMode=yes' DBDUMP=/var/tmp/hitrye.sql pg_dump -U phpbb --format=c --file=$DBDUMP hitrye $BORG create --compression zstd,5 ::'Hitrye_{now:%Y-%m-%d_%H%M}' \ $DBDUMP \ /var/www/hitrye/files \ /var/www/hitrye/images/avatars/upload $BORG prune --prefix 'Hitrye_' --keep-daily=7 --keep-weekly=2 --keep-monthly=3 rm $DBDUMP <file_sep>/roles/schedules/files/foss4g2022.ini title = FOSS4G 2022 slug = f2022 url = https://2022.foss4g.org/schedule_general.php timezone = +02 <file_sep>/Vagrantfile Vagrant.configure(2) do |config| # config.vm.box = "ubuntu/xenial64" config.vm.box = "nrclark/xenial64-minimal-libvirt" config.vm.host_name = "tile" config.vm.network "forwarded_port", guest: 80, host: 8080 config.ssh.insert_key = false config.vm.provision "ansible" do |ansible| ansible.force_remote_user = false ansible.verbose = "v" ansible.playbook = "playbook.yml" end end <file_sep>/roles/schedules/files/index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>State of the Map XML Schedules</title> <style> html { margin: 0; } body { font-family: sans-serif; font-size: 16px; background: #ddd; margin: 0; } #content { max-width: 700px; background: #f1f1f1; color: #111; margin: 0 auto; padding: 1em 1em 2em; } .link { margin: 1em 0; font-size: 20px; } </style> </head> <body> <div id="content"> <h1>Schedules</h1> <p>Please head on to the conference you're planning to visit:</p> <div class="link"><a href="f2022.html">FOSS4G 2022</a></div> </div> </body> </html> <file_sep>/roles/get_veloroad/files/nik4wsgi_config.py PYTHON = 'python3.5' NIK4 = '/opt/src/Nik4/nik4.py' STYLES = [ ['veloroad', 'Veloroad Ru', '/opt/styles/veloroad/veloroad-r.xml', True], ['veloroaden', 'Veloroad', '/opt/styles/veloroad/veloroad-en.xml', True], ['osm', 'OSM-Carto', '/opt/styles/osm-carto/osm-r.xml', False], ] TILES = { 'veloroad': ['http://tile.osmz.ru/veloroad/{z}/{x}/{y}.png', 'Map &copy; OpenStreetMap | Tiles &copy <NAME>'], 'veloroaden': ['http://tile.osmz.ru/veloroad/{z}/{x}/{y}.png', 'Map &copy; OpenStreetMap | Tiles &copy <NAME>'], 'osm': ['https://tile.openstreetmap.org/{z}/{x}/{y}.png', 'Map &copy; OpenStreetMap'], } <file_sep>/upload_pbf.sh #!/bin/bash [ $# -lt 1 ] && echo "Usage: $0 <planet.pbf> [<bounds.json>]" && exit 1 #ansible-playbook upload_pbf.yml -i hosts -e "pbf=$1" ${2+-e "bounds=$2"} ansible-playbook upload_pbf.yml -i hosts -e "pbf=$1" ${2+-e "bounds=$2"} --skip-tags osm2pgsql <file_sep>/roles/schedules/files/sotm2022.ini title = State of the Map 2022 slug = sotm2022 url = https://2022.stateofthemap.org/ timezone = +02
f97dde28717f0a99ce6b14622a6a958dac446c03
[ "Ruby", "HTML", "INI", "Python", "Shell" ]
28
Python
Zverik/ansible-tile
d0ac0c2485cea03de458b3acabd73efc1ee6e341
ad16a9b1967b1c5acb696c04b29d549203b549e5
refs/heads/master
<file_sep>from socket import * from datetime import datetime import select, sys def broadcast(sock, msg):#send to all except server and sender for s in connections: if s != servSocket and s != sock: try: s.send(msg.rstrip('\n')) except: s.close() connections.remove(s) del usernames[s] del userData[s] def command(msg, sock): commands = ['quit', 'name', 'whois', 'time', 'help'] cmdLine = msg[1:].split() cmdLine[0] = cmdLine[0].lower() if cmdLine[0] in commands: if cmdLine[0] == 'name': nameHolder = usernames[sock] if cmdLine[1] in usernames.values(): resp = 'SERVER: ' + cmdLine[1] + ' is already in use' sock.send(resp.rstrip('\n')) else: usernames[sock] = cmdLine[1] resp = '**' + nameHolder + ' changed their username to ' +cmdLine[1] + '**' broadcast(sock, resp) elif cmdLine[0] == 'help': for i in commands: resp = ' /' + i sock.send(resp) elif cmdLine[0] == 'time': resp = 'SERVER: [%s:%s:%s.%s]' % (datetime.now().hour, datetime.now().minute, datetime.now().second, datetime.now().microsecond) sock.send(resp.rstrip('\n')) elif cmdLine[0] == 'quit': connections.remove(sock) resp = '**' + usernames[sock] + ' is now OFFLINE**' broadcast(sock, resp) del usernames[sock] del userData[sock] sock.close() elif cmdLine[0] == 'whois': if cmdLine[1] in usernames.values(): for s in usernames: if usernames[s] == cmdLine[1]: resp = 'SERVER: ' + cmdLine[1] + ' is ' + str(userData[s]) sock.send(resp.rstrip('\n')) else: resp = cmdLine[1] + ' is not connected to this server' sock.send(resp.rstrip('\n')) else: resp = 'functionality not available' sock.send(resp.rstrip('\n')) else: resp = '**command not recognized**' sock.send(resp.rstrip('\n')) servPort = int(raw_input('Enter port: ')) servSocket = socket(AF_INET, SOCK_STREAM) servSocket.bind(('', servPort)) servSocket.listen(10) print 'Server is ready on port ' + str(servPort) connections = [] usernames = {} userData = {} connections.append(servSocket) try: while 1: read_sockets, write_sockets, error_sockets = select.select(connections, [], []) for s in read_sockets: if s == servSocket: connSock, addr = servSocket.accept() connections.append(connSock) usernames[connSock] = str(addr) userData[connSock] = addr resp = '**[%s | %s] is now ONLINE**' % addr connSock.send('SERVER: You are now connected to the chat server\ntype /help for a list of usable commands') broadcast(connSock, resp) else: try: msg = s.recv(4096) if msg: if msg == '/': s.send('SERVER: usage is /<command>') elif msg[0] == '/': command(msg, s) else: resp = '%s: %s' % (usernames[s], msg) print resp broadcast(s, resp) except: resp = '**[%s | %s] is now OFFLINE**' % userData[s] broadcast(s, resp) s.close() connections.remove(s) del usernames[s] del userData[s] continue except KeyboardInterrupt: servSocket.close() print '\n**server closed**' sys.exit() <file_sep>from socket import * import select, sys servName = raw_input('Enter server host: ') servPort = int(raw_input('Enter port: ')) clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((servName, servPort)) clientSocket.settimeout(2) try: while 1: sockList = [sys.stdin, clientSocket] read_sockets, write_sockets, error_sockets = select.select(sockList, [], []) for s in read_sockets: if s == clientSocket: resp = s.recv(4096) if not resp: print '**you got DISCONNECTED**' clientSocket.close() sys.exit() else: print resp sys.stdout.flush() else: msg = raw_input('') clientSocket.send(msg) sys.stdout.flush if msg.lower() == '/quit': clientSocket.close() print print '**client closed**' sys.exit() except KeyboardInterrupt: clientSocket.send('/quit') clientSocket.close() print print '**client closed**' sys.exit() <file_sep>from socket import * import select, sys def host():#server protocol, called when hosting a chat servPort = int(raw_input('Enter port: ')) servSocket = socket(AF_INET, SOCK_STREAM) servSocket.bind(('', servPort)) servSocket.listen(1) #program is one-to-one only print 'Waiting for a connection...' peerSocket , addr = servSocket.accept() resp = 'You are now in a chat with ' + user peerSocket.send(resp) msg = peerSocket.recv(4096) print msg try: while 1: socketList = [sys.stdin, peerSocket] read_sockets, write_sockets, error_sockets = select.select(socketList, [], []) for sock in read_sockets: if sock == peerSocket: resp = sock.recv(4096) if not resp: #handles sudden disonnection print '\n**you got DISCONNECTED**' servSocket.close() sys.exit() else: print resp sys.stdout.flush() else: msg = raw_input('') if msg.lower() == '/quit': #exit protocol peerSocket.send(user + ' left the chat') #informs peer that user has left print '\n**chat closed**' servSocket.close sys.exit() peerSocket.send(user + ': ' + msg.rstrip('\n')) #as per class protocol, all messages must not have a trailing new line sys.stdout.flush() except KeyboardInterrupt: print '\n**chat closed**' servSocket.close sys.exit() def client():#client protocol, called when joining a chat servName = raw_input('Enter server host: ') servPort = int(raw_input('Enter port: ')) clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((servName, servPort)) clientSocket.send('You are now in chat with ' + user) try: while 1: sockList = [sys.stdin, clientSocket] read_sockets, write_sockets, error_sockets = select.select(sockList, [], []) for s in read_sockets: if s == clientSocket: resp = s.recv(4096) if not resp: #handles sudden disconnection print '\n**you got DISCONNECTED**' clientSocket.close() sys.exit() else: print resp sys.stdout.flush() else: msg = raw_input('') if msg.lower() == '/quit': #exit protocol clientSocket.send(user + ' left the chat') clientSocket.close() print '\n**chat closed**' sys.exit() clientSocket.send(user + ': ' + msg.rstrip('\n')) sys.stdout.flush() except KeyboardInterrupt: clientSocket.close() print '\n**chat closed**' sys.exit() user = raw_input('Username: ') print 'What would you like to do?\n(1) Host a chat session\n(2) Join a chat session\n(3) Quit' choice = '0' while choice not in {'1', '2', '3'}: #main menu, handles error in choices choice = raw_input('>: ') if choice == '1': host() elif choice == '2': client() elif choice == '3': print 'App closed' sys.exit() else: print 'Please input 1, 2, or 3' <file_sep># net-for-noobs my beginners networking project
25b649f1166e7243958d8fe8b651a1a3b6de6c3d
[ "Markdown", "Python" ]
4
Python
skgaribay/net-for-noobs
cd1da6e852837a530e25485a9b9a47f10865a354
d7152ece248501c1bd946d37f570429410b9f59c
refs/heads/master
<file_sep>#!/usr/bin/env python import requests import json class Tg: base_url="https://api.telegram.org/bot" def __init__(self, token): self.token = token def send_msg(self,tgid,msg): construct_url=f"{self.base_url}{self.token}/sendMessage" header = {'Content-type': 'application/json'} payload = {"chat_id":tgid,"text":msg} r=requests.post(construct_url,data=json.dumps(payload),headers=header) if r.status_code==200: print("msg send") else: print(r.status_code) print("something goes wrong",r.headers) <file_sep>#!/usr/bin/env python import os from pprint import pprint from datetime import datetime import time import logging from ansible_vault import Vault from ansible.parsing.vault import VaultLib, VaultSecret from ansible.constants import DEFAULT_VAULT_ID_MATCH import waviot import tg logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s', level=logging.DEBUG) def get_creds_vault(vault_file,vault_password): try: vault = Vault(vault_password) secrets = vault.load(open(vault_file).read()) except: err=f"can't decode {vault_file}" print(err) logging.debug(f"ERROR: {err}") sys.exit() #####HACK for ansible version https://github.com/tomoh1r/ansible-vault/pull/34 #vault = VaultLib([(DEFAULT_VAULT_ID_MATCH, VaultSecret(vault_password.encode()))]) #secrets = yaml.safe_load(vault.decrypt(open(vault_file).read())) ##### # print(secrets) return secrets def send_alarm(creds,msg): sender=tg.Tg(creds['tg_token']) chat_id=creds['chat_id'] sender.send_msg(chat_id,msg) #sender.send_msg(,msg) logging.debug(f"send msg to {chat_id} : {msg}") def lk_water_event(tg_token,event): modem=event['modem_id'] event_type=event['event_type'] dec_code=event['code']['decimal'] descr=event['description'] date_time=event['date_time'] if dec_code==40: alarm_msg=(f"{date_time} модем: {modem} событие: {descr} ") print(alarm_msg) send_alarm(tg_token,alarm_msg) def lk_event_parser(tg_token,response): #pprint(response) if response['status']=="ok": for gmt_timestamp,event in response['events'].items(): event_type=event['event_type'] if event_type=='water': lk_water_event(tg_token,event) else: print("error status in response") def helper_list_modems(modems): modem_hex=[] modem_dec=[] for modem in modems.keys(): modem_hex.append(modem) modem_dec.append(str(int(modem,16))) modems_list=[modem_hex,modem_dec] return modems_list #def wa_search_water def roll_event_parser(response,significant_diff): significant_diff=float(significant_diff) alarms=[] alarm={} for modem in response.keys(): prev_value=0 for record in response[modem]: if record['protocol']=='water7': current_value=record['data']['0']['value'] timestamp=record['timestamp'] alarm_key=f'{timestamp}-{modem}' diff=prev_value-current_value if round(current_value)>=20: alarm[alarm_key]={'timestamp':timestamp,'modem_id':modem,'value':current_value,'state':'За пределами измерений'} #alarms.append(alarm) elif round(current_value)<=4: alarm[alarm_key]={'timestamp':timestamp,'modem_id':modem,'value':current_value,'state':'За пределами измерений'} #alarms.append(alarm) elif diff>significant_diff: alarm[alarm_key]={'timestamp':timestamp,'modem_id':modem,'value':current_value,'state':'Падение давления'} #alarms.append(alarm) elif current_value<5: alarm[alarm_key]={'timestamp':timestamp,'modem_id':modem,'value':current_value,'state':'Давление меньше 1бар'} elif current_value>7: alarm[alarm_key]={'timestamp':timestamp,'modem_id':modem,'value':current_value,'state':'Давление больше уставки '} logging.debug(f"modem {modem} event water7 timestamp:{timestamp}, current_value: {current_value}, prev_value: {prev_value}, diff: {diff}") prev_value=current_value elif record['protocol']=='water6': #and record['tag']=='water6.pair.1': code=record['payload'][-8:-4] timestamp=record['timestamp'] alarm_key=f'{timestamp}-{modem}' if code=='0028': alarm[alarm_key]={'timestamp':timestamp,'modem_id':modem,'value':'протечка','state':'Замыкание контактов'} #alarms.append(alarm) logging.debug(f"event water6 timestamp:{timestamp}, code: {code}") else: print(f"no parser for proto {record['data']}") logging.debug(f"no parser for proto {record['data']}") return alarm def alarm_manage(creds,alarms,modems): #pprint(modems) utc_offset=10800 for key,alarm in alarms.items(): alarm_modem_id=hex(int(alarm['modem_id']))[2:] date_time=datetime.utcfromtimestamp(alarm['timestamp']+utc_offset).strftime('%Y-%m-%d %H:%M:%S') modem_name=modems[alarm_modem_id]['elem_name'] temperature=modems[alarm_modem_id]['temperature'] max_pr=16 #max I for presure sensor pressure=((alarm['value']-4)/16)*max_pr alarm_message=f"{date_time} модем: {alarm_modem_id} ({alarm['modem_id']})) температура: {temperature}\n Место установки: {modem_name} событие: {alarm['state']} ({pressure:.2f}бар) - ток {alarm['value']}" if alarm_modem_id!='7a48ad': send_alarm(creds,alarm_message) def main(): now_date=int(datetime.now().timestamp()) readabledate=datetime.utcfromtimestamp(now_date+10800).strftime('%Y-%m-%d %H:%M:%S') old_date=int(datetime.now().timestamp())-3600 print(f"run {now_date}") logging.debug(f"run {now_date}({readabledate})") vault_pass=os.getenv('VAULT',default='unknown') try: creds=get_creds_vault(os.path.dirname(os.path.abspath(__file__))+'/secret1.yml',vault_pass) except OSError as e: err=f"cant'open secret file {e}" logging.debug(f"ERROR: {err}") print(err) sys.exit(e.errno) wa=waviot.Waviot(creds['login'],creds['password']) wa.get_login() #$modems=wa.get_modems_intree('827132') modems=wa.get_modems_intree('195984') mlist=helper_list_modems(modems) get_values=wa.get_request(f"https://api.waviot.ru/api/roll?modem_id={','.join(mlist[1])}&from={old_date}&to={now_date}") #response=wa.get_request("https://lk.waviot.ru/api.data/get_events/?modem_id=721D7C,7A48AC&from=1614187030&to=1614188330") #wa.print_raw_response() #wa.print_response_roll() alarms=roll_event_parser(get_values,0.5) alarm_manage(creds,alarms,modems) #lk_event_parser(creds['tg_token'],response) if __name__=="__main__": logging.debug(f"==============START==================") while True: main() time.sleep(1800) <file_sep>#!/usr/bin/env python import requests import json def get_login(inlogin,inpass): WAVIOT_JWT=False payload = {"login":inlogin,"password":<PASSWORD>} header = {'Content-type': 'application/json','X-requested-with': 'XMLHttpRequest'} r=requests.post('https://auth.waviot.ru/?action=user-login',data=json.dumps(payload),headers=header) if r.status_code==200: try: WAVIOT_JWT=json.loads(r.text)['WAVIOT_JWT'] print(WAVIOT_JWT) except: print("no WAVIOT_JWT") else: print(r.status_code) print("something goes wrong",r.headers) return WAVIOT_JWT def get_request(url,JWT): header = {'Content-type': 'application/json', 'X-requested-with': 'XMLHttpRequest', 'Authorization': 'bearer ' + JWT } r=requests.get(url,headers=header) if r.status_code==200: try: response=json.loads(r.text) except: print("no response") else: print("error",r.status_code) print("something goes wrong",r.headers) return response def parse_response_roll(injson): for modem in injson: print(modem) for record in injson[modem]: print("NEW RECORD\n {} \n===========\n".format(record)) try: print("timestamp: {}, snr: {}, rssi: {}".format( record['timestamp'], record['snr'],record['rssi'])) except: print("no") try: for sensor in record['data'].values(): print("sensor:{},value:{}".format(sensor['name'],sensor['value'])) print("\n==========\n") except: print ("no") return True if __name__=="__main__": murl='https://api.waviot.ru/api/roll?modem_id=8013997&limit=10' login="" passw="" JWT=get_login(login,passw) resp=get_request(murl,JWT) parse_response_roll(resp) <file_sep>ansible==4.2.0 ansible-base==2.10.6 ansible-vault==2.1.0 certifi==2022.12.7 cffi==1.14.5 chardet==4.0.0 cryptography==3.4.6 idna==2.10 Jinja2==2.11.3 MarkupSafe==1.1.1 packaging==20.9 pkg-resources==0.0.0 pycparser==2.20 pyparsing==2.4.7 PyYAML==5.4.1 requests==2.25.1 urllib3>=1.26.5 <file_sep># waviot-api <file_sep>#!/usr/bin/env python import requests import json from pprint import pprint class Waviot: login_url='https://auth.waviot.ru/?action=user-login' get_tree_url='https://lk.waviot.ru/api.tree/get_tree/' get_modems_url='https://lk.waviot.ru/api.tree/get_modems/' def __init__(self, login, password): self.login = login self.password = <PASSWORD> def get_login(self): WAVIOT_JWT=False payload = {"login":self.login,"password":self.<PASSWORD>} header = {'Content-type': 'application/json','X-requested-with': 'XMLHttpRequest'} r=requests.post(self.login_url,data=json.dumps(payload),headers=header) if r.status_code==200: try: WAVIOT_JWT=json.loads(r.text)['WAVIOT_JWT'] #print(WAVIOT_JWT) self.WAVIOT_JWT=WAVIOT_JWT except: print("no WAVIOT_JWT") else: print(r.status_code) print("something goes wrong",r.headers) #return WAVIOT_JWT def get_request(self,url): #print(url) header = {'Content-type': 'application/json', 'X-requested-with': 'XMLHttpRequest', 'Authorization': 'bearer ' + self.WAVIOT_JWT} r=requests.get(url,headers=header) if r.status_code==200: try: reqresponse=json.loads(r.text) self.response=reqresponse except: print(f"no response {r.text}") else: print("error",r.status_code) print("something goes wrong - headers:\n",r.headers) return reqresponse def print_raw_response(self): print(self.response) def print_response_roll(self): for modem in self.response: print(f"---{modem}---") for record in self.response[modem]: print("===== NEW RECORD {} =======\n {} \n===========\n".format(record['protocol'],record)) try: print("timestamp: {}, snr: {}, rssi: {}, station: {}".format( record['timestamp'], record['snr'],record['rssi'],record['station_id'])) except: print("no") if record['protocol']=='water7': try: for sensor in record['data'].values(): print("sensor:{},value:{}".format(sensor['name'],sensor['value'])) print("\n==========\n") except: print ("no") elif record['protocol']=='water6': code=record['payload'][-8:-4] print(code) else: print(f"no parser for proto {record['data']}") print("----------------") return True def get_subtree(self,elem_id): url=f'{self.get_tree_url}?id={elem_id}' reqresponse=self.get_request(url) subtree={} if reqresponse.get('tree')!=None: subtree=reqresponse['tree'] return subtree def get_modems_inelem(self,elem_dict): elem_id=elem_dict['id'] url=f'{self.get_modems_url}?id={elem_id}' reqresponse=self.get_request(url) modems={} if reqresponse.get('modems')!=None: for modem in reqresponse.get('modems'): modems[modem['id']]={'flavor_id':modem['flavor_id'], 'temperature':modem['temperature'], 'battery':modem['battery'], 'elem_name':elem_dict['name'], 'elem_type':elem_dict['type'] } return modems def get_modems_intree(self,elem_id): elements=self.get_subtree(elem_id) modems={} for element in elements.values(): modems.update(self.get_modems_inelem(element)) return modems
1261fa6ad5b31b9fad71487f7c7f4208ae7c62e4
[ "Markdown", "Python", "Text" ]
6
Python
gorbushka/waviot-api
09a7d4d476143598d690a230118aa0e16b0cb311
a4362bedc2eedcb5b2296f1dac2c80ca7b2fa1dd
refs/heads/master
<file_sep>from random import randint import numpy as np import pandas as pd import matplotlib.pyplot as plt min_ruleta = 0 max_ruleta = 36 numeros_ruleta = 37.0 verde = 0 max_tiradas = 35 corridas_programa = 10 estrategia_multiplicador = { 'rojos': 2, 'pares': 2, 'docenas': 3, 'columnas': 3, 'pleno': 35, } def get_pares(pares, i): if i%2 == 0: pares.append(i) return pares def get_impares(impares, i): if i%2 != 0: impares.append(i) return impares def get_docenas(docenas, i): if i<=12: docenas[0].append(i) elif i>12 and i<= 24: docenas[1].append(i) elif i>24: docenas[2].append(i) return docenas def get_columnas(columnas): col_in = 1 while col_in <= 34: columnas[0].append(col_in) col_in = col_in+3 col_in = 2 while col_in <= 35: columnas[1].append(col_in) col_in = col_in+3 col_in = 3 while col_in <= 36: columnas[2].append(col_in) col_in = col_in+3 return columnas def ini_ruleta(): rojos = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36] negros = [2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35] pares = [] impares = [] docenas = [[],[],[]] columnas = [[],[],[]] columnas = get_columnas(columnas) for i in range(1,int(numeros_ruleta)): pares = get_pares(pares, i) impares = get_impares(impares, i) docenas = get_docenas(docenas, i) valores_ruleta = { 'rojos': rojos, 'negros': negros, 'pares': pares, 'impares': impares, 'docenas': docenas, 'columnas': columnas, } return valores_ruleta def girar_ruleta(): tiros = randint(5, 150) for i in range(0,tiros): resultado = randint(min_ruleta, max_ruleta) return resultado def get_apuesta_deseada(fondos): apuesta_validada = -1 while (apuesta_validada < 0 or apuesta_validada > fondos): apuesta_deseada = float(input("Ingresa tu apuesta: $")) if (apuesta_deseada > 0 and apuesta_deseada <= fondos): apuesta_validada = apuesta_deseada return apuesta_deseada def get_lista_resultados_deseados(): resultados_deseados = [] resultados_deseados_validado = -1 while (resultados_deseados_validado < 0 or resultados_deseados_validado > max_ruleta): res_des = int(input("Resultado deseado: ")) resultados_deseados.append(res_des) if (resultados_deseados[0] > 0 and resultados_deseados[0] <= max_ruleta): resultados_deseados_validado = resultados_deseados[0] return resultados_deseados def apuesta_simple(capital_inicial, apuesta_actual, resultados_deseados, multiplicador): resultados = [] fondos = capital_inicial conteo_giros = 0 while conteo_giros < max_tiradas: if fondos < apuesta_actual: resultados.append({'valor': None, 'caja': fondos}) else: fondos -= apuesta_actual resultado_obtenido = girar_ruleta() if (resultado_obtenido in resultados_deseados): fondos+= apuesta_actual*multiplicador resultados.append({'valor': resultado_obtenido, 'caja': fondos}) conteo_giros += 1 return resultados def martin_gala(fondos, apuesta_base, resultados_deseados, multiplicador): resultados = [] apuesta_actual = apuesta_base conteo_giros = 0 while conteo_giros < max_tiradas: if fondos < apuesta_actual: resultados.append({'valor': None, 'caja': fondos}) else: fondos = fondos - apuesta_actual resultado_obtenido = girar_ruleta() if (resultado_obtenido in resultados_deseados): premio = apuesta_actual*multiplicador fondos = fondos + premio apuesta_actual = apuesta_base else: apuesta_actual = apuesta_actual * 2 resultados.append({'valor': resultado_obtenido, 'caja': fondos}) conteo_giros += 1 return resultados # En la fibonacci, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... def calcular_fib(n): if n < 2: return n else: return calcular_fib(n-1) + calcular_fib(n-2) def fibonacci(fondos, apuesta_base, resultados_deseados, multiplicador): resultados_fibo = [] apuesta_actual = apuesta_base fib_index_actual = 1 valor_fib_actual = 1 conteo_giros = 0 while conteo_giros < max_tiradas: if fondos < apuesta_actual: resultados_fibo.append({'valor': None, 'caja': fondos}) else: fondos = fondos - apuesta_actual resultado_obtenido = girar_ruleta() if (resultado_obtenido in resultados_deseados): premio = apuesta_actual*multiplicador fondos = fondos + premio if fib_index_actual < 2: fib_index_actual = 1 else: fib_index_actual = fib_index_actual - 1 valor_fib_actual = calcular_fib(fib_index_actual) apuesta_actual = apuesta_base * valor_fib_actual else: fib_index_actual = fib_index_actual + 1 valor_fib_actual = calcular_fib(fib_index_actual) apuesta_actual = apuesta_base * valor_fib_actual resultados_fibo.append({'valor': resultado_obtenido, 'caja': fondos}) conteo_giros += 1 return resultados_fibo def start_ruleta(ruleta): # ingreso fondos y valido, si es 0 el capital tiene que ser infinito fondos = float(input("Ingrese el capital total (0, si desea capital infinito): $")) while fondos < 0: fondos = float(input("Ingrese el capital total: ")) if fondos == 0: fondos = 99999999999 # ingreso y valido cantidad a apostar. apuesta_actual = get_apuesta_deseada(fondos) pleno_deseado = get_lista_resultados_deseados() # ingreso estrategia de apuesta resultados_deseados_rojos = [] resultados_rojos_as = [] resultados_rojos_mg = [] resultados_rojos_fi = [] resultados_deseados_pares = [] resultados_pares_as = [] resultados_pares_mg = [] resultados_pares_fi = [] resultados_deseados_docenas = [] resultados_docenas_as = [] resultados_docenas_mg = [] resultados_docenas_fi = [] resultados_deseados_columnas = [] resultados_columnas_as = [] resultados_columnas_mg = [] resultados_columnas_fi = [] resultados_deseados_plenos = [] resultados_plenos_as = [] resultados_plenos_mg = [] resultados_plenos_fi = [] for i in range(0, corridas_programa): resultados_deseados = ruleta.get('rojos') ap = apuesta_simple(fondos, apuesta_actual, resultados_deseados, estrategia_multiplicador.get('rojos')) mg = martin_gala(fondos, apuesta_actual, resultados_deseados, estrategia_multiplicador.get('rojos')) fi = fibonacci(fondos, apuesta_actual, resultados_deseados, estrategia_multiplicador.get('rojos')) resultados_deseados_rojos.append(resultados_deseados) resultados_rojos_as.append(ap) resultados_rojos_mg.append(mg) resultados_rojos_fi.append(fi) resultados_deseados = ruleta.get('pares') ap = apuesta_simple(fondos, apuesta_actual, resultados_deseados, estrategia_multiplicador.get('pares')) mg = martin_gala(fondos, apuesta_actual, resultados_deseados, estrategia_multiplicador.get('pares')) fi = fibonacci(fondos, apuesta_actual, resultados_deseados, estrategia_multiplicador.get('pares')) resultados_deseados_pares.append(resultados_deseados) resultados_pares_as.append(ap) resultados_pares_mg.append(mg) resultados_pares_fi.append(fi) resultados_deseados = ruleta.get('docenas')[0] ap = apuesta_simple(fondos, apuesta_actual, resultados_deseados, estrategia_multiplicador.get('docenas')) mg = martin_gala(fondos, apuesta_actual, resultados_deseados, estrategia_multiplicador.get('docenas')) fi = fibonacci(fondos, apuesta_actual, resultados_deseados, estrategia_multiplicador.get('docenas')) resultados_deseados_docenas.append(resultados_deseados) resultados_docenas_as.append(ap) resultados_docenas_mg.append(mg) resultados_docenas_fi.append(fi) resultados_deseados = ruleta.get('columnas')[0] ap = apuesta_simple(fondos, apuesta_actual, resultados_deseados, estrategia_multiplicador.get('columnas')) mg = martin_gala(fondos, apuesta_actual, resultados_deseados, estrategia_multiplicador.get('columnas')) fi = fibonacci(fondos, apuesta_actual, resultados_deseados, estrategia_multiplicador.get('columnas')) resultados_deseados_columnas.append(resultados_deseados) resultados_columnas_as.append(ap) resultados_columnas_mg.append(mg) resultados_columnas_fi.append(fi) resultados_deseados = pleno_deseado ap = apuesta_simple(fondos, apuesta_actual, resultados_deseados, estrategia_multiplicador.get('pleno')) mg = martin_gala(fondos, apuesta_actual, resultados_deseados, estrategia_multiplicador.get('pleno')) fi = fibonacci(fondos, apuesta_actual, resultados_deseados, estrategia_multiplicador.get('pleno')) resultados_deseados_plenos.append(resultados_deseados) resultados_plenos_as.append(ap) resultados_plenos_mg.append(mg) resultados_plenos_fi.append(fi) retorno = { 'resultados_deseados_rojos': resultados_deseados_rojos, 'resultados_rojos_as': resultados_rojos_as, 'resultados_rojos_mg': resultados_rojos_mg, 'resultados_rojos_fi': resultados_rojos_fi, 'resultados_deseados_pares': resultados_deseados_pares, 'resultados_pares_as': resultados_pares_as, 'resultados_pares_mg': resultados_pares_mg, 'resultados_pares_fi': resultados_pares_fi, 'resultados_deseados_docenas': resultados_deseados_docenas, 'resultados_docenas_as': resultados_docenas_as, 'resultados_docenas_mg': resultados_docenas_mg, 'resultados_docenas_fi': resultados_docenas_fi, 'resultados_deseados_columnas': resultados_deseados_columnas, 'resultados_columnas_as': resultados_columnas_as, 'resultados_columnas_mg': resultados_columnas_mg, 'resultados_columnas_fi': resultados_columnas_fi, 'resultados_deseados_plenos': resultados_deseados_plenos, 'resultados_plenos_as': resultados_plenos_as, 'resultados_plenos_mg': resultados_plenos_mg, 'resultados_plenos_fi': resultados_plenos_fi, 'fondos': fondos } return retorno def get_fr_obtenida(resultados, resultados_posibles): resultados_filtrados = [] for objeto in resultados: resultados_filtrados.append(objeto.get('valor')) veces_obtenido_resultado_deseado = 0 for x in resultados_posibles: veces_obtenido_resultado_deseado += resultados_filtrados.count(x) cantidad_tiros = len(resultados) return float(float(veces_obtenido_resultado_deseado)/float(cantidad_tiros)) def get_valor_fondos(resultado): fondo = resultado.get('caja') return float(fondo) def graficar(valores_obtenidos, fondos_iniciales): resultados_deseados_rojos = valores_obtenidos.get('resultados_deseados_rojos') resultados_rojos_as = valores_obtenidos.get('resultados_rojos_as') resultados_rojos_mg = valores_obtenidos.get('resultados_rojos_mg') resultados_rojos_fi = valores_obtenidos.get('resultados_rojos_fi') resultados_deseados_pares = valores_obtenidos.get('resultados_deseados_pares') resultados_pares_as = valores_obtenidos.get('resultados_pares_as') resultados_pares_mg = valores_obtenidos.get('resultados_pares_mg') resultados_pares_fi = valores_obtenidos.get('resultados_pares_fi') resultados_deseados_docenas = valores_obtenidos.get('resultados_deseados_docenas') resultados_docenas_as = valores_obtenidos.get('resultados_docenas_as') resultados_docenas_mg = valores_obtenidos.get('resultados_docenas_mg') resultados_docenas_fi = valores_obtenidos.get('resultados_docenas_fi') resultados_deseados_columnas = valores_obtenidos.get('resultados_deseados_columnas') resultados_columnas_as = valores_obtenidos.get('resultados_columnas_as') resultados_columnas_mg = valores_obtenidos.get('resultados_columnas_mg') resultados_columnas_fi = valores_obtenidos.get('resultados_columnas_fi') resultados_deseados_plenos = valores_obtenidos.get('resultados_deseados_plenos') resultados_plenos_as = valores_obtenidos.get('resultados_plenos_as') resultados_plenos_mg = valores_obtenidos.get('resultados_plenos_mg') resultados_plenos_fi = valores_obtenidos.get('resultados_plenos_fi') get_graficos(resultados_rojos_as, resultados_deseados_rojos, "rojos apuesta simple F.I: $"+str(fondos_iniciales)) get_graficos(resultados_rojos_mg, resultados_deseados_rojos, "rojos martin gala F.I: $"+str(fondos_iniciales)) get_graficos(resultados_rojos_fi, resultados_deseados_rojos, "rojos fibonacci F.I: $"+str(fondos_iniciales)) get_graficos(resultados_pares_as, resultados_deseados_pares, "pares apuesta simple F.I: $"+str(fondos_iniciales)) get_graficos(resultados_pares_mg, resultados_deseados_pares, "pares martin gala F.I: $"+str(fondos_iniciales)) get_graficos(resultados_pares_fi, resultados_deseados_pares, "pares fibonacci F.I: $"+str(fondos_iniciales)) get_graficos(resultados_docenas_as, resultados_deseados_docenas, "docenas apuesta simple F.I: $"+str(fondos_iniciales)) get_graficos(resultados_docenas_mg, resultados_deseados_docenas, "docenas martin gala F.I: $"+str(fondos_iniciales)) get_graficos(resultados_docenas_fi, resultados_deseados_docenas, "docenas fibonacci F.I: $"+str(fondos_iniciales)) get_graficos(resultados_columnas_as, resultados_deseados_columnas, "columnas apuesta simple F.I: $"+str(fondos_iniciales)) get_graficos(resultados_columnas_mg, resultados_deseados_columnas, "columnas martin gala F.I: $"+str(fondos_iniciales)) get_graficos(resultados_columnas_fi, resultados_deseados_columnas, "columnas fibonacci F.I: $"+str(fondos_iniciales)) get_graficos(resultados_plenos_as, resultados_deseados_plenos, "plenos apuesta simple F.I: $"+str(fondos_iniciales)) get_graficos(resultados_plenos_mg, resultados_deseados_plenos, "plenos martin gala F.I: $"+str(fondos_iniciales)) get_graficos(resultados_plenos_fi, resultados_deseados_plenos, "plenos fibonacci F.I: $"+str(fondos_iniciales)) def get_graficos(resultados, resultados_posibles, nombre_archivo): lista_de_fr = [] lista_de_fondos = [] #corridas para obtener valores for i in range(0, corridas_programa): lista_de_lista_de_resultados = [] fr_obtenidas = [] fondos_obtenidos = [] for y in range(1, max_tiradas+1): temporal_lista = [] fondos_obtenidos.append(get_valor_fondos(resultados[i][y-1])) #analiza resultados incrementalmente for x in range(0, y): temporal_lista.append(resultados[i][x]) lista_de_lista_de_resultados.append(temporal_lista) fr_obtenidas.append(get_fr_obtenida(lista_de_lista_de_resultados[y-1], resultados_posibles[0])) lista_de_fr.append(fr_obtenidas) lista_de_fondos.append(fondos_obtenidos) #para grafica de resultados tiradas = [] for i in range(1, max_tiradas+1): tiradas.append(i) #armado de graficos get_grafico_fr(tiradas, lista_de_fr, nombre_archivo) get_grafico_fondos(tiradas, lista_de_fondos, nombre_archivo) def get_grafico_fr(tiradas, lista_de_fr, nombre_archivo): df = pd.DataFrame(columns=tiradas, data=lista_de_fr) print(df) names = [] cantidad_de_lineas = len(lista_de_fr) for i in range(0, cantidad_de_lineas): names.append('FR ' + str(i+1)) df = df.set_index([names]) df.T.plot() plt.xlabel("Tiradas") plt.ylabel("Frecuencias relativas") plt.title("Grafico frecuencias relativas "+str(nombre_archivo)) plt.savefig("grafico-fr-relativas-"+str(nombre_archivo)+".svg") def get_grafico_fondos(tiradas, lista_de_valores, nombre_archivo): df = pd.DataFrame(columns=tiradas, data=lista_de_valores) print(df) names = [] cantidad_de_lineas = len(lista_de_valores) for i in range(0, cantidad_de_lineas): names.append('Fondos ' + str(i+1)) df = df.set_index([names]) df.T.plot() plt.xlabel("Numero de tirada") plt.ylabel("Fondo en $") plt.title("Grafico fondos "+str(nombre_archivo)) plt.savefig("grafico-fondos-"+str(nombre_archivo)+".svg") def main(): # creo la ruleta y la inicializo ruleta = ini_ruleta() # inicio el juego valores_obtenidos = start_ruleta(ruleta) fondos = valores_obtenidos.get('fondos') if fondos == 99999999999: fondos = 'infinito' else: fondos = str(fondos) graficar(valores_obtenidos, fondos) if __name__ == "__main__": main()<file_sep>from random import uniform, randint from math import log smalls_list = [20, 20, 20, 20, 40, 40, 40, 60, 60] bigs_list = [40, 60, 80, 100, 60, 80, 100, 80, 100] #int amount = 0 bigs = 0 initial_inv_level = 60 inv_level = 0 next_event_type = 0 num_events = 0 num_months = 120 num_values_demand = 4 smalls = 0 #float area_holding = 0.0 area_shortage = 0.0 holding_cost = 1.0 incremental_cost = 3.0 maxlag = 1.0 mean_interdemand = 0.10 minlag = 0.5 setup_cost = 32.0 shortage_cost = 5.0 time = 0.0 time_last_event = 0.0 total_ordering_cost = 0.0 prob_distrib_demand = [0.0, 0.167, 0.500, 0.833, 1000]; y = 0 time_next_event = []; while (y < 5): time_next_event.append(0.0); y = y+1 def main(): global num_events, next_event_type, smalls, bigs, smalls_list, bigs_list, time num_policies = 9 num_events = 4 print "Single-product inventory system"; print('') print('') print "Initial inventory level items: ", initial_inv_level; print "Number of demand sizes: ", num_values_demand; print "Distribution function of demand sizes: ", prob_distrib_demand[0], " ", prob_distrib_demand[1], " ", prob_distrib_demand[2], " ", prob_distrib_demand[3], " ", prob_distrib_demand[4], " " print "Mean interdemand time: ", mean_interdemand, " months" print "Delivery lag range: ", minlag, " months to ", maxlag, " months" print "Length of the simulation ", num_months, " months" print "K = ", setup_cost, " , i = ", incremental_cost, " , h = ", holding_cost, " , pi = ", shortage_cost print "Number of policies ", num_policies print('') print('') print("Policy ---- Average Total Cost ---- Average ordering cost ---- Average holding cost ---- Average shortage cost ") for i in range(0, num_policies): smalls = smalls_list[i] bigs = bigs_list[i] initialize(); maybe_timing = timing(); while (next_event_type != 3): maybe_timing = timing(); if maybe_timing == -9999999999999999999999999999999: break else: time = maybe_timing update_time_avg_stats(); if next_event_type == 1: order_arrival() elif next_event_type == 2: demand() elif next_event_type == 4: evaluate() report() def initialize(): global time, inv_level, initial_inv_level, time_last_event, total_ordering_cost, area_holding, area_shortage, time_next_event, mean_interdemand, num_months time = 0.0 inv_level = initial_inv_level time_last_event = 0.0 total_ordering_cost = 0.0 area_holding = 0.0 area_shortage = 0.0 time_next_event[0] = 0.0 time_next_event[1] = 1000000000000000000000000000000.0 time_next_event[2] = time + expon(mean_interdemand) time_next_event[3] = num_months time_next_event[4] = 0.0 def order_arrival(): global inv_level, amount, time_next_event inv_level = inv_level + amount time_next_event[1] = 1000000000000000000000000000000.0 def demand(): global prob_distrib_demand, inv_level, time_next_event, time, mean_interdemand size_demand = 0 size_demand = random_integer(prob_distrib_demand) inv_level = inv_level - size_demand time_next_event[2] = time + expon(mean_interdemand) def evaluate(): global inv_level, smalls, bigs, amount, total_ordering_cost, setup_cost, incremental_cost, time_next_event, time, minlag, maxlag if inv_level < smalls: amount = bigs - inv_level total_ordering_cost = total_ordering_cost + setup_cost + (incremental_cost * amount) time_next_event[1] = time + local_uniform(minlag, maxlag) time_next_event[4] = time + 1.0 def report(): global total_ordering_cost, num_months, holding_cost, area_holding, shortage_cost, area_shortage, smalls, bigs avg_holding_cost = 0.0 avg_ordering_cost = 0.0 avg_shortage_cost = 0.0 avg_ordering_cost = total_ordering_cost / num_months avg_holding_cost = holding_cost * area_holding / num_months avg_shortage_cost = shortage_cost * area_shortage / num_months print '(', smalls, ', ', bigs, ') ---- ', avg_ordering_cost + avg_holding_cost + avg_shortage_cost, ' ---- ', avg_ordering_cost, ' ---- ', avg_holding_cost, ' ---- ', avg_shortage_cost def expon(mean): u = uniform(0.0, 1.0) expon_number = -mean * log(u) return expon_number def update_time_avg_stats(): global time, time_last_event, inv_level, area_shortage, area_holding time_since_last_event = 0.0 time_since_last_event = time - time_last_event time_last_event = time if (inv_level < 0): area_shortage = area_shortage - (inv_level * time_since_last_event) elif inv_level > 0: area_holding = area_holding + (inv_level * time_since_last_event) def random_integer(prob_distrib): i = 1 u = 0.0 u = uniform(0, 1) while(u > prob_distrib[i]): i=i+1 return i def local_uniform(a, b): u = 0.0 u = uniform(0, 1) return a + (u * (b-a)) def timing(): global num_events, time_next_event, next_event_type i = 1 min_time_next_event = 100000000000000000000000000000.0 next_event_type = 0 for i in range(1, num_events+1): if time_next_event[i] < min_time_next_event : min_time_next_event = time_next_event[i] next_event_type = i if next_event_type == 3: return -9999999999999999999999999999999 return min_time_next_event; if __name__ == "__main__": main()<file_sep>from random import randint import numpy as np import pandas as pd import matplotlib.pyplot as plt min_ruleta = 0 max_ruleta = 36 numeros_ruleta = 37.0 valor_estadistico_ruleta = 1.0/37.0 valor_promedio_esperado = 37.0/2.0 #fr = frecuencia relativa #vp = valor promedio #vd = valor desvio #vv = valor varianza def girar_ruleta(cantidad_giros): resultados = [] for i in range(0,cantidad_giros): resultado = randint(min_ruleta, max_ruleta) resultados.append(resultado) return resultados def get_fr_esperada(): return valor_estadistico_ruleta def get_vp_esperado(cantidad_giros): return float(valor_promedio_esperado) def get_vd_esperado(cantidad_giros): valores_posibles = [] for i in range(min_ruleta, max_ruleta): valores_posibles.append(i) lista = np.array(valores_posibles) return lista.std() def get_vv_esperado(cantidad_giros): valores_posibles = [] for i in range(min_ruleta, max_ruleta): valores_posibles.append(i) lista = np.array(valores_posibles) return lista.var() def get_fr_obtenida(resultados, resultado_deseado): veces_obtenido_resultado_deseado = resultados.count(resultado_deseado) cantidad_tiros = len(resultados) return float(float(veces_obtenido_resultado_deseado)/float(cantidad_tiros)) def get_vp_obtenido(resultados): sumatoria_valores_obtenidos = 0 for i in resultados: sumatoria_valores_obtenidos+=i return float(float(sumatoria_valores_obtenidos)/float(len(resultados))) def get_vd_obtenido(resultados): lista = np.array(resultados) return lista.std() def get_vv_obtenido(resultados): lista = np.array(resultados) return lista.var() def get_grafico_resultados(tiradas, resultados_deseados, resultados): lista = [] for i in range(0, len(resultados)): element = [] element.append(resultados[i]) element.append(resultados_deseados[i]) element.append(tiradas[i]) lista.append(element) df = pd.DataFrame(columns=['resultados', 'resultados deseados', 'tiradas'], index=tiradas, data=lista) ax1 = df.plot(kind='scatter', x='tiradas', y='resultados deseados', color='r', label="Resultado deseado") ax2 = df.plot(kind='scatter', x='tiradas', y='resultados', color='g', ax=ax1, label="Resultado obtenido") print(df) plt.xlabel("Tiradas") plt.ylabel("Valores") plt.title("Grafico resultados deseados vs obtenidos") plt.savefig("grafico-resultados-"+str(len(tiradas))+".svg") def get_grafico_fr(tiradas, lista_de_fr): df = pd.DataFrame(columns=tiradas, data=lista_de_fr) print(df) names = [] cantidad_de_lineas = len(lista_de_fr) for i in range(0, cantidad_de_lineas): if i == cantidad_de_lineas-1: names.append('Frecuencia relativa esperada') else: names.append('Frecuencia relativa ' + str(i+1) + ' obtenida') df = df.set_index([names]) df.T.plot() plt.xlabel("Tiradas") plt.ylabel("Frecuencias relativas") plt.title("Grafico frecuencias relativas esperadas vs obtenidas") plt.savefig("grafico-fr-relativas-"+str(len(tiradas))+".svg") def get_grafico_vp(tiradas, lista_de_vp): df = pd.DataFrame(columns=tiradas, data=lista_de_vp) print(df) names = [] cantidad_de_lineas = len(lista_de_vp) for i in range(0, cantidad_de_lineas): if i == cantidad_de_lineas-1: names.append('Valor promedio esperado') else: names.append('Valor promedio ' + str(i+1) + ' obtenido') df = df.set_index([names]) df.T.plot() plt.xlabel("Tiradas") plt.ylabel("Valores promedio") plt.title("Grafico valores promedio esperados vs valores promedio obtenidos") plt.savefig("grafico-vp-"+str(len(tiradas))+".svg") def get_grafico_vd(tiradas, lista_de_vd): df = pd.DataFrame(columns=tiradas, data=lista_de_vd) print(df) names = [] cantidad_de_lineas = len(lista_de_vd) for i in range(0, cantidad_de_lineas): if i == cantidad_de_lineas-1: names.append('Valor desvio esperado') else: names.append('Valor desvio ' + str(i+1) + ' obtenido') df = df.set_index([names]) df.T.plot() plt.xlabel("Tiradas") plt.ylabel("Valor del desvio estandar") plt.title("Grafico valores desvio estandar esperados vs obtenidos") plt.savefig("grafico-vd-"+str(len(tiradas))+".svg") def get_grafico_vv(tiradas, lista_de_vv): df = pd.DataFrame(columns=tiradas, data=lista_de_vv) print(df) names = [] cantidad_de_lineas = len(lista_de_vv) for i in range(0, cantidad_de_lineas): if i == cantidad_de_lineas-1: names.append('Valor varianza esperado') else: names.append('Valor varianza ' + str(i+1) + ' obtenido') df = df.set_index([names]) df.T.plot() plt.xlabel("Tiradas") plt.ylabel("Valor de la varianza") plt.title("Grafico valores varianza esperados vs valores varianza obtenidos") plt.savefig("grafico-vv-"+str(len(tiradas))+".svg") def jugar_ruleta(cantidad_giros, resultado_deseado, cantidad_de_corridas_para_comparar): lista_de_resultados = [] lista_de_fr = [] lista_de_vp = [] lista_de_vd = [] lista_de_vv = [] #corridas para obtener valores for i in range(1, cantidad_de_corridas_para_comparar+1): resultados = girar_ruleta(cantidad_giros) lista_de_resultados.append(resultados) lista_de_lista_de_resultados = [] fr_obtenidas = [] vp_obtenidos = [] vd_obtenidos = [] vv_obtenidos = [] for i in range(1, cantidad_giros+1): temporal_lista = [] #analiza resultados incrementalmente for x in range(0, i): temporal_lista.append(resultados[x]) lista_de_lista_de_resultados.append(temporal_lista) fr_obtenidas.append(get_fr_obtenida(lista_de_lista_de_resultados[i-1], resultado_deseado)) vp_obtenidos.append(get_vp_obtenido(lista_de_lista_de_resultados[i-1])) vd_obtenidos.append(get_vd_obtenido(lista_de_lista_de_resultados[i-1])) vv_obtenidos.append(get_vv_obtenido(lista_de_lista_de_resultados[i-1])) lista_de_fr.append(fr_obtenidas) lista_de_vp.append(vp_obtenidos) lista_de_vd.append(vd_obtenidos) lista_de_vv.append(vv_obtenidos) #valores esperados lista_de_lista_de_resultados = [] fr_esperadas = [] vp_esperados = [] vd_esperados = [] vv_esperados = [] for i in range(1, cantidad_giros+1): fr_esperadas.append(get_fr_esperada()) vp_esperados.append(get_vp_esperado(i)) vd_esperados.append(get_vd_esperado(i)) vv_esperados.append(get_vv_esperado(i)) lista_de_fr.append(fr_esperadas) lista_de_vp.append(vp_esperados) lista_de_vd.append(vd_esperados) lista_de_vv.append(vv_esperados) #para grafica de resultados tiradas = [] resultados_deseados = [] for i in range(1, cantidad_giros+1): tiradas.append(i) resultados_deseados.append(resultado_deseado) lista_de_resultados.append(resultados_deseados) #armado de graficos get_grafico_resultados(tiradas, resultados_deseados, resultados) get_grafico_fr(tiradas, lista_de_fr) get_grafico_vp(tiradas, lista_de_vp) get_grafico_vd(tiradas, lista_de_vd) get_grafico_vv(tiradas, lista_de_vv) def main(): cantidad_giros = int(input("Ingrese la cantidad de giros para la ruleta: ")) resultado_deseado_verificado = -1 while(resultado_deseado_verificado<0 or resultado_deseado_verificado>36): resultado_deseado = int(input("Ingrese el resultado deseado para la ruleta (entre 0 y 36): ")) if resultado_deseado > 0 or resultado_deseado < 36: resultado_deseado_verificado = resultado_deseado cantidad_de_corridas_para_comparar = int(input("Ingrese la cantidad de corridas para la ruleta: ")) jugar_ruleta(cantidad_giros, resultado_deseado_verificado, cantidad_de_corridas_para_comparar) if __name__ == "__main__": main()<file_sep>from random import uniform from math import log def expon(mean): u = uniform(0.0, 1.0) expon_number = -mean * log(u) return expon_number queue_limit = 100; busy = 1; idle = 0; num_events = 2; #mean interarrival time mean_interarrival = 1 ; #mean service time mean_service = 0.5; #number of customers num_delays_required = 1000; next_event_type = 0; time_next_event = [0, 0, 0]; x = 0 time_arrival = []; while (x < queue_limit): time_arrival.append(0); x = x+1 time = 0.0; server_status = idle; num_in_q = 0; time_last_event = 0.0; num_custs_delayed = 0; total_of_delays = 0.0; area_num_in_q = 0.0; area_server_status = 0.0; time_next_event[1] = time + expon(mean_interarrival) time_next_event[2] = 1000000000000000000000000000000.0; def main(): global num_custs_delayed, num_delays_required, time, next_event_type, total_of_delays, area_num_in_q, area_server_status while num_custs_delayed < num_delays_required: maybe_time = timing() if (maybe_time == -9999999999999999999999999999999) : return time = maybe_time update_time_avg_stats() if next_event_type == 1: arrive() elif next_event_type == 2: depart() report() def timing(): global num_events, time_next_event, next_event_type i = 1 min_time_next_event = 100000000000000000000000000000.0 next_event_type = 0 for i in range(1, num_events+1): if time_next_event[i] < min_time_next_event : min_time_next_event = time_next_event[i] next_event_type = i if next_event_type == 0: return -9999999999999999999999999999999 return min_time_next_event; def update_time_avg_stats(): global time_last_event, area_num_in_q, area_server_status, time, num_in_q time_since_last_event = 0.0 time_since_last_event = time - time_last_event time_last_event = time; area_num_in_q += num_in_q * time_since_last_event area_server_status += server_status * time_since_last_event def arrive(): global server_status, time_next_event, time, mean_interarrival, server_status, busy, num_in_q, queue_limit, time_arrival, total_of_delays, num_custs_delayed, mean_service delay = 0.0 time_next_event[1] = time + expon(mean_interarrival) if (server_status == busy): num_in_q = num_in_q + 1 if (num_in_q > queue_limit): print('Overflow of the array time_arrival at') print('Time: ', time) return time_arrival[num_in_q] = time else: delay = 0.0 total_of_delays += delay num_custs_delayed = num_custs_delayed + 1 server_status = busy time_next_event[2] = time + expon(mean_service) def depart(): global time_arrival, num_in_q, server_status, time_next_event, total_of_delays, num_custs_delayed, time, time_arrival, mean_service i = 1 delay = 0.0 if(num_in_q == 0): server_status = idle time_next_event[2] = 1000000000000000000000000000000.0 else: num_in_q = num_in_q - 1 delay = time - time_arrival[1] total_of_delays += delay num_custs_delayed = num_custs_delayed + 1 time_next_event[2] = time + expon(mean_service) for i in range(1, num_in_q+1) : time_arrival[i] = time_arrival[i+1] def report(): global total_of_delays, num_custs_delayed, area_num_in_q, area_server_status, time print() print() if num_custs_delayed == 0: print('Average delay in queue in minutes: 0') else: print('Average delay in queue in minutes: ', total_of_delays / num_custs_delayed) print() print() if time == 0 or time == 0.0: print('Average number in queue: 0') print() print() print('Server utilization: 0') else: print('Average number in queue: ', area_num_in_q / time) print() print() print('Server utilization: ', area_server_status / time) print() print() print('Time simulation ended: ', time) print('-------------------------------------------------') if __name__ == "__main__": main()
985d0ac38571b1e696da4465d4ba9d2c7c92ccc7
[ "Python" ]
4
Python
oberruti/Simulacion
ff78818aff0c68db2e37e77e88ef225e234614bd
0c8b195b814e20a7a2813637bdf87f590e9a1c62
refs/heads/master
<file_sep># <font color='blue'>Overview - Add code below</font> ## <font color='red'>About NFL - Add code below</font> ### The National Football League America's most popular sports league, comprised of 32 franchises that compete each year to win the Super Bowl, the world's biggest annual sporting event. Founded in 1920, the NFL developed the model for the successful modern sports league, including national and international distribution, extensive revenue sharing, competitive excellence, and strong franchises across the country. ### Since 1960, Super Bowl is held as an annual championship game of the National Football League (NFL) played between mid-January and early February. It is the culmination of a regular season that begins in the late summer of the previous year ### In this project, we used ETL (Extract, Transform, Load) database functions to observe Superbowl history from 1967 to 2020. We tried to determine the trend for the annual MVP of the game by analysing the MVP's physical attributes such as average weight, height and age. We also look if # Data Source: Kaggle ## <font color='red'>EXTRACT - Add code below</font> ### Read the data from multiple source ### 1. CSV from Kaggle ### 2. coordinates from ### Extract coordinates from Google API ## Using base url: https://maps.googleapis.com/maps/api/place/nearbysearch/json/data/2.5/history/city?q={city ID},{country code}&type=hour&start={start}&end={end} ## Clean Up Process involved: ### 1. Removing duplicates ### 2. Removing NaN's ### 3. Dropping columns ### 4. Re assign ID ### 5. Assign numeric ### 6. Sorted data frame based on date to assign a numeric ID ### 7. Function to convert to a roman numeral number ### 8. Rename columns to match database and prepare for join ## <font color='red'>TRANSFORM</font> ### 1. Converting weight into float, height into integer from players DB. ### 2. After both tables were merged we discovered there was still duplicate players that matched the same name as the mvp winner. ### 3. Sorted data frame based on date to assign a numeric ID ### 4. Function to convert to a roman numeral number ### 5. After both databases were joined we had to calculate the mvp's player age at the time of the Superbowl win. ### 6. Create a player max value function that would filter out players with the same name as mvp that were born prior to the super bowl date. Also within that function we will assign a different unique ID to these selected players. This allowed us to match the superbowl mvp player data with the most accuracy given the information we have. ## <font color='red'>LOAD</font> ### 1. A heatmap was created to visualize all of the places where a Superbowl event was hosted from 1967-2020 using a google places API. ### 2. We selected this to show different facts from Superbowl venue statistics. ### 3. We determined that a majority of Superbowls took place in warm sunny locations and conditions. ### database name: nfl_db <file_sep>CREATE TABLE superbowl ( id integer NOT NULL PRIMARY KEY, superbowl text, superbowl_date date, winner varchar(100), loser varchar(100), score varchar(10), mvp varchar(100), city varchar(50), state varchar(50), stadium varchar(100), lat numeric(11,8), lng numeric(11,8) )<file_sep># API Key(s) # Google API Key g_key = "" # Database(s) # Postgres SQL DB user & password db_user = "postgres" db_password = ""<file_sep>CREATE TABLE players ( player_id integer NOT NULL PRIMARY KEY, name varchar(100), position varchar(50), height varchar(10), height_inch numeric(7,2), weight numeric(7,2), current_team varchar(100), birth_date date ) <file_sep>Create View superbowl_player_view As SELECT SB.id, SB.superbowl, SB.superbowl_date, SB.winner, SB.loser, SB.score, SB.mvp, SB.city, SB.state, SB.stadium, SB.lat, SB.lng, PL.player_id, PL.name, PL."position", PL.height, PL.height_inch, PL.weight, PL.current_team, PL.birth_date FROM public.superbowl SB Left Outer Join players as PL On (SB.mvp = PL.name And SB.superbowl_date > PL.birth_date And PL.player_id = (Select max(player_id) from players where name = PL.name)) Order by SB.id
ad4f1f6ab1c6241d6c5d0693d8d30d5cb4fdc5d9
[ "Markdown", "SQL", "Python" ]
5
Markdown
malisum/etl_proj_w13
8bf156dbda6bf10a419d670a770d3949ee32afae
1df9a6d5ff29620274a813b7eb148c018a071ee2
refs/heads/master
<repo_name>kikkoooo/CCS-Pool<file_sep>/scripts/app.js $(document).ready(function(){ // Get JSON file $.ajax({ type: 'GET', url: './scripts/data.json', dataType: 'json', success: function(data) { $.each(data, function(i, player){ if (player.faveColor == "red") { $("#message").append('<div class="player red">'+player.name + "</div>"); } else if (player.faveColor == "blue") { $("#message").append('<div class="player orange">'+player.name + "</div>"); } else if (player.faveColor == "orange") { $("#message").append('<div class="player blue">'+player.name + "</div>"); } }); } }); });<file_sep>/README.md # CCS-Input-Ouput Interaction III<br/> Project 2
d784d0003a3d89e94927cc4c5976710ad776a423
[ "JavaScript", "Markdown" ]
2
JavaScript
kikkoooo/CCS-Pool
1712f2046ff7615a1cd15ff5c231ea50f19848c3
912b29dce50d75977661b6e334b43f4b11a790fa
refs/heads/master
<file_sep>google.charts.load('current', { 'packages':['corechart','geochart', 'controls', 'bar'], 'mapsApiKey': '<KEY>' }); google.charts.setOnLoadCallback(drawBarChart); google.charts.setOnLoadCallback(drawLineChart1); google.charts.setOnLoadCallback(drawLineChart2); google.charts.setOnLoadCallback(drawScatter); google.charts.setOnLoadCallback(drawAreaChart1); google.charts.setOnLoadCallback(drawAreaChart2); google.charts.setOnLoadCallback(drawRegionsMap); function myFunction() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.className += " responsive"; } else { x.className = "topnav"; } } function drawBarChart() { var options = { legend: { position: 'bottom' }, hAxis: {title: 'Million Baht'}, vAxis: {title: 'Year', format: ''}, colors: ['#e1ccf9', '#ccebf9', '#ccccf9', '#ccf9e2' , '#f9f7cc', '#f9dfcc', '#f9cccc',], bars: 'horizontal' }; var chart = new google.charts.Bar(document.getElementById('bar')); $.get("./data/bar.csv", function(csvString) { var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar}); var data = google.visualization.arrayToDataTable(arrayData); chart.draw(data, google.charts.Bar.convertOptions(options)); }); } function drawLineChart1() { var options = { //title: 'Budget and Revenue in tourism', legend: { position: 'bottom' }, hAxis: {title: 'Year'}, vAxis: {title: 'Million Baht (Budget), Thousand Million Baht (Revenue)'}, colors: ['#f9cceb', '#ccebf9'] }; var chart = new google.visualization.LineChart(document.getElementById('linechart1')); $.get("./data/linechart1.csv", function(csvString) { var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar}); var data = google.visualization.arrayToDataTable(arrayData); chart.draw(data, options); }); } function drawLineChart2() { var options = { legend: { position: 'bottom' }, hAxis: {title: 'Year'}, vAxis: {title: 'Million Baht'}, colors: ['#ccebf9'] }; var chart = new google.visualization.LineChart(document.getElementById('linechart2')); $.get("./data/linechart2.csv", function(csvString) { var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar}); var data = google.visualization.arrayToDataTable(arrayData); chart.draw(data, options); }); /*var data = google.visualization.arrayToDataTable([ ['year', 'revenue'], ["2012-Q1",29898.48], ["2012-Q2",21810.84], ["2012-Q3",15925.68], ["2012-Q4",32136.65], ]); chart.draw(data, options);*/ } function drawScatter() { var options = { legend: 'none', hAxis: {title: 'Revenue (Million Baht)'}, vAxis: {title: 'Visitors'}, colors: ['#ccebf9'], trendlines: { 0: { type: 'linear', color: '#f9cceb', } } }; var chart = new google.visualization.ScatterChart(document.getElementById('scatter')); $.get("./data/scatter.csv", function(csvString) { var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar}); var data = google.visualization.arrayToDataTable(arrayData); chart.draw(data, options); }); } function drawAreaChart1() { var options = { isStacked: true, legend: { position: 'bottom' }, hAxis: {title: 'Year'}, vAxis: {title: 'Million Baht'}, colors: ['#f9cceb', '#ccebf9'] }; var chart = new google.visualization.AreaChart(document.getElementById('area1')); $.get("./data/area1.csv", function(csvString) { var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar}); var data = google.visualization.arrayToDataTable(arrayData); chart.draw(data, options); }); } function drawAreaChart2() { var options = { isStacked: true, legend: { position: 'bottom' }, hAxis: {title: 'Year'}, vAxis: {title: 'Visitors'}, colors: ['#f9cceb', '#ccebf9'] }; var chart = new google.visualization.AreaChart(document.getElementById('area2')); $.get("./data/area2.csv", function(csvString) { var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar}); var data = google.visualization.arrayToDataTable(arrayData); chart.draw(data, options); }); } function drawRegionsMap() { var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div')); var yearSelector = new google.visualization.ControlWrapper({ controlType: 'CategoryFilter', containerId: 'filter_div', options: { filterColumnLabel: 'year', ui: { allowTyping: false, allowMultiple: false, allowNone: false } } }); var mapChart = new google.visualization.ChartWrapper({ chartType: 'GeoChart', containerId: 'regions_div', options: { colorAxis: {colors: ['#d1d4d6', '#ccebf9']} } }); dashboard.bind(yearSelector, mapChart); $.get("./data/geo.csv", function(csvString) { var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar}); var data = google.visualization.arrayToDataTable(arrayData); dashboard.draw(data); }); }
6edc7e678efc9d27ed713d1d01645cd5829e2726
[ "JavaScript" ]
1
JavaScript
noltontarn/chonburi_visualize
b60ee6a6a959ef3900576d951a9030bb815a6e8a
f8fd54a905e377330c4330799b83c6ed7eae8327
refs/heads/master
<repo_name>asad/PatternSimilarity<file_sep>/nbproject/private/private.properties compile.on.save=true do.depend=false do.jar=true javac.debug=true javadoc.preview=true user.properties.file=/Users/Asad/Library/Application Support/NetBeans/8.0.1/build.properties work.dir=/Users/Asad/Software/GITROOT/asad/PatternSimilarity <file_sep>/src/pattern/PatternFingerprinter.java /* $Revision$ $Author$ $Date$ * * Copyright (C) 2012 <NAME> <<EMAIL>> * * * This program 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. * All we ask is that proper credit is given for our work, which includes * - but is not limited to - adding the above copyright notice to the beginning * of your source code files, and to any copyright notice that you may distribute * with programs based on this work. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ package pattern; import java.io.Serializable; import java.text.DecimalFormat; import java.util.*; /** * * @author <NAME> <<EMAIL>> 2007-2012 */ public class PatternFingerprinter implements IPatternFingerprinter, Comparable<IPatternFingerprinter>, Comparator<IPatternFingerprinter>, Serializable { private static final long serialVersionUID = 0156306561546552043757L; private final Set<IFeature> featureSet; private String fingerprintID = "?"; private int fingerprintSize; public PatternFingerprinter() { this(1024); } /** * * @param features */ public PatternFingerprinter(Collection<IFeature> features) { this(features, 1024); } /** * * @param fingerprintSize */ public PatternFingerprinter(int fingerprintSize) { this.fingerprintSize = fingerprintSize; featureSet = Collections.synchronizedSortedSet(new TreeSet<IFeature>()); } /** * * @param features * @param fingerprintSize */ public PatternFingerprinter(Collection<IFeature> features, int fingerprintSize) { this(fingerprintSize); for (final IFeature feature : features) { if (!this.featureSet.contains(feature)) { this.featureSet.add(new Feature(feature.getPattern())); } else { for (Iterator<IFeature> it = featureSet.iterator(); it.hasNext();) { IFeature localFeature = it.next(); if (localFeature.getPattern().equals(feature.getPattern())) { double newWeight = localFeature.getWeight() + feature.getWeight(); localFeature.setValue(newWeight); break; } } } } } /** * * @param fingerprint * @throws Exception */ @Override public synchronized void add(BitSet fingerprint) throws Exception { if (featureSet == null) { throw new Exception("Cannot perform PatternFingerprint.add() as Fingerprint not initialized"); } for (int i = 0; i < fingerprint.size(); i++) { if (fingerprint.get(i)) { add(new Feature(String.valueOf(i), 1.0)); } } } /** * * @throws Exception */ @Override public synchronized void add(IFeature feature) throws Exception { if (featureSet == null) { throw new Exception("Cannot perform PatternFingerprint.add() as Fingerprint not initialized"); } if (!this.featureSet.contains(feature)) { this.featureSet.add(new Feature(feature.getPattern(), feature.getWeight())); } else { for (Iterator<IFeature> it = featureSet.iterator(); it.hasNext();) { IFeature localFeature = it.next(); if (localFeature.getPattern().equals(feature.getPattern())) { double newWeight = localFeature.getWeight() + feature.getWeight(); localFeature.setValue(newWeight); break; } } } } /** * * @param fngp * @throws Exception */ @Override public synchronized void add(IPatternFingerprinter fngp) throws Exception { if (featureSet == null || fngp == null) { throw new Exception("Cannot perform PatternFingerprint.add() as Fingerprint not initialized"); } if (fngp.getFingerprintSize() != this.fingerprintSize) { throw new Exception("Cannot perform PatternFingerprint.add() as Fingerprint size not equal"); } for (Iterator<IFeature> it1 = fngp.getFeatures().iterator(); it1.hasNext();) { IFeature feature = it1.next(); if (!this.featureSet.contains(feature)) { this.featureSet.add(new Feature(feature.getPattern(), feature.getWeight())); } else { for (Iterator<IFeature> it2 = featureSet.iterator(); it2.hasNext();) { IFeature localFeature = it2.next(); if (localFeature.getPattern().equals(feature.getPattern())) { double newWeight = localFeature.getWeight() + feature.getWeight(); localFeature.setValue(newWeight); break; } } } } } @Override public double[] getValuesAsArray() { int pos = 0; double[] res = new double[featureSet.size()]; for (Iterator<IFeature> it = featureSet.iterator(); it.hasNext();) { IFeature feature = it.next(); res[pos] = feature.getWeight(); pos += 1; } return res; } @Override public Collection<IFeature> getFeatures() { return Collections.unmodifiableCollection(featureSet); } @Override public Collection<Double> getValues() { List<Double> collection = new ArrayList<Double>(featureSet.size()); int i = 0; for (Iterator<IFeature> it = featureSet.iterator(); it.hasNext();) { IFeature feature = it.next(); collection.add(i, feature.getWeight()); i += 1; } return collection; } @Override public int getFeatureCount() { return featureSet.size(); } @Override public BitSet getHashedFingerPrint() { double[] weightedHashedFingerPrint = getWeightedHashedFingerPrint(); BitSet binary = new BitSet(this.fingerprintSize); for (int i = 0; i < weightedHashedFingerPrint.length; i++) { if (weightedHashedFingerPrint[i] > 0.) { binary.set(i, true); } else { binary.set(i, false); } } return binary; } @Override public double[] getWeightedHashedFingerPrint() { double[] hashedFingerPrint = new double[this.fingerprintSize]; for (int i = 0; i < hashedFingerPrint.length; i++) { hashedFingerPrint[i] = 0.; } Collection<IFeature> features = this.getFeatures(); for (final IFeature feature : features) { long hashCode = feature.hashCode(); int randomNumber = (int) RandomNumber.generateMersenneTwisterRandomNumber(this.fingerprintSize, hashCode); hashedFingerPrint[randomNumber] += feature.getWeight(); } return hashedFingerPrint; } @Override public String toString() { StringBuilder result = new StringBuilder(); String NEW_LINE = System.getProperty("line.separator"); DecimalFormat df = new DecimalFormat(); result.append("ID=").append(this.fingerprintID); result.append(" (").append(this.featureSet.size()).append(") "); List<IFeature> list = new ArrayList<IFeature>(this.featureSet); for (Iterator<IFeature> it = list.iterator(); it.hasNext();) { IFeature feature = it.next(); result.append(" ").append(feature.getPattern()). append(":"). append(df.format(feature.getWeight())).append("; "); } result.append(NEW_LINE); return result.toString(); } @Override public IFeature getFeature(int index) throws Exception { if (featureSet.size() >= index) { int i = 0; for (final IFeature key : featureSet) { if (i == index) { return key; } i++; } } return null; } @Override public Double getWeight(String pattern) { if (!featureSet.isEmpty()) { int i = 0; for (final IFeature key : featureSet) { if (key.getPattern().equals(pattern)) { return key.getWeight(); } i++; } } return new Double(-1.0); } @Override public Double getWeight(int index) { if (featureSet.size() >= index) { int i = 0; for (final IFeature value : featureSet) { if (i == index) { return value.getWeight(); } i++; } } return new Double(-1.0); } /** * @return the fingerprintID */ @Override public String getFingerprintID() { return fingerprintID; } /** * @param fingerprintID the fingerprintID to set */ @Override public void setFingerprintID(String fingerprintID) { this.fingerprintID = fingerprintID; } /** * Returns 0 if two fingerprints are equal and if they share same labels it returns difference in their weight * * @param o1 * @param o2 * @return */ @Override public synchronized int compare(IPatternFingerprinter o1, IPatternFingerprinter o2) { Comparator<IPatternFingerprinter> comparator = IPatternComparators.overallComparator(); return comparator.compare(o1, o2); } /** * Returns 0 if two fingerprints are equal and if they share same labels it returns difference in their weight * * @param t * @return */ @Override public synchronized int compareTo(IPatternFingerprinter t) { return compare(this, t); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PatternFingerprinter other = (PatternFingerprinter) obj; if (this.featureSet != other.featureSet && (this.featureSet == null || !this.featureSet.equals(other.featureSet))) { return false; } if ((this.fingerprintID == null) ? (other.fingerprintID != null) : !this.fingerprintID.equals(other.fingerprintID)) { return false; } if (this.fingerprintSize != other.fingerprintSize) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 71 * hash + (this.featureSet != null ? this.featureSet.hashCode() : 0); hash = 71 * hash + (this.fingerprintID != null ? this.fingerprintID.hashCode() : 0); hash = 71 * hash + this.fingerprintSize; return hash; } // @Override // public int hashCode() { // int hash = 5; // hash = 31 * hash + (this.featureSet != null ? this.featureSet.hashCode() : 0); // hash = 31 * hash + (this.fingerprintID != null ? this.fingerprintID.hashCode() : 0); // hash = 31 * hash + this.fingerprintSize; // return hash; // } @Override public int getFingerprintSize() { return fingerprintSize; } @Override public boolean hasFeature(IFeature key) { return this.featureSet.contains(key); } } <file_sep>/README.md Pattern Similarity ================= Generic code for reporting Tanimoto/Jaccard similarity between two pattern vectors (binary/weighted) 1) Option with predefined patterns (-p) with binary similarity > java -jar PatternSimilarity.jar -f CSV -q data/file1.fp -t data/file2.fp -p data/pattern.fp -B > Tanimoto: 1.00 2) Option with predefined patterns (-p) with weighted similarity >java -jar PatternSimilarity.jar -f CSV -q data/file1.fp -t data/file2.fp -p data/pattern.fp >Tanimoto: 0.75 3) Option with binary similarity > java -jar PatternSimilarity.jar -f CSV -q data/file1.fp -t data/file2.fp -B > Tanimoto: 0.38 4) Option with weighted similarity >java -jar PatternSimilarity.jar -f CSV -q data/file1.fp -t data/file2.fp >Tanimoto: 0.40
e71fc80f2979edaba204769c6ae9907b4d3e2b9f
[ "Markdown", "Java", "INI" ]
3
INI
asad/PatternSimilarity
ce350b03a035aae3ac492d92811b9d1b586b5218
72b612f3de67005a21945df8458908d7c5be7e5f
refs/heads/master
<repo_name>drorgl/libjpeg-turbo.module<file_sep>/readme.md # libjpeg GYP Module ** Experimental ** expose libjpeg through gyp - can be used stand alone to compile libjpeg-turbo as static/shared libraries ( / dll) static/shared library can be changed in the variables section of libjpeg.gyp - can be used as part of a bigger gyp project (which was the original intent) : ``` 'dependencies':[ 'libjpeg.module/libjpeg.gyp:libjpeg' ] ``` libjpeg-turbo http://libjpeg-turbo.virtualgl.org/ Using as module from: https://github.com/svn2github/libjpeg-turbo ``` gyp libjpeg.gyp -DOS=win -Dtarget_arch=ia32 -Duse_system_yasm=0 --depth=. -f msvs -G msvs_version=2013 --generator-output=./build.vs2013/ gyp libjpeg.gyp -DOS=win -Dtarget_arch=x64 -Duse_system_yasm=0 --depth=. -f msvs -G msvs_version=2013 --generator-output=./build.vs2013/ gyp libjpeg.gyp -DOS=linux -Dtarget_arch=ia32 -Duse_system_yasm=1 --depth=. -f make --generator-output=./build.linux32/ gyp libjpeg.gyp -DOS=linux -Dtarget_arch=x64 -Duse_system_yasm=1 --depth=. -f make --generator-output=./build.linux64/ gyp libjpeg.gyp -DOS=android -Dtarget_arch=arm --depth=. -f make --generator-output=./build.android/ ``` libjpeg requires yasm to compile on ia32 and x64 architectures <file_sep>/libjpeg.gyp # started with https://github.com/zenoalbisser/chromium/blob/master/chromium/third_party/libjpeg_turbo/libjpeg.gyp # ended up rewriting most of it (<NAME>) # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { # This file is not used when use_system_libjepg==1. Settings for building with # the system libjpeg is in third_party/libjpeg/libjpeg.gyp. 'variables': { #'library' : 'static_library', 'library' : 'shared_library', 'use_system_yasm%' : "<!(node -e \"try{var x = require('child_process').spawnSync('yasm',[]);if (x.error){console.log(0);}else{console.log(1);}}catch(e){console.log(0)}\")", 'yasm_output_path': '<(INTERMEDIATE_DIR)', 'yasm_flags':[], }, 'targets': [ { 'target_name': 'libjpeg', 'type': '<(library)', 'include_dirs': [ 'config', 'libjpeg-turbo_src', ], 'direct_dependent_settings': { 'include_dirs': [ 'config', 'libjpeg-turbo_src', ], }, 'defines': [ 'WITH_SIMD', 'MOTION_JPEG_SUPPORTED', ], 'includes':[ 'yasm_compile.gypi', ], 'sources': [ 'config/jconfig.h', 'libjpeg-turbo_src/jchuff.c', 'libjpeg-turbo_src/jchuff.h', 'libjpeg-turbo_src/jdct.h', 'libjpeg-turbo_src/jdhuff.c', 'libjpeg-turbo_src/jdhuff.h', 'libjpeg-turbo_src/jerror.c', 'libjpeg-turbo_src/jerror.h', 'libjpeg-turbo_src/jinclude.h', 'libjpeg-turbo_src/jmemsys.h', 'libjpeg-turbo_src/jmorecfg.h', 'libjpeg-turbo_src/jpegint.h', 'libjpeg-turbo_src/jpeglib.h', 'libjpeg-turbo_src/jversion.h', 'libjpeg-turbo_src/jsimd.h', 'libjpeg-turbo_src/jsimddct.h', 'libjpeg-turbo_src/jpegcomp.h', 'libjpeg-turbo_src/jpeg_nbits_table.h', 'libjpeg-turbo_src/jcapimin.c', 'libjpeg-turbo_src/jcapistd.c', 'libjpeg-turbo_src/jccoefct.c', 'libjpeg-turbo_src/jccolor.c', 'libjpeg-turbo_src/jcdctmgr.c', 'libjpeg-turbo_src/jcinit.c', 'libjpeg-turbo_src/jcmainct.c', 'libjpeg-turbo_src/jcmarker.c', 'libjpeg-turbo_src/jcmaster.c', 'libjpeg-turbo_src/jcomapi.c', 'libjpeg-turbo_src/jcparam.c', 'libjpeg-turbo_src/jcphuff.c', 'libjpeg-turbo_src/jcprepct.c', 'libjpeg-turbo_src/jcsample.c', 'libjpeg-turbo_src/jctrans.c', 'libjpeg-turbo_src/jdapimin.c', 'libjpeg-turbo_src/jdapistd.c', 'libjpeg-turbo_src/jdatadst.c', 'libjpeg-turbo_src/jdatasrc.c', 'libjpeg-turbo_src/jdcoefct.c', 'libjpeg-turbo_src/jdcolor.c', 'libjpeg-turbo_src/jddctmgr.c', 'libjpeg-turbo_src/jdinput.c', 'libjpeg-turbo_src/jdmainct.c', 'libjpeg-turbo_src/jdmarker.c', 'libjpeg-turbo_src/jdmaster.c', 'libjpeg-turbo_src/jdmerge.c', 'libjpeg-turbo_src/jdphuff.c', 'libjpeg-turbo_src/jdpostct.c', 'libjpeg-turbo_src/jdsample.c', 'libjpeg-turbo_src/jdtrans.c', 'libjpeg-turbo_src/jfdctflt.c', 'libjpeg-turbo_src/jfdctfst.c', 'libjpeg-turbo_src/jfdctint.c', 'libjpeg-turbo_src/jidctflt.c', 'libjpeg-turbo_src/jidctfst.c', 'libjpeg-turbo_src/jidctint.c', 'libjpeg-turbo_src/jidctred.c', 'libjpeg-turbo_src/jquant1.c', 'libjpeg-turbo_src/jquant2.c', 'libjpeg-turbo_src/jutils.c', 'libjpeg-turbo_src/jmemmgr.c', 'libjpeg-turbo_src/jmemnobs.c', #with_arith 'libjpeg-turbo_src/jaricom.c', #with_arith_enc 'libjpeg-turbo_src/jcarith.c', #with_arith_dec 'libjpeg-turbo_src/jdarith.c', #with_turbojpeg #'libjpeg-turbo_src/turbojpeg.c', #'libjpeg-turbo_src/turbojpeg.h', #'libjpeg-turbo_src/transupp.c', #'libjpeg-turbo_src/transupp.h', #'libjpeg-turbo_src/jdatadst-tj.c', #'libjpeg-turbo_src/jdatasrc-tj.c', #'libjpeg-turbo_src/BUILDING.txt', #'libjpeg-turbo_src/change.log', #'libjpeg-turbo_src/ChangeLog.txt', #'libjpeg-turbo_src/coderules.txt', #'libjpeg-turbo_src/jccolext.c', #'libjpeg-turbo_src/jconfig.txt', #'libjpeg-turbo_src/jdcol565.c', #'libjpeg-turbo_src/jdcolext.c', #'libjpeg-turbo_src/jdmrg565.c', #'libjpeg-turbo_src/jdmrgext.c', #'libjpeg-turbo_src/jsimd_none.c', #'libjpeg-turbo_src/jstdhuff.c', #'libjpeg-turbo_src/libjpeg.txt', #'libjpeg-turbo_src/rdrle.c', #'libjpeg-turbo_src/README', #'libjpeg-turbo_src/README-turbo.txt', #'libjpeg-turbo_src/structure.txt', #'libjpeg-turbo_src/testimages', #'libjpeg-turbo_src/usage.txt', #'libjpeg-turbo_src/wrrle.c', ], 'msvs_disabled_warnings': [4018, 4101], # VS2010 does not correctly incrementally link obj files generated # from asm files. This flag disables UseLibraryDependencyInputs to # avoid this problem. 'msvs_2010_disable_uldi_when_referenced': 1, 'variables':{ 'yasm_flags':[ '-I', 'config/<(OS)', '-I', 'config', ], 'conditions':[ ['library == "shared_library"',{ 'yasm_flags':[ '-DPIC', ], }], ], }, 'conditions': [ ['library == "shared_library"',{ 'cflags':[ '-fPIC', ], }], ['target_arch in "ia32 x64"',{ 'variables':{ #'yasm_flags':'<(yasm_flags)' 'yasm_flags':[], }, }], [ 'OS!="win"', {'product_name': 'jpeg_turbo'}], ['OS == "win"',{ 'defines':[ #"INLINE=inline", ], }], ['OS == "win" and library == "shared_library"',{ 'sources':[ 'config/jpeg8.def', ], }], # Add target-specific source files. ['target_arch == "ia32"',{ 'defines':[ 'SIZEOF_SIZE_T=4', ], }], ['OS == "win" and target_arch == "ia32"',{ 'variables':{ 'yasm_flags':[ '-DWIN32', ], }, }], ['OS == "win" and target_arch == "x64"',{ 'variables':{ 'yasm_flags':[ '-DWIN64', ], }, }], ['OS != "win"',{ 'variables':{ 'yasm_flags':[ '-DELF', ], }, }], [ 'target_arch in "ia32"', { 'sources': [ #extra #'libjpeg-turbo_src/simd/jccolext-mmx.asm', #'libjpeg-turbo_src/simd/jcgryext-mmx.asm', #'libjpeg-turbo_src/simd/jdcolext-mmx.asm', #'libjpeg-turbo_src/simd/jdmrgext-mmx.asm', #'libjpeg-turbo_src/simd/jccolext-sse2.asm', #'libjpeg-turbo_src/simd/jcgryext-sse2.asm', #'libjpeg-turbo_src/simd/jdcolext-sse2.asm', #'libjpeg-turbo_src/simd/jdmrgext-sse2.asm', 'libjpeg-turbo_src/simd/jsimd_i386.c', 'libjpeg-turbo_src/simd/jsimd.h', 'libjpeg-turbo_src/simd/jsimdcfg.inc.h', 'libjpeg-turbo_src/simd/jsimdext.inc', 'libjpeg-turbo_src/simd/jcolsamp.inc', 'libjpeg-turbo_src/simd/jdct.inc', 'libjpeg-turbo_src/simd/jsimdcpu.asm', 'libjpeg-turbo_src/simd/jfdctflt-3dn.asm', 'libjpeg-turbo_src/simd/jidctflt-3dn.asm', 'libjpeg-turbo_src/simd/jquant-3dn.asm', 'libjpeg-turbo_src/simd/jccolor-mmx.asm', 'libjpeg-turbo_src/simd/jcgray-mmx.asm', 'libjpeg-turbo_src/simd/jcsample-mmx.asm', 'libjpeg-turbo_src/simd/jdcolor-mmx.asm', 'libjpeg-turbo_src/simd/jdmerge-mmx.asm', 'libjpeg-turbo_src/simd/jdsample-mmx.asm', 'libjpeg-turbo_src/simd/jfdctfst-mmx.asm', 'libjpeg-turbo_src/simd/jfdctint-mmx.asm', 'libjpeg-turbo_src/simd/jidctfst-mmx.asm', 'libjpeg-turbo_src/simd/jidctint-mmx.asm', 'libjpeg-turbo_src/simd/jidctred-mmx.asm', 'libjpeg-turbo_src/simd/jquant-mmx.asm', 'libjpeg-turbo_src/simd/jfdctflt-sse.asm', 'libjpeg-turbo_src/simd/jidctflt-sse.asm', 'libjpeg-turbo_src/simd/jquant-sse.asm', 'libjpeg-turbo_src/simd/jccolor-sse2.asm', 'libjpeg-turbo_src/simd/jcgray-sse2.asm', 'libjpeg-turbo_src/simd/jcsample-sse2.asm', 'libjpeg-turbo_src/simd/jdcolor-sse2.asm', 'libjpeg-turbo_src/simd/jdmerge-sse2.asm', 'libjpeg-turbo_src/simd/jdsample-sse2.asm', 'libjpeg-turbo_src/simd/jfdctfst-sse2.asm', 'libjpeg-turbo_src/simd/jfdctint-sse2.asm', 'libjpeg-turbo_src/simd/jidctflt-sse2.asm', 'libjpeg-turbo_src/simd/jidctfst-sse2.asm', 'libjpeg-turbo_src/simd/jidctint-sse2.asm', 'libjpeg-turbo_src/simd/jidctred-sse2.asm', 'libjpeg-turbo_src/simd/jquantf-sse2.asm', 'libjpeg-turbo_src/simd/jquanti-sse2.asm', #'libjpeg-turbo_src/simd/jcsample.h', ], }], [ 'target_arch=="x64"', { 'variables':{ 'yasm_flags':[ '-D__x86_64__', ], }, 'defines':[ 'SIZEOF_SIZE_T=8', ], 'sources': [ 'libjpeg-turbo_src/simd/jsimd_x86_64.c', 'libjpeg-turbo_src/jsimd.h', 'libjpeg-turbo_src/simd/jsimdcfg.inc.h', 'libjpeg-turbo_src/simd/jsimdext.inc', 'libjpeg-turbo_src/simd/jcolsamp.inc', 'libjpeg-turbo_src/simd/jdct.inc', 'libjpeg-turbo_src/simd/jfdctflt-sse-64.asm', 'libjpeg-turbo_src/simd/jccolor-sse2-64.asm', 'libjpeg-turbo_src/simd/jcgray-sse2-64.asm', 'libjpeg-turbo_src/simd/jcsample-sse2-64.asm', 'libjpeg-turbo_src/simd/jdcolor-sse2-64.asm', 'libjpeg-turbo_src/simd/jdmerge-sse2-64.asm', 'libjpeg-turbo_src/simd/jdsample-sse2-64.asm', 'libjpeg-turbo_src/simd/jfdctfst-sse2-64.asm', 'libjpeg-turbo_src/simd/jfdctint-sse2-64.asm', 'libjpeg-turbo_src/simd/jidctflt-sse2-64.asm', 'libjpeg-turbo_src/simd/jidctfst-sse2-64.asm', 'libjpeg-turbo_src/simd/jidctint-sse2-64.asm', 'libjpeg-turbo_src/simd/jidctred-sse2-64.asm', 'libjpeg-turbo_src/simd/jquantf-sse2-64.asm', 'libjpeg-turbo_src/simd/jquanti-sse2-64.asm', #'libjpeg-turbo_src/simd/jccolext-sse2-64.asm', #'libjpeg-turbo_src/simd/jcgryext-sse2-64.asm', #'libjpeg-turbo_src/simd/jdcolext-sse2-64.asm', #'libjpeg-turbo_src/simd/jdmrgext-sse2-64.asm', ], }], # The ARM SIMD implementation can be used for devices that support # the NEON instruction set. This is done dynamically by probing CPU # features at runtime, so always compile it for ARMv7-A devices. [ 'target_arch=="arm"', { 'defines':[ 'SIZEOF_SIZE_T=4', ], 'sources':[ 'libjpeg-turbo_src/simd/jsimd_arm.c', 'libjpeg-turbo_src/simd/jsimd_arm_neon.S', ], }], [ 'target_arch=="arm64"', { 'defines':[ 'SIZEOF_SIZE_T=8', ], 'sources':[ 'libjpeg-turbo_src/simd/jsimd_arm64.c', 'libjpeg-turbo_src/simd/jsimd_arm64_neon.S', ], }], [ 'target_arch=="mipsel"', { 'sources': [ 'libjpeg-turbo_src/simd/jsimd_mips.c', 'libjpeg-turbo_src/simd/jsimd_mips_dspr2.S', 'libjpeg-turbo_src/simd/jsimd_mips_dspr2_asm.h', ], }], ['target_arch == "powerpc"',{ 'sources':[ 'libjpeg-turbo_src/simd/jsimd_powerpc.c', 'libjpeg-turbo_src/simd/jccolor-altivec.c', 'libjpeg-turbo_src/simd/jcgray-altivec.c', 'libjpeg-turbo_src/simd/jcsample-altivec.c', 'libjpeg-turbo_src/simd/jdcolor-altivec.c', 'libjpeg-turbo_src/simd/jdmerge-altivec.c', 'libjpeg-turbo_src/simd/jdsample-altivec.c', 'libjpeg-turbo_src/simd/jfdctfst-altivec.c', 'libjpeg-turbo_src/simd/jfdctint-altivec.c', 'libjpeg-turbo_src/simd/jidctfst-altivec.c', 'libjpeg-turbo_src/simd/jidctint-altivec.c', 'libjpeg-turbo_src/simd/jquanti-altivec.c', #'libjpeg-turbo_src/simd/jsimd_altivec.h', #'libjpeg-turbo_src/simd/jccolext-altivec.c', #'libjpeg-turbo_src/simd/jcgryext-altivec.c', #'libjpeg-turbo_src/simd/jdcolext-altivec.c', #'libjpeg-turbo_src/simd/jdmrgext-altivec.c', ], 'cflags':[ '-maltivec', ], }], ], }, { 'target_name': 'cjpeg', 'type':'executable', 'dependencies':[ 'libjpeg', ], 'defines':[ 'GIF_SUPPORTED', 'PPM_SUPPORTED', #if not with_12bit #'BMP_SUPPORTED', #'TARGA_SUPPORTED', ], 'include_dirs': [ 'config', ], 'sources':[ 'libjpeg-turbo_src/cdjpeg.c', 'libjpeg-turbo_src/cderror.h', 'libjpeg-turbo_src/cdjpeg.h', 'libjpeg-turbo_src/cjpeg.c', 'libjpeg-turbo_src/rdswitch.c', 'libjpeg-turbo_src/rdgif.c', 'libjpeg-turbo_src/rdppm.c', #if not WITH_12BIT #'libjpeg-turbo_src/rdbmp.c', #'libjpeg-turbo_src/rdtarga.c', ], }, { 'target_name': 'djpeg', 'type':'executable', 'dependencies':[ 'libjpeg', ], 'include_dirs': [ 'config', ], 'defines':[ 'GIF_SUPPORTED', 'PPM_SUPPORTED', #if not with_12bit #'BMP_SUPPORTED', #'TARGA_SUPPORTED', ], 'sources':[ 'libjpeg-turbo_src/cderror.h', 'libjpeg-turbo_src/rdcolmap.c', 'libjpeg-turbo_src/djpeg.c', 'libjpeg-turbo_src/cdjpeg.c', 'libjpeg-turbo_src/cdjpeg.h', 'libjpeg-turbo_src/rdswitch.c', 'libjpeg-turbo_src/wrgif.c', 'libjpeg-turbo_src/wrppm.c', #if not WITH_12BIT #'libjpeg-turbo_src/wrbmp.c', #'libjpeg-turbo_src/wrtarga.c', ], }, { 'target_name': 'jcstest', 'type':'executable', 'dependencies':[ 'libjpeg', ], 'include_dirs': [ 'config', ], 'sources':[ 'libjpeg-turbo_src/jcstest.c', ], }, { 'target_name': 'jpegtran', 'type':'executable', 'dependencies':[ 'libjpeg', ], 'include_dirs': [ 'config', ], 'sources':[ 'libjpeg-turbo_src/rdswitch.c', 'libjpeg-turbo_src/jpegtran.c', 'libjpeg-turbo_src/transupp.c', 'libjpeg-turbo_src/transupp.h', 'libjpeg-turbo_src/cdjpeg.c', 'libjpeg-turbo_src/cdjpeg.h', ], }, { 'target_name': 'rdjpgcom', 'type':'executable', 'dependencies':[ 'libjpeg', ], 'include_dirs': [ 'config', ], 'sources':[ 'libjpeg-turbo_src/rdjpgcom.c', ], }, #{ # 'target_name': 'tjbench', # 'type':'executable', # 'dependencies':[ # 'libjpeg', # ], # 'defines':[ # 'BMP_SUPPORTED', # 'PPM_SUPPORTED', # ], # 'sources':[ # 'libjpeg-turbo_src/tjbench.c', # 'libjpeg-turbo_src/bmp.c', # 'libjpeg-turbo_src/bmp.h', # 'libjpeg-turbo_src/rdppm.c', # 'libjpeg-turbo_src/tjutil.c', # 'libjpeg-turbo_src/tjutil.h', # ], #}, #{ # 'target_name': 'tjunittest', # 'type':'executable', # 'dependencies':[ # 'libjpeg', # ], # 'sources':[ # 'libjpeg-turbo_src/tjunittest.c', # 'libjpeg-turbo_src/tjutil.h', # 'libjpeg-turbo_src/tjutil.c', # ], #}, { 'target_name': 'wrjpgcom', 'type':'executable', 'dependencies':[ 'libjpeg', ], 'include_dirs': [ 'config', ], 'sources':[ 'libjpeg-turbo_src/wrjpgcom.c', ], }, ], } #'libjpeg-turbo_src/example.c', # Local Variables: # tab-width:2 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=2 shiftwidth=2:<file_sep>/binding.gyp { "includes":["libjpeg.gyp"] }
6025fe8f35cbeebd08bb57e9e1d872e7732cacee
[ "Markdown", "Python" ]
3
Markdown
drorgl/libjpeg-turbo.module
0bee1612293ea8a489f59c221bd7807881ebf12d
303cb129d99d183a3114b5dbe5cd382b495f1ee9
refs/heads/master
<file_sep>import pygame from pygame import sprite, image, transform, draw,mask import configuration class WallModel(sprite.Sprite): def __init__(self): super().__init__() self.image = image.load('data/sprite/wall/wall_0.png').convert_alpha() self.rect = pygame.Rect(0,0,0,0)<file_sep>import pygame from pygame import sprite, image import configuration class GameObject(sprite.Sprite): def __init__(self,color = None): super().__init__() self.image = image.load('data/sprite/player/example.png').convert_alpha() self.rect = self.image.get_rect() self.rect.x = 200 self.rect.y = 300 self._speed_x = 0 self._speed_y = 0 self._is_alive = True self._animState = {"idle":True, "run_loop":False, "death":False} self._images = [] def get_speed(self): return (self._speed_x,self._speed_y) def set_speed(self, speed_x=0,speed_y=0): self._speed_x = speed_x self._speed_y = speed_y def get_is_alive(self): return self._is_alive def get_animState(self): return self._animState def get_images(self): return self._images def get_pos(self): return (self.rect.x//25,self.rect.y//25) def update(self): self.rect.x += self._speed_x self.rect.y += self._speed_y self.__out_screen() def update_anim(self): #TODO: Hacer este caso de uso pass def __out_screen(self): if self.rect.x< - self.image.get_width(): self.rect.x = configuration.SCREEN_WIDTH elif self.rect.x> configuration.SCREEN_WIDTH + self.image.get_width(): self.rect.x = -self.image.get_width() elif self.rect.y< - self.image.get_height(): self.rect.y = configuration.SCREEN_HEIGHT elif self.rect.y> configuration.SCREEN_HEIGHT+ self.image.get_height(): self.rect.y = -self.image.get_height() def _set_color(self, color): colorImage = pygame.Surface(self.image.get_size()).convert_alpha() colorImage.fill(color) self.image.blit(colorImage, (0,0), special_flags = pygame.BLEND_RGBA_MULT) def _cheack_walls(self,walls): for wall in walls: if self.rect.colliderect(wall.rect): dx,dy = self.get_speed() if dx > 0: # Moving right; Hit the left side of the wall self.rect.right = wall.rect.left if dx < 0: # Moving left; Hit the right side of the wall self.rect.left = wall.rect.right if dy > 0: # Moving down; Hit the top side of the wall self.rect.bottom = wall.rect.top if dy < 0: # Moving up; Hit the bottom side of the wall self.rect.top = wall.rect.bottom def stop_move(self): self.set_speed(0,0) def right(self,speed : int): self.set_speed(speed,0) def left(self,speed : int): self.set_speed(-speed,0) def down(self,speed : int): self.set_speed(0,speed) def up(self,speed : int): self.set_speed(0,-speed)<file_sep>import pygame from pygame import sprite, image, time,transform from audio_source import AudioSource from game_object.gameObject import GameObject import color class Player(GameObject): def __init__(self,color, x = 300,y=300): super().__init__(color) for i in range(8): self._images.append(image.load('data/sprite/player/sprite_{}.png'.format(i)).convert_alpha()) self.index = 0 self.image = self._images[self.index] self.images_right = self._images self.images_left = [transform.flip(image_,True,False) for image_ in self._images] self.images_down = [transform.rotate(image_,-90)for image_ in self.images_right] self.images_up = [transform.rotate(image_,90)for image_ in self.images_right] self.dead_image = [] for i in range(10): self.dead_image.append(image.load('data\\sprite\\player\\dead\\dead_0{}.png'.format(i)).convert_alpha()) for i in range(10,13): self.dead_image.append(image.load('data\\sprite\\player\\dead\\dead_{}.png'.format(i)).convert_alpha()) self.time_animation = 0 self.number_of_frames = 8 self.rect = self.image.get_rect() self.isFlip = False self.rect.x = x self.rect.y = y self.__max_speed = 4 self.rotate_down = False self.rotate_up = False self._special_atack = {"shoot_laser":False,"stop_time":False,"atack_on":False} self._score = 0 self._speed_boost = 5 self.audioSource = AudioSource() self.audioSource.add_audio_clip('data/sound/Point.wav','beat',0.1) self.audioSource.add_audio_clip('data\\sound\\power_up.wav','power_up',0.3) self.audioSource.add_audio_clip('data\\sound\\death.wav','death',0.3) self.__actual_time = 0 self.__atack_time = -1 self.__pause_time = 0 self.anim_on = False self.play_death_sound = False def update(self,walls, ghosts): super().update() self._cheack_walls(walls=walls) self.__check_ghosts(ghosts) if not self._is_alive: self.stop_move() if not self.play_death_sound: self.audioSource.stop_music() self.audioSource.play_audio_clip('death') self.play_death_sound = True self._images = self.dead_image if self.time_animation<time.get_ticks(): self.time_animation = time.get_ticks() + 50 self.anim_on = True elif self.anim_on: self.anim_on = False self.dead_animation() else: self.__change_image() if self._special_atack['atack_on']: if self.__atack_time==-1: self.__atack_time = time.get_ticks() + 15000 elif self.__atack_time<time.get_ticks(): self.__atack_time = -1 self._special_atack['atack_on']=False if self._special_atack['stop_time']: if self.__atack_time==-1: self.__atack_time = time.get_ticks() + 15000 elif self.__atack_time<time.get_ticks(): self.__atack_time = -1 self._special_atack['stop_time']=False def dead_animation(self): self.index+=1 if self.index<13: self.image = self._images[self.index] def __change_image(self): if self.isFlip: self._images = self.images_left else: self._images = self.images_right if self.rotate_down: self._images = self.images_down elif self.rotate_up: self._images = self.images_up if self._speed_x != 0 or self._speed_y != 0: if self.time_animation<time.get_ticks(): self.time_animation = time.get_ticks() + 100 else: self.index+=1 if self.index>self.number_of_frames-1: self.index = 0 self.image = self._images[self.index] def __check_ghosts(self, ghosts): for ghost in ghosts: if self.rect.colliderect(ghost.rect): if self._special_atack['atack_on']: ghost._is_alive = False # ghost.rect.x = 370 # ghost.rect.y = 320 self._score+=500 elif ghost.atack: self._is_alive = False elif self._special_atack['stop_time'] and ghost.get_max_speed() == 4: ghost.set_max_speed(1) ghost.stop_move() ghost.up(1) elif not self._special_atack['stop_time'] and ghost.get_max_speed() == 1: ghost.set_max_speed(4) ghost.up(4) def check_input(self, event): if self.get_is_alive(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_w or event.key == pygame.K_UP: self.up(self.__max_speed) self.__flip_and_rotate(False,False,True) if event.key == pygame.K_s or event.key == pygame.K_DOWN: self.down(self.__max_speed) self.__flip_and_rotate(False,True,False) if event.key == pygame.K_a or event.key == pygame.K_LEFT: self.left(self.__max_speed) self.__flip_and_rotate(True,False,False) if event.key == pygame.K_d or event.key == pygame.K_RIGHT: self.right(self.__max_speed) self.__flip_and_rotate(False,False,False) if event.type == pygame.KEYUP: if (event.key == pygame.K_w or event.key == pygame.K_UP) and self.get_speed()[1] == -self.__max_speed: self.stop_move() if (event.key == pygame.K_s or event.key == pygame.K_DOWN) and self.get_speed()[1] == self.__max_speed: self.stop_move() if (event.key == pygame.K_a or event.key == pygame.K_LEFT) and self.get_speed()[0] == -self.__max_speed: self.stop_move() if (event.key == pygame.K_d or event.key == pygame.K_RIGHT) and self.get_speed()[0] == self.__max_speed: self.stop_move() def __flip_and_rotate(self, isFlip : bool, rotete_down : bool, rotate_up : bool): self.isFlip = isFlip self.rotate_down = rotete_down self.rotate_up = rotate_up def check_coin_type(self, coin): sound = False if coin.coin_model.color == color.YELLOW: self._special_atack['atack_on'] = True sound = True elif coin.coin_model.color == color.BLUE: self._special_atack['stop_time'] = True sound = True if sound: self.audioSource.play_audio_clip('power_up') #agregar un tiempo de ataque self._score+=coin.score def __shoot_laser(self): #TODO: Hacer este caso de uso pass # def __pause_time(self): # #TODO: Hacer este caso de uso # pass def __atack_on(self): #TODO: Hacer este caso de uso pass def get_time_atack(self): return self.__atack_time <file_sep>import pygame from pygame import sprite, image, transform from audio_source import AudioSource class CoinModel(sprite.Sprite): def __init__(self,color : tuple): super().__init__() self.image = image.load('data/sprite/coin_model.png').convert_alpha() self._set_color(color) self.color = color self.audioSource = AudioSource() self.audioSource.add_audio_clip('data/sound/coin.wav','coin',0.3) def _set_color(self, color : tuple): colorImage = pygame.Surface(self.image.get_size()).convert_alpha() colorImage.fill(color) self.image.blit(colorImage, (0,0), special_flags = pygame.BLEND_RGBA_MULT) <file_sep>import pygame from pygame import sprite, image from game_object.coin_model import CoinModel class Coin(): _id=0 def __init__(self, coin_model : CoinModel, pos : tuple, score): super().__init__() self.id = Coin._id self.score = score self.coin_model = coin_model self.pos = pos self.rect = pygame.Rect(0,0,0,0) Coin._id+=1 def draw(self, screen): self.rect = screen.blit(self.coin_model.image,self.pos) def get_rect(self): return self.rect def play_sound(self): self.coin_model.audioSource.play_audio_clip('coin')<file_sep>import pygame import math import random import pathfinding.core.diagonal_movement,pathfinding.core.grid,pathfinding.finder.a_star from pygame import sprite, image, time,transform from audio_source import AudioSource from game_object.gameObject import GameObject from game_object.player import Player class Ghost(GameObject): def __init__(self, color : str,dead_ghost_model,level = "", x=370,y=320): super().__init__() self.image = image.load('data/sprite/ghost/{}/{}_ghost_0.png'.format(color,color)).convert_alpha() self.scared = image.load('data\\sprite\\ghost\\scared\\scared_ghost.png').convert_alpha() for i in range(4): self._images.append(image.load('data\\sprite\\ghost\\{}\\{}_ghost_{}.png'.format(color,color,i))) self.dead_ghost_model = dead_ghost_model self.normal_ghost = self._images self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.__max_speed = 4 self.set_speed(0,self.__max_speed) self.audioSource = AudioSource() self.atack = True self.current_level = Ghost._matrix_str_to_matrix_int(level) self.initial_level_form = self.current_level.copy() self.find_time = 0 self.restart_time = -1 self.delay_time = -1 self.current_path = [] self.aux = () self.find_path = False self.dead_time = -1 self.audioSource.add_audio_clip('data\\sound\\incoming-enemy.wav','incoming',0.5) # self.audioSource.add_audio_clip('data/sound/Point.wav','beat',0.1) def update(self,player : Player,walls): super().update() self._cheack_walls(walls,player) if self._is_alive: self._images = self.normal_ghost self.select_path(player) if self.find_path: self.start_path() self.atack = True else: if self.dead_time==-1: # self.stop_move() self._images = self.dead_ghost_model.images self.dead_time = time.get_ticks() + 6000 elif self.dead_time<time.get_ticks(): self._is_alive = True self.dead_time = -1 self.atack = False self.update_anim() draw = True if self._is_alive: if player._special_atack['atack_on']: if player.get_time_atack() - 500 < time.get_ticks(): draw = (time.get_ticks() % 6) == 0 if draw: self.image = self.scared else: self.image = pygame.Surface((0,0)) def start_path(self): if len(self.current_path)==0: self.restart_path_finding() elif self.find_time < time.get_ticks(): self.restart_path_finding() else: self.advance_in_path() if self.get_pos()==self.current_path[0] and self.delay_time<time.get_ticks(): self.next_node() def next_node(self): self.aux = self.current_path.pop(0) speed_x, speed_y = self.get_speed() if speed_y == 4: self.delay_time=time.get_ticks() + 10 elif speed_y == -4: self.delay_time=time.get_ticks() + 200 if speed_x == 4: self.delay_time=time.get_ticks() + 40 elif speed_x == -4: self.delay_time=time.get_ticks() + 200 def advance_in_path(self): dx = self.get_pos()[0] - self.current_path[0][0] dy = self.get_pos()[1] - self.current_path[0][1] if self.delay_time>time.get_ticks(): dx = self.get_pos()[0] - self.aux[0] dy = self.get_pos()[1] - self.aux[1] if dx==1: self.left(self.__max_speed) elif dx==-1: self.right(self.__max_speed) elif dy==1: self.up(self.__max_speed) elif dy==-1: self.down(self.__max_speed) def restart_path_finding(self): self.find_path = False self.restart_time = time.get_ticks() + 4000 self.current_path.clear() def select_path(self, player): if self.distance(player.rect.x, player.rect.y) < 200: if not self.find_path and self.restart_time<time.get_ticks(): # self.stop_move() self.iteration = 0 self.iteration_time = 0 grid = pathfinding.core.grid.Grid(matrix=self.current_level) x_ghost,y_ghost = self.get_pos() x_player,y_player = player.get_pos() start = grid.node(x_ghost, y_ghost) try: end = grid.node(x_player, y_player) except IndexError as Error: end = grid.node(1,1) finder = pathfinding.finder.a_star.AStarFinder( diagonal_movement=pathfinding.core.diagonal_movement.DiagonalMovement.never) path, runs = finder.find_path(start, end, grid) # self.current_path = list(path) for e in path: self.current_path.append(e) self.current_path.pop(0) # print(self.current_path) self.find_path = True self.find_time = time.get_ticks() + 2000 # self.audioSource.play_audio_clip('incoming') def update_anim(self): if self._speed_x>0: self.image = self._images[0] elif self._speed_x<0: self.image = self._images[2] elif self._speed_y>0: self.image = self._images[1] elif self._speed_y<0: self.image = self._images[3] def distance(self, x_player : int, y_player : int): return math.sqrt(pow(self.dx(x_player),2) + pow(self.dy(y_player),2)) def dx(self, x_player): return self.rect.x - x_player def dy(self, y_player): return self.rect.y - y_player def _cheack_walls(self,walls,player : Player, rand = -1): result = False for wall in walls: if self.rect.colliderect(wall.rect): result = self.rect.colliderect(wall.rect) dx,dy = self.get_speed() if rand==-1: rand = random.randint(0,2) if dx > 0: # Moving right; Hit the left side of the wall self.rect.right = wall.rect.left if rand == 0: self.up(self.__max_speed) elif rand == 1: self.left(self.__max_speed) elif rand == 2: self.down(self.__max_speed) if dx < 0: # Moving left; Hit the right side of the wall self.rect.left = wall.rect.right if rand == 0: self.down(self.__max_speed) elif rand == 1: self.right(self.__max_speed) elif rand == 2: self.up(self.__max_speed) if dy > 0: # Moving down; Hit the top side of the wall self.rect.bottom = wall.rect.top if rand == 0: self.right(self.__max_speed) elif rand == 1: self.up(self.__max_speed) elif rand == 2: self.left(self.__max_speed) if dy < 0: # Moving up; Hit the bottom side of the wall self.rect.top = wall.rect.bottom if rand == 0: self.left(self.__max_speed) elif rand == 1: self.down(self.__max_speed) elif rand == 2: self.right(self.__max_speed) return result @staticmethod def _matrix_str_to_matrix_int(matrix): index = 0 new_matrix = [] for i in matrix: new_matrix_2 = [] for j in matrix[index]: if j =='W': new_matrix_2.append(0) else: new_matrix_2.append(1) new_matrix.append(new_matrix_2) index+=1 return new_matrix def set_max_speed(self ,max_speed : int): self.__max_speed = max_speed def get_max_speed(self): return self.__max_speed <file_sep>import pygame from pygame import sprite, image, mixer, time class AudioSource(): def __init__(self): self.__audio_clips = {} self.__musics = {} self.__time = 0 def add_audio_clip(self, audio_path : str, audio_name : str,volume=1.0 ): try: if self.__audio_clip_exitst(audio_name): raise ValueError("[WARNING] The key exists.") else: self.__audio_clips[audio_name] = mixer.Sound(audio_path) self.__audio_clips[audio_name].set_volume(volume) except ValueError: print("[WARNING] The key exists.") except: print("[WARINIG] Not found.") def play_audio_clip(self, audio_name:str): if self.__audio_clip_exitst(audio_name): self.__audio_clips[audio_name].play() else: raise ValueError("[WARNING] The key don't exists.") def stop_audio_clip(self, audio_name:str): if self.__audio_clip_exitst(audio_name): self.__audio_clips[audio_name].stop() self.__time = 0 else: raise ValueError("[WARNING] The key don't exists.") def play_audio_clip_each(self, audio_name:str, ms : int): if self.__audio_clip_exitst(audio_name): if self.__time == 0: self.__time = time.get_ticks() + ms self.__audio_clips[audio_name].play() elif self.__time<time.get_ticks(): self.__time = 0 else: raise ValueError("[WARNING] The key don't exists.") def __audio_clip_exitst(self,audio_name:str): return not self.__audio_clips.get(audio_name,None)==None @staticmethod def play_music_loop(music_path : str,volume = 1.0): try: mixer.music.load(music_path) mixer.music.set_volume(volume) mixer.music.play(-1) except: print("[WARINIG] Not found.") @staticmethod def play_music_each(music_path : str, loops : int, volume = 1.0): try: mixer.music.load(music_path) mixer.music.set_volume(volume) mixer.music.play(loops) except: print("[WARINIG] Not found.") @staticmethod def stop_music(): mixer.music.stop()<file_sep>import sys import pygame from pygame import display, font, sprite, time, event import color import configuration from audio_source import AudioSource from game_object.player import Player from game_object.ghost import Ghost from game_object.dead_ghost_model import DeadGhostModel from coin_model_factory import CoinModelFactory,Coin from game_object.wall import Wall from game_object.wall_model import WallModel from scene.scene import Scene class Game(Scene): def __init__(self, level : list): super().__init__() self._coin_model_factory = CoinModelFactory() self.wall_model = WallModel() self.__coin_list = [] self.__wall_group = sprite.Group() self.load_level(level) self.__player = Player(color.YELLOW,x=30,y=30) self.__group = sprite.Group(self.__player) self.__ghost_group = sprite.Group() self.ghost_dead_model = DeadGhostModel() self.__ghost_group.add(Ghost('red',self.ghost_dead_model,level)) self.__ghost_group.add(Ghost('blue',self.ghost_dead_model,level)) self.__ghost_group.add(Ghost('green',self.ghost_dead_model,level)) self.__ghost_group.add(Ghost('lila',self.ghost_dead_model,level)) self.__font_score = font.Font('data/dpcomic.ttf',50) self._state = {'continue':False, 'exit':False,'win':False} self.__iteration = 1 self.__time = 0 self.audio_source.play_music_loop('data\\music\\my_music.wav',0.5) self.play_normal_music = True def process(self): self.__wall_group.update() for e in event.get(): if e.type == pygame.QUIT: pygame.quit() sys.exit() self.__player.check_input(e) self.__ghost_group.update(self.__player,self.__wall_group) self.__player.update(self.__wall_group,self.__ghost_group) self.__check_colisions() if len(self.__coin_list) == 0 and not self._state['win'] and self.__time == 0: self._state['win'] = True self.__time = time.get_ticks() + 5000 if not self.__player.get_is_alive() and self.__time == 0: self.__time = time.get_ticks() + 5000 if time.get_ticks()>self.__time and (self._state['win'] or not self.__player.get_is_alive()): self._state['exit'] = True if self.__player._special_atack['atack_on'] and self.play_normal_music: self.audio_source.stop_music() self.audio_source.play_music_loop('data\\music\\scared_ghost.wav',0.5) self.play_normal_music = False elif not self.__player._special_atack['atack_on'] and not self.play_normal_music and not self.__player._special_atack['stop_time']: self.audio_source.stop_music() self.audio_source.play_music_loop('data\\music\\my_music.wav',0.5) self.play_normal_music = True elif self.__player._special_atack['stop_time'] and self.play_normal_music: self.audio_source.stop_music() self.audio_source.play_music_loop('data\\music\\my_music_delay.wav',1) self.play_normal_music = False elif not self.__player._special_atack['stop_time'] and not self.play_normal_music and not self.__player._special_atack['atack_on']: self.audio_source.stop_music() self.audio_source.play_music_loop('data\\music\\my_music.wav',1) self.play_normal_music = True def display_frame(self): self._clock.tick(self._fps) self.screen.fill(color.BLACK) self.__wall_group.draw(self.screen) for coin in self.__coin_list: coin.draw(self.screen) self.__ghost_group.draw(self.screen) self.__group.draw(self.screen) if self._state['win']: self._draw_text(self.__font_score,'WIN',365,300) if not self.__player.get_is_alive(): self._draw_text(self.__font_score,'LOSE',365,300) display.flip() def __check_colisions(self): index=0 for e in self.__coin_list: if self.__player.rect.colliderect(e.get_rect()): # print("Me choco una moneda {}".format(e.coin_model.color)) e.play_sound() self.__player.check_coin_type(e) self.__coin_list.pop(index) index+=1 def get_state(self): return self._state def get_clock(self): return self._clock def load_level(self,level:str): x = y = 0 y_coin = 5 for row in level: for col in row: if col == "W": self.__wall_group.add(Wall(self.wall_model,pos=(x,y))) if col == "C" or col ==" ": self.__coin_list.append(Coin(self._coin_model_factory.get_coin_model('white_coin_model'),pos=(x,y_coin),score=50)) if col == "Y": self.__coin_list.append(Coin(self._coin_model_factory.get_coin_model('yellow_coin_model'),pos=(x,y_coin),score=200)) if col == "R": self.__coin_list.append(Coin(self._coin_model_factory.get_coin_model('red_coin_model'),pos=(x,y_coin),score=200)) if col == "B": self.__coin_list.append(Coin(self._coin_model_factory.get_coin_model('blue_coin_model'),pos=(x,y_coin),score=200)) x += 25 y += 25 y_coin += 25 x = 0 def get_score(self): return self.__player._score def main(): level = [ "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW", "W W YW", "W WW WWW WWWWWW W WWWWW WWW WW W", "W WW WWW WWWWWW W WWWWW WWW WW W", "W W W", "W WWWW W WWWWWWWWWWWWWW W WWWW W", "W WB BW W", "WWW WW WWWWW WWWWWW WWWWW WW WWW", "WWW WW W WWWWWW W WW WWW", "WWW WW W WWWWWWWWWWWWWW W WW WWW", "W WW W W WW WWWW", "_ WW W______W WW ____", "W W WW W______W WW W WWWW", "WWW WW W WW W______W WW W WW WWW", "WWW WW W WW WWWWWWWW WW W WW WWW", "WWW WW W WW WW W WW WWW", "WWW WW W WW WWWWWWWW WW W WW WWW", "W W BWB W W", "W WWWW W WWWWWWWWWWWWWW W WWWW W", "W W W W", "W WW WWW WWWWWW W WWWWW WWW WW W", "W WW WWW WWWWWW W WWWWW WWW WW W", "WY WR RW YW", "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW" ] #24 filas #32 columnas pygame.init() continue_ = True while continue_: myGame = Game(level) while not myGame.get_state()['exit']: myGame.process() myGame.display_frame() continue_ = myGame.get_state()['continue'] return myGame.get_score() <file_sep>import pygame from pygame import font,time, display from audio_source import AudioSource import configuration, color class Scene(): def __init__(self): self.screen = display.set_mode(size=(configuration.SCREEN_WIDTH,configuration.SCREEN_HEIGHT)) self._state = {'continue':False, 'exit':False} self._clock = time.Clock() self._fps = 30 self.audio_source = AudioSource() def process(self): pass def display_frame(self): pass def _draw_text(self, font, text : str, x : int, y : int): text_Obj = font.render(text,1,color.WHITE,self.screen) text_rect = text_Obj.get_rect() text_rect.topleft = (x,y) self.screen.blit(text_Obj, text_rect)<file_sep>import pygame from pygame import sprite, image, transform, draw,mask import configuration from game_object.wall_model import WallModel class Wall(sprite.Sprite): def __init__(self,wall_model:WallModel,pos = (0,0)): super().__init__() self.image = wall_model.image self.rect = self.image.get_rect() self.rect.x = pos[0] self.rect.y = pos[1] def update(self): super().update() <file_sep>import sys import pygame from pygame import display, font, sprite, time, event import color import configuration # from audio_source import AudioSource # from game_object.player import Player # from game_object.ghost import Ghost # from game_object.dead_ghost_model import DeadGhostModel # from coin_model_factory import CoinModelFactory,Coin # from game_object.wall import Wall # from game_object.wall_model import WallModel from pygame import font from ui.input_box import InputBox from scene.scene import Scene class End(Scene): def __init__(self, score : int, name_score_list : []): super().__init__() self.input_box = InputBox(600,100,30,60) self.tittle_text = "HIGHT SCORES" self.tittle_font = font.Font('data\\dpcomic.ttf',40) self.name_font = font.Font('data\\dpcomic.ttf',55) self.score_font = font.Font('data\\dpcomic.ttf',20) self.name_score_list = name_score_list self.score = score def process(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() self.input_box.handle_event(event) self.input_box.update() def display_frame(self): self.screen.fill(color.BLACK) self.input_box.draw(self.screen) end = self.input_box.end self._draw_text(self.tittle_font,self.tittle_text,30,10) self._draw_text(self.name_font,"NAME: ",450,110) self._draw_text(self.name_font,"SCORE: {}".format(self.score),450,170) len_ = len(self.name_score_list) if len_>10: len_=10 for i in range(len_): name = self.name_score_list[i][0] score = self.name_score_list[i][1] self._draw_text(self.score_font,"{}) {}: {}".format(i+1,name,score),20,80 + 25*i) pygame.display.flip() self._clock.tick(self._fps) def main(score,lst): pygame.init() my_end = End(score,lst) end = False while not end: my_end.process() my_end.display_frame() end = my_end.input_box.end name = my_end.input_box.text print(name) return name if __name__ == "__main__": print(main())<file_sep>import pygame from pygame import sprite, image, transform from game_object.coin_model import CoinModel from game_object.coin import Coin import color class CoinModelFactory(): def __init__(self): self.__red_coin_model = CoinModel(color.RED) self.__white_coin_model = CoinModel(color.WHITE) self.__yellow_coin_model = CoinModel(color.YELLOW) self.__blue_coin_model = CoinModel(color.BLUE) def get_coin_model(self, type : str): if type == 'red_coin_model': return self.__red_coin_model elif type == 'white_coin_model': return self.__white_coin_model elif type == 'yellow_coin_model': return self.__yellow_coin_model elif type == 'blue_coin_model': return self.__blue_coin_model else: raise ValueError('[WARNING]The type don`t exists.') @staticmethod def get_list_of_types(): return ['red_coin_model','yellow_coin_model','yellow_big_coin_model','blue_coin_model']<file_sep># import pygame # pygame.init() # infoObject = pygame.display.Info() SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600<file_sep>import pygame from pygame import sprite, image import configuration class DeadGhostModel(): def __init__(self): self.images = [] for i in range(4): self.images.append(image.load('data\\sprite\\ghost\\dead\\dead_ghost_{}.png'.format(i)))
ad5268a2d518170ca7101fa0f3c103a766aab2c8
[ "Python" ]
14
Python
Ezequiel-de-la-Fuente/Pac-Man
7165b7e7141d8d9869821ffeaf98008e73b3cee7
f2287a204a70e68fce4095dc7c8aaf4e7358a11c
refs/heads/master
<file_sep>// Angular import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { InicioComponent } from './public/independent/inicio/inicio.component'; // Propios const routes: Routes = [ { path: '', component: InicioComponent }, { path: 'hombres', loadChildren: () => import('./public/hombres/hombres.module').then( m => m.HombresModule) }, { path: 'admin', loadChildren: () => import('./admin/admin.module').then ( m => m.AdminModule) }, { path:'**', redirectTo: '/' } ]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ] }) export class AppRoutingModule { } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-pantalones', templateUrl: './pantalones.component.html', styleUrls: ['./pantalones.component.css'] }) export class PantalonesComponent implements OnInit { constructor() { } ngOnInit(): void { } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HombresRoutingModule } from './hombres-routing.module'; import { MainComponent } from './main/main.component'; import { AccesoriosComponent } from './accesorios/accesorios.component'; import { PantalonesComponent } from './pantalones/pantalones.component'; import { ZapatosComponent } from './zapatos/zapatos.component'; import { CamisasComponent } from './camisas/camisas.component'; @NgModule({ declarations: [ AccesoriosComponent, CamisasComponent, MainComponent, PantalonesComponent, ZapatosComponent ], imports: [ CommonModule, HombresRoutingModule ], exports: [ HombresRoutingModule ] }) export class HombresModule { } <file_sep>// Angular import { NgModule } from '@angular/core'; // Terceros import { AccordionModule } from 'primeng/accordion'; import { ButtonModule } from 'primeng/button'; import { MenubarModule } from 'primeng/menubar'; import { OverlayPanelModule } from 'primeng/overlaypanel'; import { TableModule } from 'primeng/table'; @NgModule({ exports: [ AccordionModule, ButtonModule, MenubarModule, OverlayPanelModule, TableModule ] }) export class PrimeNGModule { } <file_sep>// Angular import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; // Propios import { AccesoriosComponent } from './accesorios/accesorios.component'; import { CamisasComponent } from './camisas/camisas.component'; import { MainComponent } from '../mujeres/main/main.component'; import { PantalonesComponent } from './pantalones/pantalones.component'; import { ZapatosComponent } from './zapatos/zapatos.component'; const routes: Routes = [ { path: '', children: [ { path: 'todos', component: MainComponent }, { path: 'accesorios', component: AccesoriosComponent }, { path: 'camisas', component: CamisasComponent }, { path: 'pantalones', component: PantalonesComponent }, { path: 'zapatos', component: ZapatosComponent }, { path: '**', redirectTo: 'todos' }, ] } ]; @NgModule({ imports: [ RouterModule.forChild(routes) ], exports: [ RouterModule ] }) export class HombresRoutingModule { } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { IndependentRoutingModule } from './independent-routing.module'; import { InicioComponent } from './inicio/inicio.component'; @NgModule({ declarations: [InicioComponent], imports: [ CommonModule, IndependentRoutingModule ], exports: [ IndependentRoutingModule ] }) export class IndependentModule { } <file_sep>// Angular import { Component, OnInit } from '@angular/core'; // Terceros import { MenuItem } from 'primeng/api'; // Propios @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.css'] }) export class HeaderComponent implements OnInit { //Arreglo de MenuItems. Nos servirá para definir los items del header items: MenuItem[] = []; termino: string = ''; constructor() { } ngOnInit(): void { // Definición de items del header this.items = [ { // Sección inicio label:'Inicio', routerLink:'/' }, { // Sección Hombres label:'Hombres', items: [ // Sub-secciones { label:'Todos', routerLink:'hombres/todos' }, { label:'Accesorios', routerLink:'hombres/accesorios' }, { label:'Camisas', routerLink:'hombres/camisas' }, { label:'Pantalones', routerLink:'hombres/pantalones' }, { label:'Zapatos', routerLink:'hombres/zapatos' } ] }, { // Sección Mujeres label:'Mujeres', items: [ //Sub-secciones { label:'Todos', routerLink: 'mujeres/todos' }, { label:'Accesorios', routerLink: 'mujeres/accesorios' }, { label:'Camisas', routerLink: 'mujeres/camisas' }, { label:'Pantalones', routerLink: 'mujeres/pantalones' }, { label:'Zapatos', routerLink: 'mujeres/zapatos' } ] }, { // Sección ofertas label:'Ofertas', items: [ // Sub-secciones ofertas { label:'Todos', routerLink: 'ofertas/todos' }, { label:'Accesorios', routerLink: 'ofertas/accesorios' }, { label:'Camisas', routerLink: 'ofertas/camisas' }, { label:'Pantalones', routerLink: 'ofertas/pantalones' }, { label:'Zapatos', routerLink: 'ofertas/zapatos' } ] } ]; } }
12fd27dc44100275dbab714cdbd4655bb098b22d
[ "TypeScript" ]
7
TypeScript
Richard-01/proyectoFinalFront
2cec3de3e434ff29eeac050600331175134e05be
2d21b87aa97c95a5ea4e9d9339cae2bc08998240
refs/heads/master
<repo_name>stnma7e/driver<file_sep>/src/filetree.rs extern crate uuid; extern crate rusqlite; use crypto::md5::Md5; use crypto::digest::Digest; use std::io::prelude::*; use std::fs::{File}; use std::path::{Path}; use std::collections::hash_map::HashMap; use uuid::Uuid; use time; use fuse::FileAttr; use types::*; pub struct FileUpdates { pub new_files: Option<Vec<FileResponse>>, pub deleted_files: Option<Vec<FileResponse>> } pub trait FileDownloader { fn get_file_list(&mut self, root_folder: &uuid::Uuid) -> Result<FileUpdates, DriveError>; fn resolve_error(&mut self, resp_string: &str) -> Result<(), DriveError>; fn verify_checksum(&self, fd: &Uuid, checksum: Option<&str>) -> Result<FileCheckResponse, DriveError>; fn retreive_file(&mut self, uuid: &Uuid, parent_uuid: &Uuid) -> Result<u64, DriveError>; fn create_local_file(&mut self, parent_uuid: &Uuid, file_path: &Path) -> Result<Uuid, DriveError>; fn read_file(&self, uuid: &Uuid) -> Result<Vec<u8>, DriveError>; fn write_file(&self, uuid: &Uuid, data: &[u8], offset: u64) -> Result<u32, DriveError>; fn flush_file(&self, uuid: &Uuid) -> Result<(), DriveError>; } pub struct FileTree<'b> { pub child_map: HashMap<u64, Vec<u64>>, pub inode_map: HashMap<u64, FileData>, pub parent_map: HashMap<u64, u64>, pub current_inode: u64, pub file_downloader: &'b mut FileDownloader, pub conn: rusqlite::Connection, } impl<'b> FileTree<'b> { fn check_for_new_files(&mut self, parent_folder_id: &uuid::Uuid, parent_inode: u64) -> Result<(), DriveError> { println!("\n\n\n"); let updates = try!( self.file_downloader.get_file_list(parent_folder_id) .or_else(|err| { println!("trying to resolve a getfilelist error"); self.file_downloader.resolve_error(&err.response.expect(&format!("no response in errorrr: {:?}", err.kind))) .and(self.file_downloader.get_file_list(parent_folder_id)) .or_else(|err| -> Result<FileUpdates, DriveError> { println!("err: {:?}", err); Err(err) }) }) ); if let Some(new_files) = updates.new_files { for fr in new_files { let inode = self.current_inode; self.current_inode += 1; let kind = if fr.kind == FileType::Directory { "directory" } else { "regular" }; let mut size = 0; { let parent_ino = self.conn.query_row_named("SELECT ino FROM files WHERE uuid=:uuid" , &[( ":uuid", &fr.parent_uuid.clone().as_bytes().to_vec() )] , |row| -> u64 { row.get::<i32, i64>(0) as u64 } ).unwrap(); let parent = try!(self.inode_map.get(&parent_ino).ok_or(DriveError { kind: DriveErrorType::NoSuchInode, response: None, })); match self.file_downloader.retreive_file(&fr.uuid, &parent.id) { Ok(s) => { size = s; }, Err(error) => { println!("error when saving or downloading file: {:?}", error); println!("deleting metadata, and trying a fresh save"); try!( (match error.response { Some(ref resp) => { self.file_downloader.resolve_error(resp) }, None => { println!("no response in error: {:?}", error.kind); Err(error) } }) .and(self.file_downloader.retreive_file(&fr.uuid, &parent.id)) .or_else(|err| -> Result<u64, DriveError> { println!("error resolution failed. err2: {:?}", err); Ok(0) }) ); } } } self.conn.execute("INSERT INTO files (ino, uuid, parent_ino, name, size, kind) VALUES ($1, $2, $3, $4, $5, $6)", &[ &(inode as i64), &fr.uuid.clone().as_bytes().to_vec(), &(parent_inode as i64), &fr.name.clone(), &(size as i64), &kind, ] ).unwrap_or_else(|_| { // println!("file already in filetree db: {}, err: {:?}", fr.name, err); // println!("updating file information"); self.conn.execute("UPDATE files SET name=$1 WHERE uuid=$3" , &[ &fr.name.clone() , &fr.uuid.clone().as_bytes().to_vec() ] ).unwrap_or_else(|err| { println!("couldn't update file in filetree db, err: {:?}", err); 0 }); 0 }); } } if let Some(del_files) = updates.deleted_files { for fr in del_files { self.conn.execute("DELETE FROM files WHERE uuid=:uuid" , &[ &fr.uuid.clone().as_bytes().to_vec() ] ).unwrap_or_else(|err| { println!("couldn't delte file: {}, err: {:?}", fr.name, err); 0 }); } } Ok(()) } pub fn get_files(&mut self, parent_folder_path: &Path, parent_folder_id: &uuid::Uuid, parent_inode: u64) -> Result<(), DriveError> { try!(self.check_for_new_files(parent_folder_id, parent_inode)); println!("Populating FUSE fs... "); self._get_files(parent_folder_path, parent_folder_id, parent_inode) } fn _get_files(&mut self, parent_folder_path: &Path, parent_folder_id: &uuid::Uuid, parent_inode: u64) -> Result<(), DriveError> { let files = { let mut stmt = try!(self.conn.prepare("SELECT uuid, ino, name, kind, size FROM files WHERE parent_ino=:parent_ino")); let rows = try!(stmt.query_map_named(&[(":parent_ino", &(parent_inode as i64))] , |row| -> FileData { let uuid = Uuid::from_bytes(&row.get::<i32, Vec<u8>>(0)).unwrap(); let ino = row.get::<i32, i64>(1) as u64; let name = row.get::<i32, String>(2); let str_kind = row.get::<i32, String>(3); let size = row.get::<i32, i64>(4) as u64; let ts = time::now().to_timespec(); let mut fadsf = FileType::RegularFile; if str_kind == "directory" { fadsf = FileType::Directory; } let mut new_path = parent_folder_path.to_owned(); new_path.push(name.clone()); FileData { id: uuid, path: new_path, parent_inode: parent_inode, attr: FileAttr { ino: ino, size: size, blocks: size/512, atime: ts, mtime: ts, ctime: ts, crtime: ts, kind: fadsf, perm: 0o777, nlink: 0, uid: 1000, gid: 1000, rdev: 0, flags: 0, }, source_data: SourceData::CreatedFile, } } )); let mut files = Vec::new(); for i in rows { files.push(i.unwrap()) } files.clone() }; for fd in files { //println!("found parent {}, adding new child {:?}, inode: {}", parent_folder_id, fd.path, fd.attr.ino); self.inode_map.entry(fd.attr.ino).or_insert(fd.clone()); self.child_map.entry(fd.attr.ino).or_insert(Vec::new()); self.parent_map.entry(fd.attr.ino).or_insert(parent_inode); self.child_map.entry(parent_inode).or_insert(Vec::new()) .push(fd.attr.ino); // then recurse to retrieve children files if fd.attr.kind == FileType::Directory && fd.attr.ino != 1 { try!(self._get_files(&fd.path, &fd.id, fd.attr.ino)); } } Ok(()) } } pub fn get_file_checksum(file_path: &Path) -> Result<String, DriveError> { let mut f = try!(File::open(file_path)); let mut f_str = Vec::<u8>::new(); try!(f.read_to_end(&mut f_str)); let mut md5 = Md5::new(); md5.input(&f_str); Ok(md5.result_str()) } <file_sep>/src/types.rs #![allow(non_snake_case)] // to simplify json decoding for the Response types extern crate hyper; extern crate rustc_serialize; extern crate libc; extern crate std; extern crate uuid; extern crate rusqlite; use rustc_serialize::json::{Json, ToJson}; use std::collections::BTreeMap; use std::path::{PathBuf}; pub use fuse::FileType; use fuse::FileAttr; #[derive (RustcDecodable, Debug, Clone)] pub struct TokenResponse { pub access_token: String, pub token_type: String, pub expires_in: u32, pub id_token: String, pub refresh_token: String, } impl ToJson for TokenResponse { fn to_json(&self) -> Json { let mut d = BTreeMap::new(); d.insert("access_token".to_string(), self.access_token.to_json()); d.insert("token_type".to_string(), self.token_type.to_json()); d.insert("expires_in".to_string(), self.expires_in.to_json()); d.insert("id_token".to_string(), self.id_token.to_json()); d.insert("refresh_token".to_string(), self.refresh_token.to_json()); Json::Object(d) } } #[derive (RustcDecodable, Debug, Clone)] pub struct DriveFileResponse { pub kind: String, // essentially unused, will ostensibly always be "drive#file" pub id: String, pub name: String, pub mimeType: String, pub parents: Vec<String>, pub path: Option<PathBuf>, } #[derive (Debug, Clone)] pub enum SourceData { CreatedFile, Drive(DriveFileResponse), } #[derive (Debug, Clone)] pub struct FileResponse { pub uuid: uuid::Uuid, pub parent_uuid: uuid::Uuid, pub kind: FileType, pub name: String, pub source_data: SourceData, } #[derive (Debug, Clone)] pub struct FileData { pub id: uuid::Uuid, pub parent_inode: u64, pub path: PathBuf, pub attr: FileAttr, pub source_data: SourceData, } impl ToJson for DriveFileResponse { fn to_json(&self) -> Json { let mut d = BTreeMap::new(); // All standard types implement `to_json()`, so use it d.insert("kind".to_string(), self.kind.to_json()); d.insert("id".to_string(), self.id.to_json()); d.insert("name".to_string(), self.name.to_json()); d.insert("mimeType".to_string(), self.mimeType.to_json()); Json::Object(d) } } #[derive (RustcDecodable, Debug, Clone)] pub struct ErrorDetailsResponse { pub domain: String, pub reason: String, pub message: String, } #[derive (RustcDecodable, RustcEncodable, Debug, Clone)] pub struct FileCheckResponse { pub md5Checksum: String, pub size: u64, } #[derive (Clone)] pub struct AuthData { pub tr: TokenResponse, pub client_id: String, pub client_secret: String, // maybe this can be converted to a std::path::Path later? pub cache_file_path: String, } #[derive (Debug)] pub enum DriveErrorType { Hyper(hyper::error::Error), Rusqlite(rusqlite::Error), JsonDecodeFileList, JsonReadError(rustc_serialize::json::BuilderError), JsonObjectify, JsonInvalidAttribute, JsonCannotConvertToArray, JsonCannotDecode(rustc_serialize::json::DecoderError), JsonCannotEncode(rustc_serialize::json::EncoderError), Io(std::io::Error), UnsupportedDocumentType, FailedChecksum, FailedToChecksumExistingFile, Tester, NoFileName, FailedUuidLookup, NoSuchInode, NoPathForParent, FileNotYetDownloaded, WrongSourceDataType, } #[derive (Debug)] pub struct DriveError { pub kind: DriveErrorType, pub response: Option<String>, } impl From<hyper::error::Error> for DriveError { fn from(err: hyper::error::Error) -> DriveError { DriveError { kind: DriveErrorType::Hyper(err), response: None } } } impl From<rusqlite::Error> for DriveError { fn from(err: rusqlite::Error) -> DriveError { DriveError { kind: DriveErrorType::Rusqlite(err), response: None } } } impl From<rustc_serialize::json::BuilderError> for DriveError { fn from(err: rustc_serialize::json::BuilderError) -> DriveError { DriveError { kind: DriveErrorType::JsonReadError(err), response: None } } } impl From<rustc_serialize::json::DecoderError> for DriveError { fn from(err: rustc_serialize::json::DecoderError) -> DriveError { DriveError { kind: DriveErrorType::JsonCannotDecode(err), response: None } } } impl From<std::io::Error> for DriveError { fn from(err: std::io::Error) -> DriveError { DriveError { kind: DriveErrorType::Io(err), response: None } } } impl From<rustc_serialize::json::EncoderError> for DriveError { fn from(err: rustc_serialize::json::EncoderError) -> DriveError { DriveError { kind: DriveErrorType::JsonCannotEncode(err), response: None, } } } <file_sep>/src/fs.rs #![allow(unused_variables)] extern crate uuid; use std::path::Path; use libc::{ENOENT, ENOSYS}; use time; use time::Timespec; use fuse::{FileAttr, Filesystem, Request, ReplyAttr, ReplyEntry, ReplyDirectory, ReplyData, ReplyOpen, ReplyEmpty, ReplyWrite, ReplyStatfs, ReplyCreate, ReplyLock, ReplyBmap}; use std::ffi::OsStr; use std::fs::{File}; use std::os::unix::io::{IntoRawFd, FromRawFd}; use uuid::Uuid; use filetree::*; use types::*; impl<'b> Filesystem for FileTree<'b> { fn getattr(&mut self, _req: &Request, ino: u64, reply: ReplyAttr) { println!("getattr(ino={})", ino); if let Some(path) = self.inode_map.get(&ino) { let ttl = time::now().to_timespec(); reply.attr(&ttl, &path.attr); return } else { println!("erro in getattr, ino={}", ino); reply.error(ENOSYS); return } } fn lookup(&mut self, _req: &Request, parent: u64, name: &Path, reply: ReplyEntry) { if let Some(children) = self.child_map.get(&parent) { for i in children { if let Some(child) = self.inode_map.get(&i) { let path = child.path.clone(); if path.file_name().expect(&format!("no file_name {:?}", child)) == name { let ttl = time::now().to_timespec(); reply.entry(&ttl, &child.attr, 0); return } } } } reply.error(ENOENT) } fn readdir(&mut self, _req: &Request, ino: u64, fh: u64, offset: u64, mut reply: ReplyDirectory) { println!("readdir(ino={}, fh={}, offset={})", ino, fh, offset); if offset == 0 { reply.add(ino, 0, FileType::Directory, &Path::new(".")); reply.add(*self.parent_map.get(&ino).expect(&format!("no parent inode for {}", ino)), 1, FileType::Directory, &Path::new("..")); let mut new_offest = 1; if let Some(children) = self.child_map.get(&ino) { new_offest += 1; for child_inode in children { if let Some(child) = self.inode_map.get(&child_inode) { reply.add(*child_inode, new_offest, child.attr.kind, &child.path.file_name().expect(&format!("no file_name {:?}", child))); } else { println!("no inode for child {:?}, parent {:?}", child_inode, children); panic!() } } reply.ok(); return } else { println!("fdasd"); } } reply.error(ENOENT); } fn read(&mut self, _req: &Request, ino: u64, fh: u64, offset: u64, size: u32, reply: ReplyData) { println!("read(ino={}, fh={}, offset={}, size={})", ino, fh, offset, size); if let Some(fd) = self.inode_map.get(&ino) { match self.file_downloader.read_file(&fd.id) { Ok(data) => { let offset = if offset >= data.len() as u64 { println!("offset change: {} -> {}", offset, data.len()); (data.len() - 1) as u64 } else { offset }; let real_size: usize = if size as u64 + offset >= data.len() as u64 { (data.len() - offset as usize) as usize } else { size as usize }; let d = data[offset as usize..(offset + real_size as u64) as usize].to_vec(); println!("{}", d.len()); reply.data(&d); return }, Err(err) => { println!("err when reading file, id: {}: {:?}", ino, err) } } } else { println!("no inode found in map, {}", ino); } reply.error(ENOENT); } // implement open flags with file handle later fn open(&mut self, _req: &Request, ino: u64, flags: u32, reply: ReplyOpen) { println!("open(ino={})", ino); let uuid = self.conn.query_row_named("SELECT uuid FROM files WHERE ino=:ino" , &[( ":ino", &(ino as i64) )] , |row| -> Uuid { Uuid::from_bytes(&row.get::<i32, Vec<u8>>(0)).unwrap() } ).unwrap(); match self.file_downloader.verify_checksum(&uuid, None) { Ok(_) => reply.opened(0, flags), Err(err) => { println!("err in validating checksum of local file, err: {:?}", err); reply.error(0) } } } fn forget(&mut self, _req: &Request, _ino: u64, _nlookup: u64) { println!("forget(ino={})", _ino); } fn setattr(&mut self, _req: &Request, _ino: u64, _mode: Option<u32>, _uid: Option<u32>, _gid: Option<u32>, _size: Option<u64>, _atime: Option<Timespec>, _mtime: Option<Timespec>, _fh: Option<u64>, _crtime: Option<Timespec>, _chgtime: Option<Timespec>, _bkuptime: Option<Timespec>, _flags: Option<u32>, reply: ReplyAttr) { println!("setattr(ino={}, mode={:?}, uid={:?})", _ino, _mode, _uid); if let Some(path) = self.inode_map.get(&_ino) { let ts = time::now().to_timespec(); reply.attr(&ts, &path.attr); return } reply.error(ENOENT) } fn readlink(&mut self, _req: &Request, _ino: u64, reply: ReplyData) { unimplemented!() } fn mknod(&mut self, _req: &Request, _parent: u64, _name: &Path, _mode: u32, _rdev: u32, reply: ReplyEntry) { println!("mknod(name={:?}, parent={}, mode={})", _name, _parent, _mode); reply.error(ENOENT) } fn mkdir(&mut self, _req: &Request, _parent: u64, _name: &Path, _mode: u32, reply: ReplyEntry) { unimplemented!() } fn unlink(&mut self, _req: &Request, _parent: u64, _name: &Path, reply: ReplyEmpty) { unimplemented!() } fn rmdir(&mut self, _req: &Request, _parent: u64, _name: &Path, reply: ReplyEmpty) { unimplemented!() } fn symlink(&mut self, _req: &Request, _parent: u64, _name: &Path, _link: &Path, reply: ReplyEntry) { unimplemented!() } fn rename(&mut self, _req: &Request, _parent: u64, _name: &Path, _newparent: u64, _newname: &Path, reply: ReplyEmpty) { unimplemented!() } fn link(&mut self, _req: &Request, _ino: u64, _newparent: u64, _newname: &Path, reply: ReplyEntry) { unimplemented!() } fn write(&mut self, _req: &Request, _ino: u64, _fh: u64, _offset: u64, _data: &[u8], _flags: u32, reply: ReplyWrite) { println!("write(ino={}, fh={}, offset={}, len={})", _ino, _fh, _offset, _data.len()); let uuid = self.conn.query_row_named("SELECT uuid FROM files WHERE ino=:ino" , &[( ":ino", &(_ino as i64) )] , |row| -> Uuid { Uuid::from_bytes(&row.get::<i32, Vec<u8>>(0)).unwrap() } ).unwrap(); reply.written(self.file_downloader.write_file(&uuid, _data, _offset).unwrap()) } fn flush(&mut self, _req: &Request, _ino: u64, _fh: u64, _lock_owner: u64, reply: ReplyEmpty) { println!("flush(ino={}, fh={})", _ino, _fh); let uuid = self.conn.query_row_named("SELECT uuid FROM files WHERE ino=:ino" , &[( ":ino", &(_ino as i64) )] , |row| -> Uuid { Uuid::from_bytes(&row.get::<i32, Vec<u8>>(0)).unwrap() } ).unwrap(); match self.file_downloader.flush_file(&uuid) { Ok(_) => reply.ok(), Err(err) => { println!("error while flushing {}, {:?}", _ino, err); reply.error(-1); } } } fn release(&mut self, _req: &Request, _ino: u64, _fh: u64, _flags: u32, _lock_owner: u64, _flush: bool, reply: ReplyEmpty) { println!("release(ino={}, fh={}, flush={:?})", _ino, _fh, _flush); unsafe { let _: File = FromRawFd::from_raw_fd(_fh as i32); // when fd goes out of scope, it will close the file? } reply.ok(); } fn fsync(&mut self, _req: &Request, _ino: u64, _fh: u64, _datasync: bool, reply: ReplyEmpty) { unimplemented!() } fn opendir(&mut self, _req: &Request, ino: u64, _flags: u32, reply: ReplyOpen) { println!("opendir(ino={})", ino); if ino == 1 { match File::open("random asas place") { Ok(handle) => { let h = handle.into_raw_fd(); reply.opened(h as u64, _flags); return } Err(_) => { } } } if let Some(fd) = self.inode_map.get(&ino) { match File::open(&fd.path) { Ok(handle) => { let h = handle.into_raw_fd(); reply.opened(h as u64, _flags); return } Err(error) => { //println!("no downloaded folder for {}, err: {:?}", fd.path.to_string_lossy(), error); } } } else { println!("no inode found in map, {}", ino); } // reply.error(ENOENT); reply.opened(0, _flags) } fn releasedir(&mut self, _req: &Request, _ino: u64, _fh: u64, _flags: u32, reply: ReplyEmpty) { println!("releasedir(ino={}, fh={})", _ino, _fh); unsafe { let _: File = FromRawFd::from_raw_fd(_fh as i32); // when fd goes out of scope, it will close the file? } reply.ok() } fn fsyncdir(&mut self, _req: &Request, _ino: u64, _fh: u64, _datasync: bool, reply: ReplyEmpty) { unimplemented!() } fn statfs(&mut self, _req: &Request, _ino: u64, reply: ReplyStatfs) { println!("statfs(ino={})", _ino); reply.error(ENOENT) } fn setxattr(&mut self, _req: &Request, _ino: u64, _name: &OsStr, _value: &[u8], _flags: u32, _position: u32, reply: ReplyEmpty) { unimplemented!() } fn getxattr(&mut self, _req: &Request, _ino: u64, _name: &OsStr, reply: ReplyData) { println!("getxattr(ino={}, name={:?})", _ino, _name); } fn listxattr(&mut self, _req: &Request, _ino: u64, reply: ReplyEmpty) { unimplemented!() } fn removexattr(&mut self, _req: &Request, _ino: u64, _name: &OsStr, reply: ReplyEmpty) { unimplemented!() } fn access(&mut self, _req: &Request, _ino: u64, _mask: u32, reply: ReplyEmpty) { println!("access(ino={})", _ino); if self.inode_map.contains_key(&_ino) { reply.ok() } else { reply.error(ENOENT) } } fn create(&mut self, _req: &Request, parent_inode: u64, _name: &Path, _mode: u32, _flags: u32, reply: ReplyCreate) { println!("create(name{:?}, parent={}, mode={}, flags={})", _name, parent_inode, _mode, _flags); let inode = self.conn.query_row("SELECT MAX(ino) FROM files" , &[], |row| -> u64 { row.get::<i32, i64>(0) as u64 } ).unwrap() + 1; let (parent_uuid, parent_path) = self.conn.query_row_named("SELECT uuid, path FROM files WHERE parent_ino=:parent_ino" , &[ (":parent_ino", &(parent_inode as i64)) ] , |row| -> (Uuid, String) { ( Uuid::from_bytes(&row.get::<i32, Vec<u8>>(0)).unwrap() , row.get(1) ) } ).unwrap(); let ts = time::now().to_timespec(); let uuid = self.file_downloader.create_local_file(&parent_uuid, _name).unwrap(); let path = Path::new(&(parent_path + &_name.to_str().unwrap())).to_owned(); let fd = FileData { id: uuid, parent_inode: parent_inode, path: path, attr: FileAttr { ino: inode, size: 0, blocks: 0, atime: ts, mtime: ts, ctime: ts, crtime: ts, kind: FileType::RegularFile, perm: 0o777, nlink: 0, uid: 1000, gid: 1000, rdev: 0, flags: 0, }, source_data: SourceData::CreatedFile, }; self.child_map.entry(parent_inode).or_insert(Vec::new()) .push(inode); self.inode_map.entry(inode).or_insert(fd.clone()); self.child_map.entry(inode).or_insert(Vec::new()); self.parent_map.entry(inode).or_insert(parent_inode); self.conn.execute("INSERT INTO files (ino, uuid, parent_ino, name, size, kind) VALUES ($1, $2, $3, $4, $5, $6)" , &[ &(inode as i64), &uuid.clone().as_bytes().to_vec(), &(parent_inode as i64), &(_name.to_str().expect("nilfalsdfs")), &(0 as i64), ] ).unwrap(); reply.created(&ts, &fd.attr, fd.attr.ino, 0, 0) } fn getlk(&mut self, _req: &Request, _ino: u64, _fh: u64, _lock_owner: u64, _start: u64, _end: u64, _typ: u32, _pid: u32, reply: ReplyLock) { unimplemented!() } fn setlk(&mut self, _req: &Request, _ino: u64, _fh: u64, _lock_owner: u64, _start: u64, _end: u64, _typ: u32, _pid: u32, _sleep: bool, reply: ReplyEmpty) { unimplemented!() } fn bmap(&mut self, _req: &Request, _ino: u64, _blocksize: u32, _idx: u64, reply: ReplyBmap) { unimplemented!() } } <file_sep>/src/main.rs #![allow(non_snake_case)] #![allow(dead_code)] #![allow(unused_variables)] extern crate hyper; extern crate rustc_serialize; extern crate driver; extern crate fuse; extern crate uuid; extern crate time; extern crate rusqlite; use std::collections::hash_map::HashMap; use std::path::Path; use uuid::Uuid; use fuse::FileAttr; use driver::types::*; use driver::filetree::*; use driver::drive::*; fn main() { // let root_folder = (vec![], "0B7TtU3YsiIjTTS1oUE5wZFpsYVk"); let root_folder_name = ".drive_files2"; let root_folder_path = Path::new(root_folder_name); // let root_folder_id = "0B7TtU3YsiIjTWjBOM0YwYkVBa1U"; // let root_folder_id = "0B7TtU3YsiIjTaEd3WlVSMGRERlk"; // let root_folder_id = "root"; let root_folder_id = "0B7TtU3YsiIjTeW1vTGc0a1Y1MFE"; let root_folder_inode = 1; // let root_folder = (vec!["rot".to_string()], "0B7TtU3YsiIjTeHJGR1VKMHB3cWs"); let conn = rusqlite::Connection::open("files.db").unwrap(); let root_folder_uuid = { conn.query_row("SELECT uuid FROM files WHERE ino=1", &[] , |row| -> Uuid { Uuid::from_bytes(&row.get::<i32, Vec<u8>>(0)).expect("Fdafkn") }).unwrap_or(Uuid::new_v4()) }; let last_ino = { conn.query_row("SELECT ino FROM FILES WHERE ino = (SELECT MAX(ino) FROM files)" , &[] , |row| -> u64 { (row.get::<i32, i64>(0) + 1) as u64 } ).unwrap_or(root_folder_inode) }; let mut fd = DriveFileDownloader::new( root_folder_uuid, root_folder_id.to_string(), Path::new(root_folder_name).to_owned(), rusqlite::Connection::open("drive.db").unwrap() ).expect("failure in reading access file"); let mut ft = FileTree { inode_map: HashMap::new(), child_map: HashMap::new(), parent_map: HashMap::new(), current_inode: last_ino, file_downloader: &mut fd, conn: conn, }; ft.conn.execute("INSERT INTO files (ino, uuid, parent_ino, name, size, kind) VALUES ($1, $2, $3, $4, $5, $6)", &[ &(1 as i64) , &root_folder_uuid.clone().as_bytes().to_vec() , &(1 as i64) , &"root".to_string() , &(0 as i64) , &"directory" ] ).unwrap_or(0); let ts = time::now().to_timespec(); ft.inode_map.entry(root_folder_inode).or_insert(FileData { id: root_folder_uuid.clone(), path: root_folder_path.to_owned(), parent_inode: root_folder_inode, attr: FileAttr { ino: root_folder_inode, size: 0, blocks: 0, atime: ts, mtime: ts, ctime: ts, crtime: ts, kind: FileType::Directory, perm: 0o777, nlink: 0, uid: 1000, gid: 1000, rdev: 0, flags: 0, }, source_data: SourceData::CreatedFile, }); ft.child_map.entry(ft.current_inode).or_insert(Vec::new()); ft.parent_map.entry(ft.current_inode).or_insert(ft.current_inode); ft.current_inode += 1; ft.get_files(Path::new(""), &root_folder_uuid, root_folder_inode) .expect("this shit fucked up"); // println!("{:?}\n", ft.inode_map); // println!("{:?}", ft.child_map); fuse::mount(ft, &"root.2", &[]); } <file_sep>/src/drive.rs extern crate uuid; extern crate std; extern crate rusqlite; use std::borrow::Cow; use url::percent_encoding::{utf8_percent_encode, QUERY_ENCODE_SET}; use time; use time::{Timespec, Tm}; use std::str; use hyper::{Client}; use hyper::header::{ContentType, Authorization, Bearer}; use hyper::client::{Body}; use mime::{Mime, TopLevel, SubLevel}; use std::collections::hash_map::HashMap; use rustc_serialize::json::{Json, ToJson, Decoder, as_pretty_json}; use rustc_serialize::{json, Decodable}; use std::io; use std::io::SeekFrom; use std::io::prelude::*; use std::fs::{File, DirBuilder,OpenOptions}; use crypto::md5::Md5; use crypto::digest::Digest; use std::path::{Path, PathBuf}; use uuid::Uuid; use types::*; use filetree::*; pub struct DriveFileDownloader { pub client: Client, pub auth_data: AuthData, uuid_map: HashMap<Uuid, DriveFileResponse>, conn: rusqlite::Connection, } const CACHE_FILE: &'static str = "access"; const CLIENT_ID: &'static str = "460434421766-0sktb0rkbvbko8omj8vhu8vv83giraao.apps.googleusercontent.com"; const CLIENT_SECRET: &'static str = "<KEY>"; struct DownloadedFileInformation { size: u64, checksum: String, path: PathBuf, } impl DriveFileDownloader { pub fn new(root_uuid: Uuid, root_id: String, file_path: PathBuf, db_conn: rusqlite::Connection) -> Result<DriveFileDownloader, DriveError> { let c = Client::new(); let mut handle = try!(OpenOptions::new() .read(true) .write(true) .create(true) .open(CACHE_FILE)); let mut access_string = String::new(); try!(handle.read_to_string(&mut access_string)); println!("{}", access_string); let tr: TokenResponse = match json::decode(&access_string) { Ok(tr) => tr, Err(_) => { let tr = try!(request_new_access_code(&c)); println!("{}", tr.clone().to_json().to_string()); try!(handle.write_all(tr.to_json().pretty().to_string().as_bytes())); tr } }; db_conn.execute("INSERT INTO files (id, uuid, path) VALUES ($1, $2, $3)" , &[ &root_id, &root_uuid.clone().as_bytes().to_vec(), &file_path.to_str().unwrap() ] ).unwrap_or_else(| err| { println!("root probably already in drive db, err: {:?}", err); 0 } ); let mut uuid_map = HashMap::new(); uuid_map.insert(root_uuid, DriveFileResponse { kind: "drive#file".to_string(), id: root_id.clone(), name: "".to_string(), mimeType: "application/vnd.google-apps.folder".to_string(), parents: vec!(root_id), path: Some(file_path), }); Ok(DriveFileDownloader { client: c, auth_data: AuthData { tr: tr, client_id: CLIENT_ID.to_string(), client_secret: CLIENT_SECRET.to_string(), cache_file_path: CACHE_FILE.to_string(), }, uuid_map: uuid_map, conn: db_conn, }) } fn download_file(&self, uuid: &Uuid, parent_uuid: &Uuid) -> Result<DownloadedFileInformation, DriveError> { let fr = try!(self.uuid_map.get(uuid).ok_or(DriveError { kind: DriveErrorType::FailedUuidLookup, response: None, })).clone(); let parent_path = try!(self.uuid_map.get(parent_uuid).ok_or(DriveError { kind: DriveErrorType::FailedUuidLookup, response: None, })).path.clone(); if fr.mimeType == "application/vnd.google-apps.document" || fr.mimeType == "application/vnd.google-apps.form" || fr.mimeType == "application/vnd.google-apps.drawing" || fr.mimeType == "application/vnd.google-apps.fusiontable" || fr.mimeType == "application/vnd.google-apps.map" || fr.mimeType == "application/vnd.google-apps.presentation" || fr.mimeType == "application/vnd.google-apps.spreadsheet" || fr.mimeType == "application/vnd.google-apps.sites" { println!("unsupported google filetype"); return Err(DriveError { kind: DriveErrorType::UnsupportedDocumentType, response: None }) } let mut file_path = try!(parent_path.ok_or(DriveError { kind: DriveErrorType::NoPathForParent, response: None, })); file_path.push(fr.name.clone()); // we'll checksum the file (if we have it) on the system, and compare it to the // server, if all is OK, create a new metadata file let (maybe_checksum, maybe_path) = try!(self.conn.query_row_named("SELECT checksum, path FROM files WHERE uuid=:uuid" , &[(":uuid", &uuid.clone().as_bytes().to_vec())] , |row| -> (Option<String>, Option<PathBuf>) { ( row.get(0) , if let Some(path) = row.get::<i32, Option<String>>(1) { Some(Path::new(&path).to_owned()) } else { None } ) } )); let fn_download_file = |file_path: PathBuf| { // the file data doesn't yet exist, so we'll download it from scratch println!("downloading new file, creating new file: {:?}", file_path); let mut f = try!(File::create(file_path.clone())); let mut resp = try!(self.client.get(&format!("https://www.googleapis.com/drive/v3/files/{}\ ?alt=media", fr.id.clone())) .header(Authorization(Bearer{token: self.auth_data.tr.access_token.clone()})) .send()); let check_response = try!(self.verify_checksum(uuid, None)); let size = check_response.size; println!("md5: {}, size: {}", check_response.md5Checksum, size); self.conn.execute("UPDATE files SET checksum=$1, size=$2 WHERE uuid=$3", &[ &check_response.md5Checksum, &(check_response.size as i64), &uuid.clone().as_bytes().to_vec(), ]).unwrap(); Ok(DownloadedFileInformation { size: size, checksum: check_response.md5Checksum, path: file_path, }) }; if let Some(checksum) = maybe_checksum { // if the checksum matches that from Drive, then file is downloaded // correctly, and all we need to do is cache the checksum self.verify_checksum(uuid, Some(&checksum)) .and_then(|check_response| { Ok(DownloadedFileInformation { size: check_response.size, path: file_path.clone(), checksum: checksum, }) }).or_else(|_| { fn_download_file(file_path.clone()) }) } else if let Some(path) = maybe_path { // if we have a path for the file, we can chcek to see if any local data is // already valid get_file_checksum(&path).and_then(|ck| { // check with Drive for a the valid checksum self.verify_checksum(uuid, Some(&ck)) .and_then(|check_response| { Ok(DownloadedFileInformation { size: check_response.size, path: file_path.clone(), checksum: ck, }) }) }).or_else(|_| { fn_download_file(file_path.clone()) }) } else { // we have neither a path for local data, nor a local checksum fn_download_file(file_path.clone()) } } } define_encode_set! { /// This encode set is used in the URL parser for query strings. pub DRIVE_QUERY_ENCODE_SET = [QUERY_ENCODE_SET] | {':'} } impl FileDownloader for DriveFileDownloader { fn get_file_list(&mut self, root_folder_uuid: &uuid::Uuid) -> Result<FileUpdates, DriveError> { let uuid_vec = root_folder_uuid.clone().as_bytes().to_vec(); let (parent_id, parent_path) = try!(self.conn.query_row_named("SELECT id, path FROM files WHERE uuid=:uuid" , &[(":uuid", &uuid_vec)] , |row| -> (String, PathBuf) { ( row.get(0) , Path::new(&row.get::<i32, String>(1)).to_owned() ) } )); println!("getting file list for parent ID: {}", parent_id); let lastdate = self.conn.query_row_named("SELECT MAX(last_update) FROM meta WHERE uuid = :uuid" , &[(":uuid", &uuid_vec)] , |row| -> Timespec { row.get(0) } ).unwrap_or(Timespec::new(0,0)); println!("{:?}", convert_timespec_to_tm(lastdate)); // date from which modified files should be updated // older ones should be locally valid let lastdate = format!("{}", convert_timespec_to_tm(lastdate).rfc3339()); let lastdate_encoded = utf8_percent_encode(&lastdate, DRIVE_QUERY_ENCODE_SET{}); let query = format!("https://www.googleapis.com/drive/v3/files\ ?corpus=domain\ &pageSize=1000\ &fields=files\ &q=%27{}%27+in+parents\ +and+modifiedTime%3E'{}'\ +and+trashed+%3D+" , parent_id , lastdate_encoded); println!("{}", query); let new_resp = { println!("{}", parent_id); try!(self.client.get(&(query.clone()+"false")) .header(Authorization(Bearer{token: self.auth_data.tr.access_token.clone()})) .send()) }; let del_resp = { println!("{}", parent_id); try!(self.client.get(&(query+"true")) .header(Authorization(Bearer{token: self.auth_data.tr.access_token.clone()})) .send()) }; let mut resps = vec!(new_resp, del_resp); let mut files = vec!(Vec::new(), Vec::new()); for (resp, files_list) in resps.iter_mut().zip(files.iter_mut()) { // convert the response to a string, then to a JSON object let mut resp_string = String::new(); try!(resp.read_to_string(&mut resp_string)); println!("{}", resp_string); let fr_obj = try!((Json::from_str(&resp_string)).map_err(From::from) .and_then(|fr_data: Json| -> Result<json::Object, DriveError> { fr_data.into_object() .ok_or(DriveError { kind: DriveErrorType::JsonObjectify, response: Some(resp_string.clone()) }) }).or_else(|err| { println!("there's probably something wrong with the get_file_list response, err: {:?}", err); Err(err) }) ); //println!("{}", resp_string); let files = try!(fr_obj.get("files") .ok_or(DriveError { kind: DriveErrorType::JsonInvalidAttribute, response: Some(resp_string.clone()) })); let files_array = try!(files.as_array() .ok_or(DriveError { kind: DriveErrorType::JsonCannotConvertToArray, response: Some(resp_string.clone()) })); for i in files_array.into_iter() { // we'll try to decode each file's metadata JSON object in memory to a DriveFileResponse struct let mut decoder = Decoder::new(i.clone()); let fr: DriveFileResponse = try!(Decodable::decode(&mut decoder)); let kind = if fr.mimeType == "application/vnd.google-apps.folder" { FileType::Directory } else { FileType::RegularFile }; let mut path = parent_path.clone(); path.push(fr.name.clone()); let uuid = self.conn.query_row_named("SELECT uuid FROM files WHERE id=:id" , &[(":id", &fr.id)] , |row| -> Uuid { Uuid::from_bytes(&row.get::<i32, Vec<u8>>(0)).expect("failed to parse Uuid from drive db storage") } ).and_then(|uuid| -> Result<Uuid, rusqlite::Error> { self.conn.execute("UPDATE files SET path=$1, mimetype=$2 WHERE uuid=$3" , &[ &(path.to_str().expect("nilfalsdfs")) , &fr.mimeType , &uuid.clone().as_bytes().to_vec() ] ).unwrap_or_else(|err| { println!("couldn't update file in drive db, err: {:?}", err); 0 }); Ok(uuid) }).unwrap_or_else(|_| { let uuid = Uuid::new_v4(); self.conn.execute("INSERT INTO files (uuid, id, mimetype, path) VALUES ($1, $2, $3, $4)" , &[ &uuid.clone().as_bytes().to_vec() , &fr.id , &fr.mimeType , &(path.to_str().expect("fadsfnjfsad")) ] ).unwrap_or_else(|_| { println!("file already in drive db: {}", fr.name); 0 }); uuid }); { self.uuid_map.insert(uuid, fr.clone()); } assert!(fr.parents.len() == 1); let parent_uuid = self.conn.query_row_named("SELECT uuid FROM files WHERE id=:id" , &[( ":id", &fr.parents[0] )] , |row| -> Uuid { Uuid::from_bytes(&row.get::<i32, Vec<u8>>(0)).expect("failed to parse parent Uuid from drive db storage") } ).unwrap(); // println!("drive adding path: {:?} {:?}", uuid.clone().as_bytes().to_vec(), path); files_list.push(FileResponse { uuid: uuid, parent_uuid: parent_uuid, kind: kind, name: fr.name.clone(), source_data: SourceData::Drive(fr) }); } try!(self.conn.execute("INSERT INTO meta (uuid, last_update, num_files_updated) VALUES ($1, $2, $3)", &[ &uuid_vec, &time::now().to_timespec(), &(files_list.len() as i64) ] )); } for ref fr in &files[1] { self.conn.execute("DELETE FROM files WHERE uuid=:uuid" , &[ &fr.uuid.clone().as_bytes().to_vec() ] ).unwrap_or_else(|err| { println!("couldn't delte file: {}, err: {:?}", fr.name, err); 0 }); } Ok(FileUpdates{ new_files: Some(files[0].clone()), deleted_files: Some(files[1].clone()) }) } fn retreive_file(&mut self, uuid: &Uuid, parent_uuid: &Uuid) -> Result<u64, DriveError> { let fr = try!(self.uuid_map.get(uuid).ok_or(DriveError { kind: DriveErrorType::FailedUuidLookup, response: None, })).clone(); let parent_path = try!(self.uuid_map.get(parent_uuid).ok_or(DriveError { kind: DriveErrorType::FailedUuidLookup, response: None, })).path.clone(); let mut file_path = try!(parent_path.ok_or(DriveError { kind: DriveErrorType::NoPathForParent, response: None, })); file_path.push(fr.name.clone()); // let (path, mimeType) = try!(self.conn.query_row_named("SELECT path, mimetype FROM files WHERE uuid=:uuid" // , &[(":uuid", &uuid.clone().as_bytes().to_vec())] // , |row| -> (Option<PathBuf>, Option<String>) // )); { let fr = self.uuid_map.get_mut(uuid).unwrap(); fr.path = Some(file_path.clone()); if fr.mimeType == "application/vnd.google-apps.folder" { let mut dir_builder = DirBuilder::new(); dir_builder.recursive(true); // create the directory in the system filesystem try!(dir_builder.create(&file_path.clone())); return Ok(0) } } let (id, maybe_checksum) = try!(self.conn.query_row_named("SELECT id, checksum FROM files WHERE uuid=:uuid" , &[(":uuid", &uuid.clone().as_bytes().to_vec())] , |row| -> (String, Option<String>) { (row.get(0), row.get(1)) } )); println!("{:?}, {:?}", id, maybe_checksum); let info = if let Some(checksum) = maybe_checksum { try!(self.verify_checksum(uuid, Some(&checksum)) .or_else(|_| -> Result<FileCheckResponse, DriveError> { // if the checksum fails, we need to redownload it println!("updating metadata for {:?}", file_path); let dfi = try!(self.download_file(uuid, parent_uuid)); self.conn.execute("UPDATE files SET checksum=$1, size=$2 WHERE uuid=$3", &[ &dfi.checksum, &(dfi.size as i64), &uuid.clone().as_bytes().to_vec(), ]).unwrap(); self.verify_checksum(uuid, Some(&dfi.checksum)) })) } else { // if the checksum fails, we need to redownload it println!("updating metadata for {:?}", file_path); let dfi = try!(self.download_file(uuid, parent_uuid)); self.conn.execute("UPDATE files SET checksum=$1, size=$2 WHERE uuid=$3", &[ &dfi.checksum, &(dfi.size as i64), &uuid.clone().as_bytes().to_vec(), ]).unwrap(); try!(self.verify_checksum(uuid, Some(&dfi.checksum))) }; println!("shpu;d ne updating"); Ok(info.size) } fn create_local_file(&mut self, parent_uuid: &Uuid, name: &Path) -> Result<Uuid, DriveError> { let parent_path = self.conn.query_row_named("SELECT path FROM files WHERE uuid=:uuid" , &[ (":uuid", &parent_uuid.as_bytes().to_vec()) ] , |row| -> String { row.get(0) } ).unwrap(); let file_path = parent_path + &name.to_str().unwrap(); try!(File::create(&file_path)); let uuid = Uuid::new_v4(); let id_from_drive = String::new(); self.conn.execute("INSERT INTO files (id, uuid, path) VALUES ($1, $2, $3)" , &[ &id_from_drive, &uuid.clone().as_bytes().to_vec(), &file_path ] ).unwrap(); Ok(uuid) } fn read_file(&self, uuid: &Uuid) -> Result<Vec<u8>, DriveError> { let path = self.conn.query_row_named("SELECT path FROM files WHERE uuid=:uuid", &[(":uuid", &uuid.clone().as_bytes().to_vec())] , |row| -> String { row.get(0) } ).expect("failure in retrieve_file sql"); let mut handle = try!(File::open(&path)); let mut data = Vec::<u8>::new(); match handle.read_to_end(&mut data) { Ok(_) => (), Err(error) => println!("couldnt read file handle, {}: error, {}", path, error), }; Ok(data) } fn write_file(&self, uuid: &Uuid, data: &[u8], offset: u64) -> Result<u32, DriveError> { let path = self.conn.query_row_named("SELECT path FROM files WHERE uuid=:uuid" , &[( ":uuid", &uuid.clone().as_bytes().to_vec() )] , |row| -> String { row.get(0) } ).unwrap(); let mut fh = OpenOptions::new() .write(true) .truncate(false) .create(false) .open(path) .unwrap(); try!(fh.seek(SeekFrom::Start(offset))); try!(fh.write_all(data)); try!(fh.set_len(offset+(data.len() as u64))); Ok(data.len() as u32) } fn flush_file(&self, uuid: &Uuid) -> Result<(), DriveError> { let (fid, path) = self.conn.query_row_named("SELECT id, path FROM files WHERE uuid=:uuid" , &[( ":uuid", &uuid.clone().as_bytes().to_vec() )] , |row| -> (String, String) { (row.get(0), row.get(1) ) } ).unwrap(); let mut fh = OpenOptions::new() .read(true) .write(false) .open(path) .unwrap(); let mut data = Vec::<u8>::new(); try!(fh.read_to_end(&mut data)); let resp = try!(self.client .patch(&format!("https://www.googleapis.com/upload/drive/v3/files/{}", fid)) .body(&data as &[u8]) .header(Authorization(Bearer{token: self.auth_data.tr.access_token.clone()})) .send()); let fcr = try!(self.verify_checksum(&uuid, None)); self.conn.execute("UPDATE files SET checksum=$1, size=$2 WHERE uuid=$3", &[ &fcr.md5Checksum, &(fcr.size as i64), &uuid.clone().as_bytes().to_vec(), ] ).unwrap(); Ok(()) } fn verify_checksum<'a>(&self, uuid: &Uuid, checksum: Option<&'a str>) -> Result<FileCheckResponse, DriveError> { let (fid, path) = self.conn.query_row_named("SELECT id, path FROM files WHERE uuid=:uuid" , &[( ":uuid", &uuid.clone().as_bytes().to_vec() )] , |row| -> (String, String) { (row.get(0), row.get(1) ) } ).unwrap(); let checksum: Cow<'a, str> = match checksum { Some(sum) => Cow::Borrowed(sum), None => { let mut fh = try!(File::open(&path)); let mut file_string = Vec::<u8>::new(); try!(fh.read_to_end(&mut file_string)); Cow::Owned({ let mut md5 = Md5::new(); md5.input(&file_string); md5.result_str() }) } }; let mut resp = try!(self.client .get(&format!( "https://www.googleapis.com/drive/v3/files/{}\ ?fields=md5Checksum%2Csize" , fid.clone())) .header(Authorization(Bearer{token: self.auth_data.tr.access_token.clone()})) .send()); let mut resp_string = String::new(); try!(resp.read_to_string(&mut resp_string)); let fcr: FileCheckResponse = try!(json::decode(&resp_string)); let same = &checksum == &fcr.md5Checksum; if !same { println!("{} =? {}", checksum, fcr.md5Checksum); println!("same?: {:?}", same); println!("size: {}", fcr.size); return Err(DriveError { kind: DriveErrorType::FailedChecksum, response: Some(resp_string) }) } Ok(fcr) } fn resolve_error(&mut self, resp_string: &str) -> Result<(), DriveError> { println!("attempting to resolve error response: {}", resp_string); let err_data = try!(Json::from_str(&resp_string)); let err_obj = try!(err_data.as_object() .ok_or(DriveError { kind: DriveErrorType::JsonObjectify, response: Some(resp_string.to_string()) })); let error = try!(err_obj.get("error") .ok_or(DriveError { kind: DriveErrorType::JsonInvalidAttribute, response: Some(resp_string.to_string()) })); let errors = try!(error.as_object() .ok_or(DriveError { kind: DriveErrorType::JsonObjectify, response: Some(resp_string.to_string()) }) .and_then(|err_obj| err_obj.get("errors") .ok_or(DriveError { kind: DriveErrorType::JsonInvalidAttribute, response: Some(resp_string.to_string()) })) .and_then(|errors| errors.as_array() .ok_or(DriveError { kind: DriveErrorType::JsonInvalidAttribute, response: Some(resp_string.to_string()) }))); for i in errors { let mut decoder = Decoder::new(i.clone()); let err: ErrorDetailsResponse = match Decodable::decode(&mut decoder) { Ok(err) => err, Err(error) => { println!("could not decode errorDetailsResponse, error: {}, attempted edr: {}", error, i); return Err(From::from(error)) } }; if err.reason == "authError" && err.message == "Invalid Credentials" { let mut resp = try!(self.client.post("https://www.googleapis.com/oauth2/v3/token") .header(ContentType(Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, vec![]))) //.header(Host{hostname: "www.googleapis.com".to_owned(), port: None}) .body(&format!("&client_id={}\ &client_secret={}\ &refresh_token={}\ &grant_type=refresh_token", self.auth_data.client_id, self.auth_data.client_secret, self.auth_data.tr.refresh_token)) .send()); self.auth_data.tr.access_token = { let mut ref_string = String::new(); try!(resp.read_to_string(&mut ref_string)); let ref_data = try!(Json::from_str(&ref_string)); let ref_obj = try!(ref_data.as_object() .ok_or(DriveError { kind: DriveErrorType::JsonObjectify, response: Some(ref_string.clone()) })); try!(ref_obj.get("access_token") .ok_or(DriveError { kind: DriveErrorType::JsonInvalidAttribute, response: Some(ref_string.clone()) }) .and_then(|acc| { acc.as_string() .ok_or(DriveError { kind: DriveErrorType::JsonInvalidAttribute, response: Some(ref_string) }) })).to_string() }; // we'll open our access_cache file to read its current contents let mut f = try!(File::open(self.auth_data.cache_file_path.clone())); let mut access_string = String::new(); try!(f.read_to_string(&mut access_string).map_err(From::from).and_then(|_| -> Result<(), DriveError> { // if the current access file reads as it should, we'll copy the // current token response and edit the access_token field for later use let mut tr: TokenResponse = try!(json::decode(&access_string)); tr.access_token = self.auth_data.tr.access_token.clone(); let tr_json = tr.to_json(); let tr_str = format!("{}", as_pretty_json(&tr_json)); // then we'll truncate the file and paste in the updated token response // preserving all the other unused data let mut f: File = try!(File::create(self.auth_data.cache_file_path.clone()).map_err(From::from) as Result<File, DriveError>); f.write_all(tr_str.as_bytes()).map_err(From::from) })) } else if err.reason == "userRateLimitExceeded" && err.message == "User Rate Limit Exceeded" { () } } // for loop returns (), so a value for the function is needed Ok(()) } } pub fn request_new_access_code(c: &Client) -> Result<TokenResponse, DriveError> { // the space after client_id={} is necessary to seperate the link from the rest of the // prompt println!("Visit https://accounts.google.com/o/oauth2/v2/auth\ ?scope=email%20profile%20https://www.googleapis.com/auth/drive\ &redirect_uri=urn:ietf:wg:oauth:2.0:oob\ &response_type=code\ &client_id={} \ to receive the access code.", CLIENT_ID); let mut code_string = String::new(); try!(io::stdin().read_line(&mut code_string)); let mut resp = c.post("https://accounts.google.com/o/oauth2/token") .header(ContentType(Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, vec![]))) .body(&format!("code={}\ &client_id={}\ &client_secret={}\ &redirect_uri=urn:ietf:wg:oauth:2.0:oob\ &grant_type=authorization_code" , code_string, CLIENT_ID, CLIENT_SECRET)) .send() .unwrap(); print!("{}\n{}\n{}\n\n", resp.url, resp.status, resp.headers); let mut resp_string = String::new(); try!(resp.read_to_string(&mut resp_string)); json::decode(&resp_string).map_err(From::from) } pub fn convert_timespec_to_tm(ts: Timespec) -> Tm { let time_duration = ts - Timespec::new(0,0); Tm { tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 1, // days of the month start at 1, not 0 tm_mon: 1, tm_year: 70, // for difference b/w UNIX epoch and 1900 tm_wday: 0, tm_yday: 0, tm_isdst: 0, tm_utcoff: 0, tm_nsec: 0, } + time_duration } <file_sep>/Cargo.toml [package] name = "driver" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] [dependencies] hyper = "0.9.6" mime = "0.2.0" itertools = "0.4" rust-crypto = "^0.2" fuse = "0.2.7" time = "0.1.35" libc = "0.2.11" rusqlite = "0.7.3" [dependencies.url] git = "https://github.com/servo/rust-url" [dependencies.rustc-serialize] git = "https://github.com/rust-lang-nursery/rustc-serialize" [dependencies.uuid] version = "0.2" features = ["v4"] <file_sep>/README.md tool to syncronize Google drive via a FUSE filesystem <file_sep>/src/lib.rs extern crate hyper; extern crate rustc_serialize; extern crate fuse; extern crate libc; extern crate time; extern crate itertools; extern crate mime; extern crate crypto; extern crate uuid; extern crate rusqlite; #[macro_use] extern crate url; pub mod types; pub mod fs; pub mod filetree; pub mod drive;
aa83645e0f8351f4618c0a8e2130cf9d0a2b8cee
[ "TOML", "Rust", "Markdown" ]
8
Rust
stnma7e/driver
392ddfa4566eba3dff2fb4e997470368ca785879
c0dca2a326b92d89e7ba1f61056cc37693061073
refs/heads/master
<repo_name>VTUL/VIVOHarvester<file_sep>/test/test_relationship_to_rdf.py from unittest import TestCase from vivotool.utils.relationxmltordf import RelationshipTranslator class RelationshipTranslatorTestSuite(TestCase): # relationship document object for testing def setUp(self): self.translator = RelationshipTranslator() self.publication_doc = { "@direction": "from", "@category": "publication", "@id": 3456, "api:object": { "@id": 3456 } } self.user_doc = { "@direction": "to", "@category": "user", "@id": 2345, "api:object": { "@category": "user", "@id": 2345, "@username": "username", "api:user-identifier-associations": { "api:user-identifier-association": [ { "@scheme": "email-address", "#text": "<EMAIL>" } ] } } } self.doc = { "entry": { "api:relationship": { "@id": 1234, "api:related": [self.publication_doc, self.user_doc] } } } """Basic test cases.""" def test_get_user_record(self): user_doc = self.translator.get_user_record(self.doc) self.assertEqual(user_doc["@category"], "user") def test_get_user_email(self): self.assertEqual( self.translator.get_user_email( self.user_doc), "<EMAIL>") def test_get_user_id(self): self.assertEqual(self.translator.get_user_id(self.user_doc), 2345) def test_get_username(self): self.assertEqual( self.translator.get_username( self.user_doc), "username") def test_get_publication_record(self): pub_doc = self.translator.get_publication_record(self.doc) self.assertEqual(pub_doc["@category"], "publication") def test_get_publication_id(self): self.assertEqual( self.translator.get_publication_id( self.publication_doc), 3456) def test_get_authorship_id(self): self.assertEqual(self.translator.get_authorship_id(self.doc), 1234) <file_sep>/test/test_vivo.py import requests_mock from unittest import TestCase from vivotool.vivo.vivo import VIVO class TestVIVO(TestCase): def setUp(self): self.vivo = VIVO() def tearDown(self): self.vivo = None @requests_mock.mock() def test_request_vivo(self, m): m.post('http://foo.com/', text='vivomock') output = self.vivo.request_vivo( 'http://foo.com/', "", "", "", "") self.assertEqual(output, None) data = { 'email': '<EMAIL>', } output = self.vivo.request_vivo( "", "http://foo.com/", "", data, "update") self.assertEqual(output.status_code, 200) def test_get_query_content(self): output = self.vivo.get_query_content("", "otherop") self.assertEqual(output, "") output = self.vivo.get_query_content("test", "describe") expected = "DESCRIBE <test>" self.assertEqual(output, expected) output = self.vivo.get_query_content("test", "insert") expected = "INSERT DATA {\n" + \ "GRAPH <http://vitro.mannlib.cornell.edu/default/vitro-kb-2> {\n" + \ "test}\n}\n" self.assertEqual(output, expected) output = self.vivo.get_query_content("test", "delete") expected = "DELETE DATA {\n" + \ "GRAPH <http://vitro.mannlib.cornell.edu/default/vitro-kb-2> {\n" + \ "test}\n}\n" self.assertEqual(output, expected) <file_sep>/vivotool/vivo/vivo.py import requests class VIVO: """docstring for VIVO""" def get_query_content(self, objcontent, optype): ops = ["describe", "insert", "delete"] if not optype or (optype not in ops): return "" query_content = "" if optype == "describe": query_content = "DESCRIBE <" + objcontent + ">" return query_content query_content = "DATA {\n" + \ "GRAPH <http://vitro.mannlib.cornell.edu/default/vitro-kb-2> {\n" query_content += objcontent query_content += "}\n}\n" if optype == "insert": query_content = "INSERT " + query_content elif optype == "delete": query_content = "DELETE " + query_content return query_content def request_vivo(self, reqcontent, vivo_endpoint, headers, data, optype): ops = ["update", "query"] if not optype or (optype not in ops): return None data[optype] = reqcontent response = requests.post(vivo_endpoint, headers=headers, data=data) return response <file_sep>/setup.py import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="VIVOHarvester", version="0.2.2", author="<NAME>, <NAME>, <NAME>", author_email="<EMAIL>, <EMAIL>, <EMAIL>", description="VIVO harvester", license="MIT", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/VTUL/VIVOHarvester", scripts=['bin/vivotool'], packages=setuptools.find_packages(), install_requires=[ 'nose', 'rdflib', 'xmltodict', 'pyyaml', 'lxml', 'requests', 'cryptography', 'pytz', 'pymysql' ], classifiers=[ "Programming Language :: Python :: 2.7", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], ) <file_sep>/test/test_model_publication.py from unittest import TestCase from vivotool.utils.models.publication_model import Publication class TestSample(TestCase): def test_add_to_graph(self): pass <file_sep>/vivotool/utils/relationxmltordf.py import collections import xmltodict from rdflib import Graph, Literal, BNode, RDF, RDFS, URIRef, Namespace from rdflib.namespace import FOAF, DC from vivotool.utils.models.user_model import User from vivotool.utils.models.publication_model import Publication, Authorship VIVO = Namespace('http://vivoweb.org/ontology/core#') class RelationshipTranslator(object): def __add_bindings(self, graph): graph.bind('vivo', VIVO) def get_user_record(self, doc): user_doc = None for related in doc['entry']['api:relationship']['api:related']: if related['@category'] == 'user': user_doc = related return user_doc def get_user_email(self, user_doc): user_email = None records = [] user_identifier_association = user_doc['api:object'][ 'api:user-identifier-associations']['api:user-identifier-association'] if isinstance(user_identifier_association, collections.OrderedDict): records.append(user_identifier_association) else: records = user_identifier_association email_assoc = None for assoc in records: if assoc['@scheme'] == 'email-address': email_assoc = assoc if email_assoc is not None: user_email = email_assoc['#text'] return user_email def get_user_id(self, user_doc): return user_doc['api:object']['@id'] def get_username(self, user_doc): return user_doc['api:object']['@username'] def get_publication_record(self, doc): pub_doc = None for related in doc['entry']['api:relationship']['api:related']: if related['@category'] == 'publication': pub_doc = related return pub_doc def get_publication_id(self, pub_doc): return pub_doc['api:object']['@id'] def get_authorship_id(self, doc): return doc['entry']['api:relationship']['@id'] def parse(self, input_file, target_dir=""): with open(input_file) as fd: doc = xmltodict.parse(fd.read()) feed = doc['feed'] vivo_user = User() user_record = self.get_user_record(feed) if user_record is not None: vivo_user.user_id = self.get_user_id(user_record) vivo_user.username = self.get_username(user_record) vivo_user.email = self.get_user_email(user_record) vivo_publication = Publication() publication_record = self.get_publication_record(feed) if publication_record and user_record: vivo_publication.id = self.get_publication_id(publication_record) vivo_authorship = Authorship(vivo_user, vivo_publication) vivo_authorship.id = self.get_authorship_id(feed) g = Graph() self.__add_bindings(g) vivo_authorship.add_to_graph(g) g.serialize(target_dir + vivo_authorship.id + ".rdf", format='nt') <file_sep>/test/test_user.py from unittest import TestCase from vivotool.utils.userxmltordf import UserElementXml2Rdf class TestSample(TestCase): def test_convert(self): pass <file_sep>/vivotool/utils/models/__init__.py from . import publication_model from . import user_model <file_sep>/vivotool/utils/file_utils.py import os import logging import shutil from os import path class Utils: """docstring for Utils""" def save_photo_file(self, content, filename): try: file = open(filename, "wb") for block in content.iter_content(1024): file.write(block) file.close() except Exception: logging.exception("") def read_file(self, filename): rdfcontent = "" try: with open(filename, "r") as file: rdfcontent = file.read() except Exception: logging.exception("") return rdfcontent def save_xml_file(self, content, filename): try: with open(filename, "w") as file: file.write(content) except Exception: logging.exception("") def listfiles(self, path, extension): all_files = list( filter( lambda x: x.endswith(extension), os.listdir(path))) return sorted(all_files) def listdeletefiles(self, path, pattern): all_files = list( filter( lambda x: x.startswith(pattern), os.listdir(path))) return sorted(all_files) def segmentlist(self, inputlist, length): result = [] result = [inputlist[x:x + length] for x in range(0, len(inputlist), length)] return result def mergefiles(self, folderpath, inputlist, mergefilename): with open(path.join(folderpath, mergefilename), 'wb') as wfd: for f in inputlist: with open(path.join(folderpath, f), 'rb') as fd: shutil.copyfileobj(fd, wfd, 1024 * 1024 * 10) return mergefilename <file_sep>/vivotool/utils/userxmltordf.py import collections from rdflib import Graph, Literal, BNode, RDF, RDFS, URIRef, Namespace from rdflib.namespace import FOAF, DC from datetime import datetime # from utils.models.user_model import User, Appointment, Degree, Institution from vivotool.utils.models.user_model import User, Appointment, Degree, Institution class UserElementXml2Rdf(object): def convert(self, doc, rdf_filename): user = self.__get_user(doc) if user: g = Graph() user.add_to_graph(g) g.serialize(rdf_filename, format='nt') def __get_datetime(self, doc_date): yyyy = int(doc_date['api:year']) # year is required # defaults to january if not defined mm = int(doc_date.get('api:month', 1)) # defaults to january if not defined dd = int(doc_date.get('api:day', 1)) return '{:%Y-%m-%dT%H:%M:%S}'.format(datetime(yyyy, mm, dd)) def __get_user(self, doc): # TODO: handle properly when expected values don't exist... try: user = User() api_obj = doc['feed']['entry']['api:object'] user.username = api_obj['@username'] if 'api:first-name' in api_obj: user.first_name = api_obj['api:first-name'] else: return user if 'api:last-name' in api_obj: user.last_name = api_obj['api:last-name'] else: return user user.is_academic = api_obj.get( 'api:is-academic', 'false').lower() == 'true' user.is_current_staff = api_obj.get( 'api:is-current-staff', 'false').lower() == 'true' user.is_public = api_obj.get( 'api:is-public', 'false').lower() == 'true' if 'api:suffix' in api_obj: user.suffix = api_obj['api:suffix'] user.email = api_obj['api:email-address'] if 'api:position' in api_obj: user.title = api_obj['api:position'] user.email_is_public = api_obj.get( 'api:institutional-email-is-public', '').lower() == 'true' if api_obj["api:records"]["api:record"]["api:native"]: userfields = api_obj["api:records"]["api:record"]["api:native"]["api:field"] fulldetail = False if (user.is_public and user.is_academic and user.is_current_staff): fulldetail = True for f in userfields: if isinstance(f, collections.OrderedDict): if fulldetail and f['@name'] == 'overview': if f['api:text']['@privacy'].lower() == 'public': user.overview = f['api:text']['#text'] elif fulldetail and f['@name'] == 'academic-appointments': appointments = f['api:academic-appointments']['api:academic-appointment'] idx = 1 if (isinstance(appointments, list) ): # many appointments for i, appt in enumerate( f['api:academic-appointments']['api:academic-appointment']): if appt['@privacy'].lower() == 'public': appointment = self.__get_appointment( appt, user.username, idx) user.institutions.append( appointment.institution) user.appointments.append(appointment) idx += 1 elif isinstance(appointments, dict): # single appointment appt = appointments if appt['@privacy'].lower() == 'public': appointment = self.__get_appointment( appt, user.username, idx) user.institutions.append( appointment.institution) user.appointments.append(appointment) elif fulldetail and f['@name'] == 'degrees': p = f['api:degrees']['api:degree'] if isinstance(p, collections.OrderedDict): if p['@privacy'].lower() == 'public': degree = self.__get_degree( p, user.username) user.institutions.append( degree.institution) user.degrees.append(degree) else: for deg in f['api:degrees']['api:degree']: if deg['@privacy'].lower() == 'public': degree = self.__get_degree( deg, user.username) user.institutions.append( degree.institution) user.degrees.append(degree) elif f['@name'] == 'email-addresses': p = f['api:email-addresses']['api:email-address'] if isinstance( p, collections.OrderedDict) and p['@privacy'].lower() == 'public': if ('api:type' in p) and p['api:type'].lower( ) == 'work': user.email = p['api:address'] else: if f == 'email-addresses': print( "This user is private and has a work email:" + user.username) print(f) # NOTE: Some information is not necessary in resulting graph # (e.g., Photo info, addresses, phone numbers, personal websites, Relationships) return user except KeyError as ke_error: # TODO: logger that doc is invalid for getting user print( 'Unable able to properly parse input xml file: ' + str(ke_error)) return None def __get_degree(self, doc, username): degree = Degree() degree.username = username degree.field = doc.get( 'api:field-of-study', '') # default to '' if none exists degree.label = '{} {}'.format(doc['api:name'], degree.field) degree.type = ''.join( x for x in doc['api:name'] if x.isalpha()).lower() if 'api:start-date' in doc: degree.start_date = self.__get_datetime(doc['api:start-date']) if 'api:end-date' in doc: degree.end_date = self.__get_datetime(doc['api:end-date']) degree.institution = self.__get_institution(doc['api:institution']) return degree def __get_appointment(self, doc, username, idx): appointment = Appointment( id_suffix='{}-{}'.format(username, idx), is_public=True) appointment.label = doc['api:position'] if 'api:start-date' in doc: appointment.start_date = self.__get_datetime(doc['api:start-date']) if 'api:end-date' in doc: appointment.end_date = self.__get_datetime(doc['api:end-date']) appointment.institution = self.__get_institution( doc['api:institution']) return appointment def __get_institution(self, institution_doc): institution = Institution() for line in institution_doc['api:line']: if line['@type'] == 'organisation': institution.label = line['#text'] elif line['@type'] == 'suborganisation': institution.dept = line['#text'] elif line['@type'] == 'city': institution.city = line['#text'] elif line['@type'] == 'country': institution.country = line['#text'] return institution <file_sep>/vivotool/vivo/__init__.py from . import vivo <file_sep>/test/test_model_user.py from unittest import TestCase from vivotool.utils.models.user_model import User class TestSample(TestCase): def test_display_name(self): pass <file_sep>/test/test_utils.py from unittest import TestCase from vivotool.utils.photo import Photo class TestPhoto(TestCase): def test_is_photo(self): pass <file_sep>/test/test_file_utils.py import shutil import tempfile import os import requests import imghdr from os import path from unittest import TestCase from vivotool.utils.file_utils import Utils class TestFileUtils(TestCase): def setUp(self): self.utils = Utils() self.test_dir = tempfile.mkdtemp() def tearDown(self): self.utils = None shutil.rmtree(self.test_dir) def test_save_photo_file(self): testfile = path.join(self.test_dir, 'test.png') content = requests.get( "https://www.iconfinder.com/icons/216359/download/png/128") self.utils.save_photo_file(content, testfile) output = imghdr.what(testfile) self.assertEqual(output, "png") def test_read_file(self): testfile = path.join(self.test_dir, 'test.txt') with open(testfile, "w") as f: f.write("some content") output = self.utils.read_file(testfile) self.assertEqual(output, "some content") def test_save_xml_file(self): testfile = path.join(self.test_dir, 'test.xml') content = "<xml>test</xml>" self.utils.save_xml_file(content, testfile) with open(testfile, 'r') as file: output = file.read() self.assertEqual(output, content) def test_listfiles(self): xmlfile = path.join(self.test_dir, 'test.xml') txtfile = path.join(self.test_dir, 'test.txt') with open(xmlfile, 'w') as f: f.write("some content") with open(txtfile, 'w') as f: f.write("some content") expected = ['test.xml'] output = self.utils.listfiles(self.test_dir, ".xml") self.assertEqual(output, expected) def test_listdeletefiles(self): deletefile = path.join(self.test_dir, 'deletetest2.xml') deletefile1 = path.join(self.test_dir, 'deletetest1.xml') txtfile = path.join(self.test_dir, 'test.txt') with open(deletefile, 'w') as f: f.write("some content") with open(deletefile1, 'w') as f: f.write("some content") with open(txtfile, 'w') as f: f.write("some content") expected = ['deletetest1.xml', 'deletetest2.xml'] output = self.utils.listdeletefiles(self.test_dir, "delete") self.assertEqual(output, expected) def test_segmentlist(self): inputlist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] output = self.utils.segmentlist(inputlist, 3) expected = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] self.assertEqual(output, expected) inputlist = [0] output = self.utils.segmentlist(inputlist, 3) expected = [[0]] self.assertEqual(output, expected) def test_mergefiles(self): inputlist = ["1.txt", "2.txt", "3.txt", "4.txt", "5.txt"] for x in range(1, 6): testfile = path.join(self.test_dir, str(x) + '.txt') with open(testfile, "w") as f: f.write("some content\n") testfilename = "mergefile.txt" mergefile = self.utils.mergefiles( self.test_dir, inputlist, testfilename) with open(path.join(self.test_dir, mergefile), "r") as file: output = file.read() self.assertEqual( output, "some content\nsome content\nsome content\nsome content\nsome content\n") inputlist = ["1.txt"] testfile = path.join(self.test_dir, '1.txt') with open(testfile, "w") as f: f.write("some content\n") testfilename = "mergefile.txt" mergefile = self.utils.mergefiles( self.test_dir, inputlist, testfilename) with open(path.join(self.test_dir, mergefile), "r") as file: output = file.read() self.assertEqual( output, "some content\n") <file_sep>/vivotool/harvester/__init__.py from . import elements <file_sep>/vivotool/utils/db.py import pymysql.cursors class DB: """docstring for DB""" def __init__(self): pass def db_connection(self, **args): if "db" in args: conn = pymysql.connect(host=args['host'], user=args['user'], password=args['password'], db=args['db'], charset="utf8mb4", cursorclass=pymysql.cursors.DictCursor) else: conn = pymysql.connect(host=args['host'], user=args['user'], password=args['password'], charset="utf8mb4", cursorclass=pymysql.cursors.DictCursor) return conn def create_vivo_database(self, conn, dbname): try: # Create a cursor object cursorObject = conn.cursor() # Create database harvester createDBQuery = "CREATE Database " + dbname + ";" cursorObject.execute(createDBQuery) except Exception as e: print("Exeception occured:{}".format(e)) finally: conn.close() def create_vivo_table(self, conn, tablename): try: if tablename == "users": createTableQuery = "CREATE TABLE `users`" \ "(" \ "`pid` varchar(20) NOT NULL," \ "`eid` varchar(20) NOT NULL," \ "`uid` varchar(20)," \ "`public` varchar(20) NOT NULL DEFAULT 'N'," \ "`keyword` LONGTEXT," \ "`update_date` DATE DEFAULT NULL," \ "PRIMARY KEY ( pid )" \ ");" elif tablename == "publications": createTableQuery = "CREATE TABLE `publications` (" \ "`pid` varchar(20) NOT NULL," \ "`keyword` LONGTEXT," \ "`public` varchar(20) NOT NULL DEFAULT 'N'," \ "`update_date` DATE DEFAULT NULL," \ "PRIMARY KEY (`pid`)" \ ");" elif tablename == "relations": createTableQuery = "CREATE TABLE `relations` (" \ "`rid` varchar(20) NOT NULL," \ "`public` varchar(20) NOT NULL DEFAULT 'N'," \ "`update_date` DATE DEFAULT NULL," \ "PRIMARY KEY (`rid`)" \ ");" cursorObject = conn.cursor() cursorObject.execute(createTableQuery) except Exception as e: print("Exeception occured:{}".format(e)) def execute_query(self, conn, querystring, querytype): try: cursorObject = conn.cursor() cursorObject.execute(querystring) if querytype == "select": rows = cursorObject.fetchall() return rows elif querytype == "update": conn.commit() except Exception as e: print("Exeception occured:{}".format(e)) def check_exist(self, conn, tablename, keyname, value): isExist = False try: querystring = "SELECT * from " + tablename + \ " where " + keyname + " = \"" + value + "\";" cursorObject = conn.cursor() cursorObject.execute(querystring) rows = cursorObject.fetchall() for row in rows: isExist = True except Exception as e: print("MySQL Exeception occured:{}".format(e)) return isExist def select_records(self, conn, tablename, keyname, value): try: querystring = "SELECT * from " + tablename + \ " where " + keyname + " = \"" + value + "\";" cursorObject = conn.cursor() cursorObject.execute(querystring) rows = cursorObject.fetchall() return rows except Exception as e: print("MySQL Exeception occured:{}".format(e)) return None def delete_record(self, conn, tablename, keyname, value): resp = False try: querystring = "DELETE from %s where %s = %s" % ( tablename, keyname, value,) print(querystring) cursorObject = conn.cursor() cursorObject.execute(querystring) conn.commit() resp = True except Exception as e: print("MySQL Exeception occured:{}".format(e)) return resp def update_user_privacy(self, conn, tablename, privacy, keyname, value): resp = False try: querystring = "UPDATE %s set public = \"%s\" where %s = \"%s\";" % ( tablename, privacy, keyname, value,) print(querystring) cursorObject = conn.cursor() cursorObject.execute(querystring) conn.commit() resp = True except Exception as e: print("MySQL Exeception occured:{}".format(e)) return resp def insert_user(self, conn, username, elementid, uid, privacy): resp = False try: querystring = "INSERT INTO users (pid, eid, uid, public) VALUES (\"%s\", \"%s\", \"%s\", \"%s\");" % ( username, elementid, uid, privacy,) cursorObject = conn.cursor() cursorObject.execute(querystring) conn.commit() resp = True except Exception as e: print("MySQL Exeception occured:{}".format(e)) return resp def insert_publication(self, conn, pubid, privacy): resp = False try: querystring = "INSERT INTO publications (pid, public) VALUES (\"%s\", \"%s\");" % ( pubid, privacy,) cursorObject = conn.cursor() cursorObject.execute(querystring) conn.commit() resp = True except Exception as e: print("MySQL Exeception occured:{}".format(e)) return resp def insert_relation(self, conn, rid, privacy): resp = False try: querystring = "INSERT INTO relations (rid, public) VALUES (\"%s\", \"%s\");" % ( rid, privacy,) cursorObject = conn.cursor() cursorObject.execute(querystring) conn.commit() resp = True except Exception as e: print("MySQL Exeception occured:{}".format(e)) return resp <file_sep>/bin/vivotool #!/usr/bin/env python # encoding=utf8 import argparse import collections import logging import os import sys import time import xmltodict import yaml import vivotool from logging.config import fileConfig from vivotool.utils.db import DB from vivotool.utils.file_utils import Utils from vivotool.utils.photo import Photo from vivotool.utils.publicationxmltordf import PublicationXml2Rdf from vivotool.utils.relationxmltordf import RelationshipTranslator from vivotool.utils.userxmltordf import UserElementXml2Rdf from vivotool.harvester.elements import Elements from vivotool.vivo.vivo import VIVO # from importlib import reload reload(sys) sys.setdefaultencoding('utf8') parser = argparse.ArgumentParser() parser.add_argument("--file", "-f", type=str, required=True) parser.add_argument( "--optype", "-t", type=str, required=True, help="operation type") parser.add_argument("--admin", "-a", type=str) parser.add_argument("--db", "-b", type=str) parser.add_argument("--day", "-d", type=int) parser.add_argument('-o', '--outfile', help="Output file", default=sys.stdout, type=argparse.FileType('w')) args = parser.parse_args() start_time = time.time() config = yaml.safe_load(open(args.file)) xml_folder = config['folders']['upload'] localurl = config['folders']['localurl'] logging_config = config['logging']['file'] # DB params host = config["db"]["host"] port = config["db"]["port"] user = config["db"]["user"] password = config["db"]["password"] database = config["db"]["database"] # logger initialization fileConfig(logging_config) logger = logging.getLogger() logger.debug('Logger initialized') file_utils = Utils() if args.optype == "ingest": logger.debug("Start ingesting......") vivouploads = xml_folder extension = '.xml' userxmlpath = vivouploads + "xml/users/" user_xml_files = file_utils.listfiles(userxmlpath, extension) pubxmlpath = vivouploads + "xml/publications/" pub_xml_files = file_utils.listfiles(pubxmlpath, extension) rsxmlpath = vivouploads + "xml/relations/" rs_xml_files = file_utils.listfiles(rsxmlpath, extension) userrdfpath = vivouploads + "rdf/users/" pubrdfpath = vivouploads + "rdf/publications/" rsrdfpath = vivouploads + "rdf/relations/" photordfpath = vivouploads + "rdf/photos/" uex2rdf = UserElementXml2Rdf() photo = Photo() try: for xmlfile in user_xml_files: logger.debug("Start parsing: " + userxmlpath + xmlfile) with open(userxmlpath + xmlfile) as fd: doc = xmltodict.parse(fd.read()) userfilename = "rdf/users/" + xmlfile.replace(".xml", ".rdf") uex2rdf.convert(doc, vivouploads + userfilename) api_obj = doc['feed']['entry']['api:object'] pid = api_obj['@username'] eid = api_obj["@id"] public = api_obj["api:is-public"] if public == 'true': photofilename = "rdf/photos/" + eid + ".rdf" file_utils.save_xml_file( photo.create_user_photo_graph( pid, eid), vivouploads + photofilename) os.remove(userxmlpath + xmlfile) except IOError: logger.error('Error parsing file:' + xmlfile) pub_xml_to_rdf = PublicationXml2Rdf() try: for xmlfile in pub_xml_files: logger.debug("Start parsing: " + pubxmlpath + xmlfile) pub_xml_to_rdf.parse( pubxmlpath + xmlfile, pubrdfpath) os.remove(pubxmlpath + xmlfile) except IOError: logger.error('Error parsing file:' + xmlfile) translator = RelationshipTranslator() try: for xmlfile in rs_xml_files: logger.debug("Start parsing: " + rsxmlpath + xmlfile) translator.parse( rsxmlpath + xmlfile, rsrdfpath) os.remove(rsxmlpath + xmlfile) except IOError: logger.error('Error parsing file:' + xmlfile) # ingest to VIVO extension = '.rdf' user_rdf_files = file_utils.listfiles(userrdfpath, extension) photo_rdf_files = file_utils.listfiles(photordfpath, extension) pub_rdf_files = file_utils.listfiles(pubrdfpath, extension) rs_rdf_files = file_utils.listfiles(rsrdfpath, extension) vivousername = config['vivo']['username'] vivopassword = config['vivo']['password'] vivo_endpoint = config['vivo']['url'] rdfurl = config['folders']['localurl'] headers = { 'Accept': "text/turtle", } data = { 'email': vivousername, 'password': <PASSWORD> } vivo_endpoint = vivo_endpoint + '/api/sparqlUpdate' if not (args.admin == "stopingest"): vivo = VIVO() for rdf_file in user_rdf_files: objectns = file_utils.read_file(userrdfpath + rdf_file) logger.debug("Process user rdf file: " + rdf_file) reqcontent = vivo.get_query_content(objectns, "insert") response = vivo.request_vivo( reqcontent, vivo_endpoint, headers, data, "update") logger.debug(response.text) os.remove(userrdfpath + rdf_file) for rdf_file in photo_rdf_files: objectns = file_utils.read_file(photordfpath + rdf_file) logger.debug("Process photo rdf file: " + rdf_file) reqcontent = vivo.get_query_content(objectns, "insert") response = vivo.request_vivo( reqcontent, vivo_endpoint, headers, data, "update") logger.debug(response.text) os.remove(photordfpath + rdf_file) for rdf_file in pub_rdf_files: objectns = file_utils.read_file(pubrdfpath + rdf_file) logger.debug("Process publication rdf file: " + rdf_file) reqcontent = vivo.get_query_content(objectns, "insert") response = vivo.request_vivo( reqcontent, vivo_endpoint, headers, data, "update") logger.debug(response.text) os.remove(pubrdfpath + rdf_file) for rdf_file in rs_rdf_files: objectns = file_utils.read_file(rsrdfpath + rdf_file) logger.debug("Process relations rdf file: " + rdf_file) reqcontent = vivo.get_query_content(objectns, "insert") response = vivo.request_vivo( reqcontent, vivo_endpoint, headers, data, "update") logger.debug(response.text) os.remove(rsrdfpath + rdf_file) elif args.optype == "harvest": logger.debug("Start harvesting......") elements_endpoint = config['elements']['url'] authorization = config['elements']['authorization'] image_folder = config['folders']['photo'] headers = {} headers["Authorization"] = "Basic " + authorization logger.debug('Stage1: Harvesting all elements users') xmlfilename = xml_folder + "xml/temp/alluser.xml" elements = Elements() if args.day and args.day > 0: day = args.day else: day = 0 logger.debug('Harvesting from Elements the dey before %s day', str(day)) elements.harvest_elements_xml( elements_endpoint, headers, "users", 25, xmlfilename, day) logger.debug('Harvesting individual user from Elements.') total_public = 0 total_academic = 0 total_current_staff = 0 if not (args.db == "off"): db = DB() dbconn = db.db_connection( host=host, user=user, password=<PASSWORD>, db=database) extension = '.xml' all_user_folder = xml_folder + "xml/temp/" all_xml_files = file_utils.listfiles(all_user_folder, extension) vivousername = config['vivo']['username'] vivopassword = config['vivo']['password'] vivo_endpoint = config['vivo']['url'] rdfurl = config['folders']['localurl'] vivoheaders = { 'Accept': "text/turtle", } data = { 'email': vivousername, 'password': <PASSWORD> } vivo_query_endpoint = vivo_endpoint + '/api/sparqlQuery' vivo_update_endpoint = vivo_endpoint + '/api/sparqlUpdate' vivo_namespace = "http://collab.vt.edu/vivo/individual/" vivo = VIVO() # UC1: public user change the publication privacy settings if args.day and args.day > 0: logger.debug("Checking public user's publications from the giving day") if not (args.db == "off"): rows = db.select_records(dbconn, "users", "public", "Y") for row in rows: xmlfilename = xml_folder + "xml/temp/" + \ row['eid'].strip() + "daypublications.xml" elements.harvest_elements_xml( elements_endpoint, headers, "publications", row['eid'].strip(), xmlfilename, day) for xmlfile in all_xml_files: with open(all_user_folder + xmlfile) as fd: doc = xmltodict.parse(fd.read()) if "entry" in doc["feed"]: entries = doc["feed"]["entry"] for e in entries: elementid = e["api:object"]["@id"] username = e["api:object"]["@username"] if "@proprietary-id" in e["api:object"]: uid = e["api:object"]["@proprietary-id"] else: uid = "" is_public = e["api:object"]["api:is-public"] is_academic = e["api:object"]["api:is-academic"] is_current_staff = e["api:object"]["api:is-current-staff"] if is_public == "true": total_public += 1 if is_academic == "true": total_academic += 1 if is_current_staff == "true": total_current_staff += 1 if args.admin == "publicall": is_public = "true" isExist = False if not (args.db == "off"): isExist = db.check_exist(dbconn, "users", "pid", username) if isExist: logger.debug( "Delete user XML file:" + all_user_folder + xmlfile) # remove user from VIVO for new insert/update or delete uservivourl = vivo_namespace + username logger.debug(uservivourl) reqcontent = vivo.get_query_content( uservivourl, "describe") response = vivo.request_vivo( reqcontent, vivo_query_endpoint, vivoheaders, data, "query") rdfcontent = response.text logger.debug(rdfcontent) reqcontent = vivo.get_query_content(rdfcontent, "delete") response = vivo.request_vivo( reqcontent, vivo_update_endpoint, vivoheaders, data, "update") logger.debug( "Response from VIVO: %s for deleting %s", response.text, uservivourl) logger.debug("The deleted Elements user id: " + elementid) # fetch the publications xml from elements and mark as # delete xmlfilename = xml_folder + "xml/temp/delete" + elementid + "publications.xml" elements.harvest_elements_xml( elements_endpoint, headers, "publications", elementid, xmlfilename) db_op = "none" if is_public == "true" and is_academic == "true" and is_current_staff == "true": logger.debug('Harvesting Elements public user id: ' + elementid) filename = xml_folder + "xml/users/" + elementid + ".xml" elements.harvest_elements_xml( elements_endpoint, headers, "user", elementid, filename) logger.debug( 'Harvesting Elements user id: ' + elementid + '\'s publications') xmlfilename = xml_folder + "xml/temp/" + elementid + "publications.xml" elements.harvest_elements_xml( elements_endpoint, headers, "publications", elementid, xmlfilename) logger.debug( 'Harvesting Elements user id: ' + elementid + '\'s photo') elements.harvest_elements_xml( elements_endpoint, headers, "photo", elementid, image_folder) db_op = "topublic" if isExist else "public" elif is_public == "false" and is_academic == "true" and is_current_staff == "true": if not ( args.admin == "publiconly" or args.admin == "publicall"): db_op = "toprivate" if isExist else "private" logger.debug( 'Harvesting Elements private user id: ' + elementid) filename = xml_folder + "xml/users/" + elementid + ".xml" elements.harvest_elements_xml( elements_endpoint, headers, "user", elementid, filename) elif is_current_staff == "false": if isExist: db_op = "delete" if not (args.db == "off"): if db_op == "delete": db.delete_record(dbconn, "users", "pid", username) elif db_op == "toprivate": db.update_user_privacy( dbconn, "users", "N", "pid", username) elif db_op == "private": db.insert_user( dbconn, username, str(elementid), str(uid), "N") elif db_op == "topublic": db.update_user_privacy( dbconn, "users", "Y", "pid", username) elif db_op == "public": db.insert_user( dbconn, username, str(elementid), str(uid), "Y") os.remove(all_user_folder + xmlfile) pubfolder = xml_folder + "xml/temp/" eid = "" pubid = "" # handle delete publication file first logger.debug("Start deleting user's publications for update.") delfiles = file_utils.listdeletefiles(pubfolder, "delete") for delfile in delfiles: with open(pubfolder + delfile) as fd: doc = xmltodict.parse(fd.read()) if "entry" in doc["feed"]: recid = doc["feed"]["id"] eid = recid.split("/")[-2] entries = doc["feed"]["entry"] logger.debug("Process publication deletion file: " + delfile) records = [] if isinstance(entries, collections.OrderedDict): records.append(entries) else: records = entries for e in records: pubid = e["api:relationship"]["api:related"]["@id"] logger.debug( "Deleting publication id:" + pubid) # remove it from VIVO for new insert or delete pubvivourl = vivo_namespace + "publication" + pubid logger.debug(pubvivourl) reqcontent = vivo.get_query_content(pubvivourl, "describe") response = vivo.request_vivo( reqcontent, vivo_query_endpoint, vivoheaders, data, "query") rdfcontent = response.text # logger.debug(rdfcontent) reqcontent = vivo.get_query_content(rdfcontent, "delete") response = vivo.request_vivo( reqcontent, vivo_update_endpoint, vivoheaders, data, "update") logger.debug( "Delete response from VIVO: %s for deleting %s", str(response.status_code), pubvivourl) # fetch the relationship xml from elements and mark as delete logger.debug("Harvesting relationships for deletion......") filename = xml_folder + "xml/temp/delete" + pubid + "relationships.xml" elements.harvest_elements_xml( elements_endpoint, headers, "pubrelationships", pubid, filename) if not (args.db == "off"): db.delete_record(dbconn, "publications", "pid", str(pubid)) os.remove(pubfolder + delfile) xmlfiles = file_utils.listfiles(pubfolder, extension) eid = "" pubid = "" logger.debug("Start processing individual publication file.") for xmlfile in xmlfiles: # There are two "delete" files in the folder, publication and # relationships if "delete" not in xmlfile: logger.debug("Start processing publication files in the temp folder: " + xmlfile) with open(pubfolder + xmlfile) as fd: doc = xmltodict.parse(fd.read()) if "entry" in doc["feed"]: recid = doc["feed"]["id"] eid = recid.split("/")[-2] entries = doc["feed"]["entry"] logger.debug("Processing all the publications in file: " + xmlfile) records = [] if isinstance(entries, collections.OrderedDict): records.append(entries) else: records = entries for e in records: authorship = e["api:relationship"]["@type"] pubid = e["api:relationship"]["api:related"]["@id"] logger.debug("Parsing publication id: " + pubid) logger.debug("authorship type: " + authorship) # check if rec is already in db isExist = False if not (args.db == "off"): isExist = db.check_exist( dbconn, "publications", "pid", str(pubid)) if isExist and authorship == "publication-user-authorship": logger.debug( "Deleting a publication file:" + pubfolder + xmlfile) # remove it from VIVO for new insert or delete pubvivourl = vivo_namespace + "publication" + pubid # logger.debug(pubvivourl) reqcontent = vivo.get_query_content( pubvivourl, "describe") response = vivo.request_vivo( reqcontent, vivo_query_endpoint, vivoheaders, data, "query") rdfcontent = response.text # logger.debug(rdfcontent) reqcontent = vivo.get_query_content( rdfcontent, "delete") response = vivo.request_vivo( reqcontent, vivo_update_endpoint, vivoheaders, data, "update") logger.debug( "Response from VIVO: %s for deleting publication id: %s", response.text, pubid) # fetch the relationship xml from elements and mark as # delete filename = xml_folder + "xml/temp/delete" + pubid + "relationships.xml" elements.harvest_elements_xml( elements_endpoint, headers, "pubrelationships", pubid, filename) if "api:is-visible" in e["api:relationship"] and authorship == "publication-user-authorship": visible = e["api:relationship"]["api:is-visible"] public = e["api:relationship"]["api:related"]["api:object"]["api:is-public"] if args.admin == "publicall": public = "true" visible = "true" db_op = "none" if public == "true" and visible == "true": logger.debug( 'Harvesting Elements user id: ' + eid + '\'s publication id: ' + pubid) filename = xml_folder + "xml/publications/" + eid + "-" + pubid + ".xml" elements.harvest_elements_xml( elements_endpoint, headers, "publication", pubid, filename) if not isExist: db_op = "insert" logger.debug( 'Harvesting publication id: ' + pubid + '\'s relationships') filename = xml_folder + "xml/temp/" + pubid + "relationships.xml" elements.harvest_elements_xml( elements_endpoint, headers, "pubrelationships", pubid, filename) else: if isExist: db_op = "delete" if not (args.db == "off"): if db_op == "insert": db.insert_publication(dbconn, pubid, "Y") elif db_op == "delete": db.delete_record( dbconn, "publications", "pid", str(pubid)) else: logger.debug( 'This publication has no visible attr or not publication-user-authorship') os.remove(pubfolder + xmlfile) # Process all relationships logger.debug('Start processing individual relationship......') rsfolder = xml_folder + "xml/temp/" # list files contain delete and delete first logger.debug("Handing relastions deletion files......") delfiles = file_utils.listdeletefiles(rsfolder, "delete") for delfile in delfiles: with open(rsfolder + delfile) as fd: doc = xmltodict.parse(fd.read()) recid = doc["feed"]["id"] pubid = recid.split("/")[-2] if "entry" in doc["feed"]: entries = doc["feed"]["entry"] logger.debug( 'Processing relationships file to be deleted in xml/temp - ' + delfile) records = [] if isinstance(entries, collections.OrderedDict): records.append(entries) else: records = entries for e in records: if "api:relationship" in e: rsid = e["api:relationship"]["@id"] rstype = e["api:relationship"]["@type"] for rec in e["link"]: if "users" in rec["@href"]: eid = rec["@href"].split("/")[-1] logger.debug( 'Deleting relationship record - rsid: %s, pubid: %s, eid: %s', rsid, pubid, eid) authorship = vivo_namespace + "authorship" + pubid + "-" + eid # remove it from VIVO reqcontent = vivo.get_query_content(authorship, "describe") response = vivo.request_vivo( reqcontent, vivo_query_endpoint, vivoheaders, data, "query") rdfcontent = response.text reqcontent = vivo.get_query_content(rdfcontent, "delete") response = vivo.request_vivo( reqcontent, vivo_update_endpoint, vivoheaders, data, "update") logger.debug( "Response from VIVO: %s for deleting %s", str(response.status_code), authorship) if not (args.db == "off"): db.delete_record(dbconn, "relations", "rid", str(rsid)) os.remove(rsfolder + delfile) xmlfiles = file_utils.listfiles(rsfolder, extension) logger.debug(xmlfiles) logger.debug("Start processing relastions files......") for xmlfile in xmlfiles: with open(rsfolder + xmlfile) as fd: doc = xmltodict.parse(fd.read()) recid = doc["feed"]["id"] pubid = recid.split("/")[-2] if "entry" in doc["feed"]: entries = doc["feed"]["entry"] logger.debug('Parsing relationship file: ' + xmlfile) records = [] if isinstance(entries, collections.OrderedDict): records.append(entries) else: records = entries for e in records: if "api:relationship" in e: rsid = e["api:relationship"]["@id"] rstype = e["api:relationship"]["@type"] for rec in e["link"]: if "users" in rec["@href"]: eid = rec["@href"].split("/")[-1] logger.debug( 'Process rsid: %s, pubid: %s, eid: %s', rsid, pubid, eid) if rstype == "publication-user-authorship": visible = e["api:relationship"]["api:is-visible"] public = e["api:relationship"]["api:related"]["api:object"]["api:is-public"] else: visible = "false" if args.admin == "publicall": visible = "true" public = "true" # check if rec is already in db isExist = False if not (args.db == "off"): isExist = db.check_exist( dbconn, "relations", "rid", str(rsid)) authorship = vivo_namespace + "authorship" + pubid + "-" + eid if isExist: # remove it from VIVO for new insert or delete anyway reqcontent = vivo.get_query_content( authorship, "describe") response = vivo.request_vivo( reqcontent, vivo_query_endpoint, vivoheaders, data, "query") rdfcontent = response.text reqcontent = vivo.get_query_content( rdfcontent, "delete") response = vivo.request_vivo( reqcontent, vivo_update_endpoint, vivoheaders, data, "update") logger.debug( "Delete response from VIVO: %s for deleting %s", str(response.status_code), authorship) db_op = "none" if visible == "true" and public == "true": logger.debug( 'Harvesting Elements relationship id: ' + rsid) filename = xml_folder + "xml/relations/" + pubid + "-" + rsid + ".xml" elements.harvest_elements_xml( elements_endpoint, headers, "relationship", rsid, filename) if not isExist: db_op = "insert" else: if isExist: db_op = "delete" if not (args.db == "off"): if db_op == "insert": db.insert_relation(dbconn, str(rsid), "Y") elif db_op == "delete": db.delete_record( dbconn, "relations", "rid", str(rsid)) os.remove(rsfolder + xmlfile) if not (args.db == "off"): dbconn.close() logger.debug("Total public: " + str(total_public)) logger.debug("Total academic: " + str(total_academic)) logger.debug("Total current staff: " + str(total_current_staff)) elif args.optype == "db": logger.debug("Database operation") # create database db = DB() dbconn = db.db_connection(host=host, user=user, password=<PASSWORD>) db.create_vivo_database(dbconn, database) logger.debug("Database %s is created", database) dbconn = db.db_connection( host=host, user=user, password=<PASSWORD>, db=database) try: db.create_vivo_table(dbconn, "users") db.create_vivo_table(dbconn, "publications") db.create_vivo_table(dbconn, "relations") sqlQuery = "show tables;" rows = db.execute_query(dbconn, sqlQuery, "select") for row in rows: logger.debug("%s is created", row) except Exception as e: logger.debug("Exeception occured:{}".format(e)) finally: dbconn.close() elif args.optype == "getuser": db = DB() dbconn = db.db_connection( host=host, user=user, password=<PASSWORD>, db=database) rows = db.select_records(dbconn, "users", "public", "Y") content = "UID,PID\n" for row in rows: content = content + row['uid'].strip() + \ "," + row['pid'].strip() + "\n" if args.outfile.name != "<stdout>": args.outfile.write(content) args.outfile.close() else: file_utils.save_xml_file(content, "user_map.csv") dbconn.close() else: logger.debug("Wrong operation type") logger.debug("--- %s seconds ---" % (time.time() - start_time)) <file_sep>/vivotool/utils/models/publication_model.py from rdflib import BNode, Namespace, Literal, URIRef, RDF, RDFS, XSD from datetime import datetime import pytz import re COLLAB_VT = Namespace("http://collab.vt.edu/vivo/individual/") BIBO = Namespace("http://purl.org/ontology/bibo/") VCARD = Namespace('http://www.w3.org/2006/vcard/ns#') VIVO = Namespace('http://vivoweb.org/ontology/core#') OBO = Namespace('http://purl.obolibrary.org/obo/') SKOS = Namespace('http://www.w3.org/2008/05/skos#') class Publication: def __init__(self): self.id = '' self.is_public = False self.is_publication = True self.types = list() self.title = None self.abstract = None self.issue = None self.handle = None self.doi = None self.pm_id = None self.page_start = None self.page_end = None self.volume = None self.keywords = list() self.subject_areas = list() self.status = None self.publication_date = None self.journal = None self.webpages_publisher = None self.authorships = list() def __add_bindings(self, graph): graph.bind('bibo', BIBO) graph.bind('vcard', VCARD) graph.bind('vivo', VIVO) graph.bind('obo', OBO) graph.bind('skos', SKOS) def add_to_graph(self, graph): self.__add_bindings(graph) this = COLLAB_VT['publication' + self.id] # types for pub_type in self.types: if pub_type in [ 'AcademicArticle', 'Book', 'Chapter', 'Journal', 'Patent', 'Report', 'Thesis']: graph.add((this, RDF.type, BIBO[pub_type])) elif pub_type == 'Software': graph.add((this, RDF.type, OBO['ERO_0000071'])) else: graph.add((this, RDF.type, VIVO[pub_type])) graph.add((this, RDFS.label, Literal(self.title))) if self.abstract: graph.add((this, BIBO.abstract, Literal(self.abstract))) if self.issue: graph.add((this, BIBO.issue, Literal(self.issue))) if self.doi: graph.add((this, BIBO.doi, Literal(self.doi))) if self.pm_id: graph.add((this, BIBO.pmid, Literal(self.pm_id))) if self.handle: graph.add((this, BIBO.handle, Literal(self.handle))) if self.page_start: graph.add((this, BIBO.pageStart, Literal(self.page_start))) if self.page_start: graph.add((this, BIBO.pageEnd, Literal(self.page_end))) if self.volume: graph.add((this, BIBO.volume, Literal(self.volume))) # keywords for k in self.keywords: graph.add((this, VIVO.freetextKeyword, Literal(k))) # subject areas for sub_area in self.subject_areas: sub_area.uri = COLLAB_VT[sub_area.name()] sub_area.add_to_graph(graph, this) graph.add((this, VIVO.hasSubjectArea, sub_area.uri)) # publication date if self.publication_date: publication_date = self.publication_date publication_date.uri = URIRef(this + '-publicationDate') publication_date.add_to_graph(graph) graph.add((this, VIVO.dateTimeValue, publication_date.uri)) # journal if self.journal: journal = self.journal j_label = re.sub(r'["<>#%\{\}\|\\\^~\[\]`]', '', journal.label) journal.uri = COLLAB_VT['journal-' + j_label.lower().replace(' ', '-')] journal.add_to_graph(graph, this) graph.add((this, VIVO.hasPublicationVenue, journal.uri)) # webpages and webpages publisher if self.webpages_publisher: webpages_publisher = self.webpages_publisher webpages_publisher.add_to_graph(graph, this) # published or not status if self.status: graph.add( (this, BIBO.status, BIBO[self.status.lower().replace(' ', '-')])) # authorships for authorship in self.authorships: authorship.add_to_graph(graph) class PublicationDate: def __init__(self, id=None, month=1, day=1): self.id = id self.time_precision = None self.year = None self.month = month self.day = day self.type = None @staticmethod def format_datetime(yyyy, mm, dd): d = datetime(yyyy, mm, dd, tzinfo=pytz.utc) return str(d.isoformat()).replace('+00:00', 'Z') def add_to_graph(self, graph): this = self.uri graph.add((this, VIVO.dateTimePrecision, VIVO[self.time_precision])) if self.year: graph.add( (this, VIVO.dateTime, Literal( PublicationDate.format_datetime( self.year, self.month, self.day)))) graph.add((this, RDF.type, VIVO.DateTimeValue)) class Journal: def __init__(self, type='Journal'): self.label = None self.type = type self.issn = None self.eissn = None self.subject_areas = list() def add_to_graph(self, graph, venue_for): this = self.uri graph.add((this, RDFS.label, Literal(self.label))) graph.add((this, RDF.type, BIBO[self.type])) graph.add((this, VIVO.publicationVenueFor, venue_for)) if self.issn: graph.add((this, BIBO.issn, Literal(self.issn))) if self.eissn: graph.add((this, BIBO.eissn, Literal(self.eissn))) # subject areas for sub_area in self.subject_areas: sub_area.uri = COLLAB_VT[sub_area.name()] sub_area.add_to_graph(graph, this) graph.add((this, VIVO.hasSubjectArea, sub_area.uri)) class WebpagesPublisher: def __init__(self, type="publisher"): self.type = type self.label = None self.url = None def add_to_graph(self, graph, webpages_for): webpages_uri = URIRef(webpages_for + '-webpages') this = URIRef(webpages_uri + '-' + self.type) graph.add((webpages_uri, RDF.type, VCARD.Kind)) graph.add((webpages_uri, OBO.ARG_2000029, webpages_for)) graph.add((webpages_uri, VCARD.hasURL, this)) graph.add((webpages_for, OBO.ARG_2000028, webpages_uri)) graph.add((this, RDF.type, VCARD.URL)) graph.add((this, RDFS.label, Literal(self.label))) graph.add((this, VCARD.url, Literal(self.url))) class Authorship: def __init__(self, user=None, publication=None, rank=None): self.user = user self.publication = publication self.rank = rank self.id = id def add_to_graph(self, graph): if self.user.user_id: this = COLLAB_VT['authorship' + self.publication.id + '-' + self.user.user_id] self.user.uri = COLLAB_VT[self.user.username] elif self.user.last_name: with_initial = self.user.initial is not '' this = COLLAB_VT['authorship' + self.publication.id + self.user.name_in_uri().decode('utf-8')] self.user.classification = 'NonFacultyAcademic' self.user.uri = COLLAB_VT['person' + self.user.name_in_uri().decode('utf-8')] self.user.add_to_graph(graph) else: return self.publication.uri = COLLAB_VT['publication' + self.publication.id] # Person block graph.add((self.user.uri, VIVO.relatedBy, this)) # Publication block graph.add((self.publication.uri, VIVO.relatedBy, this)) # Relationship block graph.add((this, VIVO.relates, self.publication.uri)) graph.add((this, VIVO.relates, self.user.uri)) graph.add((this, RDF.type, VIVO['Authorship'])) if self.rank: graph.add((this, VIVO.rank, Literal(self.rank, datatype=XSD.int))) class SubjectArea: def __init__(self): self.label = None self.scheme = None def name(self): return 'vocab-' + self.scheme + '-' + \ self.label.lower().replace(',', '').replace(' ', '-') def add_to_graph(self, graph, subject_area_of): this = self.uri graph.add((this, RDF.type, SKOS.Concept)) graph.add((this, RDFS.label, Literal(self.label))) if self.scheme == 'mesh': graph.add( (this, RDFS.isDefinedBy, URIRef("http://www.nlm.nih.gov/mesh"))) elif self.scheme == 'science-metrix': graph.add((this, RDFS.isDefinedBy, URIRef( "http://www.science-metrix.com/"))) elif self.scheme == 'for': graph.add((this, RDFS.isDefinedBy, URIRef( "http://www.arc.gov.au/era/for"))) graph.add((this, VIVO.subjectAreaOf, subject_area_of)) <file_sep>/test/test_publication.py from unittest import TestCase from vivotool.utils.publicationxmltordf import PublicationXml2Rdf class TestSample(TestCase): def test_get_publication(self): pass <file_sep>/README.md # VIVO Harvester for Symplectic Elements A modern, full or incremental harvester to collect data from Symplectic Elements for import into VIVO # [VIVOHarvester](https://pypi.org/project/VIVOHarvester/) ## Installation ``` pip install VIVOHarvester ``` or ``` git clone <EMAIL>:VTUL/VIVOHarvester.git python setup.py install ``` ## Configuation * The local.yml example file is [here](example/configfile.yml.sample) * The logging_config.ini example file is [here](example/logging_config.ini.sample) * The upload folder structre ``` vivouploads/ ├── rdf │   ├── photos │   ├── publications │   ├── relations │   └── users └── xml ├── photos ├── publications ├── relations ├── temp └── users ``` * The photo folder structure ``` harvestedImages/ ├── fullImages └── thumbnails └── userphoto.jpeg ``` Place the [userphoto.jpeg](harvestedImages/thumbnails/userphoto.jpeg) to harvestedImages/thumbnails/ ## Usage * Harvest data from Elements (Default) ``` vivotool -f local.yml -t harvest -d 0 ``` * Harvest data from Elements a day ago (Current time -1 day) ``` vivotool -f local.yml -t harvest -d 1 ``` * Import RDF data into a VIVO instance ``` vivotool -f local.yml -t ingest ``` * Fetch user_map.csv ``` vivotool -f local.yml -t getuser ``` or ``` vivotool -f local.yml -t getuser -o yourpath/yourfilename ``` ## Database creation * Create require database ``` vivotool -f local.yml -t db ``` ## Upgrade to newer version ``` pip uninstall VIVOHarvester pip install VIVOHarvester==0.1.2 (e.g.) ``` ## Contributing Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us. ## Testing ``` py.test --cov=vivotool test/ coverage report -m coverage report ``` ## Versioning We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/VTUL/VTDLP/tags). ## Authors * Virginia Tech Libraries - Digital Libraries Development developers * [<NAME>](https://github.com/yinlinchen) * [<NAME>](https://github.com/tingtingjh) * [<NAME>](https://github.com/whunter) See also the list of [contributors](https://github.com/VTUL/VTDLP/contributors) who participated in this project. ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details <file_sep>/vivotool/utils/publicationxmltordf.py import collections import os import xmltodict from rdflib import Graph, Literal, BNode, RDF, RDFS, URIRef, Namespace from rdflib.namespace import FOAF, DC from datetime import datetime from vivotool.utils.models.publication_model import Publication, \ PublicationDate, Journal, WebpagesPublisher, Authorship, SubjectArea from vivotool.utils.models.user_model import User class PublicationXml2Rdf(object): def __get_publication(self, doc): try: publication = Publication() # object general information api_obj = doc["feed"]["entry"]["api:object"] publication.is_public = api_obj["api:is-public"] if not publication.is_public: print("RDF graph is not generated as record is private.") return None id = api_obj["@id"] publication.id = id # Publication Types pub_type = doc["feed"]["entry"]["content"]["div"]["p"][0][13:][:-1] if pub_type == 'book chapter or section': pub_type = 'Chapter' elif pub_type == 'conference paper or presentation': pub_type = 'ConferencePaper' elif pub_type == 'internet publication': pub_type = 'InternetPublication' elif pub_type == 'journal article': pub_type = 'Journal' elif pub_type == 'numbered extension publication': pub_type = 'NumberedExtensionPublication' elif pub_type == 'poster': pub_type = 'ConferencePoster' elif pub_type == 'presentation (not at a conference)': pub_type = 'PresentationNotConference' elif pub_type == 'refereed journal article': pub_type = 'AcademicArticle' elif pub_type == 'scholarly edition': pub_type = 'EditorialArticle' elif pub_type == 'software / code': pub_type = 'Software' elif pub_type == 'thesis / dissertation': pub_type = 'Thesis' else: pub_type = pub_type.capitalize() publication.types.append(pub_type) # Journal journal = Journal() for obj_key in api_obj.keys(): if obj_key == "api:repository-items": # handle publication.handle = api_obj[obj_key]["api:repository-item"]["api:public-url"].strip( ).replace("http://hdl.handle.net/", '') print('Handle: {}'.format(publication.handle)) elif obj_key == "api:all-labels": keywords = api_obj[obj_key]["api:keywords"]["api:keyword"] if (isinstance(keywords, list)): for keyword in keywords: for key in keyword.keys(): if key == "@scheme": subject_area = SubjectArea() subject_area.label = keyword["#text"] subject_area.scheme = keyword[key] publication.subject_areas.append( subject_area) if keyword["@scheme"] == "mesh": publication.keywords.append( keyword["#text"]) else: journal.subject_areas.append( subject_area) elif key == "@source" and keyword[key] in ["manual", "pubmed"]: publication.keywords.append( keyword["#text"]) for keyword in publication.keywords: print( 'Keyword: {}'.format( keyword.encode('utf-8'))) elif obj_key == "api:records": records = api_obj[obj_key]["api:record"] # get the record from PubMed or first if there are many # records if (isinstance(records, list)): record = records[0] record_chosen = False for r in records: if r["@source-name"] == "pubmed": record = r record_chosen = True if r["@id-at-source"]: publication.pm_id = r["@id-at-source"] print( 'PubMed: {}'.format( publication.pm_id)) elif r["@source-name"] == "crossref": if not record_chosen: record = r for f in r["api:native"]["api:field"]: if f["@name"] == "doi": publication.doi = f["api:text"] print('doi: {}'.format( publication.doi)) elif f["@name"] == "eissn": journal.eissn = f["api:text"] elif r["@source-name"] == "dspace": for f in r["api:native"]["api:field"]: if f["@name"] == "public-url": handle = f["api:text"].strip().replace( "http://hdl.handle.net/", '') if not publication.handle: publication.handle = handle print('Handle: {}'.format( publication.handle)) elif int(handle.split('/')[1]) > int(publication.handle.split('/')[1]): publication.handle = handle print('Handle: {}'.format( publication.handle)) else: record = records # field info from the first record publication_fields = record["api:native"]["api:field"] for f in publication_fields: f_name = f["@name"] if f_name == "title": publication.title = f["api:text"].strip('.') elif f_name == "abstract": publication.abstract = f["api:text"] elif f_name == "pagination" and f["api:pagination"]: pagination = f["api:pagination"] if "api:begin-page" in pagination.keys(): publication.page_start = pagination["api:begin-page"] if "api:end-page" in pagination.keys(): publication.page_end = pagination["api:end-page"] else: publication.page_end = publication.page_start elif f_name == "issue": publication.issue = f["api:text"] elif f_name == "volume": publication.volume = f["api:text"] elif "publication-date" in f_name: publication_date = PublicationDate(id) date_info = f["api:date"] time_precision = "Precision" for key in date_info.keys(): if key == "api:day": time_precision = "Day" + time_precision publication_date.day = int(date_info[key]) elif key == "api:month": time_precision = "Month" + time_precision publication_date.month = int( date_info[key]) elif key == "api:year": time_precision = "year" + time_precision publication_date.year = int(date_info[key]) publication_date.time_precision = time_precision publication_date.type = "DateTimeValue" publication.publication_date = publication_date elif f_name == "journal": journal.label = f["api:text"] elif f_name == "issn": journal.issn = f["api:text"] elif f_name == "publication-status": publication.status = f["api:text"].lower() elif f_name == "publisher-url" or f_name == "author-url": if "publisher" in f_name: webpages_publisher = WebpagesPublisher( 'publisher') webpages_publisher.label = "Publisher's Version" else: webpages_publisher = WebpagesPublisher( 'author') webpages_publisher.label = "Author's Version" webpages_publisher.url = f["api:text"] publication.webpages_publisher = webpages_publisher elif f_name == "authors": people = f["api:people"]["api:person"] if (isinstance(people, list)): for idx, p in enumerate( f["api:people"]["api:person"]): user = User() for key in p.keys(): if key == "api:links": user.user_id = p[key]["api:link"]["@id"] elif key == "api:last-name": user.last_name = p[key].strip().replace( ' ', '-') elif key == "api:first-names": user.first_name = p[key] elif key == "api:initials": user.initial = p[key] authorship = Authorship( user, publication, idx + 1) publication.authorships.append( authorship) else: user = User() p = people for key in p.keys(): if key == "api:links": user.user_id = p[key]["api:link"]["@id"] elif key == "api:last-name": user.last_name = p[key].strip().replace( ' ', '-') elif key == "api:first-names": user.first_name = p[key] elif key == "api:initials": user.initial = p[key] authorship = Authorship(user, publication, 1) publication.authorships.append(authorship) if journal.label: publication.journal = journal return publication except KeyError as key_error: print('Unable to properly parse xml file due to ' + str(key_error)) return None def parse(self, fileName, target_dir=""): try: with open(fileName) as fd: doc = xmltodict.parse(fd.read()) publication = self.__get_publication(doc) if publication: g = Graph() publication.add_to_graph(g) rdf_file = os.path.splitext( os.path.basename(fileName))[0] + ".rdf" g.serialize(target_dir + rdf_file, format='nt') print("Resulting RDF graph in: " + rdf_file) except KeyError as key_error: print('Error parsing ' + fileName + ' due to ' + str(key_error)) <file_sep>/vivotool/harvester/elements.py import argparse import collections import logging import lxml.etree as etree import pytz import requests import os import xmltodict import yaml from datetime import datetime, timedelta from vivotool.utils.file_utils import Utils from shutil import copyfile class Elements(object): """docstring for ClassName""" def elements_request(self, elementsurl, headers, *category): try: response = requests.get(elementsurl, headers=headers) except requests.exceptions.HTTPError as errh: print("Http Error:", errh) except requests.exceptions.ConnectionError as errc: print("Error Connecting:", errc) except requests.exceptions.Timeout as errt: print("Timeout Error:", errt) except requests.exceptions.RequestException as err: print("Something else is wrong", err) if category and category[0] == "photo": return response else: result = etree.fromstring(response.text.encode('utf-8')) return etree.tostring(result, pretty_print=True) def get_next_URL(self, content): if not content: return "" result_dict = xmltodict.parse(content) if "api:pagination" in result_dict["feed"]: pagination = result_dict["feed"]["api:pagination"]["api:page"] hasNext = False for p in pagination: if isinstance(p, collections.OrderedDict): hasNext = True else: hasNext = False if hasNext: nexturl = pagination[1]["@href"] else: nexturl = "" else: nexturl = "" return nexturl def harvest_elements_xml( self, elements_endpoint, headers, query_type, params, filename, *day): file_utils = Utils() if day and day[0] > 0: harvest_time = self.last_modified_date(day[0]) query_url = self.createElementsQueryURL( elements_endpoint, query_type, params, harvest_time) else: query_url = self.createElementsQueryURL( elements_endpoint, query_type, params) if query_type == "photo": response = self.elements_request(query_url, headers, "photo") fullImages = filename + "fullImages/" + params + ".jpeg" thumbnails = filename + "thumbnails/" + params + ".jpeg" if response.status_code == 200: file_utils.save_photo_file( response, fullImages) file_utils.save_photo_file( response, thumbnails) else: stubphoto = filename + "thumbnails/userphoto.jpeg" copyfile(stubphoto, fullImages) copyfile(stubphoto, thumbnails) elif query_type == "users" or query_type == "publications" or query_type == "pubrelationships": response = self.elements_request(query_url, headers) file_utils.save_xml_file(response, filename) nexturl = self.get_next_URL(response) num = 1 while len(nexturl) > 0: next_response = self.elements_request(nexturl, headers) next_filename = filename.replace(".xml", str(num) + ".xml") file_utils.save_xml_file(next_response, next_filename) num += 1 nexturl = self.get_next_URL(next_response) else: response = self.elements_request(query_url, headers) file_utils.save_xml_file(response, filename) def createElementsQueryURL( self, elements_endpoint, query_type, params, *day): query_url = elements_endpoint if query_type == "user": query_url += "users/" + str(params) elif query_type == "users" and day: query_url += "users" + "?detail=full&per-page=" + \ str(params) + "&modified-since=" + day[0] elif query_type == "users": query_url += "users" + "?detail=full&per-page=" + str(params) elif query_type == "publications" and day: query_url += "users/" + str(params) + \ "/publications?detail=full&per-page=25&modified-since=" + day[0] elif query_type == "publications": query_url += "users/" + str(params) + \ "/publications?detail=full&per-page=25" # elif query_type == "publicationbyday" and day: # query_url += "publications" + "?detail=full&per-page=25" + \ # "&modified-since=" + day[0] elif query_type == "publication": query_url += "publications/" + str(params) elif query_type == "relationship": query_url += "relationships/" + str(params) elif query_type == "pubrelationships" and day: query_url += "publications/" + str(params) + \ "/relationships?detail=full&per-page=25&modified-since=" + day[0] elif query_type == "pubrelationships": query_url += "publications/" + str(params) + \ "/relationships?detail=full&per-page=25" elif query_type == "photo": query_url += "users/" + str(params) + "/photo" else: raise ValueError('Invalidated input') return query_url def last_modified_date(self, day): try: val = int(day) except ValueError: raise if day <= 0: logging.error("day should be a positive number") return "" sinceday = datetime.now() - timedelta(days=day) calculate_date = datetime( sinceday.year, sinceday.month, sinceday.day, sinceday.hour, sinceday.minute, sinceday.second, tzinfo=pytz.utc) return str(calculate_date.isoformat()).replace('+00:00', 'Z') <file_sep>/vivotool/utils/__init__.py from . import file_utils from . import userxmltordf from .models import user_model <file_sep>/vivotool/utils/photo.py import rdflib from rdflib import Graph, Literal, BNode, RDF, RDFS, URIRef, Namespace from rdflib.namespace import FOAF, DC class Photo: def create_user_photo_graph(self, pid, eid): VITRO_PUBLIC = Namespace( "http://vitro.mannlib.cornell.edu/ns/vitro/public#") COLLAB_VT = Namespace("http://collab.vt.edu/vivo/individual/") user = COLLAB_VT[pid] userimage = COLLAB_VT[pid + '-image'] imageDownload = COLLAB_VT[pid + '-imageDownload'] imageThumbnail = COLLAB_VT[pid + '-imageThumbnail'] imageThumbnailDownload = COLLAB_VT[pid + '-imageThumbnailDownload'] thingURL = URIRef("http://www.w3.org/2002/07/owl#Thing") fileURL = URIRef( "http://vitro.mannlib.cornell.edu/ns/vitro/public#File") fileByteStreamURL = URIRef( "http://vitro.mannlib.cornell.edu/ns/vitro/public#FileByteStream") jpegmimeType = Literal("image/jpeg") filename = Literal(eid + ".jpeg") directDownloadUrl = Literal( "/harvestedImages/fullImages/" + eid + ".jpeg") thumbnailDownloadUrl = Literal( "/harvestedImages/thumbnails/" + eid + ".jpeg") g = Graph() g.bind('vitro-public', VITRO_PUBLIC) g.add((user, VITRO_PUBLIC.mainImage, userimage)) g.add((userimage, RDF.type, thingURL)) g.add((userimage, RDF.type, fileURL)) g.add((userimage, VITRO_PUBLIC.downloadLocation, imageDownload)) g.add((userimage, VITRO_PUBLIC.thumbnailImage, imageThumbnail)) g.add((userimage, VITRO_PUBLIC.filename, filename)) g.add((userimage, VITRO_PUBLIC.mimeType, jpegmimeType)) g.add((imageDownload, RDF.type, fileByteStreamURL)) g.add( (imageDownload, VITRO_PUBLIC.directDownloadUrl, directDownloadUrl)) g.add((imageThumbnail, RDF.type, thingURL)) g.add((imageThumbnail, RDF.type, fileURL)) g.add( (imageThumbnail, VITRO_PUBLIC.downloadLocation, imageThumbnailDownload)) g.add((imageThumbnail, VITRO_PUBLIC.filename, filename)) g.add((imageThumbnail, VITRO_PUBLIC.mimeType, jpegmimeType)) g.add((imageThumbnailDownload, RDF.type, fileByteStreamURL)) g.add( (imageThumbnailDownload, VITRO_PUBLIC.directDownloadUrl, thumbnailDownloadUrl)) return g.serialize(format='nt') <file_sep>/test/test_harvester.py import requests import requests_mock import tempfile import os from os import path from unittest import TestCase from vivotool.harvester.elements import Elements from vivotool.utils.file_utils import Utils from datetime import datetime, timedelta from unittest import mock class TestElements(TestCase): def setUp(self): self.elements = Elements() self.utils = Utils() self.test_dir = tempfile.mkdtemp() os.makedirs(self.test_dir + "/fullImages/") os.makedirs(self.test_dir + "/thumbnails/") def tearDown(self): self.elements = None @requests_mock.mock() def test_request_elements(self, m): m.get('http://foo.com/photo', text='photo') m.get('http://foo.com/user/1003', text='<feed>test</feed>') output = self.elements.elements_request( 'http://foo.com/photo', "", "photo") self.assertEqual(output.text, "photo") output = self.elements.elements_request("http://foo.com/user/1003", "") self.assertEqual(output.decode("utf-8"), "<feed>test</feed>\n") def test_get_next_URL(self): output = self.elements.get_next_URL("") # check empty string self.assertEqual(output, "") test_xml_content = """<feed xmlns="http://www.w3.org/2005/Atom" xmlns:api="testapi"> <api:pagination results-count="9429" items-per-page="25"> <api:page position="this" href="https://test.com"/> <api:page position="next" href="https://test.com?after-id=2784"/> </api:pagination> </feed> """ output = self.elements.get_next_URL(test_xml_content) expected = "https://test.com?after-id=2784" self.assertEqual(output, expected) # test if there is no next URL test_xml_content = """<feed xmlns="http://www.w3.org/2005/Atom" xmlns:api="testapi"> <api:pagination results-count="9429" items-per-page="25"> <api:page position="this" href="https://test.com"/> </api:pagination> </feed> """ output = self.elements.get_next_URL(test_xml_content) expected = "" self.assertEqual(output, expected) test_xml_content = """<feed xmlns="http://www.w3.org/2005/Atom" xmlns:api="testapi"> </feed> """ output = self.elements.get_next_URL(test_xml_content) expected = "" self.assertEqual(output, expected) def mock_queryurl(elements_endpoint, query_type, params, *day): return "http://foo.com/" + query_type + "/" + params def mock_elements_request(elementsurl, headers, *category): class MockResponse: def __init__(self, data, status_code): self.data = data self.status_code = status_code if category and category[0] == "photo": return MockResponse("<feed>test</feed>\n", 200) else: return "<feed>test</feed>\n" def mock_save_photo_file(content, filename): content = "<feed>test</feed>\n" with open(filename, "w") as file: file.write(content) @mock.patch( 'vivotool.harvester.elements.Elements.createElementsQueryURL', side_effect=mock_queryurl) @mock.patch( 'vivotool.harvester.elements.Elements.elements_request', side_effect=mock_elements_request) @mock.patch( 'vivotool.utils.file_utils.Utils.save_photo_file', side_effect=mock_save_photo_file) def test_harvest_elements_xml(self, m1, m2, m3): # test query_type == "photo" self.elements.harvest_elements_xml( 'http://foo.com/', "", "photo", "1003", self.test_dir + "/") imagefile1 = path.join(self.test_dir, 'fullImages/1003.jpeg') imagefile2 = path.join(self.test_dir, 'thumbnails/1003.jpeg') output = self.utils.read_file(imagefile1) self.assertEqual(output, "<feed>test</feed>\n") output = self.utils.read_file(imagefile2) self.assertEqual(output, "<feed>test</feed>\n") # test query_type == "users" testfile = path.join(self.test_dir, 'testuser.xml') self.elements.harvest_elements_xml( 'http://foo.com/', "", "users", "1003", testfile) output = self.utils.read_file(testfile) self.assertEqual(output, "<feed>test</feed>\n") # test query_type == "publications" with day testfile = path.join(self.test_dir, 'testpublications.xml') self.elements.harvest_elements_xml( 'http://foo.com/', "", "publications", "9003", testfile, 10) output = self.utils.read_file(testfile) self.assertEqual(output, "<feed>test</feed>\n") # test query_type = "user" testfile = path.join(self.test_dir, 'testsingleuser.xml') self.elements.harvest_elements_xml( 'http://foo.com/', "", "user", "1003", testfile) output = self.utils.read_file(testfile) self.assertEqual(output, "<feed>test</feed>\n") def test_createElementsQueryURL(self): elements_endpoint = "http://foo.com" # check user queryurl output = self.elements.createElementsQueryURL( elements_endpoint, "user", 1033) self.assertEqual(output, elements_endpoint + "users/1033") # check users and day harvest_time = self.elements.last_modified_date(5)[:10] expected = str(datetime.now() - timedelta(days=5))[:10] output = self.elements.createElementsQueryURL( elements_endpoint, "users", 25, harvest_time) self.assertEqual( output, elements_endpoint + "users?detail=full&per-page=25&modified-since=" + expected) # check users queryurl output = self.elements.createElementsQueryURL( elements_endpoint, "users", 25) self.assertEqual( output, elements_endpoint + "users?detail=full&per-page=25") # check publications and day harvest_time = self.elements.last_modified_date(5)[:10] expected = str(datetime.now() - timedelta(days=5))[:10] output = self.elements.createElementsQueryURL( elements_endpoint, "publications", 1033, harvest_time) self.assertEqual( output, elements_endpoint + "users/1033/publications?detail=full&per-page=25&modified-since=" + expected) # check publications output = self.elements.createElementsQueryURL( elements_endpoint, "publications", 1033) self.assertEqual(output, elements_endpoint + "users/1033/publications?detail=full&per-page=25") # check publication output = self.elements.createElementsQueryURL( elements_endpoint, "publication", 1033) self.assertEqual(output, elements_endpoint + "publications/1033") # check relationship output = self.elements.createElementsQueryURL( elements_endpoint, "relationship", 1033) self.assertEqual(output, elements_endpoint + "relationships/1033") # check pubrelationships and day harvest_time = self.elements.last_modified_date(5)[:10] expected = str(datetime.now() - timedelta(days=5))[:10] output = self.elements.createElementsQueryURL( elements_endpoint, "pubrelationships", 1033, harvest_time) self.assertEqual( output, elements_endpoint + "publications/1033/relationships?detail=full&per-page=25&modified-since=" + expected) # check pubrelationships output = self.elements.createElementsQueryURL( elements_endpoint, "pubrelationships", 1033) self.assertEqual( output, elements_endpoint + "publications/1033/relationships?detail=full&per-page=25") # check photo output = self.elements.createElementsQueryURL( elements_endpoint, "photo", 1033) self.assertEqual(output, elements_endpoint + "users/1033/photo") # check invalidated input self.assertRaises( ValueError, lambda: self.elements.createElementsQueryURL( elements_endpoint, "xyz", 1033)) def test_last_modified_date(self): day = 1 output = self.elements.last_modified_date(day)[:10] expected = str(datetime.now() - timedelta(days=day))[:10] self.assertEqual(output, expected) day = "string" self.assertRaises( ValueError, lambda: self.elements.last_modified_date(day)[ :1]) day = "1" self.assertRaises( TypeError, lambda: self.elements.last_modified_date(day)[ :1]) day = -1 output = self.elements.last_modified_date(day)[:10] expected = "" self.assertEqual(output, expected) <file_sep>/vivotool/utils/models/user_model.py #!/usr/bin/env python """ User Model Modified + Inspired by: https://github.com/andreasf/pentabarf-rdf/ """ import re from rdflib import Graph, BNode, Namespace, Literal, URIRef, RDF, RDFS, URIRef, XSD from rdflib.namespace import FOAF, DC, RDFS, RDF COLLAB_VT = Namespace("http://collab.vt.edu/vivo/individual/") VCARD = Namespace('http://www.w3.org/2006/vcard/ns#') VIVO = Namespace('http://vivoweb.org/ontology/core#') OBO = Namespace('http://purl.obolibrary.org/obo/') class User: def __init__( self, title=None, first_name=None, last_name=None, username=None): self.title = title self.username = username self.user_id = None self.first_name = first_name self.last_name = last_name self.initial = None self.classification = 'FacultyMember' self.suffix = '' self.overview = '' self.email = '' self.email_is_public = False self.degrees = [] self.institutions = [] self.appointments = [] self.vcard = VCard(self) self.is_academic = False self.is_current_staff = False self.is_public = False def id(self): return self.username def display_name(self): # TODO: need further check # if not self.first_name: # return if self.last_name and self.first_name: return '{}, {}'.format( self.last_name.encode('utf-8'), self.first_name.encode('utf-8')) elif self.last_name and self.initial: return '{}, {}'.format( self.last_name.encode('utf-8'), self.initial.encode('utf-8')) elif self.last_name: return '{}'.format(self.last_name.encode('utf-8')) def name_in_uri(self): if self.last_name and self.initial: name = '-{}-{}'.format(self.last_name.encode('utf-8'), self.initial.encode('utf-8')) elif self.last_name: return '-{}'.format(self.last_name.encode('utf-8')) name = re.sub(r'["<>#%\{\}\|\\\^~\[\]`]', '', name) return name.lower().replace(' ', '-') def add_to_graph(self, graph): if self.classification == 'NonFacultyAcademic': user = self.uri else: if self.display_name() is None: return user = COLLAB_VT[self.id()] self.__add_bindings(graph) graph.add((user, VIVO.overview, Literal(self.overview))) for appointments in self.appointments: appointments.add_to_graph(graph, self) for degree in self.degrees: degree.add_to_graph(graph, self) graph.add((user, RDF.type, VIVO[self.classification])) graph.add( (user, RDFS.label, Literal( self.display_name().decode('utf-8')))) self.vcard.add_to_graph(graph) def __add_bindings(self, graph): graph.bind('vivo', VIVO) graph.bind('vcard', VCARD) graph.bind('obo', OBO) class Institution: def __init__(self): self.label = None self.city = None self.country = None self.dept = None def add_to_graph(self, graph): institution = COLLAB_VT[self.id()] graph.add((institution, RDF.type, VIVO['University'])) graph.add((institution, RDFS.label, Literal(self.label))) if self.dept: dept = COLLAB_VT[self.dept_id()] graph.add((institution, OBO.BFO_0000051, dept)) graph.add((dept, OBO.BFO_0000050, institution)) graph.add((dept, RDF.type, VIVO['AcademicDepartment'])) graph.add((dept, RDFS.label, Literal(self.dept))) def id(self): return 'institution-{}'.format(self.label.lower().replace(' ', '-')) def dept_id(self): return 'dept-{}-{}'.format(self.dept.lower().replace(' ', '-'), self.label.lower().replace(' ', '-')) class Degree: def __init__(self, username=None, type=None, label=None, field=''): self.username = username self.type = type self.label = label self.field = field self.institution = Institution() self.start_date = None self.end_date = None self.date_interval = None self.is_public = False def add_to_graph(self, graph, user_obj): degree = COLLAB_VT[self.degree_id()] degree_institution = COLLAB_VT[self.institution.id()] awarded_degree = COLLAB_VT[self.individual_degree_id()] user = COLLAB_VT[user_obj.id()] graph.add((user, VIVO.relatedBy, degree)) graph.add((degree, RDF.type, VIVO['AcademicDegree'])) graph.add((degree, RDFS.label, Literal(self.label))) graph.add((awarded_degree, RDF.type, VIVO['AwardedDegree'])) graph.add((awarded_degree, VIVO.relates, COLLAB_VT[self.degree_id()])) graph.add((awarded_degree, VIVO.relates, COLLAB_VT[self.username])) graph.add((awarded_degree, OBO.RO_0002353, COLLAB_VT[self.eduprocess_id()])) graph.add( (awarded_degree, RDFS.label, Literal( '{}: {}'.format( user_obj.display_name().decode('utf-8'), self.label)))) graph.add((awarded_degree, VIVO.assignedBy, degree_institution)) graph.add((degree_institution, VIVO.relatedBy, awarded_degree)) self.institution.add_to_graph(graph) self.__add_dates_to_graph(graph) self.__add_eduprocess_to_graph(graph, user_obj) def __add_eduprocess_to_graph(self, graph, user): edu_process = COLLAB_VT[self.eduprocess_id()] degree_institution = COLLAB_VT[self.institution.id()] awarded_degree = COLLAB_VT[self.individual_degree_id()] graph.add((edu_process, RDF.type, VIVO['EducationalProcess'])) graph.add((edu_process, VIVO.dateTimeInterval, COLLAB_VT[self.date_time_interval_id()])) graph.add((edu_process, OBO.RO_0000057, degree_institution)) graph.add((edu_process, OBO.RO_0002234, awarded_degree)) graph.add((edu_process, OBO.RO_0000057, COLLAB_VT[user.id()])) def __add_dates_to_graph(self, graph): if self.start_date or self.end_date: degree_start_date = COLLAB_VT[self.individual_degree_id( ) + '-startDate'] degree_end_date = COLLAB_VT[self.individual_degree_id( ) + '-endDate'] degree_interval = COLLAB_VT[self.date_time_interval_id()] graph.add((degree_interval, RDF.type, VIVO['DateTimeInterval'])) if self.start_date: self.__add_degree_date_to_graph( graph, degree_start_date, self.start_date) graph.add((degree_interval, VIVO.start, degree_start_date)) if self.end_date: self.__add_degree_date_to_graph( graph, degree_end_date, self.end_date) graph.add((degree_interval, VIVO.end, degree_end_date)) def __add_degree_date_to_graph(self, graph, subject, date): graph.add((subject, RDF.type, VIVO['DateTimeValue'])) graph.add( (subject, VIVO.dateTime, Literal( date, datatype=XSD.dateTime))) graph.add((subject, VIVO.dateTimePrecision, VIVO['yearPrecision'])) def degree_id(self): # example: 'degree-ma-geography' return 'degree-' + self.type.lower().replace(' ', '-') + \ '-' + self.field.lower().replace(' ', '-') def individual_degree_id(self): # example: 'degree-username-ma-geography' return 'degree-{}-{}-{}'.format(self.username.lower(), self.type.lower().replace(' ', '-'), self.field.lower().replace(' ', '-')) def date_time_interval_id(self): # example: 'degree-username-ma-geography-dateInterval-2000-2001' # TODO: find a better way to store, parse out years for the datetime interval # Assumption: Will return different format if both start and end dates # aren't defined from datetime import datetime if self.start_date and self.end_date: start_year = datetime.strptime( self.start_date, '%Y-%m-%dT%H:%M:%S').year end_year = datetime.strptime( self.end_date, '%Y-%m-%dT%H:%M:%S').year return '{}-dateInterval-{}-{}'.format( self.individual_degree_id(), start_year, end_year) else: return self.individual_degree_id() + '-dateInterval' def eduprocess_id(self): # example: 'eduprocess-username-ma-geography' return 'eduprocess-{}-{}-{}'.format( self.username.lower(), self.type.lower().replace( ' ', '-'), self.field.lower().replace(' ', '-')) class Appointment: def __init__(self, is_public=False, id_suffix=''): self.is_public = is_public self.id_suffix = id_suffix self.label = None self.institution = Institution() self.start_date = None self.end_date = None def add_to_graph(self, graph, user_obj): if (self.is_public is False): return appointment = COLLAB_VT[self.id()] user = COLLAB_VT[user_obj.id()] graph.add((appointment, RDF.type, VIVO['Position'])) graph.add((appointment, RDFS.label, Literal(self.label))) self.__add_interval_to_graph(graph, appointment) self.institution.add_to_graph(graph) if self.institution.dept: graph.add((appointment, VIVO.relates, COLLAB_VT[self.institution.dept_id()])) graph.add((user, VIVO.relatedBy, appointment)) graph.add((appointment, VIVO.relates, user)) def id(self): return 'appointment-{}'.format(self.id_suffix) def date_interval_id(self): return '{}-dateInterval'.format(self.id()) def __add_interval_to_graph(self, graph, appointment): if (self.start_date or self.end_date): interval = COLLAB_VT[self.date_interval_id()] graph.add((appointment, VIVO.dateTimeInterval, interval)) graph.add((interval, RDF.type, VIVO['DateTimeInterval'])) if self.start_date: start_date = COLLAB_VT[self.id() + '-startDate'] graph.add((interval, VIVO.start, start_date)) self.__add_date_to_graph(graph, start_date, self.start_date) if self.end_date: end_date = COLLAB_VT[self.id() + '-endDate'] graph.add((interval, VIVO.end, end_date)) self.__add_date_to_graph(graph, end_date, self.end_date) def __add_date_to_graph(self, graph, subject, date): graph.add((subject, RDF.type, VIVO['DateTimeValue'])) graph.add( (subject, VIVO.dateTime, Literal( date, datatype=XSD.dateTime))) graph.add((subject, VIVO.dateTimePrecision, VIVO['yearPrecision'])) class VCard: def __init__(self, user=None): self.user = user if user is None: user = User() def add_to_graph(self, graph): self.__add_vcard(graph) def __add_vcard(self, graph): if self.user.classification == 'NonFacultyAcademic': user = self.user.uri # person vcard vt_vcard = COLLAB_VT['personvcard' + self.user.name_in_uri().decode('utf-8')] vt_vcardname = COLLAB_VT['personvcardname' + self.user.name_in_uri().decode('utf-8')] else: user = COLLAB_VT[self.user.username] # vcard vt_vcard = COLLAB_VT['vcard-' + self.user.username] # vcardemail vt_vcardemail = COLLAB_VT['vcardemail-' + self.user.username] if self.user.email_is_public: graph.add((vt_vcard, VCARD.hasEmail, vt_vcardemail)) graph.add((vt_vcardemail, RDF.type, VCARD['Email'])) graph.add((vt_vcardemail, RDF.type, VCARD['Work'])) graph.add( (vt_vcardemail, VCARD.email, Literal( self.user.email))) # vcardname # TODO: Which fields are mandatory? Which fields are optional? vt_vcardname = COLLAB_VT['vcardname-' + self.user.username] if self.user.suffix: graph.add( (vt_vcardname, VCARD.suffix, Literal( self.user.suffix))) # vcardtitle vt_vcardtitle = COLLAB_VT['vcardtitle-' + self.user.username] graph.add((vt_vcard, VCARD.hasTitle, vt_vcardtitle)) graph.add((vt_vcardtitle, RDF.type, VCARD['Title'])) graph.add((vt_vcardtitle, VCARD.title, Literal(self.user.title))) graph.add((user, OBO.ARG_2000028, vt_vcard)) graph.add((vt_vcard, RDF.type, VCARD.Individual)) graph.add((vt_vcard, OBO.ARG_2000029, user)) graph.add((vt_vcard, VCARD.hasName, vt_vcardname)) graph.add((vt_vcardname, RDF.type, VCARD.Name)) graph.add( (vt_vcardname, VCARD.givenName, Literal( self.user.first_name))) graph.add( (vt_vcardname, VCARD.familyName, Literal( self.user.last_name)))
277fac7d75f7d04a1eac5297d0b661936952b687
[ "Markdown", "Python" ]
26
Python
VTUL/VIVOHarvester
bb3e191eed4239f271d38cd41686f5432c61cb5e
d9310b4974e00cc78677a498dcd0dac8fa4860a4
refs/heads/master
<file_sep>// // ZACoreDataStack.swift // CoreDataStack // // Created by <NAME> on 10/23/15. // Copyright © 2015 <NAME>. All rights reserved. // import CoreData private var _stacks:[String:NSPersistentStoreCoordinator] = [:] public class ZACoreDataStack { // MARK: - Private Attributes private let coreDataUbiquitizedKey = "com.apple.coredata.ubiquity.ubiquitized" private let iCloudEnabledKey = "CoreDataStack.iCloudEnabledKey" private let cloudStoreSuffix = "_cloud.sqlite" private let localStoreSuffix = "_local.sqlite" private var modelName: String? = nil private var _persistentStoreCoordinator: NSPersistentStoreCoordinator? private var _managedObjectContext: NSManagedObjectContext private lazy var applicationDocumentsDirectory: NSURL = { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() // MARK: - Initialization and Deinitialization public convenience init(model:String) { self.init(key:model, model: model, isCloudEnabledByDefault: false) } public convenience init(model:String, isCloudEnabledByDefault:Bool) { self.init(key:model, model: model, isCloudEnabledByDefault: isCloudEnabledByDefault) } public convenience init(key:String, model:String) { self.init(key:key, model: model, isCloudEnabledByDefault: false) } public init(key:String, model:String, isCloudEnabledByDefault:Bool) { modelName = model _managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) if model.characters.count > 0 { if let modelURL = NSBundle.mainBundle().URLForResource(model, withExtension: "momd"), let managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL) { if _stacks[key] != nil { self._persistentStoreCoordinator = _stacks[key] registerForStoreNotifications() } else { self._persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) if let coordinator = self._persistentStoreCoordinator { do { try configurePersistentStoreCoordinator(coordinator, isCloudEnabledByDefault: isCloudEnabledByDefault) _managedObjectContext.persistentStoreCoordinator = coordinator // store global reference for sharing between stack instances _stacks[key] = coordinator registerForStoreNotifications() } catch { print("error configuring persistent store container") } } } } else { print("ERROR: model file not found") } } else { print("ERROR: model name cannot be emptystring") } } deinit { deRegisterForStoreNotifications() } // MARK: - Configure Stack Objects private func configurePersistentStoreCoordinator(persistentStoreCoordinator: NSPersistentStoreCoordinator, isCloudEnabledByDefault:Bool) throws { if let modelName = self.modelName { var options:[String:AnyObject]? = nil let url:NSURL let isCloudEnabled:Bool if NSUserDefaults.standardUserDefaults().objectForKey(iCloudEnabledKey) != nil { isCloudEnabled = NSUserDefaults.standardUserDefaults().boolForKey(iCloudEnabledKey) } else { isCloudEnabled = isCloudEnabledByDefault NSUserDefaults.standardUserDefaults().setBool(isCloudEnabledByDefault, forKey: iCloudEnabledKey) } if isCloudEnabled { url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(self.cloudStoreName()) options = [NSPersistentStoreUbiquitousContentNameKey : modelName, NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] } else { url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(self.localStoreName()) options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] } try persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options) if self.isCoreDataCloudEnabled() { print("\nConfigured for CLOUD\n") } else { print("\nConfigured for LOCAL\n") } } } private func cloudStoreName() -> String { let result:String if let modelName = self.modelName { result = "\(modelName)\(cloudStoreSuffix)" } else { result = "" } return result } private func localStoreName() -> String { let result:String if let modelName = self.modelName { result = "\(modelName)\(localStoreSuffix)" } else { result = "" } return result } // MARK: - Stack Object Accessors public func currentPersistentStore() -> NSPersistentStore? { var store:NSPersistentStore? = nil if let persistentStoreCoordinator = _managedObjectContext.persistentStoreCoordinator { store = persistentStoreCoordinator.persistentStores[0] } return store } public func currentManagedObjectContext() -> NSManagedObjectContext { return self._managedObjectContext } // MARK: - Core Data Saving support public func saveContext () { if _managedObjectContext.hasChanges { do { try _managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } // MARK: - CoreData Notification Handlers private func registerForStoreNotifications() { let notificationCenter : NSNotificationCenter = NSNotificationCenter.defaultCenter(); notificationCenter.addObserverForName(NSPersistentStoreCoordinatorStoresWillChangeNotification, object: self._persistentStoreCoordinator, queue: NSOperationQueue.mainQueue()) { (note : NSNotification) -> Void in print("\nNSPersistentStoreCoordinatorStoresWillChangeNotification\n") self._managedObjectContext.performBlock({ () -> Void in if self._managedObjectContext.hasChanges { self.saveContext() } else { self._managedObjectContext.reset() } }) // TODO: disable user interface } notificationCenter.addObserverForName(NSPersistentStoreCoordinatorStoresDidChangeNotification, object: self._persistentStoreCoordinator, queue: NSOperationQueue.mainQueue()) { (note : NSNotification) -> Void in print("\nNSPersistentStoreCoordinatorStoresDidChangeNotification\n") if self.isCoreDataCloudEnabled() { print("\nCLOUD\n") } else { print("\nLOCAL\n") } // TODO: enable user interface } notificationCenter.addObserverForName(NSPersistentStoreCoordinatorWillRemoveStoreNotification, object: self._persistentStoreCoordinator, queue: NSOperationQueue.mainQueue()) { (note : NSNotification) -> Void in print("\nNSPersistentStoreCoordinatorWillRemoveStoreNotification\n") } notificationCenter.addObserverForName(NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: self._persistentStoreCoordinator, queue: NSOperationQueue.mainQueue()) { (note : NSNotification) -> Void in print("\nNSPersistentStoreDidImportUbiquitousContentChangesNotification\n") self._managedObjectContext.performBlock({ () -> Void in self._managedObjectContext.mergeChangesFromContextDidSaveNotification(note) }) } } private func deRegisterForStoreNotifications() { let notificationCenter : NSNotificationCenter = NSNotificationCenter.defaultCenter(); notificationCenter.removeObserver(NSPersistentStoreCoordinatorStoresWillChangeNotification) notificationCenter.removeObserver(NSPersistentStoreCoordinatorStoresDidChangeNotification) notificationCenter.removeObserver(NSPersistentStoreCoordinatorWillRemoveStoreNotification) notificationCenter.removeObserver(NSPersistentStoreDidImportUbiquitousContentChangesNotification) } // MARK: - Core Data Cloud/Local Migration Methods public func isCoreDataCloudEnabled() -> Bool { var result = false if NSUserDefaults.standardUserDefaults().objectForKey(iCloudEnabledKey) != nil { result = NSUserDefaults.standardUserDefaults().boolForKey(iCloudEnabledKey) } return result } private func buildNewStore(url:NSURL, options:[NSObject : AnyObject], type:String) -> Bool { var result = false // remove any existing store at target location if NSFileManager.defaultManager().fileExistsAtPath(url.absoluteString) { do { try NSFileManager.defaultManager().removeItemAtURL(url) } catch { print("removeItemAtURL error - do we care?") } } if let currentStore = self.currentPersistentStore(), let coordinator = self._persistentStoreCoordinator { do { try coordinator.migratePersistentStore(currentStore, toURL: url, options: options, withType: type) result = true } catch { print("Unresolved error") } } return result } public func resetCloudData() { self.removeStoreFromCloud() if let store = self.currentPersistentStore() { self.currentManagedObjectContext().reset() do { try self.currentManagedObjectContext().persistentStoreCoordinator?.removePersistentStore(store) try NSPersistentStoreCoordinator.removeUbiquitousContentAndPersistentStoreAtURL(store.URL!, options: store.options) } catch { } } } public func removeStoreFromCloud() { if self.isCoreDataCloudEnabled() { var success = true // update options for local data store let newOptions:[NSObject : AnyObject] = [NSPersistentStoreRemoveUbiquitousMetadataOption : true] // set cloud store location let cloudURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent(self.cloudStoreName()) if let currentStore = self.currentPersistentStore(), let coordinator = self._persistentStoreCoordinator { do { try coordinator.migratePersistentStore(currentStore, toURL: cloudURL, options: newOptions, withType: NSSQLiteStoreType) } catch { print("Unresolved error") } } else { success = false } if success { NSUserDefaults.standardUserDefaults().setBool(false, forKey: iCloudEnabledKey) } } } public func moveStoreToCloud() { if !self.isCoreDataCloudEnabled() { var success = true if let modelName = self.modelName { // update options for local data store let newOptions:[NSObject : AnyObject] = [NSPersistentStoreUbiquitousContentNameKey : modelName] // set cloud store location let cloudURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent(self.cloudStoreName()) if let currentStore = self.currentPersistentStore(), let coordinator = self._persistentStoreCoordinator { do { try coordinator.migratePersistentStore(currentStore, toURL: cloudURL, options: newOptions, withType: NSSQLiteStoreType) } catch { print("Unresolved error") } } else { success = false } } else { success = false } if success { NSUserDefaults.standardUserDefaults().setBool(true, forKey: iCloudEnabledKey) } } } } <file_sep>Pod::Spec.new do |s| s.platform = :ios s.ios.deployment_target = '8.0' s.name = "ZACoreDataStack" s.version = "0.0.8" s.summary = "ZACoreDataStack provides an independent core data stack initialized with just the model file name" s.homepage = "https://github.com/zullevig/ZACoreDataStack" s.license = { :type => "MIT", :file => "LICENSE" } s.author = "<NAME>" s.source = { :git => "https://github.com/zullevig/ZACoreDataStack.git", :tag => s.version } s.source_files = "ZACoreDataStack/**/*.{swift}" s.framework = "CoreData" end <file_sep># ZACoreDataStack A CoreData stack framework supporting the creation of the stack with just the name of the data model and enabling iCloud syncing by setting a single flag. ### Creating the CoreData stack ``` let coreDataStack = ZACoreDataStack(model: "CoreDataStack", isCloudEnabledByDefault: true) ``` ### Installation with CocoaPods To integrate ZACoreDataStack into your Xcode project using CocoaPods, specify it in your Podfile: ``` platform :ios, '8.0' pod 'ZACoreDataStack', '~> 0.0.0' ``` Then, run the following command: ``` $ pod install ```
6411853737aa27f4c9d058abcf073fd4ecb3ba64
[ "Swift", "Ruby", "Markdown" ]
3
Swift
zullevig/ZACoreDataStack
fd43465b5fab2959e566bfa9984143dc70cedd51
5b4ea879352e1990a0ba7eb2c8820310c2cb770b
refs/heads/master
<file_sep>'use strict'; function enumOwnSymbols(obj) { /* istanbul ignore if */ if (typeof Symbol !== 'function') { return []; } switch (typeof obj) { case 'object': { obj = obj || {}; break; } case 'function': { break; } default: { return []; } } var symbols = Object.getOwnPropertySymbols(obj); for (var i = symbols.length - 1; i >= 0; i--) { var descriptor = Object.getOwnPropertyDescriptor(obj, symbols[i]); if (!descriptor.enumerable) { symbols.splice(i, 1); } } return symbols; } module.exports = enumOwnSymbols;
55fd8e28bf781fc7676537f351cdf85dcf69b093
[ "JavaScript" ]
1
JavaScript
sttk/fav-prop.enum-own-symbols
1479393e3d3c0dd344c63f8a9cedab0f0869a3f4
3e8da918021325311a4b847f09278a1f33359396
refs/heads/main
<repo_name>BenteaB/PlanBy<file_sep>/README.md # PlanBy Bets app ever is processing.... No fiti atenti ce baban o sa fie toata chestia asta <file_sep>/Calendar/dorin1.py from flask import Flask, render_template, request, jsonify import requests from bs4 import BeautifulSoup from flask_cors import CORS import json app = Flask(__name__) CORS(app) # cross origin @app.route("/site.html",methods=['GET','POST','PUT']) def get_orar(): data = request.json x = json.loads(data) #print(x["grupa"]) #doar dictionar ai voie in jscript url = "https://www.cs.ubbcluj.ro/files/orar/2020-1/tabelar/I1.html" r = requests.get(url) soup = BeautifulSoup(r.text, "html.parser") table_all = soup.find_all("table") citit = x["grupa"] #citit = input("Numarul grupei(ex: 211/1): ") gr, subgr = citit.split("/") gr = int(gr)-211 subgr = int(subgr) gr = 0 subgr = 1 table = table_all[gr] k = 0 lista = {} rows = table.find_all("tr") for row in rows[1:]: zi = row.find_all("td")[0].text.strip() ora = row.find_all("td")[1].text.strip() frecv = row.find_all("td")[2].text.strip() form = row.find_all("td")[4].text.strip() tip = row.find_all("td")[5].text.strip() disc = row.find_all("td")[6].text.strip() prof = row.find_all("td")[7].text.strip() if frecv == "": frecv = 0 elif frecv == "sapt. 1": frecv = 1 elif frecv == "sapt. 2": frecv = 2 if form[-2:] == "/1": form = 1 elif form[-2:] == "/2": form = 2 else: form = subgr #prof = prof.split(" ", 1)[1] if form == subgr: # nu am mai pus formatia lista[k] = {"zi":zi,"ora":ora,"frecv":frecv,"tip":tip,"disc":disc,"prof":prof} k += 1 #for el in lista: #print(el) return lista app.run(debug = True)<file_sep>/prostie.py import urllib url = ['http://google.com','http://bing.com'] for i in url: html = urllib.urlopen(i).read() print(html.encode('utf-8')) <file_sep>/Errors.py class PlatformError(Exception): pass class HourError(Exception): pass<file_sep>/Calendar/EmailReaderToPopUp.py import email import imaplib import re from flask import Flask, render_template, request, jsonify import requests from flask_cors import CORS import json from datetime import date from Errors import PlatformError, HourError def get_body(msg): if msg.is_multipart(): return get_body(msg.get_payload(0)) else: return msg.get_payload(None, True) def ConvertMessageToString(raw): string_message = str(get_body(raw)) string_message = string_message.replace("\\r", "") string_message = string_message.replace("\\n", "") return string_message def FindPlatform(message): platforms = {"Discord": ["discord"], "Zoom": ["zoom"], "Microsoft Teams": ["ms teams", "msteams", "teams", "microfost teams"], "Google meet":["google meet", "meet"], "Messenger": ["messenger", "facebook"]} temp = message.lower() for elem in platforms: for platform in platforms[elem]: if platform in temp: return elem raise PlatformError("Nu am gasit nici o platforma!\n") def FindDay(message): days = [] months = [] separators = ["/", "."] for i in range (1, 31): days.append(str(i)) for i in range(1, 13): months.append(str(i)) for i in reversed(days): day = i occurrences = [m.start() for m in re.finditer(day, message)] for j in occurrences: try: month = int(message[j + 3 : j + 5]) except ValueError: try: month = int(message[j + 3]) except ValueError: continue except IndexError: break except IndexError: try: month = int(message[j + 3]) except ValueError: continue except IndexError: break print(day) if (str(month) in months) and (message[j + 2] in separators): print(day, str(month)) return day + " " + str(month) raise HourError("Nu am gasit nici o data calendaristica in email!\n") def FindHour(message): hours = [] separator = [" ", ":", ";", "-"] rez = "" for i in range(0, 25): i = str(i) if len(i) < 2: i = "0" + i hours.append(i) for i in range(0, 10): hours.append(str(i)) for i in hours: hour = i occurrences = [m.start() for m in re.finditer(hour, message)] for j in occurrences: try: minutes = int(message[j + 3 : j + 5]) except ValueError: continue else: if minutes % 10 == 0 and minutes >= 0 and minutes <= 50: if len(hour) == 1: j -= 1 if message[j + 3 : j + 5].isdigit() and (message[j + 2] in separator): return hour + ":" + message[j + 3 : j + 5] raise HourError("Nu am gasit nici o ora in email!\n") def Logare(): user = "<EMAIL>" password = "<PASSWORD>" imap_url = "imap.gmail.com" M = imaplib.IMAP4_SSL(imap_url) M.login(user, password) M.select('INBOX') M.select() return M def SearchPlatformAndHour(Account): typ, data = Account.search(None, 'unseen') Platform = None Hour = None for num in reversed(data[0].split()): typ, data = Account.fetch(num, '(RFC822)') raw = email.message_from_bytes(data[0][1]) TheMessage = ConvertMessageToString(raw) try: Platform = FindPlatform(TheMessage) except PlatformError: continue try: Hour = FindHour(TheMessage) except HourError: continue try: DataCalendaristica = FindDay(TheMessage) except HourError as re: print(re) return [Platform, Hour, DataCalendaristica] raise Exception("Nu am putut gasi un meeting!\n") def Delogare(Account): Account.close() Account.logout() app = Flask(__name__) CORS(app) # cross origin @app.route("/index.html", methods=['GET', 'POST', 'PUT']) def run(): data = request.json x = json.loads(data) k = 0 while True: cont = Logare() k += 1 print("Cautarea nr: " + str(k)) try: Platforma, Hour, DataCalendaristica = SearchPlatformAndHour(cont) dictionar = {} dictionar["platforma"] = Platforma dictionar["ora"] = Hour lista = DataCalendaristica.split() dictionar["zi"] = lista[0] dictionar["luna"] = lista[1] Delogare(cont) return dictionar #meetings -> contine toate meetingurile din mailurile necitite except Exception as ex: continue Delogare(cont) app.run(debug = True)<file_sep>/Calendar/script.js const date = new Date(); const renderCalendar = () => { date.setDate(1); const monthDays = document.querySelector(".days"); const lastDay = new Date( date.getFullYear(), date.getMonth() + 1, 0 ).getDate(); const prevLastDay = new Date( date.getFullYear(), date.getMonth(), 0 ).getDate(); const firstDayIndex = date.getDay(); const lastDayIndex = new Date( date.getFullYear(), date.getMonth() + 1, 0 ).getDay(); const nextDays = 7 - lastDayIndex - 1; const months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; document.querySelector(".date h1").innerHTML = months[date.getMonth()]; document.querySelector(".date p").innerHTML = new Date().toDateString(); let days = ""; for (let x = firstDayIndex; x > 0; x--) { days += `<div class="prev-date">${prevLastDay - x + 1}</div>`; } for (let i = 1; i <= lastDay; i++) { if ( i === new Date().getDate() && date.getMonth() === new Date().getMonth() ) { days += `<div class="today" id = ${i}>${i}</div>`; } else { days += `<div class = day id = ${i}>${i}</div>`; } } for (let j = 1; j <= nextDays; j++) { days += `<div class="next-date">${j}</div>`; monthDays.innerHTML = days; } }; document.querySelector(".prev").addEventListener("click", () => { date.setMonth(date.getMonth() - 1); renderCalendar(); }); document.querySelector(".next").addEventListener("click", () => { date.setMonth(date.getMonth() + 1); renderCalendar(); }); var events_plan = Array(32); for (i = 1; i <= 31; ++i){ events_plan[i] = ""; } let eventsForDate = "" let lastDayClicked = -1; let actualDayClicked; document.querySelector(".days").addEventListener("click", () => { if (lastDayClicked != -1 && lastDayClicked != new Date().getDate() && document.getElementById(lastDayClicked).style.background != "rgb(77, 166, 255)"){ document.getElementById(lastDayClicked).style.background = "#222227"; } if (window.event.target.className === "days"){ return; } if (window.event.target.className === "today") { lastDayClicked = window.event.target.textContent; document.querySelector(".listOfEvents").innerHTML = events_plan[lastDayClicked]; return; } actualDayClicked = window.event.target.textContent if (lastDayClicked == -1){ window.event.target.style.background = "#777"; } else if(document.getElementById(actualDayClicked).style.background != "rgb(77, 166, 255)"){ window.event.target.style.background = "#777"; } console.log(actualDayClicked); document.querySelector(".listOfEvents").innerHTML = events_plan[actualDayClicked]; lastDayClicked = window.event.target.textContent; }) document.getElementById("btn").addEventListener("click", () => { if (document.getElementById("time").value === "" || document.getElementById("name").value === "" || lastDayClicked === -1) { return; } if (lastDayClicked != new Date().getDate()){ document.getElementById(lastDayClicked).style.background = "#4da6ff" } console.log(events_plan[lastDayClicked]); events_plan[lastDayClicked] += document.getElementById("name").value + ": " + document.getElementById("time").value + "<br>"; document.querySelector(".listOfEvents").innerHTML = events_plan[lastDayClicked]; }) document.getElementById("mail").addEventListener("click", () => { if (lastDayClicked != -1 && lastDayClicked != new Date().getDate() && document.getElementById(lastDayClicked).style.background != "rgb(77, 166, 255)"){ document.getElementById(lastDayClicked).style.background = "#222227"; } if (lastDayClicked != -1 && document.getElementById(lastDayClicked).style.background != "rgb(77, 166, 255"){ document.getElementById(last) = "#777"; } console.log(actualDayClicked); document.querySelector(".listOfEvents").innerHTML = events_plan[actualDayClicked]; if (lastDayClicked != new Date().getDate()){ document.getElementById(actualDayClicked).style.background = "#4da6ff" } events_plan[actualDayClicked] += document.getElementById("name").value + ": " + document.getElementById("time").value + "<br>"; document.querySelector(".listOfEvents").innerHTML = events_plan[actualDayClicked]; document.getElementById("mail").style.visibility = "hidden"; }) fetch("http://localhost:5000/index.html", {method: 'POST', headers: {'content-type': 'application/json'}, body: JSON.stringify('{"grupa":"211/1"}')}).then( response => { return response.json(); } ).then( res => { console.log(res); document.getElementById("mail").style.visibility = "visible"; document.getElementById("name").value = res["platforma"] document.getElementById("time").value = res["ora"] actualDayClicked = res["zi"]; console.log(actualDayClicked) } ) var group; document.getElementById("btnGrupa").addEventListener("click", () => { group = document.getElementById("grupa").value; functie() }) const functie = () => { fetch("http://localhost:5000/site.html", {method: 'POST', headers: {'content-type': 'application/json'}, body: JSON.stringify( JSON.stringify({"grupa":group}) ) }).then( response => { return response.json(); } ).then( res => { console.log(res); for (curs in res) { if (curs["zi"] === "Luni"){ for (var i = 2; i <= 30; ++i) { events_plan[i] += curs["disc"] + " " + curs["ora"] + " " + curs["prof"] + "<br>" document.querySelector(".listOfEvents").innerHTML = events_plan[lastDayClicked]; } } } } ) } //res -> ce iese din python //console.log(window.event.target.textContent) //document.querySelector(".listOfEvents").innerHTML = events_name[window.event.target.textContent] + ":" + events_hours[window.event.target.textContent] //document.querySelector(".Events").style.visibility = "visible" //events_name[window.event.target.textContent][events_name.length] //events_hours[window.event.target.textContent][events_hours.length] renderCalendar();
8445ad2d5214b461b731dedb63bdbc92675e5755
[ "Markdown", "Python", "JavaScript" ]
6
Markdown
BenteaB/PlanBy
46dd6f0b4d20b36a1778a426e3c8e84d10d1fd6c
785a466e376fd6c9e817b057bfa7675f25ae61a5
refs/heads/master
<repo_name>norrise120/stacks-queues<file_sep>/lib/stack.rb class Stack STACK_SIZE = 20 def initialize @store = Array.new(QUEUE_SIZE) @front = @rear = -1 end def push(element) if @front == -1 @rear = 1 @front = 0 @store[@front] = element elsif @front == @rear raise ArgumentError, "Stack is full" else new_rear = (@rear + 1) % STACK_SIZE @store[@rear] = element @rear = new_rear end end def pop if @front == -1 raise ArgumentError, "Stack is empty" else popped = @store[@rear - 1] @store[@rear - 1] = nil @rear = (@rear - 1) % STACK_SIZE return popped end end def empty? stack = @store.compact if stack.length == 0 return true else return false end end def to_s return @store.compact.to_s end end <file_sep>/lib/queue.rb QUEUE_SIZE = 20 class Queue def initialize @store = Array.new(QUEUE_SIZE) @front = @rear = -1 end def enqueue(element) if @front == -1 #Q is empty @rear = 1 @front = 0 @store[@front] = element elsif @front == @rear raise ArgumentError, "Queue is full" else new_rear = (@rear + 1) % QUEUE_SIZE @store[@rear] = element @rear = new_rear end end def dequeue if @front == -1 raise ArgumentError, "Queue is empty" else dequeued = @store[@front] @store[@front] = nil @front = (@front + 1) % QUEUE_SIZE return dequeued end end def front return @store[@front] end def size return @store.compact.length end def empty? queue = @store.compact if queue.length == 0 return true else return false end end def to_s return @store.compact.to_s end end
fd35d5f2d8aa2f79658dad46c9f7c3002a5f769a
[ "Ruby" ]
2
Ruby
norrise120/stacks-queues
184a23145be67db824f08f24e3f9d42c3ac50836
a55b180be83dda2c925352c8a14e3bc95100329b
refs/heads/master
<file_sep>Rails.application.routes.draw do root 'page#home' get 'menu', to: 'page#menu' end
1e7b2173924573480d650091e9c21f9d7663f8b5
[ "Ruby" ]
1
Ruby
6la6T/Mon-site
1306733995e93cdb22056d546ccf406d2fb60713
53ba431d714875a46060d93fc40d964eac9ee3b0
refs/heads/master
<repo_name>dbsry267/Oclubis<file_sep>/Oclubis/src/com/oclubis/action/SignoutAction.java package com.oclubis.action; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.oclubis.service.UserService; import com.oclubis.vo.UserVO; public class SignoutAction implements IAction { @Override public void excute(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); session.invalidate(); RequestDispatcher rd = request.getRequestDispatcher("jsp/oclubis.jsp"); rd.forward(request, response); } } <file_sep>/Oclubis/src/com/oclubis/vo/CommentVO.java package com.oclubis.vo; public class CommentVO { private int postnum; private String content; private String writer; private String date; public CommentVO() { } public CommentVO(int postnum, String content, String writer) { super(); this.postnum = postnum; this.content = content; this.writer = writer; } public int getPostnum() { return postnum; } public void setPostnum(int postnum) { this.postnum = postnum; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } } <file_sep>/README.md # Oclubis Java 수행 동아리 협업 웹 <file_sep>/Oclubis/src/com/oclubis/action/UpdateuserAction.java package com.oclubis.action; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.oclubis.service.UserService; public class UpdateuserAction implements IAction { @Override public void excute(HttpServletRequest request, HttpServletResponse response) throws Exception { try { String act = request.getParameter("button"); String userid = request.getParameter("check"); UserService service = new UserService(); if ("delete".equals(act)) { service.deleteUser(userid); } if ("change".equals(act)) { int value = Integer.parseInt(request.getParameter("permissionvalue")); service.updatePermission(userid, value); } RequestDispatcher rd = request.getRequestDispatcher("user.do"); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); request.setAttribute("error", e.getMessage()); RequestDispatcher rd = request.getRequestDispatcher("jsp/error.jsp"); rd.forward(request, response); } } } <file_sep>/Oclubis/src/com/oclubis/action/LikeAction.java package com.oclubis.action; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.oclubis.service.PostService; import com.oclubis.vo.PostVO; import com.oclubis.vo.UserVO; public class LikeAction implements IAction { @Override public void excute(HttpServletRequest request, HttpServletResponse response) throws Exception { try { // TODO Auto-generated method stub String like = request.getParameter("like"); if (like.equals("dislike")) { int num = Integer.parseInt(request.getParameter("number")); PostService service = new PostService(); HttpSession session = request.getSession(); UserVO user = (UserVO) session.getAttribute("user"); service.deleteLike(num, user.getName()); response.sendRedirect("main.do"); } if (like.equals("like")) { int num = Integer.parseInt(request.getParameter("number")); PostService service = new PostService(); HttpSession session = request.getSession(); UserVO user = (UserVO) session.getAttribute("user"); service.addLike(num, user.getName()); response.sendRedirect("main.do"); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); request.setAttribute("error", e.getMessage()); RequestDispatcher rd = request.getRequestDispatcher("jsp/error.jsp"); rd.forward(request, response); } } } <file_sep>/Oclubis/src/com/oclubis/dao/ReactDao.java package com.oclubis.dao; public class ReactDao { } <file_sep>/Oclubis/src/com/oclubis/service/UserService.java package com.oclubis.service; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import com.oclubis.dao.UserDao; import com.oclubis.exception.IdOverlapException; import com.oclubis.vo.UserVO; public class UserService extends AbstractService { public UserVO signin(UserVO user) throws Exception { Connection conn = null; try { conn = getConnection(); UserDao dao = new UserDao(conn); UserVO vo = dao.searchUser(user); return vo; } finally { // TODO: handle finally clause if (conn != null) { conn.close(); } } } public void signup(UserVO user) throws Exception { Connection conn = null; try { conn = getConnection(); UserDao dao = new UserDao(conn); boolean check = dao.searchId(user.getId()); if (!check) { throw new IdOverlapException("중복되는 id가 존재합니다."); } dao.insertUser(user); } finally { if (conn != null) { conn.close(); } } } public List<UserVO> getUserList() throws Exception { Connection conn = null; try { conn = getConnection(); UserDao dao = new UserDao(conn); List<UserVO> list = dao.getUserList(); return list; } finally { if (conn != null) { conn.close(); } } } public void deleteUser(String userid) throws Exception { Connection conn = null; try { conn = getConnection(); UserDao dao = new UserDao(conn); dao.deleteUser(userid); } finally { // TODO: handle finally clause if (conn != null) { conn.close(); } } } public void updatePermission(String userid, int value) throws Exception { Connection conn = null; try { conn = getConnection(); UserDao dao = new UserDao(conn); dao.updateUserPermission(userid, value); } finally { // TODO: handle finally clause if (conn != null) { conn.close(); } } } } <file_sep>/Oclubis/src/com/oclubis/action/SigninAction.java package com.oclubis.action; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang3.StringUtils; import com.oclubis.service.UserService; import com.oclubis.vo.UserVO; public class SigninAction implements IAction{ @Override public void excute(HttpServletRequest request, HttpServletResponse response) throws Exception { try { String id = request.getParameter("id"); String pwd = request.getParameter("pwd"); validate(id, pwd); UserVO user = new UserVO(id, pwd); UserService service = new UserService(); UserVO result = service.signin(user); request.setAttribute("user", result); request.getSession().setAttribute("user", result); RequestDispatcher rd = null; if (result.getPermission() == 3) { // rd = request.getRequestDispatcher("jsp/admin.jsp"); response.sendRedirect("jsp/admin.jsp"); } else { // rd = request.getRequestDispatcher("main.do"); response.sendRedirect("main.do"); } // rd.forward(request, response); } catch (Exception e) { // TODO: handle exception request.setAttribute("error", e.getMessage()); RequestDispatcher rd = request.getRequestDispatcher("jsp/signin.jsp"); rd.forward(request, response); } } private void validate(String id, String pwd) throws Exception { if (StringUtils.isBlank(id)) throw new Exception("id에 공백이 포함되어있습니다."); if (StringUtils.isBlank(pwd)) throw new Exception("비밀번호에 공백이 포함되어 있습니다."); } } <file_sep>/Oclubis/src/com/oclubis/vo/ClubVO.java package com.oclubis.vo; public class ClubVO { private String name; private String president; private String intro; public ClubVO() {} public ClubVO(String name, String president) { this.name = name; this.president = president; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPresident() { return president; } public void setPresident(String president) { this.president = president; } public String getIntro() { return intro; } public void setIntro(String intro) { this.intro = intro; } } <file_sep>/Oclubis/src/com/oclubis/action/SignupAction.java package com.oclubis.action; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import com.oclubis.service.UserService; import com.oclubis.vo.UserVO; public class SignupAction implements IAction { @Override public void excute(HttpServletRequest request, HttpServletResponse response) throws Exception { try { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); // 1. 입력값 추출 String id = request.getParameter("id"); String pwd = request.getParameter("pwd"); String name = request.getParameter("name"); String club = request.getParameter("club"); System.out.printf("id : %s, pwd : %s, name : %s, club : %s", id, pwd, name, club); UserVO user = new UserVO(id, pwd, name, club); // 2. 입력값 검증 validate(user); UserService service = new UserService(); service.signup(user); // 회원가입 처리 RequestDispatcher rd = request.getRequestDispatcher("jsp/signin.jsp"); rd.forward(request, response); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); request.setAttribute("error", e.getMessage()); RequestDispatcher rd = request.getRequestDispatcher("jsp/signup.jsp"); rd.forward(request, response); } } private void validate(UserVO vo) throws Exception { if (StringUtils.isEmpty(vo.getId())) throw new Exception("아이디를 입력해주세요"); if (StringUtils.isEmpty(vo.getPwd())) throw new Exception("비밀번호를 입력해주세요"); if (StringUtils.isEmpty(vo.getName())) throw new Exception("이름을 입력해주세요"); if (StringUtils.isEmpty(vo.getClub())) throw new Exception("동아리를 선택해주세요"); } }
9be7877259f109d5d3ed4b7b67727e7d34a60221
[ "Markdown", "Java" ]
10
Java
dbsry267/Oclubis
67fbf8c1e98544ac99a18d1626d35f88d4addd39
f07a60430bbc8ea4d0a8d2ef1bb64cf91d268f48
refs/heads/master
<repo_name>STrix8/vimrc<file_sep>/gitPullVimrc.sh #!/bin/bash git pull cp .vimrc ~/.vimrc <file_sep>/gitPushVimrc.sh #!/bin/bash cp ~/.vimrc ./.vimrc git commit -a -m "$1" git push <file_sep>/README.md # vimrc vimrc これは.vimrc ほぼコピペでつらい
a535ad4e5c92e5b1dcdfdc1494716da7312765ab
[ "Markdown", "Shell" ]
3
Shell
STrix8/vimrc
3bd67b219ff4172de5a80f4b098ee003dee513fe
4b8928b3b6a248800a78672ca33357b0fb4ef055
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using HtmlAgilityPack; namespace cnblogs.ContentViews { public partial class itemSearch : PhoneApplicationPage { private string searchValueHttpUri; private int pageValue = 1; public itemSearch() { InitializeComponent(); } private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { if (NavigationContext.QueryString.Count > 0) { searchValueHttpUri = NavigationContext.QueryString["searchParam"]; getSearchResult(searchValueHttpUri, pageValue); } } private void getSearchResult(string searchValueHttpUri, int pageParam) { HtmlAgilityPack.HtmlWeb htmlDoc = new HtmlAgilityPack.HtmlWeb(); htmlDoc.LoadCompleted += new EventHandler<HtmlDocumentLoadCompleted>(htmlDocCompleteSearch); htmlDoc.LoadAsync("http://zzk.cnblogs.com/s?w=" + searchValueHttpUri + "&t=b&p=" + pageParam + ""); } private void htmlDocCompleteSearch(object sender, HtmlDocumentLoadCompleted e) { if (e.Error == null) { HtmlDocument htmlDoc = e.Document; if (htmlDoc != null) { List<SearchEntity> searchList = new List<SearchEntity>(); HtmlNode node = htmlDoc.GetElementbyId("searchResult"); HtmlNodeCollection noC = node.SelectNodes("//*[@class=\"searchItem\"]"); foreach (HtmlNode h in noC) { HtmlNode hn1 = HtmlNode.CreateNode(h.OuterHtml); SearchEntity search = new SearchEntity(); foreach (HtmlNode child in hn1.ChildNodes) { if (child.Attributes["class"] != null && child.Attributes["class"].Value == "searchItemTitle") { HtmlNode hsn = HtmlNode.CreateNode(child.OuterHtml); string searchTitleValue = hsn.SelectSingleNode("//*[@class=\"searchItemTitle\"]").InnerText.Trim(); search.searchTitle = searchTitleValue; //MessageBox.Show("searchTitle--------------" + searchTitleValue); } else if (child.Attributes["class"] != null && child.Attributes["class"].Value == "searchCon") { HtmlNode hsn = HtmlNode.CreateNode(child.OuterHtml); string searchConValue = hsn.SelectSingleNode("//*[@class=\"searchCon\"]").InnerText.Trim(); search.searchCon = searchConValue; //MessageBox.Show("searchCon--------------" + searchConValue); } else if (child.Attributes["class"] != null && child.Attributes["class"].Value == "searchItemInfo") { HtmlNode hsn = HtmlNode.CreateNode(child.OuterHtml); foreach (HtmlNode searchItemInfoChild in hsn.ChildNodes) { if (searchItemInfoChild.Attributes["class"] != null && searchItemInfoChild.Attributes["class"].Value == "searchItemInfo") { string userName = searchItemInfoChild.SelectSingleNode("//*[@class=\"searchItemInfo-userName\"]").InnerText.Trim(); string publishDate = searchItemInfoChild.SelectSingleNode("//*[@class=\"searchItemInfo-publishDate\"]").InnerText.Trim(); string good = searchItemInfoChild.SelectSingleNode("//*[@class=\"searchItemInfo-good\"]").InnerText.Trim(); string comments = searchItemInfoChild.SelectSingleNode("//*[@class=\"searchItemInfo-comments\"]").InnerText.Trim(); string views = searchItemInfoChild.SelectSingleNode("//*[@class=\"searchItemInfo-views\"]").InnerText.Trim(); string searchInfoValue = userName + publishDate + good + comments + views; search.searchInfo = searchInfoValue; //MessageBox.Show("searchInfo--------------" + userName+publishDate+good+comments+views); } if (searchItemInfoChild.Attributes["class"] != null && searchItemInfoChild.Attributes["class"].Value == "searchURL") { string searchURLValue = searchItemInfoChild.SelectSingleNode("//*[@class=\"searchURL\"]").InnerText.Trim(); search.searchURL = searchURLValue; //MessageBox.Show("searchInfo--------------" + searchURLValue); } } //string searchInfo = child.SelectSingleNode("//*[@class=\"searchItemInfo\"]").InnerText; //MessageBox.Show("searchInfo--------------" + searchInfo); } } searchList.Add(search); } this.listBox1.ItemsSource = searchList; } } } private void ApplicationBarIconButton_Click(object sender, EventArgs e) { //MessageBox.Show("button1"); pageValue--; if (pageValue < 1) { pageValue = 1; } getSearchResult(searchValueHttpUri, pageValue); } private void ApplicationBarIconButton_Click_1(object sender, EventArgs e) { pageValue++; if (pageValue >= 100) { pageValue = 100; } getSearchResult(searchValueHttpUri, pageValue); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using WP7_WebLib.HttpPost; using System.IO; namespace cnblogs.Views { public partial class login : PhoneApplicationPage { public login() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { /**Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("__EVENTARGUMENT", ""); parameters.Add("__EVENTTARGET", ""); parameters.Add("__EVENTVALIDATION", "/w<KEY>"); parameters.Add("__VIEWSTATE", "/wEPDwULLTE1MzYzODg2NzZkGAEFHl9fQ29udHJvbHNSZX<KEY>"); parameters.Add("btnLogin", "登 录"); //parameters.Add("chkRemember", "on"); parameters.Add("tbPassword", "<PASSWORD>.."); parameters.Add("tbUserName", "shandowsoftware"); parameters.Add("txtReturnUrl", "http://home.cnblogs.com/");*/ //getResponseHtml(parameters); /**CookieContainer myCookie = new CookieContainer(); HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://passport.cnblogs.com/login.aspx"); myRequest.Method = "POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; myRequest.CookieContainer = myCookie; myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);*/ string username=this.username.Text; string password = this.password.Password; NavigationService.Navigate(new Uri("/Views/flashMemory.xaml?username="+username+"&password="+password+"", UriKind.Relative)); } private void GetRequestStreamCallback(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; System.IO.Stream postStream = request.EndGetRequestStream(asynchronousResult); // Prepare Parameters String string parametersString = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTE1MzYzODg2NzZkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBQtjaGtSZW1lbWJlcm1QYDyKKI9af4b67Mzq2xFaL9Bt&__EVENTVALIDATION=%2FwEdAAUyDI6H%2Fs9f%2BZALqNAA4PyUhI6Xi65hwcQ8%2FQoQCF8JIahXufbhIqPmwKf992GTkd0wq1PKp6%2B%2F1yNGng6H71Uxop4oRunf14dz2Zt2%2BQKDEIYpifFQj3yQiLk3eeHVQqcjiaAP&tbUserName=shandowsoftware&tbPassword=<PASSWORD>..&chkRemember=on&btnLogin=%E7%99%BB++%E5%BD%95&txtReturnUrl=http://home.cnblogs.com/"; //foreach (KeyValuePair<string, string> parameter in parameters) //{ // parametersString = parametersString + (parametersString != "" ? "&" : "") + string.Format("{0}={1}", parameter.Key, parameter.Value); //} byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(parametersString); // Write to the request stream. postStream.Write(byteArray, 0, parametersString.Length); postStream.Close(); // Start the asynchronous operation to get the response request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request); } private void GetResponseCallback(IAsyncResult asynchronousResult) { Stream streamResponse = null; string responseString = null; try { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); streamResponse = response.GetResponseStream(); CookieCollection cookieColl = response.Cookies; using (StreamReader streamRead = new StreamReader(streamResponse)) { responseString = streamRead.ReadToEnd(); } } catch { } finally { if(streamResponse!=null) { streamResponse.Close(); } } if(responseString!=null) { Dispatcher.BeginInvoke(() => { string result=responseString.Substring(400,1400); textBlockResult.Text =result; }); } /**StreamReader streamRead = new StreamReader(streamResponse); string responseString = streamRead.ReadToEnd(); Dispatcher.BeginInvoke(() => { textBlockResult.Text = responseString; }); // Close the stream object streamResponse.Close(); streamRead.Close();*/ } /** private void GetResponseCallback(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); Stream streamResponse = response.GetResponseStream(); CookieCollection cookieColl = response.Cookies; StreamReader streamRead = new StreamReader(streamResponse); string responseString = streamRead.ReadToEnd(); Dispatcher.BeginInvoke(() => { textBlockResult.Text = responseString; }); // Close the stream object streamResponse.Close(); streamRead.Close(); }*/ /**public void getResponseHtml(Dictionary<string, object> parameters) { PostClient proxy = new PostClient(parameters); proxy.DownloadStringCompleted += (sender, e) => { if (e.Error == null) { //Process the result... string data = e.Result; MessageBox.Show(data); } }; proxy.DownloadStringAsync(new Uri("http://passport.cnblogs.com/login.aspx", UriKind.Absolute)); } */ } }<file_sep>using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace PhoneApp1 { public class Question { public string questionTitle { get; set; } public string questionLink { get; set; } public string questionIntroduce { get; set; } public string questionInfo { get; set; } public string questionUserImage { get; set; } public string questionGoldImage { get; set; } public string questionGoldCount { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using HtmlAgilityPack; using System.IO; using System.Text; namespace cnblogs.ContentViews { public partial class QuestionContent : PhoneApplicationPage { public QuestionContent() { InitializeComponent(); } private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { if (NavigationContext.QueryString.Count > 0) { string titleHttpUri = NavigationContext.QueryString["titleLinkValue"]; string questionUrl = "http://q.cnblogs.com"+titleHttpUri; //MessageBox.Show(questionUrl); HtmlAgilityPack.HtmlWeb htmlDoc = new HtmlAgilityPack.HtmlWeb(); htmlDoc.LoadCompleted += new EventHandler<HtmlDocumentLoadCompleted>(htmlDocComplete); htmlDoc.LoadAsync(questionUrl); } } private void htmlDocComplete(object sender, HtmlDocumentLoadCompleted e) { if (e.Error == null) { HtmlDocument htmlDoc = e.Document; if (htmlDoc != null) { HtmlNode node = htmlDoc.GetElementbyId("main"); //HtmlNode answerNode= htmlDoc.GetElementbyId("panelAnswerList"); //MessageBox.Show(node.InnerHtml); string str = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' />" + "<title></title></head><body>" + node.InnerHtml + "<p></p>"+"</body></html>"; string result = ConvertEncode(str); myWebBrowser.NavigateToString(result); } } } /// <summary> /// 将字符串编码格式转换为unicode /// </summary> /// <param name="strSource"></param> /// <returns></returns> private string ConvertEncode(string strSource) { MemoryStream mstream = new MemoryStream(Encoding.UTF8.GetBytes(strSource)); StreamReader reader = new StreamReader(mstream, Encoding.Unicode); string strResult = reader.ReadToEnd(); reader.Close(); mstream.Dispose(); reader.Dispose(); return strResult; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using PhoneApp1; using HtmlAgilityPack; using System.Xml.XPath; namespace cnblogs { public partial class MainPage : PhoneApplicationPage { // 构造函数 public MainPage() { InitializeComponent(); // 将 listbox 控件的数据上下文设置为示例数据 DataContext = App.ViewModel; this.Loaded += new RoutedEventHandler(MainPage_Loaded); } // 为 ViewModel 项加载数据 private void MainPage_Loaded(object sender, RoutedEventArgs e) { if (!App.ViewModel.IsDataLoaded) { App.ViewModel.LoadData(); } } private void PanoramaItem_Loaded(object sender, RoutedEventArgs e) { HtmlAgilityPack.HtmlWeb htmlDoc = new HtmlAgilityPack.HtmlWeb(); htmlDoc.LoadCompleted += new EventHandler<HtmlDocumentLoadCompleted>(htmlDocComplete); htmlDoc.LoadAsync("http://www.cnblogs.com/"); } private void htmlDocComplete(object sender, HtmlDocumentLoadCompleted e) { if (e.Error == null) { HtmlDocument htmlDoc = e.Document; if (htmlDoc != null) { HtmlNode node = htmlDoc.GetElementbyId("headline_block"); //IEnumerable<HtmlNode> nodeList =htmlDoc.DocumentNode.Descendants("a"); HtmlNode hn = HtmlNode.CreateNode(node.OuterHtml); IEnumerable<HtmlNode> nodeList = hn.Descendants("a"); List<Recom> listContent = new List<Recom>(); int index = 0; foreach (HtmlNode item in nodeList) { index++; string title = item.InnerText; if (title == null || title.Length < 2) continue; //MessageBox.Show("test-----------" + index); string recomTitle = title; //MessageBox.Show("out--------" + title); string titlelnk = item.GetAttributeValue("href", ""); //MessageBox.Show("titlelnk--------" + titlelnk); string viewsTitleLnk=""; Recom recom = new Recom(); if(index==1){ viewsTitleLnk= titlelnk + "&&" + "/ContentViews/"; }else if(index==3||index==5){ viewsTitleLnk= titlelnk + "&&" + "/ContentViews/indexContent.xaml"; recom.viweImages = "/images/cream.png"; }else if(index==6||index==8){ viewsTitleLnk = titlelnk + "&&" + "/ContentViews/nowNewsContent.xaml"; recom.viweImages = "/images/news.png"; } recom.recomTitle = recomTitle; recom.titleLink = viewsTitleLnk; listContent.Add(recom); } this.listBox1.ItemsSource = listContent; } } } private void TextBlock_Tap(object sender, System.Windows.Input.GestureEventArgs e) { TextBlock textBlock = (TextBlock)e.OriginalSource; string tagLink = (string)textBlock.Tag; int index=tagLink.IndexOf("&&"); string titleLink = tagLink.Substring(0,tagLink.IndexOf("&&")); string viewsLink = tagLink.Substring(tagLink.IndexOf("&&")+2); //MessageBox.Show("viewsLink--------" + viewsLink); //MessageBox.Show("this is -----------" + titleLink); NavigationService.Navigate(new Uri("" + viewsLink + "?titleLinkValue=" + titleLink + "", UriKind.Relative)); } /// <summary> /// 首页 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnPost1_Tap(object sender, System.Windows.Input.GestureEventArgs e) { NavigationService.Navigate(new Uri("/Views/index.xaml", UriKind.Relative)); } /// <summary> /// 候选 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnPost2_Tap(object sender, System.Windows.Input.GestureEventArgs e) { NavigationService.Navigate(new Uri("/Views/wait.xaml", UriKind.Relative)); } /// <summary> /// 推荐 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnPost5_Tap(object sender, System.Windows.Input.GestureEventArgs e) { NavigationService.Navigate(new Uri("/Views/login.xaml", UriKind.Relative)); } /// <summary> /// 精华 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnPost4_Tap(object sender, System.Windows.Input.GestureEventArgs e) { NavigationService.Navigate(new Uri("/Views/cream.xaml", UriKind.Relative)); } /// <summary> /// 新闻 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnPost3_Tap(object sender, System.Windows.Input.GestureEventArgs e) { NavigationService.Navigate(new Uri("/Views/nowNews.xaml", UriKind.Relative)); } /// <summary> /// 关于 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnPost6_Tap(object sender, System.Windows.Input.GestureEventArgs e) { NavigationService.Navigate(new Uri("/Views/about.xaml", UriKind.Relative)); } /// <summary> /// 加载问答列表 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PanoramaItem_Loaded_1(object sender, RoutedEventArgs e) { HtmlAgilityPack.HtmlWeb htmlDoc = new HtmlAgilityPack.HtmlWeb(); htmlDoc.LoadCompleted += new EventHandler<HtmlDocumentLoadCompleted>(htmlDocCompleteQuestion); htmlDoc.LoadAsync("http://q.cnblogs.com/"); } private void htmlDocCompleteQuestion(object sender, HtmlDocumentLoadCompleted e) { if (e.Error == null) { HtmlDocument htmlDoc = e.Document; if (htmlDoc != null) { List<Question> listContent = new List<Question>(); HtmlNode node = htmlDoc.GetElementbyId("main"); HtmlNode hn = HtmlNode.CreateNode(node.OuterHtml); HtmlNodeCollection noC = hn.SelectNodes("//*[@class=\"one_entity\"]"); foreach (HtmlNode h in noC) { HtmlNode hn1 = HtmlNode.CreateNode(h.OuterHtml); //MessageBox.Show("hn1------"+hn1.InnerHtml); foreach (HtmlNode child in hn1.ChildNodes) { Question question = new Question(); /**if (child.Attributes["class"] == null || child.Attributes["class"].Value != "answercount") continue; HtmlNode hsn = HtmlNode.CreateNode(child.OuterHtml); string answerCount = hsn.InnerText.Trim(); MessageBox.Show(answerCount.Substring(0,answerCount.IndexOf("回答数")).Trim());*/ if (child.Attributes["class"] != null && child.Attributes["class"].Value == "answercount") { HtmlNode hsn = HtmlNode.CreateNode(child.OuterHtml); string answerCount = hsn.InnerText.Trim(); //MessageBox.Show(answerCount.Substring(0, answerCount.IndexOf("回答数")).Trim());//回答人数 } else if (child.Attributes["class"] != null && child.Attributes["class"].Value == "news_item") { HtmlNode hsn = HtmlNode.CreateNode(child.OuterHtml); HtmlNode gold = hsn.SelectSingleNode("//*[@class=\"gold\"]"); string goldCount = ""; if (gold != null) { goldCount = gold.InnerText.Trim(); //MessageBox.Show("gold----------" + gold.InnerText.Trim()); //悬赏金币 } else { goldCount = "0"; //MessageBox.Show("gold----------0"); //悬赏金币 空则为0 } IEnumerable<HtmlNode> nodeList = hsn.SelectSingleNode("//*[@class=\"news_entry\"]").Descendants("a"); string title = ""; string titlelink = ""; foreach (HtmlNode item in nodeList) { title = item.InnerHtml.Trim(); titlelink = item.GetAttributeValue("href", ""); //MessageBox.Show("out--------" + item.InnerHtml.Trim()); //问题标题 } HtmlNode questionIntroduce = hsn.SelectSingleNode("//*[@class=\"news_summary\"]"); HtmlNode questionAuthor = hsn.SelectSingleNode("//*[@class=\"news_contributor\"]"); HtmlNode questionPushDate = hsn.SelectSingleNode("//*[@class=\"date\"]"); IEnumerable<HtmlNode> imgAuthorList = hsn.SelectSingleNode("//*[@class=\"author\"]").Descendants("img"); foreach (HtmlNode imgAuthor in imgAuthorList) { string userImage = imgAuthor.GetAttributeValue("src", ""); if (userImage.IndexOf(".gif") > -1) { question.questionUserImage = "/images/UserNo-Frame.png"; } else { question.questionUserImage = userImage; } //MessageBox.Show("out--------" + item.InnerHtml.Trim()); //问题标题 } string introduce = questionIntroduce.InnerText.Trim(); string author = questionAuthor.InnerText.Trim(); string date = questionPushDate.InnerText.Trim(); question.questionTitle = title; question.questionLink = titlelink; question.questionIntroduce = introduce; question.questionInfo = author + " " + date; question.questionGoldImage = "/images/gold.png"; question.questionGoldCount = goldCount; listContent.Add(question); //MessageBox.Show("questionIntroduce------------" + questionIntroduce.InnerText.Trim()); //问题简介 //MessageBox.Show("news_footer----------" + questionAuthor.InnerText.Trim()); //提问者 //MessageBox.Show("date----------" + questionPushDate.InnerText.Trim()); //发布时间 //string answerCount = hsn.InnerText.Trim(); } else { continue; } } //HtmlNode newnode = hn.SelectSingleNode("/div/div/div[3]"); /**IEnumerable<HtmlNode> nodeList = node.Ancestors(); //获取该元素所有的父节点的集合 foreach (HtmlNode item in nodeList) { Console.Write(item.Name + " "); //输出 div div body html #document }*/ } this.listBox2.ItemsSource = listContent; } } } private void TextBlock_Tap_1(object sender, System.Windows.Input.GestureEventArgs e) { TextBlock textBlock = (TextBlock)e.OriginalSource; string tagLink = (string)textBlock.Tag; NavigationService.Navigate(new Uri("/ContentViews/QuestionContent.xaml?titleLinkValue=" + tagLink + "", UriKind.Relative)); } private void btnSearch_Tap(object sender, System.Windows.Input.GestureEventArgs e) { string searchValue = this.searchValue.Text; if (searchValue == null || searchValue.Equals("")) { MessageBox.Show("写点什么吧!"); } else { NavigationService.Navigate(new Uri("/ContentViews/itemSearch.xaml?searchParam=" + searchValue + "", UriKind.Relative)); //NavigationService.Navigate(new Uri("/ContentViews/itemSearch.xaml", UriKind.Relative)); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using HtmlAgilityPack; namespace PhoneApp1.Views { public partial class question : PhoneApplicationPage { public question() { InitializeComponent(); } private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { HtmlAgilityPack.HtmlWeb htmlDoc = new HtmlAgilityPack.HtmlWeb(); htmlDoc.LoadCompleted += new EventHandler<HtmlDocumentLoadCompleted>(htmlDocComplete); htmlDoc.LoadAsync("http://q.cnblogs.com/"); } private void htmlDocComplete(object sender, HtmlDocumentLoadCompleted e) { if (e.Error == null) { HtmlDocument htmlDoc = e.Document; if (htmlDoc != null) { List<Question> listContent = new List<Question>(); HtmlNode node = htmlDoc.GetElementbyId("main"); HtmlNode hn = HtmlNode.CreateNode(node.OuterHtml); HtmlNodeCollection noC = hn.SelectNodes("//*[@class=\"one_entity\"]"); foreach (HtmlNode h in noC) { HtmlNode hn1 = HtmlNode.CreateNode(h.OuterHtml); //MessageBox.Show("hn1------"+hn1.InnerHtml); foreach (HtmlNode child in hn1.ChildNodes) { Question question = new Question(); /**if (child.Attributes["class"] == null || child.Attributes["class"].Value != "answercount") continue; HtmlNode hsn = HtmlNode.CreateNode(child.OuterHtml); string answerCount = hsn.InnerText.Trim(); MessageBox.Show(answerCount.Substring(0,answerCount.IndexOf("回答数")).Trim());*/ if (child.Attributes["class"] != null && child.Attributes["class"].Value == "answercount") { HtmlNode hsn = HtmlNode.CreateNode(child.OuterHtml); string answerCount = hsn.InnerText.Trim(); //MessageBox.Show(answerCount.Substring(0, answerCount.IndexOf("回答数")).Trim());//回答人数 } else if (child.Attributes["class"] != null && child.Attributes["class"].Value == "news_item") { HtmlNode hsn = HtmlNode.CreateNode(child.OuterHtml); HtmlNode gold = hsn.SelectSingleNode("//*[@class=\"gold\"]"); string goldCount = ""; if (gold != null) { goldCount = gold.InnerText.Trim(); //MessageBox.Show("gold----------" + gold.InnerText.Trim()); //悬赏金币 } else { goldCount = "0"; //MessageBox.Show("gold----------0"); //悬赏金币 空则为0 } IEnumerable<HtmlNode> nodeList = hsn.SelectSingleNode("//*[@class=\"news_entry\"]").Descendants("a"); string title = ""; foreach (HtmlNode item in nodeList) { title = item.InnerHtml.Trim(); //MessageBox.Show("out--------" + item.InnerHtml.Trim()); //问题标题 } HtmlNode questionIntroduce = hsn.SelectSingleNode("//*[@class=\"news_summary\"]"); HtmlNode questionAuthor = hsn.SelectSingleNode("//*[@class=\"news_contributor\"]"); HtmlNode questionPushDate = hsn.SelectSingleNode("//*[@class=\"date\"]"); IEnumerable<HtmlNode> imgAuthorList = hsn.SelectSingleNode("//*[@class=\"author\"]").Descendants("img"); foreach (HtmlNode imgAuthor in imgAuthorList) { string userImage = imgAuthor.GetAttributeValue("src", ""); if (userImage.IndexOf(".gif") > 0) { question.questionUserImage = "/images/skydrive.png"; } else { question.questionUserImage = userImage; } //MessageBox.Show("out--------" + item.InnerHtml.Trim()); //问题标题 } string introduce = questionIntroduce.InnerText.Trim(); string author = questionAuthor.InnerText.Trim(); string date = questionPushDate.InnerText.Trim(); question.questionTitle = title; question.questionIntroduce = introduce; question.questionInfo = author + " " + date; question.questionGoldImage = "/images/gold.png"; question.questionGoldCount = goldCount; listContent.Add(question); //MessageBox.Show("questionIntroduce------------" + questionIntroduce.InnerText.Trim()); //问题简介 //MessageBox.Show("news_footer----------" + questionAuthor.InnerText.Trim()); //提问者 //MessageBox.Show("date----------" + questionPushDate.InnerText.Trim()); //发布时间 //string answerCount = hsn.InnerText.Trim(); } else { continue; } } //HtmlNode newnode = hn.SelectSingleNode("/div/div/div[3]"); /**IEnumerable<HtmlNode> nodeList = node.Ancestors(); //获取该元素所有的父节点的集合 foreach (HtmlNode item in nodeList) { Console.Write(item.Name + " "); //输出 div div body html #document }*/ } this.listBox1.ItemsSource = listContent; } } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using HtmlAgilityPack; using cnblogs; namespace PhoneApp1.Views { public partial class index : PhoneApplicationPage { public index() { InitializeComponent(); } private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { HtmlAgilityPack.HtmlWeb htmlDoc = new HtmlAgilityPack.HtmlWeb(); htmlDoc.LoadCompleted += new EventHandler<HtmlDocumentLoadCompleted>(htmlDocComplete); htmlDoc.LoadAsync("http://www.cnblogs.com/"); } private void htmlDocComplete(object sender, HtmlDocumentLoadCompleted e) { if (e.Error == null) { HtmlDocument htmlDoc = e.Document; if (htmlDoc != null) { HtmlNode node = htmlDoc.GetElementbyId("post_list"); List<BlogIndexContent> listContent = new List<BlogIndexContent>(); foreach (HtmlNode child in node.ChildNodes) { if (child.Attributes["class"] == null || child.Attributes["class"].Value != "post_item") continue; HtmlNode hn = HtmlNode.CreateNode(child.OuterHtml); BlogIndexContent listContextObj = new BlogIndexContent(); string tuijian = hn.SelectSingleNode("//*[@class=\"diggnum\"]").InnerText; string title = hn.SelectSingleNode("//*[@class=\"titlelnk\"]").InnerText; string jieshao = hn.SelectSingleNode("//*[@class=\"post_item_summary\"]").InnerText; string xinxi = hn.SelectSingleNode("//*[@class=\"post_item_foot\"]").InnerText; string xinxi2 = hn.SelectSingleNode("//*[@class=\"lightblue\"]").InnerText.Trim(); string xinxi3 = hn.SelectSingleNode("//*[@class=\"article_comment\"]").InnerText.Trim(); string xinxi4 = hn.SelectSingleNode("//*[@class=\"article_view\"]").InnerText.Trim(); string titleIDValue = hn.SelectSingleNode("//*[@class=\"diggnum\"]").InnerText; string titlelnk = hn.SelectSingleNode("//*[@class=\"titlelnk\"]").GetAttributeValue("href", ""); IEnumerable<HtmlNode> userImageNode = hn.SelectSingleNode("//*[@class=\"post_item_summary\"]").Descendants("img"); foreach (HtmlNode imgAuthor in userImageNode) { string userImage = imgAuthor.GetAttributeValue("src", ""); //MessageBox.Show("userimage----------"+userImage); if (userImage != null && userImage.IndexOf(".png") > -1 || userImage.IndexOf(".jpg") > -1) { listContextObj.userImage = userImage; } else { listContextObj.userImage = "/images/skydrive.png"; } //MessageBox.Show("out--------" + item.InnerHtml.Trim()); //问题标题 } //string userImage = hn.SelectSingleNode("//*[@class=\"pfs\"]").GetAttributeValue("src", ""); listContextObj.Title = title; listContextObj.Introduce = jieshao; listContextObj.Info = xinxi2 + xinxi3 + xinxi4; listContextObj.titleLink = titlelnk; listContextObj.recommendCount = tuijian; //listContextObj.userImage = userImage; listContextObj.recommendImage = "/images/cream.png"; listContent.Add(listContextObj); } this.listBox1.ItemsSource = listContent; } } } private void TextBlock_Tap_1(object sender, System.Windows.Input.GestureEventArgs e) { TextBlock textBlock = (TextBlock)e.OriginalSource; string tagLink = (string)textBlock.Tag; //MessageBox.Show(tagLink); NavigationService.Navigate(new Uri("/ContentViews/indexContent.xaml?titleLinkValue=" + tagLink + "", UriKind.Relative)); } } }<file_sep>using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace cnblogs { public class FlashMemory { public string userImage { get; set; } public string userAuthor { get; set; } public string userContent { get; set; } public string userReleaseDate { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using HtmlAgilityPack; namespace PhoneApp1.Views { public partial class recommend : PhoneApplicationPage { public recommend() { InitializeComponent(); } private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { HtmlAgilityPack.HtmlWeb htmlDoc = new HtmlAgilityPack.HtmlWeb(); htmlDoc.LoadCompleted += new EventHandler<HtmlDocumentLoadCompleted>(htmlDocComplete); htmlDoc.LoadAsync("http://www.cnblogs.com/"); } private void htmlDocComplete(object sender, HtmlDocumentLoadCompleted e) { if (e.Error == null) { HtmlDocument htmlDoc = e.Document; if (htmlDoc != null) { HtmlNode node = htmlDoc.GetElementbyId("headline_block"); //IEnumerable<HtmlNode> nodeList =htmlDoc.DocumentNode.Descendants("a"); HtmlNode hn = HtmlNode.CreateNode(node.OuterHtml); IEnumerable<HtmlNode> nodeList=hn.Descendants("a"); List<Recom> listContent = new List<Recom>(); foreach (HtmlNode item in nodeList) { //MessageBox.Show("out--------"+item.InnerHtml); //MessageBox.Show("out--------" + item.InnerText); string title = item.InnerText; if(title==null||title.Length<2) continue; string recomTitle = title; //MessageBox.Show("out--------" + title); string titlelnk = item.GetAttributeValue("href", ""); //MessageBox.Show("titlelnk--------" + titlelnk); Recom recom = new Recom(); recom.recomTitle = recomTitle; recom.titleLink = titlelnk; listContent.Add(recom); } this.listBox1.ItemsSource = listContent; } } } private void TextBlock_Tap(object sender, System.Windows.Input.GestureEventArgs e) { TextBlock textBlock = (TextBlock)e.OriginalSource; string tagLink = (string)textBlock.Tag; //MessageBox.Show("this is -----------" + tagLink); NavigationService.Navigate(new Uri("/Views/Pasta.xaml?titleLinkValue=" + tagLink + "", UriKind.Relative)); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using System.IO; using HtmlAgilityPack; namespace cnblogs.Views { public partial class flashMemory : PhoneApplicationPage { public flashMemory() { InitializeComponent(); } public CookieContainer cookieContainer = new CookieContainer(); public HttpWebRequest myRequest; private string username; private string password; private string flashMemoryValue; private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { //myRequest = (HttpWebRequest)WebRequest.Create("http://passport.cnblogs.com/login.aspx"); if (NavigationContext.QueryString.Count > 0) { username = NavigationContext.QueryString["username"]; password = NavigationContext.QueryString["password"]; } myRequest = (HttpWebRequest)WebRequest.Create("http://m.cnblogs.com/mobileLoginPost.aspx"); myRequest.Method = "POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; if (cookieContainer==null) { myRequest.CookieContainer = new CookieContainer(); } myRequest.CookieContainer = cookieContainer; myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest); getFlashMemoryList(); } private void GetRequestStreamCallback(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; System.IO.Stream postStream = request.EndGetRequestStream(asynchronousResult); // Prepare Parameters String //string parametersString = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTE1MzYzODg2NzZkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBQtjaGtSZW1lbWJlcm1QYDyKKI9af4b67Mzq2xFaL9Bt&__EVENTVALIDATION=%2FwEdAAUyDI6H%2Fs9f%2BZALqNAA4PyUhI6Xi65hwcQ8%2FQoQCF8JIahXufbhIqPmwKf992GTkd0wq1PKp6%2B%2F1yNGng6H71Uxop4oRunf14dz2Zt2%2BQKDEIYpifFQj3yQiLk3eeHVQqcjiaAP&tbUserName=shandowsoftware&tbPassword=<PASSWORD>..&chkRemember=on&btnLogin=%E7%99%BB++%E5%BD%95&txtReturnUrl=http://home.cnblogs.com/"; string parametersString = "tbUserName="+username+"&tbPassword="+password+"&chkRemember=on&txtReturnUrl="; byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(parametersString); // Write to the request stream. postStream.Write(byteArray, 0, parametersString.Length); postStream.Close(); // Start the asynchronous operation to get the response request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request); } private void GetResponseCallback(IAsyncResult asynchronousResult) { Stream streamResponse = null; string responseString = null; try { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); streamResponse = response.GetResponseStream(); CookieCollection cookieCollection = response.Cookies; cookieContainer.Add(new Uri("http://space.cnblogs.com/mobile/ming_post.aspx"), cookieCollection); //cookieContainer.Add(new Uri("http://home.cnblogs.com/ajax/ing/Publish"), cookieCollection); using (StreamReader streamRead = new StreamReader(streamResponse)) { responseString = streamRead.ReadToEnd(); } } catch { } finally { if (streamResponse != null) { streamResponse.Close(); } } if (responseString != null) { Dispatcher.BeginInvoke(() => { string result = responseString; //textBlockResult.Text = result; }); } } //得到get响应html private void getFlashMemoryList() { HtmlAgilityPack.HtmlWeb htmlDoc = new HtmlAgilityPack.HtmlWeb(); htmlDoc.LoadCompleted += new EventHandler<HtmlDocumentLoadCompleted>(htmlDocComplete); htmlDoc.LoadAsync("http://home.cnblogs.com/ing/mobile/home"); } private void htmlDocComplete(object sender, HtmlDocumentLoadCompleted e){ if(e.Error==null){ HtmlDocument htmlDoc = e.Document; if(htmlDoc!=null){ List<FlashMemory> flashMemoryList = new List<FlashMemory>(); HtmlNode node = htmlDoc.GetElementbyId("feed_list"); //MessageBox.Show("node--------------"+node.InnerHtml); HtmlNode hn = HtmlNode.CreateNode(node.OuterHtml); IEnumerable<HtmlNode> nodeList = hn.Descendants("li"); foreach(HtmlNode item in nodeList){ //MessageBox.Show(item.InnerHtml); HtmlNode hnChild = HtmlNode.CreateNode(item.OuterHtml); if (item.Attributes["class"] != null && item.Attributes["class"].Value == "entry_b") { FlashMemory flashMemoryb = new FlashMemory(); IEnumerable<HtmlNode> userImageNodeList = hnChild.SelectSingleNode("//*[@class=\"feed_avatar\"]").Descendants("img"); string userImageLink = ""; foreach (HtmlNode authorImage in userImageNodeList) { string userImageb = authorImage.GetAttributeValue("src", ""); //MessageBox.Show("userImage-------"+userImageb); if (userImageb.IndexOf(".gif") > 0) { userImageLink = "/images/skydrive.png"; } else { userImageLink = userImageb; } } string authorb = hnChild.SelectSingleNode("//*[@class=\"ing-author\"]").InnerText.Trim(); string authorContentb = hnChild.SelectSingleNode("//*[@class=\"ing_body\"]").InnerText.Trim(); string authorReleaseDateb = hnChild.SelectSingleNode("//*[@class=\"ing_time gray\"]").InnerText.Trim(); /**MessageBox.Show("authorb----------" + authorb); MessageBox.Show("authorContentb----------" + authorContentb); MessageBox.Show("authorReleaseDateb----------" + authorReleaseDateb);*/ flashMemoryb.userImage=userImageLink; flashMemoryb.userAuthor = authorb; flashMemoryb.userContent = authorContentb; flashMemoryb.userReleaseDate = authorReleaseDateb; flashMemoryList.Add(flashMemoryb); } if (item.Attributes["class"] != null && item.Attributes["class"].Value == "entry_a") { FlashMemory flashMemorya = new FlashMemory(); IEnumerable<HtmlNode> userImageNodeList = hnChild.SelectSingleNode("//*[@class=\"feed_avatar\"]").Descendants("img"); string userImageLink = ""; foreach (HtmlNode authorImage in userImageNodeList) { string userImagea = authorImage.GetAttributeValue("src", ""); //MessageBox.Show("userImagea--------"+userImagea); if (userImagea.IndexOf(".gif") > 0) { userImageLink = "/images/skydrive.png"; } else { userImageLink = userImagea; } } string authora = hnChild.SelectSingleNode("//*[@class=\"ing-author\"]").InnerText.Trim(); string authorContenta = hnChild.SelectSingleNode("//*[@class=\"ing_body\"]").InnerText.Trim(); string authorReleaseDatea = hnChild.SelectSingleNode("//*[@class=\"ing_time gray\"]").InnerText.Trim(); /**MessageBox.Show("authora----------" + authora); MessageBox.Show("authorContenta----------" + authorContenta); MessageBox.Show("authorReleaseDatea----------" + authorReleaseDatea);*/ flashMemorya.userImage = userImageLink; flashMemorya.userAuthor = authora; flashMemorya.userContent = authorContenta; flashMemorya.userReleaseDate = authorReleaseDatea; flashMemoryList.Add(flashMemorya); } } this.listBox1.ItemsSource = flashMemoryList; } } } private void submitData_Tap(object sender, System.Windows.Input.GestureEventArgs e) { flashMemoryValue=this.flashMemoryContent.Text.Trim(); if (flashMemoryValue == null||flashMemoryValue.Equals("")) { MessageBox.Show("写点什么吧!"); } else { myRequest = (HttpWebRequest)WebRequest.Create("http://space.cnblogs.com/mobile/ming_post.aspx"); //myRequest = (HttpWebRequest)WebRequest.Create("http://home.cnblogs.com/ajax/ing/Publish"); myRequest.Method = "POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; //myRequest.Accept = "application/json,text/javascript,*/*;q=0.01"; //myRequest.ContentType = "application/json;chartset=utf-8"; if (cookieContainer == null) { myRequest.CookieContainer = new CookieContainer(); } myRequest.CookieContainer = cookieContainer; myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackqq), myRequest); this.listBox1.ItemsSource = null; getFlashMemoryList(); } } private void GetRequestStreamCallbackqq(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; System.IO.Stream postStream = request.EndGetRequestStream(asynchronousResult); // Prepare Parameters String //string parametersString = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTE1MzYzODg2NzZkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBQtjaGtSZW1lbWJlcm1QYDyKKI9af4b67Mzq2xFaL9Bt&__EVENTVALIDATION=%2FwEdAAUyDI6H%2Fs9f%2BZALqNAA4PyUhI6Xi65hwcQ8%2FQoQCF8JIahXufbhIqPmwKf992GTkd0wq1PKp6%2B%2F1yNGng6H71Uxop4oRunf14dz2Zt2%2BQKDEIYpifFQj3yQiLk3eeHVQqcjiaAP&tbUserName=shandowsoftware&tbPassword=<PASSWORD>..&chkRemember=on&btnLogin=%E7%99%BB++%E5%BD%95&txtReturnUrl=http://home.cnblogs.com/"; //string jsonText="{\"content\":\"来自[windows phone]客户端\",\"publicFlag\":1}"; string jsonText = "txbContent=[来自windows phone客户端]" + flashMemoryValue + "&ingSubmit=%E6%8F%90%E4%BA%A4"; byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(jsonText); // Write to the request stream. postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); // Start the asynchronous operation to get the response request.BeginGetResponse(new AsyncCallback(GetResponseCallbackqq), request); } private void GetResponseCallbackqq(IAsyncResult asynchronousResult) { Stream streamResponse = null; string responseString = null; try { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); streamResponse = response.GetResponseStream(); //cookieCollection = response.Cookies; using (StreamReader streamRead = new StreamReader(streamResponse)) { responseString = streamRead.ReadToEnd(); } } catch { } finally { if (streamResponse != null) { streamResponse.Close(); } } if (responseString != null) { Dispatcher.BeginInvoke(() => { string result = responseString; //textBlockResult.Text = ""; //textBlockResult.Text = result; }); } else { Dispatcher.BeginInvoke(() => { //textBlockResult.Text = ""; //textBlockResult.Text = "error"; }); } } } }
3957c635d0c236ae0265764efcc4a9d128eaba91
[ "C#" ]
10
C#
shandowsoftware/cnblogs-wpapp
789e5607c8d20757701393492e5ed032fb0d01a2
fbecaff836cc5b4613af9956389a31eb5f81ed58
refs/heads/master
<file_sep>package com.example.cargoexchange; /** * Created by FoolishFan on 2016/7/14. */ public class UserData { private String userName; //鐢ㄦ埛鍚� private String userPwd; //鐢ㄦ埛瀵嗙爜 private int userId; //鐢ㄦ埛ID鍙� public int pwdresetFlag=0; //鑾峰彇鐢ㄦ埛鍚� public String getUserName() { //鑾峰彇鐢ㄦ埛鍚� return userName; } //璁剧疆鐢ㄦ埛鍚� public void setUserName(String userName) { //杈撳叆鐢ㄦ埛鍚� this.userName = userName; } //鑾峰彇鐢ㄦ埛瀵嗙爜 public String getUserPwd() { //鑾峰彇鐢ㄦ埛瀵嗙爜 return userPwd; } //璁剧疆鐢ㄦ埛瀵嗙爜 public void setUserPwd(String userPwd) { //杈撳叆鐢ㄦ埛瀵嗙爜 this.userPwd = userPwd; } //鑾峰彇鐢ㄦ埛id public int getUserId() { //鑾峰彇鐢ㄦ埛ID鍙� return userId; } //璁剧疆鐢ㄦ埛id public void setUserId(int userId) { //璁剧疆鐢ㄦ埛ID鍙� this.userId = userId; } /* public UserData(String userName, String userPwd, int userId) { //鐢ㄦ埛淇℃伅 super(); this.userName = userName; this.userPwd = <PASSWORD>; this.userId = userId; }*/ public UserData(String userName, String userPwd) { //杩欓噷鍙噰鐢ㄧ敤鎴峰悕鍜屽瘑鐮� super(); this.userName = userName; this.userPwd = <PASSWORD>; } } <file_sep>package com.example.floatView; import com.example.cargoexchange.R; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.PixelFormat; import android.os.IBinder; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; public class FloatWindowService extends Service{ private LayoutParams mWindowParam; private WindowManager mWindowManager; private LinearLayout mFloatWindow; private Button mFLoatBtn; public FloatWindowService() { // TODO Auto-generated constructor stub } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); creatFloatWindow(); } private void creatFloatWindow() { mWindowManager = (WindowManager)getApplication().getSystemService(getApplication().WINDOW_SERVICE); mWindowParam = new WindowManager.LayoutParams(); mWindowParam.type = LayoutParams.TYPE_PHONE; mWindowParam.format = PixelFormat.RGB_888; mWindowParam.flags = LayoutParams.FLAG_NOT_FOCUSABLE; mWindowParam.gravity = Gravity.LEFT|Gravity.TOP; mWindowParam.x = 0; mWindowParam.y = 0; mWindowParam.width = LayoutParams.WRAP_CONTENT; mWindowParam.height = LayoutParams.WRAP_CONTENT; LayoutInflater layoutInflater = LayoutInflater.from(getApplication()); mFloatWindow = (LinearLayout)layoutInflater.inflate(R.layout.float_window_layout, null); mWindowManager.addView(mFloatWindow, mWindowParam); mFLoatBtn = (Button)mFloatWindow.findViewById(R.id.floatBtn); mFloatWindow.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); mFLoatBtn.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { mWindowParam.x = (int)event.getRawX() - mFLoatBtn.getMeasuredWidth()/2; mWindowParam.y = (int)event.getRawY() - mFLoatBtn.getMeasuredHeight()/2 - (int)getStatusBarHeight(getApplicationContext()); mWindowManager.updateViewLayout(mFloatWindow, mWindowParam); return false; } }); mFLoatBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "Hello, FloatWindow", Toast.LENGTH_SHORT).show(); } }); } private double getStatusBarHeight(Context context){ double statusBarHeight = Math.ceil(25 * context.getResources().getDisplayMetrics().density); return statusBarHeight; } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if(mFloatWindow != null){ mWindowManager.removeView(mFloatWindow); } } } <file_sep>package com.example.floatView; import com.example.cargoexchange.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class FloatWindowsManagerActivity extends Activity { private Button mShowBtn; private Button mHideBtn; public FloatWindowsManagerActivity() { // TODO Auto-generated constructor stub } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.float_window_manager); mShowBtn = (Button) findViewById(R.id.show); mHideBtn = (Button) findViewById(R.id.hide); if (null != mShowBtn || null != mHideBtn) { mShowBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(FloatWindowsManagerActivity.this, FloatWindowService.class); startService(intent); finish(); } }); mHideBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(FloatWindowsManagerActivity.this, FloatWindowService.class); stopService(intent); } }); } /*View.OnClickListener buttonClickListener = new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(FloatWindowsManagerActivity.this, FloatWindowService.class); switch (v.getId()) { case R.id.show: startService(intent); break; case R.id.hide: stopService(intent); break; } } };*/ } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } }
c611cc55183d261f847ee7aec8cefe8d020d40ac
[ "Java" ]
3
Java
Keith-WangHZ/CarGoExchange
c7a19da13f14252bbb1eb453a33ac3c80ec595c9
65403fc712b2ce1057fb6b0b2825cf9d4f221707
refs/heads/main
<repo_name>siamolly/apibook_408411089<file_sep>/routes/apiGroup.js const { response } = require('express'); const express = require('express'); const fetch = require('node-fetch'); const router = express.Router(); //GET all data router.get('/', async function (req, res, next) { let data; try { const response = await fetch('http://localhost:1337/group'); const data = await response.json(); res.render('apiGroup/index', { data }); } catch (err) { console.log('Errors on getting books!'); res.render('apiGroup/index', { data:'' }); } }); // display add book page router.get('/add', async function (req, res, next) { // res.send('display add book page') res.render('apiGroup/add',{ group:'', company:'', id:'', }); }); // add a new book router.post('/add', async function (req, res, next) { // res.send('Add a new book.') const group = req.body.group; const company = req.body.company; const time = req.body.time; const form_data = { group: group, company: company, time: time, }; try{ //await db.query('INSERT INTO company SET ?', form_data); const reaponse = await fetch('http://localhost:1337/group',{ method: 'post', body: JSON.stringify(form_data), headers: { 'Content-Type': 'application/json' }, }); const data = await response.json(); res.redirect('/apiGroup'); } catch (err){ console.log(err); res.render('/apiGroup/add',{ group: form_data.group, company: form_data.company, time: form_data.time, }); } }); // display edit book page router.get('/edit/:id', async function (req, res, next) { //res.send('display edit book page'); const id = req.params.id; try{ const reaponse = await fetch(`http://localhost:1337/group/${id}`); const data = await response.json(); // const [rows] = await db.query('SELECT * FROM company WHERE id = ?',[id]); res.render('apiGroup/edit',{ id: data.id, group: data.name, company: data.company, time: data.time, }); }catch (err) { console.log(err); } }); // update book data router.post('/update', async function (req, res, next) { //res.send('update book data'); const group = req.body.group; const company = req.body.company; const time = req.body.time; const id = req.body.id; try{ /* await db.query('UPDATE company SET company.group = ?, company = ?, time = ? WHERE id = ? ', [ group, company, time, id, ]); */ //res.status(200).json({message: 'Updating successful'}); res.redirect('/group'); } catch (err){ console.log(err); } }); module.exports = router;<file_sep>/strapi-import-export-demo/extensions/users-permissions/config/jwt.js module.exports = { jwtSecret: process.env.JWT_SECRET || '3e81bea2-eaed-446c-8be6-b10997ed1942' };
35abc2a2c12943c60127cb7d8ff7f44f963558a3
[ "JavaScript" ]
2
JavaScript
siamolly/apibook_408411089
821208de64e4b5deba9ae85bf76824d35aa03781
410bcd616efcb539be33deca7cd467f122858488
refs/heads/master
<repo_name>androlua/javaide<file_sep>/common/src/main/java/com/jecelyin/common/app/JecApp.java /* * Copyright (C) 2016 <NAME> <<EMAIL>> * * This file is part of 920 Text Editor. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jecelyin.common.app; import android.app.Application; import android.content.Context; import android.os.StrictMode; import com.jecelyin.common.utils.L; import com.jecelyin.common.utils.SysUtils; /** * @author <NAME> <<EMAIL>> */ public abstract class JecApp extends Application { private static Context context; private static long startupTimestamp; @Override public void onCreate() { super.onCreate(); context = getApplicationContext(); if (startupTimestamp == 0) startupTimestamp = System.currentTimeMillis(); if (SysUtils.isDebug(this)) { L.debug = true; //内存泄漏监控 StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); builder.detectAll(); builder.penaltyLog(); StrictMode.setVmPolicy(builder.build()); } installMonitor(); } public static Context getContext() { return context; } public static long getStartupTimestamp() { return startupTimestamp; } abstract protected void installMonitor(); abstract public void watch(Object object); } <file_sep>/app/src/main/java/com/duy/compile/CompileManager.java /* * Copyright (c) 2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.duy.compile; import android.app.Activity; import android.content.Intent; import com.duy.compile.external.CompileHelper; import com.duy.ide.debug.activities.DebugActivity; import com.duy.ide.editor.code.MainActivity; import com.duy.project.file.java.JavaProjectFolder; import com.duy.run.activities.ExecuteActivity; import java.io.File; /** * Created by Duy on 11-Feb-17. */ public class CompileManager { public static final String FILE_PATH = "file_name"; // extras indicators public static final String IS_NEW = "is_new"; public static final String INITIAL_POS = "initial_pos"; public static final int ACTIVITY_EDITOR = 1001; public static final String MODE = "run_mode"; public static final String PROJECT_FILE = "project_file"; public static final String ACTION = "action"; public static final String ARGS = "program_args"; public static final String DEX_FILE = "dex_path"; private final Activity mActivity; public CompileManager(Activity activity) { this.mActivity = activity; } public void debug(String name) { Intent intent = new Intent(mActivity, DebugActivity.class); intent.putExtra(FILE_PATH, name); mActivity.startActivity(intent); } public void edit(String fileName, Boolean isNew) { Intent intent = new Intent(mActivity, MainActivity.class); intent.putExtra(FILE_PATH, fileName); intent.putExtra(IS_NEW, isNew); intent.putExtra(INITIAL_POS, 0); mActivity.startActivityForResult(intent, ACTIVITY_EDITOR); } public void executeDex(JavaProjectFolder projectFile, File dex) { Intent intent = new Intent(mActivity, ExecuteActivity.class); intent.putExtra(ACTION, CompileHelper.Action.RUN_DEX); intent.putExtra(PROJECT_FILE, projectFile); intent.putExtra(DEX_FILE, dex); mActivity.startActivity(intent); } public void buildApk() { } public interface ProcessCallback { void onFailed(String s); } } <file_sep>/app/src/main/java/com/duy/ide/code_sample/fragments/SelectProjectFragment.java package com.duy.ide.code_sample.fragments; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.duy.ide.R; import com.duy.ide.code_sample.adapters.ProjectCategoryAdapter; import com.duy.ide.code_sample.model.CodeCategory; import com.duy.ide.code_sample.model.CodeProjectSample; /** * Created by Duy on 27-Jul-17. */ public class SelectProjectFragment extends Fragment { public static final String TAG = "SampleFragment"; private ProjectClickListener listener; public static SelectProjectFragment newInstance(CodeCategory category) { Bundle args = new Bundle(); args.putSerializable("category", category); SelectProjectFragment fragment = new SelectProjectFragment(); fragment.setArguments(args); return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_category, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final CodeCategory category = (CodeCategory) getArguments().getSerializable("category"); final RecyclerView recyclerView = view.findViewById(R.id.list_view); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); ProjectCategoryAdapter adapter = new ProjectCategoryAdapter(getActivity(), category); adapter.setListener(listener); recyclerView.setAdapter(adapter); } @Override public void onAttach(Context context) { super.onAttach(context); try { listener = (ProjectClickListener) getActivity(); } catch (Exception e) { //class cast exception } } public interface ProjectClickListener extends SelectCategoryFragment.CategoryClickListener { void onProjectClick(CodeProjectSample codeProjectSample); } } <file_sep>/fileexplorer/src/main/java/com/jecelyin/android/file_explorer/util/FileUtils.java /* * Copyright (C) 2016 <NAME> <<EMAIL>> * * This file is part of 920 Text Editor. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jecelyin.android.file_explorer.util; import com.jecelyin.android.file_explorer.ExplorerException; import com.jecelyin.android.file_explorer.io.JecFile; import com.jecelyin.android.file_explorer.listener.BoolResultListener; import com.jecelyin.android.file_explorer.listener.FileListResultListener; import com.stericson.RootTools.RootTools; import java.io.File; import java.util.ArrayList; import java.util.List; /** * @author <NAME> <<EMAIL>> */ public class FileUtils { private static Boolean mRootAccess = null; public static boolean hasRootAccess() { if (mRootAccess != null) return mRootAccess; try { mRootAccess = RootTools.isAccessGiven(); } catch (Exception e) { mRootAccess = false; } return mRootAccess; } /** * Indicates whether file is considered to be "text". * * @return {@code true} if file is text, {@code false} if not. */ public static boolean isTextFile(File f) { return !f.isDirectory() && isMimeText(f.getPath()); } /** * Indicates whether requested file path is "text". This is done by * comparing file extension to a static list of extensions known to be text. * If the file has no file extension, it is also considered to be text. * * @param file File path * @return {@code true} if file is text, {@code false} if not. */ private static boolean isMimeText(String file) { if (file == null) return false; if (!file.contains(".")) return false; file = file.substring(file.lastIndexOf("/") + 1); // String ext = file.substring(file.lastIndexOf(".") + 1); return MimeTypes.getInstance().getMimeType(file).startsWith("text/"); } public static void copyDirectory(final JecFile srcDir, JecFile destDir , final boolean moveFile) { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new ExplorerException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new ExplorerException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getAbsolutePath().equals(destDir.getAbsolutePath())) { throw new ExplorerException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } final JecFile destDir2 = destDir.newFile(srcDir.getName()); // Cater for destination being directory within the source directory (see IO-141) if (destDir.getAbsolutePath().startsWith(srcDir.getAbsolutePath())) { srcDir.listFiles(new FileListResultListener() { @Override public void onResult(JecFile[] srcFiles) { List<JecFile> exclusionList = null; if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (JecFile srcFile : srcFiles) { JecFile copiedFile = destDir2.newFile(srcFile.getName()); exclusionList.add(copiedFile.getAbsoluteFile()); } } doCopyDirectory(srcDir, destDir2, moveFile, exclusionList); } }); } else { doCopyDirectory(srcDir, destDir2, moveFile, null); } } private static void doCopyDirectory(final JecFile srcDir, final JecFile destDir, final boolean moveFile, final List<JecFile> exclusionList) { srcDir.listFiles(new FileListResultListener() { @Override public void onResult(final JecFile[] srcFiles) { if (srcFiles == null) { // null if abstract pathname does not denote a directory, or if an I/O error occurs throw new ExplorerException("Failed to list contents of " + srcDir); } if (destDir.exists()) { if (!destDir.isDirectory()) { throw new ExplorerException("Destination '" + destDir + "' exists but is not a directory"); } doCopyDirectory(srcDir, destDir, srcFiles, moveFile, exclusionList); } else { destDir.mkdirs(new BoolResultListener() { @Override public void onResult(boolean result) { if (!result && !destDir.isDirectory()) { throw new ExplorerException("Destination '" + destDir + "' directory cannot be created"); } doCopyDirectory(srcDir, destDir, srcFiles, moveFile, exclusionList); } }); } } }); } private static void doCopyDirectory(JecFile srcDir, final JecFile destDir, JecFile[] srcFiles, final boolean moveFile, final List<JecFile> exclusionList) throws ExplorerException { if (!destDir.canWrite()) { throw new ExplorerException("Destination '" + destDir + "' cannot be written to"); } for (final JecFile srcFile : srcFiles) { JecFile dstFile = destDir.newFile(srcFile.getName()); //new File(destDir, srcFile.getName()); if (exclusionList == null || !exclusionList.contains(srcFile.getAbsoluteFile())) { if (srcFile.isDirectory()) { doCopyDirectory(srcFile, dstFile, moveFile, exclusionList); } else { copyFile(srcFile, dstFile, moveFile); } } } } public static void copyFile(final JecFile srcFile, final JecFile dstFile, boolean moveFile) { if (moveFile) { srcFile.renameTo(dstFile, new BoolResultListener() { @Override public void onResult(boolean result) { if (!result) throw new ExplorerException("Source '" + srcFile + "' move to destination '" + dstFile + "' fail"); } }); } else { srcFile.copyTo(dstFile, new BoolResultListener() { @Override public void onResult(boolean result) { if (!result) throw new ExplorerException("Source '" + srcFile + "' copy to destination '" + dstFile + "' fail"); } }); } } } <file_sep>/app/src/main/java/com/duy/ide/formatter/FormatFactory.java package com.duy.ide.formatter; import android.content.Context; import com.android.annotations.Nullable; import com.duy.ide.setting.AppSetting; import com.google.googlejavaformat.java.Formatter; import com.google.googlejavaformat.java.FormatterException; import com.google.googlejavaformat.java.JavaFormatterOptions; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; /** * Created by Duy on 13-Aug-17. */ public class FormatFactory { @Nullable public static Type getType(File ext) { if (ext.getPath().contains(".")) { switch (ext.getPath().substring(ext.getPath().lastIndexOf(".") + 1).toLowerCase()) { case "java": return Type.JAVA; case "xml": return Type.XML; default: return null; } } else { return null; } } public static String format(Context context, String src, @Nullable Type type) throws Exception { if (type == null) throw new UnsupportedTypeException(); switch (type) { case JAVA: return formatJava(context, src); case XML: return formatXml(context, src); default: return src; } } private static String formatJava(Context context, String src) throws FormatterException { AppSetting setting = new AppSetting(context); JavaFormatterOptions.Builder builder = JavaFormatterOptions.builder(); builder.style(setting.getFormatType() == 0 ? JavaFormatterOptions.Style.GOOGLE : JavaFormatterOptions.Style.AOSP); return new Formatter(builder.build()).formatSource(src); } private static String formatXml(Context context, String src) throws TransformerException, ParserConfigurationException, IOException, SAXException { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(src))); AppSetting setting = new AppSetting(context); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", setting.getTab().length() + ""); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); transformer.transform(source, result); return result.getWriter().toString(); } public enum Type {XML, JAVA} } <file_sep>/app/src/main/java/com/duy/run/view/ConsoleEditText.java package com.duy.run.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.support.annotation.UiThread; import android.support.annotation.WorkerThread; import android.support.v7.widget.AppCompatEditText; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.TextWatcher; import android.text.style.ForegroundColorSpan; import android.util.AttributeSet; import com.duy.ide.setting.AppSetting; import com.duy.run.utils.IntegerQueue; import com.spartacusrex.spartacuside.util.ByteQueue; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.concurrent.atomic.AtomicBoolean; /** * Created by Duy on 30-Jul-17. */ public class ConsoleEditText extends AppCompatEditText { private static final String TAG = "ConsoleEditText"; private static final int NEW_OUTPUT = 1; private static final int NEW_ERR = 2; //length of text private int mLength = 0; //out, in and err stream private PrintStream outputStream; private InputStream inputStream; private PrintStream errorStream; /** * uses for input */ private IntegerQueue mInputBuffer = new IntegerQueue(IntegerQueue.QUEUE_SIZE); /** * buffer for output */ private ByteQueue mStdoutBuffer = new ByteQueue(IntegerQueue.QUEUE_SIZE); /** * buffer for output */ private ByteQueue mStderrBuffer = new ByteQueue(IntegerQueue.QUEUE_SIZE); private AtomicBoolean isRunning = new AtomicBoolean(true); //filter input text, block a part of text private TextListener mTextListener = new TextListener(); private EnterListener mEnterListener = new EnterListener(); private byte[] mReceiveBuffer; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (!isRunning.get()) { return; } if (msg.what == NEW_OUTPUT) { writeStdoutToScreen(); } else if (msg.what == NEW_ERR) { writeStderrToScreen(); } } }; public ConsoleEditText(Context context) { super(context); init(context); } public ConsoleEditText(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public ConsoleEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } private void init(Context context) { if (!isInEditMode()) { AppSetting pref = new AppSetting(context); setTypeface(pref.getConsoleFont()); setTextSize(pref.getConsoleTextSize()); } setFilters(new InputFilter[]{mTextListener}); setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE); addTextChangedListener(mEnterListener); setMaxLines(2000); createIOStream(); } private void createIOStream() { mReceiveBuffer = new byte[4 * 1024]; mStdoutBuffer = new ByteQueue(4 * 1024); mStderrBuffer = new ByteQueue(4 * 1024); inputStream = new ConsoleInputStream(mInputBuffer); outputStream = new PrintStream(new ConsoleOutputStream(mStdoutBuffer, new StdListener() { @Override public void onUpdate() { mHandler.sendMessage(mHandler.obtainMessage(NEW_OUTPUT)); } })); errorStream = new PrintStream(new ConsoleErrorStream(mStderrBuffer, new StdListener() { @Override public void onUpdate() { mHandler.sendMessage(mHandler.obtainMessage(NEW_ERR)); } })); } private void writeStdoutToScreen() { int bytesAvailable = mStdoutBuffer.getBytesAvailable(); int bytesToRead = Math.min(bytesAvailable, mReceiveBuffer.length); try { int bytesRead = mStdoutBuffer.read(mReceiveBuffer, 0, bytesToRead); // mEmulator.append(mReceiveBuffer, 0, bytesRead); String out = new String(mReceiveBuffer, 0, bytesRead); mLength = mLength + out.length(); appendStdout(out); } catch (InterruptedException e) { } } private void writeStderrToScreen() { int bytesAvailable = mStderrBuffer.getBytesAvailable(); int bytesToRead = Math.min(bytesAvailable, mReceiveBuffer.length); try { int bytesRead = mStderrBuffer.read(mReceiveBuffer, 0, bytesToRead); // mEmulator.append(mReceiveBuffer, 0, bytesRead); String out = new String(mReceiveBuffer, 0, bytesRead); mLength = mLength + out.length(); appendStderr(out); } catch (InterruptedException e) { } // // String out = new String(Character.toChars(read)); // mLength = mLength + out.length(); // appendStdout(out); } @WorkerThread public PrintStream getOutputStream() { return outputStream; } @WorkerThread public InputStream getInputStream() { return inputStream; } @WorkerThread public PrintStream getErrorStream() { return errorStream; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); } @UiThread private void appendStdout(final CharSequence spannableString) { mHandler.post(new Runnable() { @Override public void run() { append(spannableString); } }); } @UiThread private void appendStderr(final CharSequence str) { mHandler.post(new Runnable() { @Override public void run() { SpannableString spannableString = new SpannableString(str); spannableString.setSpan(new ForegroundColorSpan(Color.MAGENTA), 0, str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); append(spannableString); } }); } public void stop() { mInputBuffer.write(-1); isRunning.set(false); } public interface StdListener { void onUpdate(); } private static class ConsoleOutputStream extends OutputStream { private ByteQueue mStdoutBuffer; private StdListener listener; private ConsoleOutputStream(ByteQueue mStdoutBuffer, StdListener listener) { this.mStdoutBuffer = mStdoutBuffer; this.listener = listener; } @Override public void write(@NonNull byte[] b, int off, int len) throws IOException { try { mStdoutBuffer.write(b, off, len); listener.onUpdate(); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void write(int b) throws IOException { write(new byte[]{(byte) b}, 0, 1); } } private static class ConsoleErrorStream extends OutputStream { private ByteQueue mStderrBuffer; private StdListener stdListener; public ConsoleErrorStream(ByteQueue mStderrBuffer, StdListener stdListener) { this.mStderrBuffer = mStderrBuffer; this.stdListener = stdListener; } @Override public void write(@NonNull byte[] b, int off, int len) throws IOException { try { mStderrBuffer.write(b, off, len); stdListener.onUpdate(); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void write(int b) throws IOException { write(new byte[]{(byte) b}, 0, 1); } } private static class ConsoleInputStream extends InputStream { private final Object mLock = new Object(); @NonNull private IntegerQueue mInputBuffer; public ConsoleInputStream(@NonNull IntegerQueue mInputBuffer) { this.mInputBuffer = mInputBuffer; } @Override public int read() throws IOException { synchronized (mLock) { return mInputBuffer.read(); } } } private class EnterListener implements TextWatcher { private int start; private int count; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { this.start = start; this.count = count; } @Override public void afterTextChanged(Editable s) { if (count == 1 && s.charAt(start) == '\n' && start >= mLength) { String data = s.toString().substring(mLength); for (char c : data.toCharArray()) { mInputBuffer.write(c); } mInputBuffer.write(-1); //flush mLength = s.length(); //append to console } } } private class TextListener implements InputFilter { public CharSequence removeStr(CharSequence removeChars, int startPos) { if (startPos < mLength) { //this mean output from console return removeChars; //can not remove console output } else { return ""; } } public CharSequence insertStr(CharSequence newChars, int startPos) { if (startPos < mLength) { //it mean output from console return newChars; } else { //(startPos >= mLength) SpannableString spannableString = new SpannableString(newChars); spannableString.setSpan(new ForegroundColorSpan(Color.GREEN), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return spannableString; } } public CharSequence updateStr(CharSequence oldChars, int startPos, CharSequence newChars) { if (startPos < mLength) { return oldChars; //don't edit } else {//if (startPos >= mLength) SpannableString spannableString = new SpannableString(newChars); spannableString.setSpan(new ForegroundColorSpan(Color.GREEN), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return spannableString; } } public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { CharSequence returnStr = source; String curStr = dest.subSequence(dstart, dend).toString(); String newStr = source.toString(); int length = end - start; int dlength = dend - dstart; if (dlength > 0 && length == 0) { // Case: Remove chars, Simple returnStr = TextListener.this.removeStr(dest.subSequence(dstart, dend), dstart); } else if (length > 0 && dlength == 0) { // Case: Insert chars, Simple returnStr = TextListener.this.insertStr(source.subSequence(start, end), dstart); } else if (curStr.length() > newStr.length()) { // Case: Remove string or replace if (curStr.startsWith(newStr)) { // Case: Insert chars, by append returnStr = TextUtils.concat(curStr.subSequence(0, newStr.length()), TextListener.this.removeStr(curStr.subSequence(newStr.length(), curStr.length()), dstart + curStr.length())); } else { // Case Replace chars. returnStr = TextListener.this.updateStr(curStr, dstart, newStr); } } else if (curStr.length() < newStr.length()) { // Case: Append String or rrepace. if (newStr.startsWith(curStr)) { // Addend, Insert returnStr = TextUtils.concat(curStr, TextListener.this.insertStr(newStr.subSequence(curStr.length(), newStr.length()), dstart + curStr.length())); } else { returnStr = TextListener.this.updateStr(curStr, dstart, newStr); } } else { // No update os str... } // If the return value is same as the source values, return the source value. return returnStr; } } } <file_sep>/app/build.gradle apply plugin: 'com.android.application' apply plugin: 'io.fabric' android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion useLibrary 'org.apache.http.legacy' defaultConfig { applicationId "com.duy.compiler.javanide" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion multiDexEnabled true versionCode 33 versionName "1.2.5" vectorDrawables.useSupportLibrary = true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' ndk { moduleName "aapt" abiFilters 'armeabi-v7a', 'x86' } } debug { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' ndk { moduleName "aapt" abiFilters 'armeabi-v7a' } } } configurations.all { resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9' } externalNativeBuild { ndkBuild { path 'src/main/jni/Android.mk' } } dataBinding { enabled = true } lintOptions { disable 'MissingTranslation' } } configurations { all*.exclude group: 'commons-logging', module: 'commons-logging' } repositories { mavenCentral() } dependencies { testCompile 'junit:junit:4.12' compile fileTree(dir: 'libs', include: ['*.jar']) // compile files('libs/commons-codec-1.10.jar') // compile files('libs/commons-compress-1.5.jar') // compile files('libs/dx.jar') compile project(':pager') compile project(':colorpicker') compile project(':splitview') compile project(':treeview') compile project(':fileexplorer') compile project(':javacompiler') compile project(':dx') compile project(':javacodeformatter') compile project(':androidlogcat') compile project(':manifest_merger') //android support compile 'com.android.support:multidex:1.0.2' compile "com.android.support:support-annotations:$supportLibVersion" compile "com.android.support:support-v4:$supportLibVersion" compile "com.android.support:appcompat-v7:$supportLibVersion" compile "com.android.support:design:$supportLibVersion" compile "com.android.support:cardview-v7:$supportLibVersion" compile "com.android.support:recyclerview-v7:$supportLibVersion" //firebase sdk compile "com.google.firebase:firebase-core:$googleServiceVersion" compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') { transitive = true } compile 'io.github.kobakei:ratethisapp:1.2.0' compile 'commons-io:commons-io:2.4' compile 'com.github.clans:fab:1.6.4' compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1' compile 'com.miguelcatalan:materialsearchview:1.4.0' compile 'com.sothree.slidinguppanel:library:3.3.1' } apply plugin: 'com.google.gms.google-services' <file_sep>/styles/src/main/java/com/jecelyin/editor/v2/Pref.java /* * Copyright (C) 2016 <NAME> <<EMAIL>> * * This file is part of 920 Text Editor. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jecelyin.editor.v2; import android.content.Context; import android.content.SharedPreferences; import android.os.Environment; import android.preference.PreferenceManager; import android.support.annotation.IntDef; import android.text.TextUtils; import com.jecelyin.common.utils.L; import com.jecelyin.common.utils.StringUtils; import com.jecelyin.common.utils.SysUtils; import com.jecelyin.styles.R; import com.stericson.RootTools.RootTools; import java.io.File; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; /** * @author <NAME> <<EMAIL>> */ public class Pref implements SharedPreferences.OnSharedPreferenceChangeListener { public static final String KEY_FONT_SIZE = "pref_font_size"; public static final String KEY_CURSOR_WIDTH = "pref_cursor_width"; public static final String KEY_TOUCH_TO_ADJUST_TEXT_SIZE = "pref_touch_to_adjust_text_size"; public static final String KEY_WORD_WRAP = "pref_word_wrap"; public static final String KEY_SHOW_LINE_NUMBER = "pref_show_linenumber"; public static final String KEY_SHOW_WHITESPACE = "pref_show_whitespace"; public static final String KEY_AUTO_INDENT = "pref_auto_indent"; public static final String KEY_INSERT_SPACE_FOR_TAB = "pref_insert_space_for_tab"; public static final String KEY_TAB_SIZE = "pref_tab_size"; public static final String KEY_SYMBOL = "pref_symbol"; public static final String KEY_AUTO_CAPITALIZE = "pref_auto_capitalize"; public static final String KEY_ENABLE_HIGHLIGHT = "pref_enable_highlight"; public static final String KEY_HIGHLIGHT_FILE_SIZE_LIMIT = "pref_highlight_file_size_limit"; public static final String KEY_THEME = "pref_current_theme"; public static final String KEY_AUTO_SAVE = "pref_auto_save"; public static final String KEY_REMEMBER_LAST_OPENED_FILES = "pref_remember_last_opened_files"; public static final String KEY_SCREEN_ORIENTATION = "pref_screen_orientation"; public static final String KEY_KEEP_SCREEN_ON = "pref_keep_screen_on"; public static final String KEY_ENABLE_ROOT = "pref_enable_root"; public static final String KEY_TOOLBAR_ICONS = "pref_toolbar_icons"; public static final String KEY_PREF_AUTO_CHECK_UPDATES = "pref_auto_check_updates"; public static final String KEY_PREF_KEEP_BACKUP_FILE = "pref_keep_backup_file"; public static final String KEY_PREF_ENABLE_DRAWERS = "pref_enable_drawers"; public static final String KEY_LAST_OPEN_PATH = "last_open_path"; public static final String KEY_READ_ONLY = "readonly_mode"; public static final String KEY_SHOW_HIDDEN_FILES = "show_hidden_files"; public static final String KEY_FILE_SORT_TYPE = "show_file_sort"; public static final String KEY_FULL_SCREEN = "fullscreen_mode"; public static final String KEY_LAST_TAB = "last_tab"; public static final int DEF_MIN_FONT_SIZE = 9; public static final int DEF_MAX_FONT_SIZE = 32; public static final int SCREEN_ORIENTATION_AUTO = 0; public static final int SCREEN_ORIENTATION_LANDSCAPE = 1; public static final int SCREEN_ORIENTATION_PORTRAIT = 2; public static final String VALUE_SYMBOL = TextUtils.join("\n", new String[]{"{", "}", "<", ">" , ",", ";", "'", "\"", "(", ")", "/", "\\", "%", "[", "]", "|", "#", "=", "$", ":" , "&", "?", "!", "@", "^", "+", "*", "-", "_", "`", "\\t", "\\n"}); public static final int[] THEMES = new int[]{ R.style.DefaultTheme, R.style.DarkTheme }; private static final Object mContent = new Object(); private static Pref instance; static { // All Private Keys should go here like this: // privateKeys.put("box_key", "<KEY>"); // privateKeys.put("box_secret", "<KEY>"); // privateKeys.put("dropbox_key", "<KEY>"); // privateKeys.put("dropbox_secret", "plkrfrygu17glgn"); // privateKeys.put("drive_key", "645291897772.apps.googleusercontent.com"); // privateKeys.put("drive_secret", "<KEY>"); // privateKeys.put("skydrive_key", "00000000400F4500"); // privateKeys.put("skydrive_secret", "<KEY>"); } private final SharedPreferences pm; private final Map<String, Object> map; private final Context context; private final WeakHashMap<SharedPreferences.OnSharedPreferenceChangeListener, Object> mListeners = new WeakHashMap<>(); private Set<String> toolbarIcons; public Pref(Context context) { this.context = context; pm = PreferenceManager.getDefaultSharedPreferences(context); pm.registerOnSharedPreferenceChangeListener(this); //init variable map = new HashMap<>(); map.put(KEY_FONT_SIZE, 13); map.put(KEY_CURSOR_WIDTH, 2); map.put(KEY_TOUCH_TO_ADJUST_TEXT_SIZE, false); map.put(KEY_WORD_WRAP, true); map.put(KEY_SHOW_LINE_NUMBER, true); map.put(KEY_SHOW_WHITESPACE, true); map.put(KEY_AUTO_INDENT, true); map.put(KEY_INSERT_SPACE_FOR_TAB, true); map.put(KEY_TAB_SIZE, 4); map.put(KEY_SYMBOL, VALUE_SYMBOL); map.put(KEY_AUTO_CAPITALIZE, true); map.put(KEY_ENABLE_HIGHLIGHT, true); map.put(KEY_HIGHLIGHT_FILE_SIZE_LIMIT, 500); map.put(KEY_THEME, 0); map.put(KEY_AUTO_SAVE, false); map.put(KEY_ENABLE_ROOT, true); map.put(KEY_REMEMBER_LAST_OPENED_FILES, true); map.put(KEY_SCREEN_ORIENTATION, "auto"); map.put(KEY_KEEP_SCREEN_ON, false); map.put(KEY_PREF_AUTO_CHECK_UPDATES, true); map.put(KEY_PREF_KEEP_BACKUP_FILE, true); map.put(KEY_PREF_ENABLE_DRAWERS, true); //not at preference setting toolbarIcons = pm.getStringSet(KEY_TOOLBAR_ICONS, null); map.put(KEY_LAST_OPEN_PATH, Environment.getExternalStorageDirectory().getPath() + File.separator + "JavaNIDE"); map.put(KEY_READ_ONLY, false); map.put(KEY_SHOW_HIDDEN_FILES, false); map.put(KEY_FILE_SORT_TYPE, 0); map.put(KEY_FULL_SCREEN, false); map.put(KEY_LAST_TAB, 0); Map<String, ?> values = pm.getAll(); for (String key : map.keySet()) { updateValue(key, values); } } public static Pref getInstance(Context context) { if (instance == null) { instance = new Pref(context.getApplicationContext()); } return instance; } public static String getGoogleDriveKey() { return null; //drive_key } public static String getGoogleDriveSecret() { return null; //drive_key } public static String getBoxAPIKey() { return null; // TODO: 16/1/2 } public static String getBoxApiSecret() { return null; } private void updateValue(String key, Map<String, ?> values) { Object value = map.get(key); // 跳过一些不能通过本方法取值的东东 if (value == null) return; Class cls = value.getClass(); try { if (cls == int.class || cls == Integer.class) { // value = StringUtils.toInt(pm.getString(key, String.valueOf(value))); Object in = values.get(key); if (in != null) value = in instanceof Integer ? (int) in : StringUtils.toInt(String.valueOf(in)); } else if (cls == boolean.class || cls == Boolean.class) { // value = pm.getBoolean(key, (boolean)value); Boolean b = (Boolean) values.get(key); value = b == null ? (boolean) value : b; } else { // value = pm.getString(key, (String)value); String str = (String) values.get(key); value = str == null ? (String) value : str; } } catch (Exception e) { L.e("key = " + key, e); return; } map.put(key, value); } public void registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { synchronized (this) { mListeners.put(listener, mContent); } } public void unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { synchronized (this) { mListeners.remove(listener); } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { updateValue(key, sharedPreferences.getAll()); Set<SharedPreferences.OnSharedPreferenceChangeListener> listeners = mListeners.keySet(); for (SharedPreferences.OnSharedPreferenceChangeListener listener : listeners) { if (listener != null) { listener.onSharedPreferenceChanged(sharedPreferences, key); } } } public boolean isShowLineNumber() { return (boolean) map.get(KEY_SHOW_LINE_NUMBER); } public boolean isShowWhiteSpace() { return (boolean) map.get(KEY_SHOW_WHITESPACE); } public int getTheme() { return (int) map.get(KEY_THEME); } /** * theme index of {@link #THEMES} * * @param theme */ public void setTheme(int theme) { map.put(KEY_THEME, theme); pm.edit().putInt(KEY_THEME, theme).commit(); } public boolean isHighlight() { return (boolean) map.get(KEY_ENABLE_HIGHLIGHT); } public int getHighlightSizeLimit() { return 1024 * (int) map.get(KEY_HIGHLIGHT_FILE_SIZE_LIMIT); } public boolean isAutoSave() { return (boolean) map.get(KEY_AUTO_SAVE); } public boolean isKeepScreenOn() { return (boolean) map.get(KEY_KEEP_SCREEN_ON); } public Integer[] getToolbarIcons() { if (toolbarIcons == null) return null; Integer[] list = new Integer[toolbarIcons.size()]; int i = 0; for (String id : toolbarIcons) { list[i++] = Integer.valueOf(id); } return list; } public void setToolbarIcons(Integer[] toolbarIcons) { this.toolbarIcons = new HashSet<>(); for (Integer id : toolbarIcons) { this.toolbarIcons.add(String.valueOf(id)); } pm.edit().putStringSet(KEY_TOOLBAR_ICONS, this.toolbarIcons).apply(); } public Object getValue(String key) { return map.get(key); } public String getLastOpenPath() { return (String) map.get(KEY_LAST_OPEN_PATH); } public void setLastOpenPath(String path) { pm.edit().putString(KEY_LAST_OPEN_PATH, path).apply(); map.put(KEY_LAST_OPEN_PATH, path); } public int getFontSize() { return (int) map.get(KEY_FONT_SIZE); } public int getCursorThickness() { int width = (int) map.get(KEY_CURSOR_WIDTH); if (width == 0) return 0; return SysUtils.dpAsPixels(context, width); } public boolean isReadOnly() { return (boolean) map.get(KEY_READ_ONLY); } public void setReadOnly(boolean b) { pm.edit().putBoolean(KEY_READ_ONLY, b).apply(); map.put(KEY_READ_ONLY, b); } public boolean isAutoIndent() { return (boolean) map.get(KEY_AUTO_INDENT); } public boolean isWordWrap() { return (boolean) map.get(KEY_WORD_WRAP); } public boolean isTouchScaleTextSize() { return (boolean) map.get(KEY_TOUCH_TO_ADJUST_TEXT_SIZE); } public boolean isAutoCheckUpdates() { return (boolean) map.get(KEY_PREF_AUTO_CHECK_UPDATES); } public boolean isAutoCapitalize() { return (boolean) map.get(KEY_AUTO_CAPITALIZE); } public boolean isOpenLastFiles() { return (boolean) map.get(KEY_REMEMBER_LAST_OPENED_FILES); } public int getTabSize() { return (int) map.get(KEY_TAB_SIZE); } @ScreenOrientation public int getScreenOrientation() { String ori = (String) map.get(KEY_SCREEN_ORIENTATION); if ("landscape".equals(ori)) { return SCREEN_ORIENTATION_LANDSCAPE; } else if ("portrait".equals(ori)) { return SCREEN_ORIENTATION_PORTRAIT; } else { return SCREEN_ORIENTATION_AUTO; } } public boolean isRootable() { return ((boolean) map.get(KEY_ENABLE_ROOT)) && RootTools.isRootAvailable() && RootTools.isAccessGiven(); } public boolean isKeepBackupFile() { return (boolean) map.get(KEY_PREF_KEEP_BACKUP_FILE); } public String getSymbol() { return (String) map.get(KEY_SYMBOL); } public boolean isShowHiddenFiles() { return (boolean) map.get(KEY_SHOW_HIDDEN_FILES); } public void setShowHiddenFiles(boolean b) { pm.edit().putBoolean(KEY_SHOW_HIDDEN_FILES, b).apply(); map.put(KEY_SHOW_HIDDEN_FILES, b); } public int getFileSortType() { return (int) map.get(KEY_FILE_SORT_TYPE); } public void setFileSortType(int type) { pm.edit().putInt(KEY_FILE_SORT_TYPE, type).apply(); map.put(KEY_FILE_SORT_TYPE, type); } public boolean isFullScreenMode() { return (boolean) map.get(KEY_FULL_SCREEN); } public void setFullScreenMode(boolean b) { pm.edit().putBoolean(KEY_FULL_SCREEN, b).apply(); map.put(KEY_FULL_SCREEN, b); } public int getLastTab() { return (int) map.get(KEY_LAST_TAB); } public void setLastTab(int index) { pm.edit().putInt(KEY_LAST_TAB, index).apply(); map.put(KEY_LAST_TAB, index); } public boolean isEnabledDrawers() { return (boolean) map.get(KEY_PREF_ENABLE_DRAWERS); } @IntDef({SCREEN_ORIENTATION_AUTO, SCREEN_ORIENTATION_LANDSCAPE, SCREEN_ORIENTATION_PORTRAIT}) public @interface ScreenOrientation { } } <file_sep>/app/src/main/java/com/duy/ide/editor/code/highlight/xml/XmlHighlighter.java package com.duy.ide.editor.code.highlight.xml; import android.support.annotation.NonNull; import android.support.v4.util.Pair; import android.text.Editable; import android.text.Spannable; import android.text.style.ForegroundColorSpan; import com.duy.ide.editor.code.highlight.HighlightImpl; import com.duy.ide.editor.code.highlight.java.StringHighlighter; import com.duy.ide.editor.code.view.HighlightEditor; import com.duy.ide.themefont.themes.database.CodeTheme; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.regex.Matcher; import static com.duy.ide.autocomplete.Patterns.XML_ATTRS; import static com.duy.ide.autocomplete.Patterns.XML_TAGS; /** * Created by Duy on 06-Aug-17. */ public class XmlHighlighter extends HighlightImpl { private StringHighlighter stringHighlighter; private XmlCommentHighlighter commentHighlighter; public XmlHighlighter(HighlightEditor highlightEditor) { this.codeTheme = highlightEditor.getCodeTheme(); this.commentHighlighter = new XmlCommentHighlighter(codeTheme); this.stringHighlighter = new StringHighlighter(codeTheme); } @Override public void highlight(@NonNull Editable allText, @NonNull CharSequence textToHighlight, int start) { try { commentHighlighter.highlight(allText, textToHighlight, start); ArrayList<Pair<Integer, Integer>> region = commentHighlighter.getCommentRegion(); if (region.size() == 0) { highlightStringAndOther(allText, textToHighlight, start); return; } Collections.sort(region, new Comparator<Pair<Integer, Integer>>() { @Override public int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) { return o1.first.compareTo(o2.first); } }); int startIndex, endIndex; if (region.size() > 0 && start < region.get(0).first - 1) { highlightStringAndOther(allText, allText.subSequence(start, region.get(0).first - 1), start); } for (int i = 0; i < region.size() - 1; i++) { startIndex = region.get(i).second + 1; endIndex = region.get(i + 1).first - 1; if (startIndex < endIndex) { highlightStringAndOther(allText, allText.subSequence(startIndex, endIndex), startIndex); } } if (region.size() > 0) { startIndex = region.get(region.size() - 1).second + 1; endIndex = start + textToHighlight.length(); if (startIndex <= endIndex) { highlightStringAndOther(allText, allText.subSequence(startIndex, endIndex), startIndex); } } } catch (Exception ignored) { ignored.printStackTrace(); } } @Override public void setCodeTheme(CodeTheme codeTheme) { super.setCodeTheme(codeTheme); commentHighlighter.setCodeTheme(codeTheme); stringHighlighter.setCodeTheme(codeTheme); } @Override public void setErrorRange(long startPosition, long endPosition) { } private void highlightStringAndOther(@NonNull Editable allText, @NonNull CharSequence textToHighlight, int start) { highlightAttr(allText, textToHighlight, start); stringHighlighter.highlight(allText, textToHighlight, start); } private void highlightAttr(@NonNull Editable allText, @NonNull CharSequence textToHighlight, int start) { for (Matcher m = XML_ATTRS.matcher(textToHighlight); m.find(); ) { allText.setSpan(new ForegroundColorSpan(codeTheme.getNumberColor()), start + m.start(), start + m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } for (Matcher m = XML_TAGS.matcher(textToHighlight); m.find(); ) { allText.setSpan(new ForegroundColorSpan(codeTheme.getKeywordColor()), start + m.start(), start + m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } } <file_sep>/app/src/androidTest/java/com/duy/compile/external/java/JavaCompilerAPITest.java package com.duy.compile.external.java; import android.support.test.filters.SmallTest; import android.support.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; /** * Created by duy on 19/07/2017. */ @RunWith(AndroidJUnit4.class) @SmallTest public class JavaCompilerAPITest { @Before public void setup() { } @Test public void testCompile() throws IOException { } }<file_sep>/app/src/main/java/com/duy/compile/external/CompileHelper.java package com.duy.compile.external; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.duy.compile.external.android.AndroidBuilder; import com.duy.compile.external.android.util.Util; import com.duy.compile.external.dex.DexTool; import com.duy.compile.external.java.Jar; import com.duy.compile.external.java.Java; import com.duy.compile.external.java.Javac; import com.duy.dex.Dex; import com.duy.dx.merge.CollisionPolicy; import com.duy.dx.merge.DexMerger; import com.duy.ide.DLog; import com.duy.ide.file.FileManager; import com.duy.project.file.android.AndroidProjectFolder; import com.duy.project.file.java.JavaProjectFolder; import com.sun.tools.javac.main.Main; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import javax.tools.DiagnosticCollector; import javax.tools.DiagnosticListener; /** * Created by duy on 18/07/2017. */ public class CompileHelper { private static final String TAG = "CommandManager"; @Nullable public static File buildJarAchieve(Context context, JavaProjectFolder projectFile, DiagnosticListener listener) throws IOException { int status = compileJava(context, projectFile, listener); if (status != Main.EXIT_OK) { throw new RuntimeException("Compile time error... Exit code(" + status + ")"); } //now create normal jar file Jar.createJarArchive(projectFile); return projectFile.getOutJarArchive(); } public static int compileJava(Context context, JavaProjectFolder pf) { return compileJava(context, pf, null); } public static int compileJava(Context context, JavaProjectFolder projectFile, @Nullable DiagnosticListener listener) { try { String[] args = new String[]{ "-verbose", "-cp", projectFile.getJavaClassPath(context), "-sourcepath", projectFile.getSourcePath(), //sourcepath "-d", projectFile.getDirBuildClasses().getPath(), //output dir projectFile.getMainClass().getPath(projectFile) //main class }; DLog.d(TAG, "compileJava args = " + Arrays.toString(args)); int compileStatus; compileStatus = Javac.compile(args, listener); return compileStatus; } catch (Throwable e) { e.printStackTrace(); } return Main.EXIT_ERROR; } public static void compileAndRun(Context context, InputStream in, File tempDir, JavaProjectFolder projectFile) throws Exception { compileJava(context, projectFile); convertToDexFormat(context, projectFile); executeDex(context, in, projectFile.getDexedClassesFile(), tempDir, projectFile.getMainClass().getName()); } public static void dexLibs(@NonNull JavaProjectFolder projectFile) throws Exception { DLog.d(TAG, "dexLibs() called with: projectFile = [" + projectFile + "]"); File dirLibs = projectFile.dirLibs; if (dirLibs.exists()) { File[] files = dirLibs.listFiles(); if (files != null && files.length > 0) { for (File jarLib : files) { // skip native libs in sub directories if (!jarLib.isFile() || !jarLib.getName().endsWith(".jar")) { continue; } // compare hash of jar contents to name of dexed version String md5 = Util.getMD5Checksum(jarLib); File dexLib = new File(projectFile.getDirDexedLibs(), jarLib.getName().replace(".jar", "-" + md5 + ".dex")); if (dexLib.exists()) { continue; } String[] args = new String[]{"--dex", "--verbose", "--no-strict", "--output=" + dexLib.getPath(), jarLib.getPath()}; DexTool.main(args); } } } } public static File dexBuildClasses(@NonNull JavaProjectFolder projectFile) throws IOException { DLog.d(TAG, "dexBuildClasses() called with: projectFile = [" + projectFile + "]"); String input = projectFile.dirBuildClasses.getPath(); FileManager.ensureFileExist(new File(input)); String[] args = new String[]{"--dex", "--verbose", "--no-strict", "--output=" + projectFile.getDexedClassesFile().getPath(), //output dex file input}; //input file DexTool.main(args); return projectFile.getDexedClassesFile(); } public static File dexMerge(@NonNull JavaProjectFolder projectFile) throws IOException { DLog.d(TAG, "dexMerge() called with: projectFile = [" + projectFile + "]"); FileManager.ensureFileExist(projectFile.getDexedClassesFile()); if (projectFile.getDirDexedLibs().exists()) { File[] files = projectFile.getDirDexedLibs().listFiles(); if (files != null && files.length > 0) { for (File dexedLib : files) { DexMerger dexMerger = new DexMerger( new Dex[]{ new Dex(projectFile.getDexedClassesFile()), new Dex(dexedLib)}, CollisionPolicy.FAIL); Dex merged = dexMerger.merge(); merged.writeTo(projectFile.getDexedClassesFile()); } } } return projectFile.getDexedClassesFile(); } public static void executeDex(Context context, InputStream in, @NonNull File outDex, @NonNull File tempDir, String mainClass) throws FileNotFoundException { FileManager.ensureFileExist(outDex); String[] args = new String[]{"-jar", outDex.getPath(), mainClass}; Java.run(args, tempDir.getPath(), in); } public static void convertToDexFormat(Context context, @NonNull JavaProjectFolder projectFile) throws Exception { Log.d(TAG, "convertToDexFormat() called with: projectFile = [" + projectFile + "]"); dexLibs(projectFile); dexBuildClasses(projectFile); dexMerge(projectFile); } public static File buildApk(Context context, AndroidProjectFolder projectFile, DiagnosticCollector diagnosticCollector) throws Exception { AndroidBuilder.build(context, projectFile, diagnosticCollector); return projectFile.getApkUnaligned(); } public class Action { public static final int RUN = 0; public static final int RUN_DEX = 1; public static final int BUILD_JAR = 2; } } <file_sep>/app/src/main/java/com/duy/project/view/dialog/DialogNewAndroidProject.java package com.duy.project.view.dialog; import android.app.Dialog; import android.content.Context; import android.content.res.AssetManager; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatDialogFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import com.duy.ide.R; import com.duy.ide.autocomplete.Patterns; import com.duy.ide.code_sample.model.AssetUtil; import com.duy.ide.file.FileManager; import com.duy.project.file.android.AndroidProjectFolder; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * Created by Duy on 16-Jul-17. */ public class DialogNewAndroidProject extends AppCompatDialogFragment implements View.OnClickListener { public static final String TAG = "DialogNewAndroidProject"; private EditText editAppName, editPackage; private Button btnCreate, btnCancel; @Nullable private DialogNewJavaProject.OnCreateProjectListener listener; private EditText mActivityName, layoutName; private CheckBox mAppCompat; public static DialogNewAndroidProject newInstance() { Bundle args = new Bundle(); DialogNewAndroidProject fragment = new DialogNewAndroidProject(); fragment.setArguments(args); return fragment; } @Override public void onAttach(Context context) { super.onAttach(context); try { listener = (DialogNewJavaProject.OnCreateProjectListener) getActivity(); } catch (Exception e) { } } @Override public void onStart() { super.onStart(); Dialog dialog = getDialog(); if (dialog != null) { dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.dialog_new_android_project, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); editPackage = view.findViewById(R.id.edit_package_name); editAppName = view.findViewById(R.id.edit_project_name); btnCreate = view.findViewById(R.id.btn_create); btnCancel = view.findViewById(R.id.btn_cancel); btnCreate.setOnClickListener(this); btnCancel.setOnClickListener(this); mActivityName = view.findViewById(R.id.edit_activity_name); layoutName = view.findViewById(R.id.edit_layout_name); mAppCompat = view.findViewById(R.id.backwards_compatibility); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_cancel: dismiss(); break; case R.id.btn_create: doCreateProject(); break; } } private void doCreateProject() { if (isOk()) { ///create new android project String packageName = editPackage.getText().toString(); String activityName = mActivityName.getText().toString(); String activityClass = String.format("%s.%s", packageName, activityName); String mainLayoutName = layoutName.getText().toString(); String appName = editAppName.getText().toString(); String classpath = FileManager.getClasspathFile(getContext()).getPath(); String projectName = appName.replaceAll("\\s+", ""); boolean useAppCompat = mAppCompat.isChecked(); try { AndroidProjectFolder projectFile = new AndroidProjectFolder( new File(FileManager.EXTERNAL_DIR), activityClass, packageName, projectName); //create directory projectFile.mkdirs(); AssetManager assets = getContext().getAssets(); copyResources(projectFile, useAppCompat, assets); createStringXml(projectFile, appName); copyKeyStore(projectFile, assets); createManifest(projectFile, activityClass, packageName, assets); createMainActivity(projectFile, activityClass, packageName, activityName, appName, useAppCompat, assets); createMainXml(projectFile, mainLayoutName, assets); copyLibrary(projectFile, assets); if (listener != null) listener.onProjectCreated(projectFile); this.dismiss(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(getContext(), "Can not create project. Error " + e.getMessage(), Toast.LENGTH_SHORT).show(); } } } private void copyResources(AndroidProjectFolder projectFile, boolean useAppCompat, AssetManager assets) throws FileNotFoundException { String resourcePath = projectFile.getDirRes().getPath(); AssetUtil.copyAssetFolder(assets, "templates/src/main/res", resourcePath); File file = new File(resourcePath, "values/styles.xml"); String content = FileManager.streamToString(new FileInputStream(file)).toString(); content = content.replace("{APP_STYLE}", useAppCompat ? "Theme.AppCompat.Light" : "@android:style/Theme.Holo.Light"); FileManager.saveFile(file, content); } private void copyLibrary(AndroidProjectFolder projectFile, AssetManager assets) { //copy android support library AssetUtil.copyAssetFolder(assets, "templates/libs", projectFile.dirLibs.getPath()); } private void copyKeyStore(AndroidProjectFolder projectFile, AssetManager assets) throws IOException { //copy keystore File file = projectFile.getKeyStore().getFile(); FileOutputStream out = new FileOutputStream(file); FileManager.copyStream(assets.open("templates/src/main/androiddebug.jks"), out); out.close(); } private void createStringXml(AndroidProjectFolder projectFile, String appName) throws Exception { File stringxml = new File(projectFile.getDirRes(), "values/strings.xml"); String strings = FileManager.streamToString(new FileInputStream( stringxml)).toString(); strings = strings.replace("{APP_NAME}", appName); strings = strings.replace("{MAIN_ACTIVITY_NAME}", appName); Log.d(TAG, "doCreateProject strings = " + strings); FileManager.saveFile(stringxml, strings); } private void createManifest(AndroidProjectFolder projectFile, String activityClass, String packageName, AssetManager assets) throws IOException { File manifest = projectFile.getXmlManifest(); InputStream manifestTemplate = assets.open("templates/src/main/AndroidManifest.xml"); String contentManifest = FileManager.streamToString(manifestTemplate).toString(); contentManifest = contentManifest.replace("{PACKAGE}", packageName); contentManifest = contentManifest.replace("{MAIN_ACTIVITY}", activityClass); Log.d(TAG, "doCreateProject contentManifest = " + contentManifest); FileManager.saveFile(manifest, contentManifest); } private void createMainActivity(AndroidProjectFolder projectFile, String activityClass, String packageName, String activityName, String appName, boolean useAppCompat, AssetManager assets) throws IOException { File activityFile = FileManager.createFileIfNeed(new File(projectFile.dirJava, activityClass.replace(".", File.separator) + ".java")); String name = useAppCompat ? "templates/src/main/MainActivityAppCompat.java" : "templates/src/main/MainActivity.java"; InputStream activityTemplate = assets.open(name); String contentClass = FileManager.streamToString(activityTemplate).toString(); contentClass = contentClass.replace("{PACKAGE}", packageName); contentClass = contentClass.replace("{APP_NAME}", appName); contentClass = contentClass.replace("{ACTIVITY_NAME}", activityName); Log.d(TAG, "doCreateProject contentManifest = " + contentClass); FileManager.saveFile(activityFile, contentClass); } private void createMainXml(AndroidProjectFolder projectFile, String mainLayoutName, AssetManager assets) throws IOException { if (!mainLayoutName.contains(".")) mainLayoutName += ".xml"; File layoutMain = new File(projectFile.getDirLayout(), mainLayoutName); layoutMain.createNewFile(); InputStream layoutTemplate = assets.open("templates/src/main/activity_main.xml"); String contentLayout = FileManager.streamToString(layoutTemplate).toString(); FileManager.saveFile(layoutMain, contentLayout); } /** * check input data * * @return true if all is ok */ private boolean isOk() { //check app name if (editAppName.getText().toString().isEmpty()) { editAppName.setError(getString(R.string.enter_name)); return false; } String packageName = editPackage.getText().toString(); if (packageName.isEmpty()) { editPackage.setError(getString(R.string.enter_package)); return false; } if (!packageName.contains(".")) { editPackage.setError("Invalid package name: The package name must be least one '.' separator"); return false; } if (!Patterns.PACKAGE_NAME.matcher(packageName).find()) { editPackage.setError("Invalid package name"); return false; } //check activity name String activityName = this.mActivityName.getText().toString(); if (activityName.isEmpty()) { this.mActivityName.setError(getString(R.string.enter_name)); return false; } if (!Patterns.RE_IDENTIFIER.matcher(activityName).find()) { this.mActivityName.setText("Invalid name"); return false; } //check layout name if (layoutName.getText().toString().isEmpty()) { layoutName.setError(getString(R.string.enter_name)); return false; } if (!Patterns.RE_IDENTIFIER.matcher(layoutName.getText().toString()).find()) { layoutName.setText("Invalid name"); return false; } return true; } } <file_sep>/app/src/main/java/com/duy/ide/activities/InstallActivity.java package com.duy.ide.activities; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.AssetManager; import android.net.ConnectivityManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AlertDialog; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.duy.ide.R; import com.duy.ide.file.FileManager; import com.duy.ide.setting.AppSetting; import com.jecelyin.android.file_explorer.FileExplorerActivity; import org.apache.commons.io.IOUtils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import static android.os.Environment.DIRECTORY_DOWNLOADS; /** * Created by Duy on 16-Jul-17. */ public class InstallActivity extends AbstractAppCompatActivity implements View.OnClickListener { public static final String SYSTEM_VERSION = "System v3.0"; private static final int REQUEST_CODE_SELECT_FILE = 1101; private AppSetting mPreferences; private ProgressBar mProgressBar; private TextView mInfo; private Button mInstallButton; // private TextView mTxtVersion; private ProgressDialog progressDialog; private boolean mIsInstalling = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_install); setupToolbar(); setTitle(R.string.install); mPreferences = new AppSetting(this); mProgressBar = findViewById(R.id.progress_bar); mInfo = findViewById(R.id.txt_info); mInstallButton = findViewById(R.id.btn_install); // mTxtVersion = (TextView) findViewById(R.id.txt_version); // String version = getString(R.string.system_version) + mPreferences.getSystemVersion(); // mTxtVersion.setText(version); findViewById(R.id.btn_install).setOnClickListener(this); findViewById(R.id.btn_select_file).setOnClickListener(this); findViewById(R.id.down_load_from_github).setOnClickListener(this); extractFileFromAsset(); } @Override public void onClick(View v) { /* if (v.getId() == R.id.btn_install) { if (isConnected()) { downloadFile(); } else { showDialogNotConnect(); } } else if (v.getId() == R.id.btn_select_file) { selectFile(); } else if (v.getId() == R.id.down_load_from_github) { downloadFromGit(); }*/ } private void extractFileFromAsset() { new CopyFromAssetTask(this).execute(); } private void downloadFromGit() { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.classes_link))); try { startActivity(intent); } catch (Exception e) { Toast.makeText(this, "No browser installed", Toast.LENGTH_SHORT).show(); } } private void selectFile() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); FileExplorerActivity.startPickFileActivity(this, Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS).getPath(), REQUEST_CODE_SELECT_FILE, null); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_CODE_SELECT_FILE: if (resultCode == RESULT_OK) { File file = new File(FileExplorerActivity.getFile(data)); new InstallTask(this).execute(file); } break; } } private void showDialogError(Exception e) { if (isFinishing()) return; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.error); builder.setMessage(e == null ? " " : e.getMessage()); builder.create().show(); } private boolean isConnected() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); return cm.getActiveNetworkInfo() != null; } private void showDialogNotConnect() { } private void showDialogSuccess() { if (isFinishing()) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.success); builder.setPositiveButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); setResult(RESULT_OK); finish(); } }); builder.create().show(); } private void showDialogFailed(Exception error) { if (isFinishing()) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.error); builder.setMessage(error.getMessage()); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.create().show(); } @Override public void onBackPressed() { if (!mIsInstalling) { super.onBackPressed(); } } private void showDialogDownload() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Download system"); } private void installFailed() { Toast.makeText(this, "Install failed", Toast.LENGTH_SHORT).show(); } private class InstallTask extends AsyncTask<File, String, Boolean> { private Exception error = null; private Context context; public InstallTask(Context context) { this.context = context; } @Override protected void onPreExecute() { super.onPreExecute(); mInfo.setText(R.string.start_install_system); mProgressBar.setIndeterminate(true); mInstallButton.setEnabled(false); mIsInstalling = true; } @Override protected Boolean doInBackground(File... params) { try { File zip = params[0]; File outputDir = FileManager.getSdkDir(context); unzipArchive(zip, outputDir); zip.delete(); if (!(FileManager.isSdkInstalled(context))) { throw new RuntimeException("Install failed, Not a classes.zip file"); } } catch (Exception e) { publishProgress("Error when install system"); e.printStackTrace(); error = e; return false; } publishProgress("System install complete!"); return true; } @Override protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); mInfo.setText(values[0]); } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if (result) { showDialogSuccess(); } else { showDialogFailed(error); } mInstallButton.setEnabled(true); mProgressBar.setIndeterminate(false); mIsInstalling = false; } public void unzipArchive(File archive, File outputDir) { try { ZipFile zipfile = new ZipFile(archive); for (Enumeration e = zipfile.entries(); e.hasMoreElements(); ) { ZipEntry entry = (ZipEntry) e.nextElement(); unzipEntry(zipfile, entry, outputDir); } } catch (Exception e) { e.printStackTrace(); } } private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(inputStream, outputStream); } finally { outputStream.close(); inputStream.close(); } } private void createDir(File dir) { if (!dir.mkdirs()) throw new RuntimeException("Can not create dir " + dir); } } private class CopyFromAssetTask extends AsyncTask<File, String, File> { private Context context; public CopyFromAssetTask(Context context) { this.context = context; } @Override protected void onPreExecute() { super.onPreExecute(); mInfo.setText(R.string.copy_from_asset); mProgressBar.setIndeterminate(true); mInstallButton.setEnabled(false); mIsInstalling = true; } @Override protected File doInBackground(File... params) { try { AssetManager assets = context.getAssets(); InputStream open = assets.open("android-21/android-21.zip"); File outFile = new File(getFilesDir(), "classes.zip"); FileOutputStream fileOutputStream = new FileOutputStream(outFile); FileManager.copyStream(open, fileOutputStream); fileOutputStream.close(); return outFile; } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(File file) { super.onPostExecute(file); if (file != null) { new InstallTask(context).execute(file); } else { installFailed(); } } } } <file_sep>/app/src/main/java/com/duy/ide/editor/code/highlight/HighlightImpl.java package com.duy.ide.editor.code.highlight; import com.duy.ide.themefont.themes.database.CodeTheme; /** * Created by Duy on 06-Aug-17. */ public abstract class HighlightImpl implements Highlighter { protected CodeTheme codeTheme; public CodeTheme getCodeTheme() { return codeTheme; } @Override public void setCodeTheme(CodeTheme codeTheme) { this.codeTheme = codeTheme; } @Override public void setErrorRange(long startPosition, long endPosition) { } } <file_sep>/settings.gradle include ':app', ':splitview', ':colorpicker', ':pager', ':treeview', ':dx', ':manifest_merger', ':javacodeformatter', ':javacompiler', ':gitforandroid', ':androidlogcat', ':fileexplorer', ':common', ':styles' <file_sep>/app/src/test/java/com/duy/builder/AaptTest.java package com.duy.builder; import junit.framework.TestCase; /** * Created by Duy on 22-Aug-17. */ public class AaptTest extends TestCase { public void test() { } } <file_sep>/fileexplorer/src/main/java/com/jecelyin/android/file_explorer/util/RootUtils.java /* * Copyright (C) 2016 <NAME> <<EMAIL>> * * This file is part of 920 Text Editor. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jecelyin.android.file_explorer.util; import android.text.TextUtils; import com.jecelyin.common.utils.L; import com.stericson.RootShell.RootShell; import com.stericson.RootShell.execution.Command; import com.stericson.RootShell.execution.Shell; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; /** * @author <NAME> <<EMAIL>> */ public class RootUtils { private static final String TAG = "RootUtils"; public static void commandWait(Shell shell, Command cmd) throws Exception { while (!cmd.isFinished()) { synchronized (cmd) { try { if (!cmd.isFinished()) { cmd.wait(2000); } } catch (InterruptedException e) { e.printStackTrace(); } } if (!cmd.isExecuting() && !cmd.isFinished()) { if (!shell.isExecuting && !shell.isReading) { Exception e = new Exception(); e.setStackTrace(Thread.currentThread().getStackTrace()); e.printStackTrace(); L.d(TAG, "Waiting for a command to be executed in a shell that is not executing and not reading! \n\n Command: " + cmd.getCommand(), e); } else if (shell.isExecuting && !shell.isReading) { Exception e = new Exception(); e.setStackTrace(Thread.currentThread().getStackTrace()); e.printStackTrace(); L.d(TAG, "Waiting for a command to be executed in a shell that is executing but not reading! \n\n Command: " + cmd.getCommand(), e); } else { Exception e = new Exception(); e.setStackTrace(Thread.currentThread().getStackTrace()); e.printStackTrace(); L.d(TAG, "Waiting for a command to be executed in a shell that is not reading! \n\n Command: " + cmd.getCommand(), e); } } } } public static String getRealPath(String file) { List<String> paths = new ArrayList<>(); File parent = new File(file); do { paths.add(parent.getName()); } while ((parent = parent.getParentFile()) != null); List<FileInfo> infos; FileInfo fi; String path; StringBuilder sb = new StringBuilder(); for (int i = paths.size() - 1; i >= 0; i--) { path = paths.get(i); if ("/".equals(path)) { continue; } sb.append("/").append(path); infos = listFileInfo(sb.toString()); if (infos.isEmpty()) break; fi = infos.get(0); if (fi.isSymlink) { sb.setLength(0); sb.append(fi.linkedPath); } } return sb.toString(); } public static List<FileInfo> listFileInfo(String path) { final List<String> result = new ArrayList<>(); final List<FileInfo> files = new ArrayList<>(); Command command = new Command(0, false, "ls -la \"" + path + "\"") { @Override public void commandOutput(int id, String line) { RootShell.log(line); result.add(line); super.commandOutput(id, line); } }; try { //Try without root... Shell shell = RootShell.getShell(true); shell.add(command); RootUtils.commandWait(shell, command); } catch (Exception e) { L.e(e); return files; } for (String line : result) { line = line.trim(); // lstat '//persist' failed: Permission denied if (line.startsWith("lstat \'" + path) && line.contains("\' failed: Permission denied")) { line = line.replace("lstat \'" + path, ""); line = line.replace("\' failed: Permission denied", ""); if (line.startsWith("/")) { line = line.substring(1); } FileInfo failedToRead = new FileInfo(false, line); files.add(failedToRead); continue; } // /data/data/com.android.shell/files/bugreports: No such file or directory if (line.startsWith("/") && line.contains(": No such file")) { continue; } try { files.add(lsParser(path, line)); } catch (Exception e) { L.e("parse line error: " + line, e); } } result.clear(); return files; } private static FileInfo lsParser(String path, String line) { final String[] split = line.split(" "); int index = 0; FileInfo file = new FileInfo(false, ""); String date = ""; String time = ""; //drwxrwx--x 3 root sdcard_rw 4096 2016-12-17 15:02 obb for (String token : split) { if (token.trim().isEmpty()) continue; switch (index) { case 0: { file.permissions = token; break; } case 1: { if (TextUtils.isDigitsOnly(token)) continue; file.owner = token; break; } case 2: { file.group = token; break; } case 3: { if (token.contains("-")) { // No length, this is the date file.size = -1; date = token; } else if (token.contains(",")) { //In /dev, ls lists the major and minor device numbers file.size = -2; } else { // Length, this is a file try { file.size = Long.parseLong(token); } catch (Exception e) { throw new NumberFormatException(e.getMessage() + " Line: " + line); } } break; } case 4: { if (file.size == -1) { // This is the time time = token; } else { // This is the date date = token; } break; } case 5: { if (file.size == -2) { date = token; } else if (file.size > -1) { time = token; } break; } case 6: if (file.size == -2) { time = token; } break; } index++; } if (line.length() > 0) { final String nameAndLink = line.substring(line.indexOf(time) + time.length() + 1); if (nameAndLink.contains(" -> ")) { final String[] splitSl = nameAndLink.split(" -> "); file.name = splitSl[0].trim(); String realPath = splitSl[1].trim(); if (realPath.charAt(0) != '/') { file.linkedPath = new File(path).getParent() + "/" + realPath; } else { file.linkedPath = realPath; } } else { file.name = nameAndLink; } } try { file.lastModified = new SimpleDateFormat("yyyy-MM-ddHH:mm", Locale.getDefault()) .parse(date + time).getTime(); } catch (Exception e) { // L.e(e); //ignore: java.text.ParseException: Unparseable date: "" file.lastModified = 0; } file.readAvailable = true; file.directoryFileCount = ""; char type = file.permissions.charAt(0); if (type == 'd') { file.isDirectory = true; } else if (type == 'l') { file.isSymlink = true; String linkPath = file.linkedPath; for (; ; ) { List<FileInfo> fileInfos = listFileInfo(linkPath); if (fileInfos.isEmpty()) break; FileInfo fi = fileInfos.get(0); if (!fi.isSymlink) { file.isDirectory = fi.isDirectory; break; } linkPath = fi.linkedPath; } } return file; } public static class RootCommand extends Command { private StringBuilder stringBuilder; public RootCommand(String commandFormat, Object... args) { super(0, true, String.format(commandFormat, args)); stringBuilder = new StringBuilder(); } @Override public void commandOutput(int id, String line) { stringBuilder.append(line).append("\n"); super.commandOutput(id, line); } @Override public void commandCompleted(int id, int exitcode) { super.commandCompleted(id, exitcode); onFinish(exitcode == 0, stringBuilder.toString()); } public void onFinish(boolean success, String output) { } } } <file_sep>/app/src/main/java/com/duy/project/activities/FileManagerActivity.java package com.duy.project.activities; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import com.duy.ide.R; import com.duy.ide.activities.AbstractAppCompatActivity; public class FileManagerActivity extends AbstractAppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_file); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); } }<file_sep>/system/classes/Readme.MD 1. android.jar - Android 19 platform 2. android-support-v4.aar - support-v4-26.0.0-alpha1.aar 3. android-support-v4.jar - support-v4-26.0.0-alpha1-sources.jar 4. android-support-v7.aar - appcompat-v7-26.0.0-alpha1.aar 5. android-support-v7.jar - appcompat-v7-26.0.0-alpha1-sources.jar<file_sep>/app/src/main/java/com/duy/run/activities/ExecuteActivity.java package com.duy.run.activities; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.annotation.WorkerThread; import android.support.v7.app.AlertDialog; import android.util.Log; import com.duy.JavaApplication; import com.duy.compile.CompileManager; import com.duy.compile.external.CompileHelper; import com.duy.ide.R; import com.duy.ide.activities.AbstractAppCompatActivity; import com.duy.project.file.java.JavaProjectFolder; import com.duy.run.view.ConsoleEditText; import java.io.File; import java.io.InputStream; /** * Created by Duy on 30-Jul-17. */ public class ExecuteActivity extends AbstractAppCompatActivity { private static final int RUN_TIME_ERR = 1; private static final String TAG = "ExecuteActivity"; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case RUN_TIME_ERR: Exception exception = (Exception) msg.obj; showDialogError(exception.getMessage()); break; } } }; private ConsoleEditText mConsoleEditText; private void showDialogError(String message) { if (isFinishing()) return; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(message).setPositiveButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.create().show(); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_exec); setupToolbar(); bindView(); initInOut(); final Intent intent = getIntent(); if (intent != null) { final JavaProjectFolder projectFile = (JavaProjectFolder) intent.getSerializableExtra(CompileManager.PROJECT_FILE); if (projectFile == null) { finish(); return; } final int action = intent.getIntExtra(CompileManager.ACTION, -1); setTitle(projectFile.getMainClass().getSimpleName()); Thread runThread = new Thread(new Runnable() { @Override public void run() { try { runProgram(ExecuteActivity.this, projectFile, action, intent); } catch (Error error) { error.printStackTrace(mConsoleEditText.getErrorStream()); } catch (Exception e) { e.printStackTrace(mConsoleEditText.getErrorStream()); } catch (Throwable e) { e.printStackTrace(mConsoleEditText.getErrorStream()); } } }); runThread.start(); } else { finish(); } } private void initInOut() { JavaApplication application = (JavaApplication) getApplication(); application.addStdErr(mConsoleEditText.getErrorStream()); application.addStdOut(mConsoleEditText.getOutputStream()); } @WorkerThread private void runProgram(Context context, JavaProjectFolder projectFile, int action, Intent intent) throws Exception { InputStream in = mConsoleEditText.getInputStream(); File tempDir = getDir("dex", MODE_PRIVATE); switch (action) { case CompileHelper.Action.RUN: { CompileHelper.compileAndRun(context, in, tempDir, projectFile); break; } case CompileHelper.Action.RUN_DEX: { File dex = (File) intent.getSerializableExtra(CompileManager.DEX_FILE); if (dex != null) { String mainClass = projectFile.getMainClass().getName(); CompileHelper.executeDex(context, in, dex, tempDir, mainClass); } break; } } } @Override protected void onStop() { super.onStop(); Log.d(TAG, "onStop() called"); mConsoleEditText.stop(); JavaApplication application = (JavaApplication) getApplication(); application.removeErrStream(mConsoleEditText.getErrorStream()); application.removeOutStream(mConsoleEditText.getOutputStream()); } @Override protected void onDestroy() { super.onDestroy(); } private void bindView() { mConsoleEditText = (ConsoleEditText) findViewById(R.id.console_view); } } <file_sep>/app/src/test/java/com/duy/ide/autocomplete/autocomplete/TestJavacParser.java package com.duy.ide.autocomplete.autocomplete; import com.google.common.collect.ImmutableList; import com.sun.tools.javac.file.JavacFileManager; import com.sun.tools.javac.parser.Parser; import com.sun.tools.javac.parser.ParserFactory; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Log; import com.sun.tools.javac.util.Options; import junit.framework.TestCase; import java.io.File; import java.io.IOError; import java.io.IOException; import java.net.URI; import javax.tools.DiagnosticCollector; import javax.tools.DiagnosticListener; import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; import javax.tools.StandardLocation; import static com.google.common.base.Charsets.UTF_8; /** * Created by Duy on 15-Aug-17. */ public class TestJavacParser extends TestCase { private String src = "package com.duy.project.view.dialog;\n" + "\n" + "import android.app.Activity;\n" + "import android.app.Dialog;\n" + "import android.content.Context;\n" + "import android.os.AsyncTask;\n" + "import android.os.Bundle;\n" + "import android.support.annotation.NonNull;\n" + "import android.support.annotation.Nullable;\n" + "import android.support.design.widget.TextInputLayout;\n" + "import android.support.v4.widget.SwipeRefreshLayout;\n" + "import android.support.v7.app.AlertDialog;\n" + "import android.support.v7.app.AppCompatDialogFragment;\n" + "import android.support.v7.widget.DividerItemDecoration;\n" + "import android.support.v7.widget.LinearLayoutManager;\n" + "import android.support.v7.widget.RecyclerView;\n" + "import android.text.TextUtils;\n" + "import android.view.LayoutInflater;\n" + "import android.view.View;\n" + "import android.view.ViewGroup;\n" + "import android.view.Window;\n" + "import android.view.WindowManager;\n" + "import android.widget.Button;\n" + "import android.widget.EditText;\n" + "import android.widget.TextView;\n" + "import android.widget.Toast;\n" + "\n" + "import com.duy.ide.R;\n" + "import com.duy.ide.file.FileManager;\n" + "import com.duy.ide.file.FileSelectListener;\n" + "import com.duy.ide.file.PreferenceHelper;\n" + "import com.duy.ide.file.adapter.FileAdapterListener;\n" + "import com.duy.ide.file.adapter.FileDetail;\n" + "import com.duy.ide.file.adapter.FileListAdapter;\n" + "import com.duy.ide.utils.Build;\n" + "\n" + "import org.apache.commons.io.FileUtils;\n" + "import org.apache.commons.io.FilenameUtils;\n" + "\n" + "import java.io.File;\n" + "import java.text.SimpleDateFormat;\n" + "import java.util.LinkedList;\n" + "import java.util.Locale;\n" + "\n" + "/**\n" + " * Created by Duy on 17-Jul-17.\n" + " */\n" + "\n" + "public class DialogSelectDirectory extends AppCompatDialogFragment implements View.OnClickListener, View.OnLongClickListener,\n" + " SwipeRefreshLayout.OnRefreshListener, FileAdapterListener {\n" + " public static final String TAG = \"DialogSelectDirectory\";\n" + "\n" + " private FileSelectListener listener;\n" + " private RecyclerView listFiles;\n" + " private Activity activity;\n" + " private String currentFolder;\n" + " private boolean wantAFile = false;\n" + " private SwipeRefreshLayout swipeRefreshLayout;\n" + " @Nullable\n" + " private FileListAdapter mAdapter;\n" + " private TextView txtPath;\n" + " private int request;\n" + "\n" + " public static DialogSelectDirectory newInstance(String path, int request) {\n" + "\n" + " Bundle args = new Bundle();\n" + " args.putString(\"path\", path);\n" + " args.putInt(\"request\", request);\n" + " DialogSelectDirectory fragment = new DialogSelectDirectory();\n" + " fragment.setArguments(args);\n" + " return fragment;\n" + " }\n" + "\n" + " @Override\n" + " public void onResume() {\n" + " super.onResume();\n" + " }\n" + "\n" + " @Override\n" + " public void onAttach(Context context) {\n" + " super.onAttach(context);\n" + " try {\n" + " listener = (FileSelectListener) getActivity();\n" + " } catch (Exception ignored) {\n" + "\n" + " }\n" + " activity = getActivity();\n" + " request = getArguments().getInt(\"request\");\n" + " }\n" + "\n" + " @Override\n" + " public void onStart() {\n" + " super.onStart();\n" + " Dialog dialog = getDialog();\n" + " if (dialog != null) {\n" + " Window window = dialog.getWindow();\n" + " if (window != null) window.setLayout(WindowManager.LayoutParams.MATCH_PARENT,\n" + " WindowManager.LayoutParams.MATCH_PARENT);\n" + " }\n" + " }\n" + "\n" + " @Nullable\n" + " @Override\n" + " public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n" + " return inflater.inflate(R.layout.dialog_choose_file, container, false);\n" + " }\n" + "\n" + " @Override\n" + " public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {\n" + " super.onViewCreated(view, savedInstanceState);\n" + "\n" + " currentFolder = getArguments().getString(\"path\", FileManager.EXTERNAL_DIR);\n" + " wantAFile = false;\n" + "\n" + " bindView(view);\n" + "\n" + " //load file\n" + " new UpdateList(currentFolder).execute();\n" + " }\n" + "\n" + " private void bindView(View view) {\n" + " listFiles = view.findViewById(R.id.list_file);\n" + " listFiles.setHasFixedSize(true);\n" + " listFiles.setLayoutManager(new LinearLayoutManager(activity));\n" + " listFiles.addItemDecoration(new DividerItemDecoration(getContext(),\n" + " DividerItemDecoration.VERTICAL));\n" + "\n" + " swipeRefreshLayout = view.findViewById(R.id.refresh_view);\n" + " swipeRefreshLayout.setOnRefreshListener(this);\n" + "\n" + " view.findViewById(R.id.action_new_folder).setOnClickListener(this);\n" + " txtPath = view.findViewById(R.id.txt_path);\n" + " view.findViewById(R.id.btn_select).setOnClickListener(new View.OnClickListener() {\n" + " @Override\n" + " public void onClick(View view) {\n" + " if (listener != null) {\n" + " listener.onFileSelected(new File(currentFolder), request);\n" + " dismiss();\n" + " }\n" + " }\n" + " });\n" + " }\n" + "\n" + " private void createNewFolder() {\n" + " AlertDialog.Builder builder = new AlertDialog.Builder(activity);\n" + " builder.setTitle(R.string.new_folder);\n" + " builder.setView(R.layout.dialog_new_file);\n" + " final AlertDialog alertDialog = builder.create();\n" + " alertDialog.show();\n" + " final EditText editText = (EditText) alertDialog.findViewById(R.id.edit_file_name);\n" + " final TextInputLayout textInputLayout = (TextInputLayout) alertDialog.findViewById(R.id.hint);\n" + " assert textInputLayout != null;\n" + " textInputLayout.setHint(getString(R.string.enter_new_folder_name));\n" + " Button btnOK = null;\n" + "// btnOK = (Button) alertDialog.findViewById(R.id.btn_ok);\n" + " Button btnCancel = (Button) alertDialog.findViewById(R.id.btn_cancel);\n" + " btnCancel.setOnClickListener(new View.OnClickListener() {\n" + " @Override\n" + " public void onClick(View v) {\n" + " alertDialog.cancel();\n" + " }\n" + " });\n" + " btnOK.setOnClickListener(new View.OnClickListener() {\n" + " @Override\n" + " public void onClick(View v) {\n" + " //get string path of in edit text\n" + " String fileName = editText != null ? editText.getText().toString() : null;\n" + " if (fileName.isEmpty()) {\n" + " editText.setError(getString(R.string.enter_new_file_name));\n" + " return;\n" + " }\n" + " //create new file\n" + " File file = new File(currentFolder, fileName);\n" + " file.mkdirs();\n" + " new UpdateList(currentFolder).execute();\n" + " alertDialog.cancel();\n" + " }\n" + " });\n" + "\n" + " }\n" + "\n" + " @Override\n" + " public void onClick(View v) {\n" + " int i = v.getId();\n" + " if (i == R.id.action_new_folder) {\n" + " createNewFolder();\n" + " }\n" + " }\n" + "\n" + " @Override\n" + " public boolean onLongClick(View v) {\n" + " return false;\n" + " }\n" + "\n" + " @Override\n" + " public void onRefresh() {\n" + " new UpdateList(currentFolder).execute();\n" + " }\n" + "\n" + " @Override\n" + " public void onItemClick(View v, String name, int action) {\n" + " if (action == ACTION_LONG_CLICK) {\n" + " if (name.equals(\"..\")) {\n" + " if (currentFolder.equals(\"/\")) {\n" + " new UpdateList(PreferenceHelper.getWorkingFolder(activity)).execute();\n" + " } else {\n" + " File tempFile = new File(currentFolder);\n" + " if (tempFile.isFile()) {\n" + " tempFile = tempFile.getParentFile()\n" + " .getParentFile();\n" + " } else {\n" + " tempFile = tempFile.getParentFile();\n" + " }\n" + " new UpdateList(tempFile.getAbsolutePath()).execute();\n" + " }\n" + " } else if (name.equals(getString(R.string.home))) {\n" + " // TODO: 14-Mar-17\n" + " new UpdateList(PreferenceHelper.getWorkingFolder(activity)).execute();\n" + " }\n" + "\n" + "// final File selectedFile = new File(currentFolder, name);\n" + "\n" + "// if (selectedFile.isFile() && wantAFile) {\n" + "// // TODO: 15-Mar-17\n" + "// if (listener != null) listener.onFileLongClick(selectedFile);\n" + "// } else if (selectedFile.isDirectory()) {\n" + "// }\n" + " } else if (action == ACTION_CLICK) {\n" + " if (name.equals(\"..\")) {\n" + " if (currentFolder.equals(\"/\")) {\n" + " new UpdateList(PreferenceHelper.getWorkingFolder(activity)).execute();\n" + " } else {\n" + " File tempFile = new File(currentFolder);\n" + " if (tempFile.isFile()) {\n" + " tempFile = tempFile.getParentFile()\n" + " .getParentFile();\n" + " } else {\n" + " tempFile = tempFile.getParentFile();\n" + " }\n" + " new UpdateList(tempFile.getAbsolutePath()).execute();\n" + " }\n" + " return;\n" + " } else if (name.equals(getString(R.string.home))) {\n" + " // TODO: 14-Mar-17\n" + " new UpdateList(PreferenceHelper.getWorkingFolder(activity)).execute();\n" + " return;\n" + " }\n" + "\n" + " final File selectedFile = new File(currentFolder, name);\n" + "//\n" + "// if (selectedFile.isFile() && wantAFile) {\n" + "// // TODO: 15-Mar-17\n" + "// if (listener != null) listener.onFileSelected(selectedFile, request);\n" + "// } else if (selectedFile.isDirectory()) {\n" + " new UpdateList(selectedFile.getAbsolutePath()).execute();\n" + "// }\n" + " }\n" + " }\n" + "\n" + "\n" + " public void refresh() {\n" + " new UpdateList(currentFolder).execute();\n" + " }\n" + "\n" + " @Override\n" + " public void onRemoveClick(View view, String name, int action) {\n" + " Toast.makeText(activity, \"Don't support this action\", Toast.LENGTH_SHORT).show();\n" + " }\n" + "\n" + "\n" + " private class UpdateList extends AsyncTask<Void, Void, LinkedList<FileDetail>> {\n" + " private String path;\n" + " private String exceptionMessage;\n" + "\n" + " public UpdateList(@NonNull String path) {\n" + " this.path = path;\n" + " }\n" + "\n" + " @Override\n" + " protected void onPreExecute() {\n" + " super.onPreExecute();\n" + " txtPath.setText(path);\n" + " }\n" + "\n" + " @Override\n" + " protected LinkedList<FileDetail> doInBackground(final Void... params) {\n" + " try {\n" + " if (TextUtils.isEmpty(path)) {\n" + " return null;\n" + " }\n" + "\n" + " File tempFolder = new File(path);\n" + " if (tempFolder.isFile()) {\n" + " tempFolder = tempFolder.getParentFile();\n" + " }\n" + "\n" + " String[] canOpen = {\"java\", \"class\", \"jar\"};\n" + "\n" + " final LinkedList<FileDetail> fileDetails = new LinkedList<>();\n" + " final LinkedList<FileDetail> folderDetails = new LinkedList<>();\n" + " currentFolder = tempFolder.getAbsolutePath();\n" + "\n" + " if (!tempFolder.canRead()) {\n" + "\n" + " } else {\n" + " File[] files = tempFolder.listFiles();\n" + " for (final File f : files) {\n" + " if (f.isDirectory() && !f.getName().equalsIgnoreCase(\"fonts\")) {\n" + " folderDetails.add(new FileDetail(f.getName(), getString(R.string.folder), \"\"));\n" + " } else if (f.isFile()\n" + " && FilenameUtils.isExtension(f.getName().toLowerCase(), canOpen)\n" + " && FileUtils.sizeOf(f) <= Build.MAX_FILE_SIZE * FileUtils.ONE_KB) {\n" + " final long fileSize = f.length();\n" + " SimpleDateFormat format = new SimpleDateFormat(\"MMM dd, yyyy hh:mm a\", Locale.getDefault());\n" + " String date = format.format(f.lastModified());\n" + " fileDetails.add(new FileDetail(f.getName(),\n" + "\n" + "\n" + " @Override\n" + " protected void onPostExecute(final LinkedList<FileDetail> names) {\n" + " if (names != null) {\n" + " boolean isRoot = currentFolder.equals(\"/\");\n" + " }\n" + " super.onPostExecute(names);\n" + " }\n" + " }\n" + "\n" + "\n" + "}"; public void test1() { Context context = new Context(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); context.put(DiagnosticListener.class, diagnostics); Options.instance(context).put("allowStringFolding", "false"); JCTree.JCCompilationUnit unit; JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8); try { fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of()); } catch (IOException e) { // impossible throw new IOError(e); } SimpleJavaFileObject source = new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) { @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return src; } }; Log.instance(context).useSource(source); ParserFactory parserFactory = ParserFactory.instance(context); Parser parser = parserFactory.newParser( src, /*keepDocComments=*/ true, /*keepEndPos=*/ true, /*keepLineMap=*/ true); unit = parser.parseCompilationUnit(); unit.sourcefile = source; } public void test4() { Context context = new Context(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); context.put(DiagnosticListener.class, diagnostics); Options.instance(context).put("allowStringFolding", "false"); JCTree.JCCompilationUnit unit; JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8); try { fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of()); } catch (IOException e) { // impossible throw new IOError(e); } SimpleJavaFileObject source = new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) { @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return src; } }; Log.instance(context).useSource(source); ParserFactory parserFactory = ParserFactory.instance(context); Parser parser = parserFactory.newParser( src, /*keepDocComments=*/ true, /*keepEndPos=*/ true, /*keepLineMap=*/ true); unit = parser.parseCompilationUnit(); unit.sourcefile = source; } public void test3() { Context context = new Context(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); context.put(DiagnosticListener.class, diagnostics); Options.instance(context).put("allowStringFolding", "false"); JCTree.JCCompilationUnit unit; JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8); try { fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of()); } catch (IOException e) { // impossible throw new IOError(e); } SimpleJavaFileObject source = new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) { @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return src; } }; Log.instance(context).useSource(source); ParserFactory parserFactory = ParserFactory.instance(context); Parser parser = parserFactory.newParser( src, /*keepDocComments=*/ true, /*keepEndPos=*/ true, /*keepLineMap=*/ true); unit = parser.parseCompilationUnit(); unit.sourcefile = source; } public void test2() { Context context = new Context(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); context.put(DiagnosticListener.class, diagnostics); Options.instance(context).put("allowStringFolding", "false"); JCTree.JCCompilationUnit unit; JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8); try { fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of()); } catch (IOException e) { // impossible throw new IOError(e); } SimpleJavaFileObject source = new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) { @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return src; } }; Log.instance(context).useSource(source); ParserFactory parserFactory = ParserFactory.instance(context); Parser parser = parserFactory.newParser( src, /*keepDocComments=*/ true, /*keepEndPos=*/ true, /*keepLineMap=*/ true); unit = parser.parseCompilationUnit(); unit.sourcefile = source; } }<file_sep>/app/src/main/java/com/duy/ide/activities/DonateActivity.java package com.duy.ide.activities; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.view.View; import android.widget.Toast; import com.duy.ide.BuildConfig; import com.duy.ide.DLog; import com.duy.ide.R; import com.google.firebase.analytics.FirebaseAnalytics; import aidl.util.IabBroadcastReceiver; import aidl.util.IabHelper; import aidl.util.IabResult; import aidl.util.Inventory; import aidl.util.Purchase; import static com.duy.ide.utils.DonateUtils.REQUEST_DONATE; /** * Created by Duy on 11-Aug-17. */ public class DonateActivity extends AbstractAppCompatActivity implements IabBroadcastReceiver.IabBroadcastListener, View.OnClickListener { private static final String SKU_DONATE_ONE = "java_nide_donate_one_dollar"; private static final String SKU_DONATE_TWO = "java_nide_donate_two_dollar"; private static final String SKU_DONATE_THREE = "java_nide_donate_three_dollar"; private static final String SKU_DONATE_FOUR = "java_nide_donate_four_dollar"; private static final String SKU_DONATE_FIVE = "java_nide_donate_five_dollar"; private static final String TAG = "DonateActivity"; private Handler mHandler = new Handler(); private IabHelper mIabHelper; private IabBroadcastReceiver mBroadcastReceiver; private IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { @Override public void onQueryInventoryFinished(IabResult result, Inventory inv) { if (mIabHelper == null) return; if (result.isFailure()) { iabError(new RuntimeException("Failed to query inventory: " + result)); } DLog.d(TAG, "Query inventory was successful. "); if (inv != null) { Purchase premiumPurchase = inv.getPurchase(SKU_DONATE_ONE); DLog.d(TAG, "onQueryInventoryFinished: " + premiumPurchase); boolean success = premiumPurchase != null && verifyDeveloperPayload(premiumPurchase); if (success) { Toast.makeText(DonateActivity.this, "Thank for donate me", Toast.LENGTH_SHORT).show(); } } } }; private aidl.util.IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() { @Override public void onIabPurchaseFinished(IabResult result, Purchase info) { if (mIabHelper == null) return; if (result.isFailure()) { iabError(new RuntimeException("Error purchasing: " + result)); return; } if (!verifyDeveloperPayload(info)) { iabError(new RuntimeException("Error purchasing. Authenticity verification failed.")); return; } DLog.d(TAG, "Purchase successful."); if (info.getSku().equals(SKU_DONATE_ONE)) { Toast.makeText(DonateActivity.this, "Thank for donate me", Toast.LENGTH_SHORT).show(); } } }; private boolean verifyDeveloperPayload(Purchase premiumPurchase) { String developerPayload = premiumPurchase.getDeveloperPayload(); return true; } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_donate); setupToolbar(); setTitle(R.string.donate_for_project); findViewById(R.id.btn_donate_1).setOnClickListener(this); findViewById(R.id.btn_donate_2).setOnClickListener(this); findViewById(R.id.btn_donate_3).setOnClickListener(this); findViewById(R.id.btn_donate_4).setOnClickListener(this); findViewById(R.id.btn_donate_5).setOnClickListener(this); initIab(); } private void initIab() { String base64Key = "MIIBIjANBgkqhkiG<KEY>IIBCgKCAQEAh+uvYlgvcAOOi9fTL8AUN7KDGq" + "j3diAZ+5V6d5Ovl7QJNMuDJJpUEsMHzj/fpd/NO7k2gevNLGwX1JKM5BhWLDq/FHB8xTHT1yalZ69fhPPN" + "tqCENtdtOTFj4owfzgCSW2TL2gBWzh/JpyBXH9rYyKsgcm5SNg5zA2uCp7Sb5yQDSLFCIiEkrriDPQS0GR" + "c<KEY>hcBiTeFAkyJ1pDdweaiNkcQowR04YOQt/NqF4X6peBs+5a4jzZ6UQWvl/YZ+yxz" + "8<KEY>"; mIabHelper = new IabHelper(this, base64Key); mIabHelper.enableDebugLogging(BuildConfig.DEBUG); mIabHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { @Override public void onIabSetupFinished(IabResult result) { if (!result.isSuccess()) { iabError(null); return; } if (mIabHelper == null) return; mBroadcastReceiver = new IabBroadcastReceiver(DonateActivity.this); IntentFilter intentFilter = new IntentFilter(IabBroadcastReceiver.ACTION); registerReceiver(mBroadcastReceiver, intentFilter); DLog.d(TAG, "onIabSetupFinished: setup success"); try { mIabHelper.queryInventoryAsync(mGotInventoryListener); } catch (Exception e) { iabError(e); } } }); } private void iabError(Exception e) { if (e != null) { Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (!mIabHelper.handleActivityResult(requestCode, resultCode, data)) { } else { DLog.d(TAG, "onActivityResult handled by IABUtil."); } } private void purchase(String sku) { FirebaseAnalytics.getInstance(this).logEvent("purchase" + sku, new Bundle()); String payload = ""; try { mIabHelper.launchPurchaseFlow(this, sku, REQUEST_DONATE, mPurchaseFinishedListener, payload); } catch (Exception e) { iabError(e); } } @Override public void receivedBroadcast() { try { mIabHelper.queryInventoryAsync(mGotInventoryListener); } catch (IabHelper.IabAsyncInProgressException e) { iabError(e); } } @Override protected void onDestroy() { super.onDestroy(); DLog.d(TAG, "onDestroy() called"); if (mBroadcastReceiver != null) { unregisterReceiver(mBroadcastReceiver); } try { if (mIabHelper != null) { mIabHelper.disposeWhenFinished(); mIabHelper = null; } } catch (Exception e) { //iab unregister } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_donate_1: purchase(SKU_DONATE_ONE); break; case R.id.btn_donate_2: purchase(SKU_DONATE_TWO); break; case R.id.btn_donate_3: purchase(SKU_DONATE_THREE); break; case R.id.btn_donate_4: purchase(SKU_DONATE_FOUR); break; case R.id.btn_donate_5: purchase(SKU_DONATE_FIVE); break; } } } <file_sep>/app/src/main/java/com/duy/ide/command/Commander.java package com.duy.ide.command; import java.util.ArrayList; /** * Created by Duy on 20-Dec-17. */ public class Commander implements ICommand { private ArrayList<ICommand> commands = new ArrayList<>(); public void addCommand(ICommand command) { commands.add(command); } public ArrayList<ICommand> getCommands() { return commands; } @Override public boolean execute(Object... params) { for (ICommand command : commands) { boolean execute = command.execute(params); if (!execute) { System.out.printf("Task %s executed with failed result%n", command); return false; } } System.out.println("Task" + this + " executed successful!"); return true; } @Override public String toString() { return super.toString(); } } <file_sep>/app/src/main/java/com/duy/compile/external/android/AndroidBuilder.java package com.duy.compile.external.android; import android.content.Context; import android.util.Log; import com.android.annotations.NonNull; import com.android.sdklib.build.ApkBuilderMain; import com.duy.compile.external.CompileHelper; import com.duy.ide.DLog; import com.duy.ide.file.FileManager; import com.duy.project.file.android.AndroidProjectFolder; import com.duy.project.file.android.KeyStore; import com.sun.tools.javac.main.Main; import java.io.File; import java.util.Arrays; import javax.tools.DiagnosticCollector; import kellinwood.security.zipsigner.ProgressEvent; import kellinwood.security.zipsigner.ZipSigner; import kellinwood.security.zipsigner.optional.CustomKeySigner; import static com.duy.compile.external.android.util.S.dirLibs; public class AndroidBuilder { private static final String TAG = "BuildTask"; private static void buildApk(AndroidProjectFolder projectFile) throws Exception { String[] args = { projectFile.getApkUnsigned().getPath(), "-v", "-u", "-z", projectFile.getResourceFile().getPath(), "-f", projectFile.getDexedClassesFile().getPath() }; DLog.d(TAG, "buildApk args = " + Arrays.toString(args)); ApkBuilderMain.main(args); } public static void build(Context context, AndroidProjectFolder projectFile, @NonNull DiagnosticCollector diagnosticCollector) throws Exception { AndroidBuilder.extractLibrary(projectFile); //create R.java System.out.println("Run aidl"); AndroidBuilder.runAidl(projectFile); System.out.println("Run aapt"); AndroidBuilder.runAapt(context, projectFile); //compile java System.out.println("Compile Java file"); int status = CompileHelper.compileJava(context, projectFile, diagnosticCollector); System.gc(); if (status != Main.EXIT_OK) { System.out.println("Compile error"); throw new RuntimeException("Compile time error!"); } //classes to dex System.out.println("Convert classes to dex"); CompileHelper.convertToDexFormat(context, projectFile); //zip apk System.out.println("Build apk"); AndroidBuilder.buildApk(projectFile); System.out.println("Zip sign"); AndroidBuilder.zipSign(projectFile); System.out.println("Zip align"); AndroidBuilder.zipAlign(); System.out.println("Publish apk"); AndroidBuilder.publishApk(); } private static void extractLibrary(AndroidProjectFolder projectFolder) { File[] files = dirLibs.listFiles(); if (files != null) { for (File lib : files) { if (lib.isFile() && lib.getPath().endsWith(".aar")) { } } } } private static void runAidl(AndroidProjectFolder projectFile) throws Exception { Log.d(TAG, "runAidl() called"); // TODO make aidl.so } private static void runAapt(Context context, AndroidProjectFolder projectFile) throws Exception { Log.d(TAG, "runAapt() called"); com.duy.aapt.Aapt aapt = new com.duy.aapt.Aapt(); StringBuilder command = new StringBuilder("aapt p -f --auto-add-overlay" //"-v" + //print info + " -M " + projectFile.getXmlManifest().getPath() //manifest file + " -F " + projectFile.getResourceFile().getPath() //output resources.ap_ + " -I " + FileManager.getClasspathFile(context).getPath() //include + " -A " + projectFile.getDirAssets().getPath() //input assets dir + " -S " + projectFile.getDirRes().getPath() //input resource dir + " -J " + projectFile.getClassR().getParent());//parent file of R.java file //test // File appcompatDir = new File(Environment.getExternalStorageDirectory(), ".JavaNIDE/appcompat-v7-21.0.0"); // File appcompatRes = new File(appcompatDir, "res"); // File appcompatAsset = new File(appcompatDir, "assets"); // command.append(" -S ").append(appcompatRes.getPath()); // command.append(" -A ").append(appcompatAsset.getPath()); File dirLibs = projectFile.getDirLibs(); File[] files = dirLibs.listFiles(); if (files != null) { for (File lib : files) { if (lib.isFile() && false) { if (lib.getPath().endsWith(".jar")) { command.append(" -I ").append(lib.getPath()); } else if (lib.getPath().endsWith(".aar")) { command.append(" -I ").append(lib.getPath()).append(File.separator).append("res"); } } } } Log.d(TAG, "runAapt command = " + command); int exitCode = aapt.fnExecute(command.toString()); if (exitCode != 0) { throw new Exception("AAPT exit(" + exitCode + ")"); } } private static void zipSign(AndroidProjectFolder projectFile) throws Exception { // if (!appContext.getString(R.string.keystore).contentEquals(projectFile.jksEmbedded.getName())) { // TODO use user defined certificate // } // use embedded private key KeyStore keyStore = projectFile.getKeyStore(); String keystorePath = keyStore.getFile().getPath(); char[] keystorePw = keyStore.getPassword(); String certAlias = keyStore.getCertAlias(); char[] certPw = keyStore.getCertPassword(); String signatureAlgorithm = "SHA1withRSA"; ZipSigner zipsigner = new ZipSigner(); zipsigner.addProgressListener(new SignProgress() { @Override public void onProgress(ProgressEvent event) { super.onProgress(event); System.out.println("Sign progress: " + event.getPercentDone()); } }); CustomKeySigner.signZip(zipsigner, keystorePath, keystorePw, certAlias, certPw, signatureAlgorithm, projectFile.getApkUnsigned().getPath(), projectFile.getApkUnaligned().getPath()); } private static void zipAlign() throws Exception { // TODO make zipalign.so } private static void publishApk() throws Exception { // if (projectFile.apkRedistributable.exists()) { // projectFile.apkRedistributable.delete(); // } // Util.copy(projectFile.apkUnaligned, new FileOutputStream(projectFile.apkRedistributable)); // // projectFile.apkRedistributable.setReadable(true, false); } public void run() { } public static class SignProgress implements kellinwood.security.zipsigner.ProgressListener { public void onProgress(kellinwood.security.zipsigner.ProgressEvent event) { } } }<file_sep>/app/src/main/java/com/duy/ide/localdata/DatabaseHelper.java package com.duy.ide.localdata; /** * Created by Duy on 12-Aug-17. */ public class DatabaseHelper { } <file_sep>/app/src/main/java/com/duy/ide/editor/uidesigner/dynamiclayoutinflator/DynamicLayoutInflator.java package com.duy.ide.editor.uidesigner.dynamiclayoutinflator; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.StateListDrawable; import android.os.Build; import android.support.annotation.Nullable; import android.text.InputType; import android.text.TextUtils; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; /** * Copyright <NAME> 2015. * Source: https://github.com/nickwah/DynamicLayoutInflator * <p> * Licensed under the MIT License: * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ public class DynamicLayoutInflator { public static final int NO_LAYOUT_RULE = -999; public static final String[] CORNERS = {"TopLeft", "TopRight", "BottomRight", "BottomLeft"}; private static final String ns = null; public static int highestIdNumberUsed = 1234567; public static Map<String, ViewParamRunnable> viewRunnables; private static ImageLoader imageLoader = null; public static void setImageLoader(ImageLoader il) { imageLoader = il; } public static void setDelegate(View root, Object delegate) { DynamicLayoutInfo info; if (root.getTag() == null || !(root.getTag() instanceof DynamicLayoutInfo)) { info = new DynamicLayoutInfo(); root.setTag(info); } else { info = (DynamicLayoutInfo) root.getTag(); } info.delegate = delegate; } public static View inflateName(Context context, String name) { return inflateName(context, name, null); } public static View inflateName(Context context, String name, ViewGroup parent) { if (name.startsWith("<")) { // Assume it's XML return DynamicLayoutInflator.inflate(context, name, parent); } else { File savedFile = context.getFileStreamPath(name + ".xml"); try { InputStream fileStream = new FileInputStream(savedFile); return DynamicLayoutInflator.inflate(context, fileStream, parent); } catch (FileNotFoundException e) { } try { InputStream assetStream = context.getAssets().open(name + ".xml"); return DynamicLayoutInflator.inflate(context, assetStream, parent); } catch (IOException e) { } int id = context.getResources().getIdentifier(name, "layout", context.getPackageName()); if (id > 0) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); return inflater.inflate(id, parent, false); } } return null; } public static View inflate(Context context, File xmlPath) { InputStream inputStream = null; try { inputStream = new FileInputStream(xmlPath); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } return DynamicLayoutInflator.inflate(context, inputStream); } public static View inflate(Context context, String xml) { InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); return DynamicLayoutInflator.inflate(context, inputStream); } public static View inflate(Context context, String xml, ViewGroup parent) { InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); return DynamicLayoutInflator.inflate(context, inputStream, parent); } public static View inflate(Context context, InputStream inputStream) { return inflate(context, inputStream, null); } public static View inflate(Context context, InputStream inputStream, ViewGroup parent) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(inputStream); try { return inflate(context, document.getDocumentElement(), parent); } finally { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return null; } public static View inflate(Context context, Node node) { return inflate(context, node, null); } public static View inflate(Context context, Node node, ViewGroup parent) { View mainView = getViewForName(context, node.getNodeName()); if (parent != null) parent.addView(mainView); // have to add to parent to enable certain layout attrs applyAttributes(mainView, getAttributesMap(node), parent); if (mainView instanceof ViewGroup && node.hasChildNodes()) { parseChildren(context, node, (ViewGroup) mainView); } return mainView; } private static void parseChildren(Context context, Node node, ViewGroup mainView) { NodeList nodeList = node.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node currentNode = nodeList.item(i); if (currentNode.getNodeType() != Node.ELEMENT_NODE) continue; inflate(context, currentNode, mainView); // this recursively can call parseChildren } } private static View getViewForName(Context context, String name) { try { if (!name.contains(".")) { name = "android.widget." + name; } Class<?> clazz = Class.forName(name); Constructor<?> constructor = clazz.getConstructor(Context.class); return (View) constructor.newInstance(context); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } private static HashMap<String, String> getAttributesMap(Node currentNode) { NamedNodeMap attributeMap = currentNode.getAttributes(); int attributeCount = attributeMap.getLength(); HashMap<String, String> attributes = new HashMap<>(attributeCount); for (int j = 0; j < attributeCount; j++) { Node attr = attributeMap.item(j); String nodeName = attr.getNodeName(); if (nodeName.startsWith("android:")) nodeName = nodeName.substring(8); attributes.put(nodeName, attr.getNodeValue()); } return attributes; } @SuppressLint("NewApi") private static void applyAttributes(View view, Map<String, String> attrs, ViewGroup parent) { if (viewRunnables == null) createViewRunnables(); ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); int layoutRule; int marginLeft = 0, marginRight = 0, marginTop = 0, marginBottom = 0, paddingLeft = 0, paddingRight = 0, paddingTop = 0, paddingBottom = 0; boolean hasCornerRadius = false, hasCornerRadii = false; for (Map.Entry<String, String> entry : attrs.entrySet()) { String attr = entry.getKey(); if (viewRunnables.containsKey(attr)) { viewRunnables.get(attr).apply(view, entry.getValue(), parent, attrs); continue; } if (attr.startsWith("cornerRadius")) { hasCornerRadius = true; hasCornerRadii = !attr.equals("cornerRadius"); continue; } layoutRule = NO_LAYOUT_RULE; boolean layoutTarget = false; switch (attr) { case "id": String idValue = parseId(entry.getValue()); if (parent != null) { DynamicLayoutInfo info = getDynamicLayoutInfo(parent); int newId = highestIdNumberUsed++; view.setId(newId); info.nameToIdNumber.put(idValue, newId); } break; case "width": case "layout_width": switch (entry.getValue()) { case "wrap_content": layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT; break; case "fill_parent": case "match_parent": layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; break; default: layoutParams.width = DimensionConverter.stringToDimensionPixelSize(entry.getValue(), view.getResources().getDisplayMetrics(), parent, true); break; } break; case "height": case "layout_height": switch (entry.getValue()) { case "wrap_content": layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT; break; case "fill_parent": case "match_parent": layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; break; default: layoutParams.height = DimensionConverter.stringToDimensionPixelSize(entry.getValue(), view.getResources().getDisplayMetrics(), parent, false); break; } break; case "layout_gravity": if (parent != null && parent instanceof LinearLayout) { ((LinearLayout.LayoutParams) layoutParams).gravity = parseGravity(entry.getValue()); } else if (parent != null && parent instanceof FrameLayout) { ((FrameLayout.LayoutParams) layoutParams).gravity = parseGravity(entry.getValue()); } break; case "layout_weight": if (parent != null && parent instanceof LinearLayout) { ((LinearLayout.LayoutParams) layoutParams).weight = Float.parseFloat(entry.getValue()); } break; case "layout_below": layoutRule = RelativeLayout.BELOW; layoutTarget = true; break; case "layout_above": layoutRule = RelativeLayout.ABOVE; layoutTarget = true; break; case "layout_toLeftOf": layoutRule = RelativeLayout.LEFT_OF; layoutTarget = true; break; case "layout_toRightOf": layoutRule = RelativeLayout.RIGHT_OF; layoutTarget = true; break; case "layout_alignBottom": layoutRule = RelativeLayout.ALIGN_BOTTOM; layoutTarget = true; break; case "layout_alignTop": layoutRule = RelativeLayout.ALIGN_TOP; layoutTarget = true; break; case "layout_alignLeft": case "layout_alignStart": layoutRule = RelativeLayout.ALIGN_LEFT; layoutTarget = true; break; case "layout_alignRight": case "layout_alignEnd": layoutRule = RelativeLayout.ALIGN_RIGHT; layoutTarget = true; break; case "layout_alignParentBottom": layoutRule = RelativeLayout.ALIGN_PARENT_BOTTOM; break; case "layout_alignParentTop": layoutRule = RelativeLayout.ALIGN_PARENT_TOP; break; case "layout_alignParentLeft": case "layout_alignParentStart": layoutRule = RelativeLayout.ALIGN_PARENT_LEFT; break; case "layout_alignParentRight": case "layout_alignParentEnd": layoutRule = RelativeLayout.ALIGN_PARENT_RIGHT; break; case "layout_centerHorizontal": layoutRule = RelativeLayout.CENTER_HORIZONTAL; break; case "layout_centerVertical": layoutRule = RelativeLayout.CENTER_VERTICAL; break; case "layout_centerInParent": layoutRule = RelativeLayout.CENTER_IN_PARENT; break; case "layout_margin": marginLeft = marginRight = marginTop = marginBottom = DimensionConverter.stringToDimensionPixelSize(entry.getValue(), view.getResources().getDisplayMetrics()); break; case "layout_marginLeft": marginLeft = DimensionConverter.stringToDimensionPixelSize(entry.getValue(), view.getResources().getDisplayMetrics(), parent, true); break; case "layout_marginTop": marginTop = DimensionConverter.stringToDimensionPixelSize(entry.getValue(), view.getResources().getDisplayMetrics(), parent, false); break; case "layout_marginRight": marginRight = DimensionConverter.stringToDimensionPixelSize(entry.getValue(), view.getResources().getDisplayMetrics(), parent, true); break; case "layout_marginBottom": marginBottom = DimensionConverter.stringToDimensionPixelSize(entry.getValue(), view.getResources().getDisplayMetrics(), parent, false); break; case "padding": paddingBottom = paddingLeft = paddingRight = paddingTop = DimensionConverter.stringToDimensionPixelSize(entry.getValue(), view.getResources().getDisplayMetrics()); break; case "paddingLeft": paddingLeft = DimensionConverter.stringToDimensionPixelSize(entry.getValue(), view.getResources().getDisplayMetrics()); break; case "paddingTop": paddingTop = DimensionConverter.stringToDimensionPixelSize(entry.getValue(), view.getResources().getDisplayMetrics()); break; case "paddingRight": paddingRight = DimensionConverter.stringToDimensionPixelSize(entry.getValue(), view.getResources().getDisplayMetrics()); break; case "paddingBottom": paddingBottom = DimensionConverter.stringToDimensionPixelSize(entry.getValue(), view.getResources().getDisplayMetrics()); break; } if (layoutRule != NO_LAYOUT_RULE && parent instanceof RelativeLayout) { if (layoutTarget) { int anchor = idNumFromIdString(parent, parseId(entry.getValue())); ((RelativeLayout.LayoutParams) layoutParams).addRule(layoutRule, anchor); } else if (entry.getValue().equals("true")) { ((RelativeLayout.LayoutParams) layoutParams).addRule(layoutRule); } } } // TODO: this is a giant mess; come up with a simpler way of deciding what to draw for the background if (attrs.containsKey("background") || attrs.containsKey("borderColor")) { String bgValue = attrs.containsKey("background") ? attrs.get("background") : null; if (bgValue != null && bgValue.startsWith("@drawable/")) { view.setBackground(getDrawableByName(view, bgValue)); } else if (bgValue == null || bgValue.startsWith("#") || bgValue.startsWith("@color")) { if (view instanceof Button || attrs.containsKey("pressedColor")) { int bgColor = parseColor(view, bgValue == null ? "#00000000" : bgValue); int pressedColor; if (attrs.containsKey("pressedColor")) { pressedColor = parseColor(view, attrs.get("pressedColor")); } else { pressedColor = adjustBrightness(bgColor, 0.9f); } GradientDrawable gd = new GradientDrawable(); gd.setColor(bgColor); GradientDrawable pressedGd = new GradientDrawable(); pressedGd.setColor(pressedColor); if (hasCornerRadii) { float radii[] = new float[8]; for (int i = 0; i < CORNERS.length; i++) { String corner = CORNERS[i]; if (attrs.containsKey("cornerRadius" + corner)) { radii[i * 2] = radii[i * 2 + 1] = DimensionConverter.stringToDimension(attrs.get("cornerRadius" + corner), view.getResources().getDisplayMetrics()); } gd.setCornerRadii(radii); pressedGd.setCornerRadii(radii); } } else if (hasCornerRadius) { float cornerRadius = DimensionConverter.stringToDimension(attrs.get("cornerRadius"), view.getResources().getDisplayMetrics()); gd.setCornerRadius(cornerRadius); pressedGd.setCornerRadius(cornerRadius); } if (attrs.containsKey("borderColor")) { String borderWidth = "1dp"; if (attrs.containsKey("borderWidth")) { borderWidth = attrs.get("borderWidth"); } int borderWidthPx = DimensionConverter.stringToDimensionPixelSize(borderWidth, view.getResources().getDisplayMetrics()); gd.setStroke(borderWidthPx, parseColor(view, attrs.get("borderColor"))); pressedGd.setStroke(borderWidthPx, parseColor(view, attrs.get("borderColor"))); } StateListDrawable selector = new StateListDrawable(); selector.addState(new int[]{android.R.attr.state_pressed}, pressedGd); selector.addState(new int[]{}, gd); view.setBackground(selector); getDynamicLayoutInfo(view).bgDrawable = gd; } else if (hasCornerRadius || attrs.containsKey("borderColor")) { GradientDrawable gd = new GradientDrawable(); int bgColor = parseColor(view, bgValue == null ? "#00000000" : bgValue); gd.setColor(bgColor); if (hasCornerRadii) { float radii[] = new float[8]; for (int i = 0; i < CORNERS.length; i++) { String corner = CORNERS[i]; if (attrs.containsKey("cornerRadius" + corner)) { radii[i * 2] = radii[i * 2 + 1] = DimensionConverter.stringToDimension(attrs.get("cornerRadius" + corner), view.getResources().getDisplayMetrics()); } gd.setCornerRadii(radii); } } else if (hasCornerRadius) { float cornerRadius = DimensionConverter.stringToDimension(attrs.get("cornerRadius"), view.getResources().getDisplayMetrics()); gd.setCornerRadius(cornerRadius); } if (attrs.containsKey("borderColor")) { String borderWidth = "1dp"; if (attrs.containsKey("borderWidth")) { borderWidth = attrs.get("borderWidth"); } gd.setStroke(DimensionConverter.stringToDimensionPixelSize(borderWidth, view.getResources().getDisplayMetrics()), parseColor(view, attrs.get("borderColor"))); } view.setBackground(gd); getDynamicLayoutInfo(view).bgDrawable = gd; } else { view.setBackgroundColor(parseColor(view, bgValue)); } } } if (layoutParams instanceof ViewGroup.MarginLayoutParams) { ((ViewGroup.MarginLayoutParams) layoutParams).setMargins(marginLeft, marginTop, marginRight, marginBottom); } view.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom); view.setLayoutParams(layoutParams); } private static DynamicLayoutInfo getDynamicLayoutInfo(View parent) { DynamicLayoutInfo info; if (parent.getTag() != null && parent.getTag() instanceof DynamicLayoutInfo) { info = (DynamicLayoutInfo) parent.getTag(); } else { info = new DynamicLayoutInfo(); parent.setTag(info); } return info; } private static View.OnClickListener getClickListener(final ViewGroup myParent, final String methodName) { return new View.OnClickListener() { @Override public void onClick(View view) { ViewGroup root = myParent; DynamicLayoutInfo info = null; while (root != null && (root.getParent() instanceof ViewGroup)) { if (root.getTag() != null && root.getTag() instanceof DynamicLayoutInfo) { info = (DynamicLayoutInfo) root.getTag(); if (info.delegate != null) break; } root = (ViewGroup) root.getParent(); } if (info != null && info.delegate != null) { final Object delegate = info.delegate; invokeMethod(delegate, methodName, false, view); } else { Log.e("DynamicLayoutInflator", "Unable to find valid delegate for click named " + methodName); } } private void invokeMethod(Object delegate, final String methodName, boolean withView, View view) { Object[] args = null; String finalMethod = methodName; if (methodName.endsWith(")")) { String[] parts = methodName.split("[(]", 2); finalMethod = parts[0]; try { String argText = parts[1].replace("&quot;", "\""); JSONArray arr = new JSONArray("[" + argText.substring(0, argText.length() - 1) + "]"); args = new Object[arr.length()]; for (int i = 0; i < arr.length(); i++) { args[i] = arr.get(i); } } catch (JSONException e) { e.printStackTrace(); } } else if (withView) { args = new Object[1]; args[0] = view; } Class<?> klass = delegate.getClass(); try { Class<?>[] argClasses = null; if (args != null && args.length > 0) { argClasses = new Class[args.length]; if (withView) { argClasses[0] = View.class; } else { for (int i = 0; i < args.length; i++) { Class<?> argClass = args[i].getClass(); if (argClass == Integer.class) argClass = int.class; // Nobody uses Integer... argClasses[i] = argClass; } } } Method method = klass.getMethod(finalMethod, argClasses); method.invoke(delegate, args); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); if (!withView && !methodName.endsWith(")")) { invokeMethod(delegate, methodName, true, view); } } } }; } private static String parseId(String value) { if (value.startsWith("@+id/")) { return value.substring(5); } else if (value.startsWith("@id/")) { return value.substring(4); } return value; } private static int parseGravity(String value) { int gravity = Gravity.NO_GRAVITY; String[] parts = value.toLowerCase().split("[|]"); for (String part : parts) { switch (part) { case "center": gravity = gravity | Gravity.CENTER; break; case "left": case "textStart": gravity = gravity | Gravity.LEFT; break; case "right": case "textEnd": gravity = gravity | Gravity.RIGHT; break; case "top": gravity = gravity | Gravity.TOP; break; case "bottom": gravity = gravity | Gravity.BOTTOM; break; case "center_horizontal": gravity = gravity | Gravity.CENTER_HORIZONTAL; break; case "center_vertical": gravity = gravity | Gravity.CENTER_VERTICAL; break; } } return gravity; } public static int idNumFromIdString(View view, String id) { if (!(view instanceof ViewGroup)) return 0; Object tag = view.getTag(); if (!(tag instanceof DynamicLayoutInfo)) return 0; // not inflated by this class DynamicLayoutInfo info = (DynamicLayoutInfo) view.getTag(); if (!info.nameToIdNumber.containsKey(id)) { ViewGroup grp = (ViewGroup) view; for (int i = 0; i < grp.getChildCount(); i++) { int val = idNumFromIdString(grp.getChildAt(i), id); if (val != 0) return val; } return 0; } return info.nameToIdNumber.get(id); } @Nullable public static View findViewByIdString(View view, String id) { int idNum = idNumFromIdString(view, id); if (idNum == 0) return null; return view.findViewById(idNum); } public static int parseColor(View view, String text) { if (text.startsWith("@color/")) { Resources resources = view.getResources(); return resources.getColor(resources.getIdentifier(text.substring("@color/".length()), "color", view.getContext().getPackageName())); } if (text.length() == 4 && text.startsWith("#")) { text = "#" + text.charAt(1) + text.charAt(1) + text.charAt(2) + text.charAt(2) + text.charAt(3) + text.charAt(3); } return Color.parseColor(text); } public static int adjustBrightness(int color, float amount) { int red = color & 0xFF0000 >> 16; int green = color & 0x00FF00 >> 8; int blue = color & 0x0000FF; int result = (int) (blue * amount); result += (int) (green * amount) << 8; result += (int) (red * amount) << 16; return result; } public static Drawable getDrawableByName(View view, String name) { Resources resources = view.getResources(); return resources.getDrawable(resources.getIdentifier(name, "drawable", view.getContext().getPackageName())); } public static void createViewRunnables() { viewRunnables = new HashMap<>(30); viewRunnables.put("scaleType", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { if (view instanceof ImageView) { ImageView.ScaleType scaleType = ((ImageView) view).getScaleType(); switch (value.toLowerCase()) { case "center": scaleType = ImageView.ScaleType.CENTER; break; case "center_crop": scaleType = ImageView.ScaleType.CENTER_CROP; break; case "center_inside": scaleType = ImageView.ScaleType.CENTER_INSIDE; break; case "fit_center": scaleType = ImageView.ScaleType.FIT_CENTER; break; case "fit_end": scaleType = ImageView.ScaleType.FIT_END; break; case "fit_start": scaleType = ImageView.ScaleType.FIT_START; break; case "fit_xy": scaleType = ImageView.ScaleType.FIT_XY; break; case "matrix": scaleType = ImageView.ScaleType.MATRIX; break; } ((ImageView) view).setScaleType(scaleType); } } }); viewRunnables.put("orientation", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { if (view instanceof LinearLayout) { ((LinearLayout) view).setOrientation(value.equals("vertical") ? LinearLayout.VERTICAL : LinearLayout.HORIZONTAL); } } }); viewRunnables.put("text", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { if (view instanceof TextView) { ((TextView) view).setText(value); } } }); viewRunnables.put("textSize", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { if (view instanceof TextView) { ((TextView) view).setTextSize(TypedValue.COMPLEX_UNIT_PX, DimensionConverter.stringToDimension(value, view.getResources().getDisplayMetrics())); } } }); viewRunnables.put("textColor", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { if (view instanceof TextView) { ((TextView) view).setTextColor(parseColor(view, value)); } } }); viewRunnables.put("textStyle", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { if (view instanceof TextView) { int typeFace = Typeface.NORMAL; if (value.contains("bold")) typeFace |= Typeface.BOLD; else if (value.contains("italic")) typeFace |= Typeface.ITALIC; ((TextView) view).setTypeface(null, typeFace); } } }); viewRunnables.put("textAlignment", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { int alignment = View.TEXT_ALIGNMENT_TEXT_START; switch (value) { case "center": alignment = View.TEXT_ALIGNMENT_CENTER; break; case "left": case "textStart": break; case "right": case "textEnd": alignment = View.TEXT_ALIGNMENT_TEXT_END; break; } view.setTextAlignment(alignment); } else { int gravity = Gravity.LEFT; switch (value) { case "center": gravity = Gravity.CENTER; break; case "left": case "textStart": break; case "right": case "textEnd": gravity = Gravity.RIGHT; break; } ((TextView) view).setGravity(gravity); } } }); viewRunnables.put("ellipsize", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { if (view instanceof TextView) { TextUtils.TruncateAt where = TextUtils.TruncateAt.END; switch (value) { case "start": where = TextUtils.TruncateAt.START; break; case "middle": where = TextUtils.TruncateAt.MIDDLE; break; case "marquee": where = TextUtils.TruncateAt.MARQUEE; break; case "end": break; } ((TextView) view).setEllipsize(where); } } }); viewRunnables.put("singleLine", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { if (view instanceof TextView) { ((TextView) view).setSingleLine(); } } }); viewRunnables.put("hint", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { if (view instanceof EditText) { ((EditText) view).setHint(value); } } }); viewRunnables.put("inputType", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { if (view instanceof TextView) { int inputType = 0; switch (value) { case "textEmailAddress": inputType |= InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS; break; case "number": inputType |= InputType.TYPE_CLASS_NUMBER; break; case "phone": inputType |= InputType.TYPE_CLASS_PHONE; break; } if (inputType > 0) ((TextView) view).setInputType(inputType); } } }); viewRunnables.put("gravity", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { int gravity = parseGravity(value); if (view instanceof TextView) { ((TextView) view).setGravity(gravity); } else if (view instanceof LinearLayout) { ((LinearLayout) view).setGravity(gravity); } else if (view instanceof RelativeLayout) { ((RelativeLayout) view).setGravity(gravity); } } }); viewRunnables.put("src", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { if (view instanceof ImageView) { String imageName = value; if (imageName.startsWith("//")) imageName = "http:" + imageName; if (imageName.startsWith("http")) { if (imageLoader != null) { if (attrs.containsKey("cornerRadius")) { int radius = DimensionConverter.stringToDimensionPixelSize(attrs.get("cornerRadius"), view.getResources().getDisplayMetrics()); imageLoader.loadRoundedImage((ImageView) view, imageName, radius); } else { imageLoader.loadImage((ImageView) view, imageName); } } } else if (imageName.startsWith("@drawable/")) { imageName = imageName.substring("@drawable/".length()); ((ImageView) view).setImageDrawable(getDrawableByName(view, imageName)); } } } }); viewRunnables.put("visibility", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { int visibility = View.VISIBLE; String visValue = value.toLowerCase(); if (visValue.equals("gone")) visibility = View.GONE; else if (visValue.equals("invisible")) visibility = View.INVISIBLE; view.setVisibility(visibility); } }); viewRunnables.put("clickable", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { view.setClickable(value.equals("true")); } }); viewRunnables.put("tag", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { // Sigh, this is dangerous because we use tags for other purposes if (view.getTag() == null) view.setTag(value); } }); viewRunnables.put("onClick", new ViewParamRunnable() { @Override public void apply(View view, String value, ViewGroup parent, Map<String, String> attrs) { view.setOnClickListener(getClickListener(parent, value)); } }); } public interface ViewParamRunnable { void apply(View view, String value, ViewGroup parent, Map<String, String> attrs); } public interface ImageLoader { void loadImage(ImageView view, String url); void loadRoundedImage(ImageView view, String url, int radius); } public static class DynamicLayoutInfo { public HashMap<String, Integer> nameToIdNumber; public Object delegate; public GradientDrawable bgDrawable; public DynamicLayoutInfo() { nameToIdNumber = new HashMap<>(); } } } <file_sep>/common/src/main/java/com/jecelyin/common/utils/StringUtils.java /* * Copyright (C) 2016 <NAME> <<EMAIL>> * * This file is part of 920 Text Editor. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jecelyin.common.utils; import android.text.TextUtils; import java.net.URLDecoder; import java.net.URLEncoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * String工具类 */ public class StringUtils { public static boolean isEmpty(String input) { return TextUtils.isEmpty(input); } /** * 不能使用 {@link MessageDigest#isEqual} 因为像华为emui 2.3这个函数不能正确比较 * @param digesta * @param digestb * @return */ public static boolean isEqual(byte[] digesta, byte[] digestb) { if (digesta.length != digestb.length) { return false; } // Perform a constant time comparison to avoid timing attacks. int v = 0; for (int i = 0; i < digesta.length; i++) { v |= (digesta[i] ^ digestb[i]); } return v == 0; } /** * 检测变量的值是否为一个整型数据; */ public final static boolean isInt(String value) { if (isEmpty(value)) return false; try { Integer.parseInt(value); } catch (NumberFormatException e) { return false; } return true; } /** * 判断变量的值是否为double类型 */ public final static boolean isDouble(String value) { if (isEmpty(value)) return false; try { Double.parseDouble(value); } catch (NumberFormatException e) { return false; } return true; } /** * 解析一个字符串为整数; */ public final static int toInt(String value) { return toInt(value, 0); } public final static int toInt(String value, int defaultValue) { try { return Integer.parseInt(value); } catch (Exception e) { return defaultValue; } } /** * 解析一个字符串为double */ public final static double toDouble(String value) { return toDouble(value, 0); } public final static double toDouble(String value, double defaultValue) { if (isDouble(value)) return Double.parseDouble(value); return defaultValue; } /** * 解析一个字符串为float */ public static float toFloat(String value) { return toFloat(value, 0); } public static float toFloat(String value, float defaultValue) { try { return Float.parseFloat(value); } catch (Exception e) { return defaultValue; } } /** * 对象转整数 * * @param obj * @return 转换异常返回 0 */ public static long toLong(String obj) { try { return Long.parseLong(obj); } catch (Exception e) { } return 0; } /** * 字符串转布尔值 * * @param b * @return 转换异常返回 false */ public static boolean toBool(String b) { try { return Boolean.parseBoolean(b); } catch (Exception e) { } return false; } /** * 判定输入汉字 * @param c * @return */ public final static boolean isChinese(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) { return true; } return false; } /** * Returns a string containing the tokens joined by delimiters. * @param tokens an array objects to be joined. */ public static String join(CharSequence delimiter, int[] tokens) { StringBuilder sb = new StringBuilder(); boolean firstTime = true; for (Object token: tokens) { if (firstTime) { firstTime = false; } else { sb.append(delimiter); } sb.append(token); } return sb.toString(); } public static String urlencode(String s) { try { s = URLEncoder.encode(s, "UTF-8"); } catch (Exception e) { } return s; } public static String urldecode(String s) { try { s = URLDecoder.decode(s, "UTF-8"); } catch (Exception e) { } return s; } public static String md5(String s) { try { // Create MD5 Hash MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) hexString.append(Integer.toHexString(0xFF & messageDigest[i])); return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } public static String formatSize(long size, int decimalPoints) { return formatSize(size, decimalPoints, true); } public static String formatSize(long size) { return formatSize(size, true); } public static String formatSize(long size, boolean includeUnits) { return formatSize(size, 2, includeUnits); } public static String formatSize(long size, int decimalPoints, boolean includeUnits) { int kb = 1024; int mb = kb * kb; int gb = mb * kb; if(size < 0) return ""; int factor = (10 ^ decimalPoints); String ssize = ""; if (size <= kb) ssize = size + " B"; else if (size > kb && size <= mb) ssize = ((double)Math.round(((double)size / kb) * factor) / factor) + (includeUnits ? " KB" : ""); else if (size > mb && size <= gb) ssize = ((double)Math.round(((double)size / mb) * factor) / factor) + (includeUnits ? " MB" : ""); else if (size > gb) ssize = ((double)Math.round(((double)size / gb) * factor) / factor) + (includeUnits ? " GB" : ""); return ssize; } } <file_sep>/app/src/main/java/com/duy/ide/command/Command.java package com.duy.ide.command; /** * Created by Duy on 20-Dec-17. */ public class Command implements ICommand{ @Override public boolean execute(Object... params) { return false; } } <file_sep>/fileexplorer/src/main/java/com/jecelyin/android/file_explorer/adapter/FileListItemAdapter.java /* * Copyright (C) 2016 <NAME> <<EMAIL>> * * This file is part of 920 Text Editor. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jecelyin.android.file_explorer.adapter; import android.content.res.Resources; import android.databinding.DataBindingUtil; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.SparseIntArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.jecelyin.android.file_explorer.R; import com.jecelyin.android.file_explorer.databinding.FileListItemBinding; import com.jecelyin.android.file_explorer.io.JecFile; import com.jecelyin.android.file_explorer.model.FileItemModel; import com.jecelyin.android.file_explorer.util.MimeTypes; import com.jecelyin.android.file_explorer.util.OnCheckedChangeListener; import com.jecelyin.common.adapter.BindingViewHolder; import com.jecelyin.common.listeners.OnItemClickListener; import com.jecelyin.common.utils.StringUtils; import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView; import java.text.SimpleDateFormat; import java.util.Calendar; /** * @author <NAME> <<EMAIL>> */ public class FileListItemAdapter extends RecyclerView.Adapter<BindingViewHolder<FileListItemBinding>> implements FastScrollRecyclerView.SectionedAdapter { private JecFile[] data; private final String year; private final SparseIntArray checkedArray; private OnCheckedChangeListener onCheckedChangeListener; private OnItemClickListener onItemClickListener; private JecFile[] mOriginalValues; private int itemCount; public FileListItemAdapter() { // year = String.valueOf(new Date().getYear()); year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR)); checkedArray = new SparseIntArray(); } public void setData(JecFile[] data) { this.data = data; itemCount = data.length; mOriginalValues = data.clone(); notifyDataSetChanged(); } public void filter(CharSequence filterText) { if (mOriginalValues == null) return; if (TextUtils.isEmpty(filterText)) { data = mOriginalValues; itemCount = mOriginalValues.length; notifyDataSetChanged(); return; } data = new JecFile[mOriginalValues.length]; filterText = filterText.toString().toLowerCase(); int index = 0; for(JecFile path : mOriginalValues) { if (path.getName().toLowerCase().contains(filterText)) { data[index++] = path; } } itemCount = index; notifyDataSetChanged(); } @NonNull @Override public String getSectionName(int position) { JecFile file = getItem(position); char c = file.getName().charAt(0); if ( (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ) { return String.valueOf(c); } return "#"; } public JecFile getItem(int position) { return data[position]; } public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) { this.onCheckedChangeListener = onCheckedChangeListener; } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } @Override public int getItemCount() { return itemCount; } @Override public BindingViewHolder<FileListItemBinding> onCreateViewHolder(ViewGroup parent, int viewType) { FileListItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.file_list_item, parent, false); return new BindingViewHolder<>(binding); } @Override public void onBindViewHolder(final BindingViewHolder<FileListItemBinding> holder, final int position) { JecFile path = data[position]; MimeTypes mimeTypes = MimeTypes.getInstance(); Resources res = holder.itemView.getResources(); int color, icon; if (path.isDirectory()) { color = R.color.type_folder; icon = R.drawable.file_type_folder; } else if (mimeTypes.isImageFile(path)) { color = R.color.type_media; icon = R.drawable.file_type_image; } else if (mimeTypes.isVideoFile(path)) { color = R.color.type_media; icon = R.drawable.file_type_video; } else if (mimeTypes.isAudioFile(path)) { color = R.color.type_media; icon = R.drawable.file_type_audio; } else if (mimeTypes.isAPKFile(path)) { color = R.color.type_apk; icon = R.drawable.file_type_apk; } else if (mimeTypes.isArchive(path)) { color = R.color.type_archive; icon = R.drawable.file_type_archive; } else if (mimeTypes.isCodeFile(path)) { color = R.color.type_code; icon = R.drawable.file_type_code; } else if (mimeTypes.isTextFile(path)) { color = R.color.type_text; icon = R.drawable.file_type_text; } else { color = R.color.type_file; icon = TextUtils.isEmpty(path.getExtension()) ? R.drawable.file_type_file : 0; } final FileListItemBinding binding = holder.getBinding(); binding.iconImageView.setDefaultImageResource(icon); binding.iconImageView.setDefaultBackgroundColor(res.getColor(color)); FileItemModel item = new FileItemModel(); item.setName(path.getName()); item.setExt(icon == 0 && color == R.color.type_file ? path.getExtension() : ""); item.setDate(getDate(path.lastModified())); item.setSecondLine(path.isFile() ? StringUtils.formatSize(path.length()) : ""); binding.setItem(item); binding.iconImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toggleChecked(position, binding); } }); holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { toggleChecked(position, binding); return true; } }); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (checkedArray != null && checkedArray.size() > 0) { toggleChecked(position, binding); return; } if (onItemClickListener != null) onItemClickListener.onItemClick(position, v); } }); boolean isChecked = isChecked(position); setViewCheckedStatus(isChecked, binding); } private void setViewCheckedStatus(boolean isChecked, FileListItemBinding binding) { binding.iconImageView.setChecked(isChecked); if(!isChecked) { binding.getRoot().setSelected(false); binding.extTextView.setVisibility(View.VISIBLE); } else { binding.getRoot().setSelected(true); binding.extTextView.setVisibility(View.INVISIBLE); } } private void toggleChecked(int position, FileListItemBinding binding) { boolean isChecked = isChecked(position); if(isChecked) { checkedArray.delete(position); } else { checkedArray.put(position, 1); } setViewCheckedStatus(!isChecked, binding); if(onCheckedChangeListener != null) { onCheckedChangeListener.onCheckedChanged(getItem(position), position, !isChecked); onCheckedChangeListener.onCheckedChanged(checkedArray.size()); } } public boolean isChecked(int position) { return checkedArray.get(position) == 1; } private String getDate(long f) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String date = (sdf.format(f)); if (date.substring(0, 4).equals(year)) date = date.substring(5); return date; } public void checkAll(boolean checked) { if (checked) { int count = getItemCount(); for (int i = 0; i < count; i++) { checkedArray.put(i, 1); } } else { checkedArray.clear(); } if (onCheckedChangeListener != null) { onCheckedChangeListener.onCheckedChanged(checkedArray.size()); } notifyDataSetChanged(); } } <file_sep>/app/src/main/java/com/duy/project/view/dialog/DialogNewFolder.java package com.duy.project.view.dialog; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatDialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.EditText; import android.widget.Toast; import com.duy.ide.R; import com.duy.project.ProjectFileContract; import com.duy.project.file.java.JavaProjectFolder; import java.io.File; /** * Created by Duy on 20-Dec-17. */ public class DialogNewFolder extends AppCompatDialogFragment implements View.OnClickListener { public static final String TAG = "DialogNewFolder"; private static final String KEY_PROJECT_FILE = "project_file"; private static final String KEY_PARENT_FILE = "parent_file"; private EditText mEditName; @Nullable private ProjectFileContract.FileActionListener listener; public static DialogNewFolder newInstance(@NonNull JavaProjectFolder p, @Nullable File currentFolder) { Bundle args = new Bundle(); args.putSerializable(KEY_PROJECT_FILE, p); args.putSerializable(KEY_PARENT_FILE, currentFolder); DialogNewFolder fragment = new DialogNewFolder(); fragment.setArguments(args); return fragment; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.dialog_new_folder, container, false); } @Override public void onStart() { super.onStart(); Dialog dialog = getDialog(); if (dialog != null && dialog.getWindow() != null) { Window window = dialog.getWindow(); window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } } @Override public void onAttach(Context context) { super.onAttach(context); try { listener = (ProjectFileContract.FileActionListener) getActivity(); } catch (ClassCastException e) { e.printStackTrace(); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_cancel: this.dismiss(); break; case R.id.btn_create: createNewFolder(); break; } } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mEditName = view.findViewById(R.id.edit_class_name); view.findViewById(R.id.btn_create).setOnClickListener(this); view.findViewById(R.id.btn_cancel).setOnClickListener(this); } private void createNewFolder() { String fileName = mEditName.getText().toString(); if (fileName.isEmpty()) { mEditName.setError(getString(R.string.enter_name)); return; } try { File parent = (File) getArguments().getSerializable(KEY_PARENT_FILE); File folder = new File(parent, fileName); if (!parent.exists()) { parent.mkdirs(); } folder.mkdir(); listener.onNewFileCreated(folder); dismiss(); } catch (Exception e) { Toast.makeText(getContext(), "Can not create new file", Toast.LENGTH_SHORT).show(); } } } <file_sep>/styles/src/main/java/com/jecelyin/editor/v2/FullScreenActivity.java /* * Copyright (C) 2016 <NAME> <<EMAIL>> * * This file is part of 920 Text Editor. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jecelyin.editor.v2; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import android.view.WindowManager; import com.jecelyin.common.app.JecActivity; /** * @author <NAME> <<EMAIL>> */ public class FullScreenActivity extends JecActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); int theme = Pref.getInstance(this).getTheme(); if (theme != 0) { setTheme(Pref.THEMES[theme]); } if (isFullScreenMode()) { enabledFullScreenMode(); } } @Override protected boolean isFullScreenMode() { return Pref.getInstance(this).isFullScreenMode(); } private void enabledFullScreenMode() { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); View decorView = getWindow().getDecorView(); // Hide the status bar. int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN; decorView.setSystemUiVisibility(uiOptions); } } <file_sep>/app/src/main/java/com/duy/compile/message/MessageContract.java package com.duy.compile.message; import android.support.annotation.WorkerThread; import com.duy.JavaApplication; /** * Created by duy on 19/07/2017. */ public class MessageContract { public interface View { @WorkerThread void append(String text); @WorkerThread void appendOut(byte[] chars, int start, int end); @WorkerThread void appendErr(byte[] chars, int start, int end); @WorkerThread void clear(); void setPresenter(Presenter presenter); } public interface Presenter { @WorkerThread void clear(); @WorkerThread void append(String s); void resume(JavaApplication application); void pause(JavaApplication application); } } <file_sep>/app/src/main/java/com/duy/JavaApplication.java package com.duy; import android.support.annotation.NonNull; import android.support.multidex.MultiDexApplication; import android.support.v7.app.AppCompatDelegate; import android.util.Log; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; /** * Created by Duy on 17-Jul-17. */ public class JavaApplication extends MultiDexApplication { private ArrayList<PrintStream> out = new ArrayList<>(); private ArrayList<PrintStream> err = new ArrayList<>(); private InterceptorOutputStream systemOut; private InterceptorOutputStream systemErr; @Override public void onCreate() { super.onCreate(); systemOut = new InterceptorOutputStream(System.out, out); systemErr = new InterceptorOutputStream(System.err, err); System.setOut(systemOut); System.setErr(systemErr); //for log cat AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); } public void addStdOut(PrintStream out) { systemOut.add(out); } public void addStdErr(PrintStream err) { systemErr.add(err); } public void removeOutStream(PrintStream out) { systemOut.remove(out); } public void removeErrStream(PrintStream err) { systemErr.remove(err); } private static class InterceptorOutputStream extends PrintStream { private static final String TAG = "InterceptorOutputStream"; private ArrayList<PrintStream> streams; public InterceptorOutputStream(@NonNull OutputStream file, ArrayList<PrintStream> streams) { super(file, true); this.streams = streams; } public ArrayList<PrintStream> getStreams() { return streams; } public void setStreams(ArrayList<PrintStream> streams) { this.streams = streams; } public void add(PrintStream out) { Log.d(TAG, "add() called with: out = [" + out + "]"); this.streams.add(out); } public void remove(PrintStream out) { Log.d(TAG, "remove() called with: out = [" + out + "]"); this.streams.remove(out); } @Override public void write(@NonNull byte[] buf, int off, int len) { super.write(buf, off, len); if (streams != null) { for (PrintStream printStream : streams) { printStream.write(buf, off, len); } } } } }
63bcedb70abdd0595801c895dcc9886e9479528f
[ "Markdown", "Java", "Gradle" ]
33
Java
androlua/javaide
c4247558825877df8f2b12bf353bdbca14dd610e
9165fc7df9cdffc8316c2f63b151392b68dd1879
refs/heads/main
<file_sep>/* Hier werden die persistenten Daten der Rest-of-Work-Uhr im EEPROM behandelt. */ void InitEE (void) { EEPROM.get(0, Config); if (Config.check != 0x55aa) { Config.check = 0x55aa; for (int i = 0; i < 6; i++) { Config.PumpeDa[i] = false; strcpy(Config.Pflanzen[i], "Noch nix"); Config.PumpeZeit[i] = 10; } Config.PumpeDa[6] = true; Config.PumpeZeit[6] = 0; strcpy(Config.Pflanzen[6], "Überlauf"); Config.PumpeDa[7] = true; Config.PumpeZeit[7] = 0; strcpy(Config.Pflanzen[7], "Wassereimer"); EEPROM.put(0, Config); EEPROM.commit(); Serial.println("EEPROM initialisiert"); } else { Serial.println("EEPROM ok"); } } void GetEE (void) { EEPROM.get(0, Config); } void PutEE (void) { EEPROM.put(0, Config); EEPROM.commit(); } <file_sep>String MakeDateString(time_t DateTime) { String DateString = ""; DateString = day(DateTime); DateString += "."; DateString += month(DateTime); DateString += "."; DateString += year(DateTime); return DateString; } String MakeTimeString(time_t DateTime) { String TimeString = ""; TimeString += hour(DateTime); TimeString += ":"; if (minute(DateTime) < 10) TimeString += "0"; TimeString += minute(DateTime); return TimeString; } int MakeDateDisplay (void) { int Day, Month; Day = day(now()); Month = month(now()); return (Day * 100 + Month); } time_t SyncTimeToNTP1(void) { uint32_t CurrentTime, NewTime; static bool NTPSync = false; CurrentTime = now(); while (!NTPSync) { Serial.println("******Time-Sync******"); while (!timeClient.update()) { Serial.print("."); delay(100); } NewTime = timeClient.getEpochTime(); if (abs(NewTime - CurrentTime) < 10000) NTPSync = true; } Serial.println(""); NTPSync = false; return (LTZ.toLocal(timeClient.getEpochTime(), &tcr)); } time_t SyncTimeToNTP(void) { Serial.println("******Time-Sync******"); while(!timeClient.update()) Serial.print("."); Serial.println(""); return (LTZ.toLocal(timeClient.getEpochTime(), &tcr)); } time_t TimeCalc (int Td, int Tm, int Ty) { tmElements_t Tin; Tin.Second = 0; Tin.Minute = 0; Tin.Hour = 0; Tin.Day = Td; Tin.Month = Tm; Tin.Year = Ty; return (makeTime(Tin)); } void I2CScanner (void) { static int nDevices; static int ScanCount = 0; static byte address; byte error; Serial.print("I2C-Scan #"); Serial.println(ScanCount); nDevices = 0; for (address = 1; address < 127; address++ ) { // The i2c_scanner uses the return value of // the Write.endTransmisstion to see if // a device did acknowledge to the address. Wire.beginTransmission(address); error = Wire.endTransmission(); if (error == 0) { Serial.print("I2C Baustein gefunden unter 0x"); if (address < 16) Serial.print("0"); Serial.print(address, HEX); Serial.println(" !"); nDevices++; } else if (error == 4) { Serial.print("Unbekannter Fehler bei Sdresse 0x"); if (address < 16) Serial.print("0"); Serial.println(address, HEX); } } if (nDevices == 0) Serial.println("Keine I2C Bausteine gefunden\n"); else Serial.println("fertig\n"); LastScan = millis(); // wait 1 second for next scan ScanCount++; } void ReadAnalog(void) { static int MessCount = 0; static unsigned long TimeReadAnalog = 0; if (millis() > TimeReadAnalog) { Vcc = (float)ESP.getVcc() / 1000; sensor.requestTemperatures(); Temperatur = sensor.getTempCByIndex(0); for (int i = 0; i < 4; i++) { int AnaVal0 = ads0.readADC_SingleEnded(i); int AnaVal1 = ads1.readADC_SingleEnded(i); // ADC 0 AnalogRaw[i] = AnaVal0; AnalogRaw[i + 4] = AnaVal1; if (AnaVal0 < 11600) Analog[i] = 100; else if (AnaVal0 > 21500) Analog[i] = 0; else Analog[i] = map(AnaVal0, 11600, 21500, 100, 0); // ADC 1 if (AnaVal1 < 11600) Analog[i + 4] = 100; else if (AnaVal1 > 21500) Analog[i + 4] = 0; else Analog[i + 4] = map(AnaVal1, 11600, 21500, 100, 0); } for (int i = 0; i < 8; i++) { Volt[i] = (int)(AnalogRaw[i] * 0.125); } TimeReadAnalog = millis() + 1000; } } void DoPumpenTest (void) { static bool Running = false; if (DoTest) { if (millis() < TestRunTime[TestPumpe]) { PumpeStatus[TestPumpe] = 99; mcp.digitalWrite(TestPumpe, HIGH); if (!SayTestOnce) { Serial.println("Geht los"); SayTestOnce = true; } } else { mcp.digitalWrite(TestPumpe, LOW); PumpeStatus[TestPumpe] = 0; DoTest = false; SayTestOnce = false; Serial.println("Fertg"); } } } void RunPumpe(void) { for (int i = 0; i < 6; i++) { if (TestRunTime[i] > millis()) { mcp.digitalWrite(i, HIGH); PumpeStatus[i] = true; } else { mcp.digitalWrite(i, LOW); PumpeStatus[i] = false; } } } <file_sep>/* Elke's Wasserwerk für die Überwinterung */ #include <Wire.h> #include "Adafruit_MCP23017.h" #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #include <ESP8266mDNS.h> #include <ESP8266HTTPUpdateServer.h> //für http-Update #include <ESP8266Ping.h> #include <DNSServer.h> #include <WiFiManager.h> //https://github.com/tzapu/WiFiManager #include <ESP8266Ping.h> #include <FS.h> //Include File System Headers //#include <LittleFS.h> #include <EEPROM.h> #include <NTPClient.h> #include <WiFiUDP.h> #include <TimeLib.h> #include <Timezone.h> // from https://github.com/JChristensen/Timezone #define ARDUINOJSON_USE_LONG_LONG 1 #include <ArduinoJson.h> #include <PubSubClient.h> #include <OneWire.h> #include <DallasTemperature.h> #include <Adafruit_ADS1015.h> ADC_MODE(ADC_VCC); #define sdaPIN D2 #define sclPIN D1 Adafruit_MCP23017 mcp; #define ONE_WIRE_BUS D4 OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensor(&oneWire); DeviceAddress insideThermometer; // ADC ADS1115 Adafruit_ADS1115 ads0(0x49); // ADS1115, single ended Adafruit_ADS1115 ads1(0x48); // ADS1115, single ended float Temperatur, Vcc; //MQTT #define INTERVAL 60 //Interval Sekunden zwischen den Messungen #define RECOVER 10 //Interval, wenn Publish nicht erfolgreich #define TOPIC_1 "19a/wasserwerk/cpusupply" #define TOPIC_2 "19a/wasserwerk/timestamp" #define TOPIC_3 "19a/wasserwerk/temperatur" #define TOPIC_6 "19a/wasserwerk/ip-adresse" #define TOPIC_7 "19a/wasserwerk/daten" char FloatString[30]; WiFiClient espClient; PubSubClient MQTT_Client(espClient); const char* mqtt_server = "192.168.2.13"; const char ClientName[] = "19a-wasserwerk"; // NTP TimeChangeRule CEST = {"CEST", Last, Sun, Mar, 2, 120}; //Central European Summer Time TimeChangeRule CET = {"CET ", Last, Sun, Oct, 3, 60}; //Central European Standard Time Timezone LTZ(CEST, CET); // this is the Timezone object that will be used to calculate local time TimeChangeRule *tcr; //pointer to the time change rule, use to get the TZ abbrev const long utcOffsetInSeconds = 0; unsigned long UpdateIntervall = 1800; WiFiUDP udp; NTPClient timeClient(udp, "pool.ntp.org", utcOffsetInSeconds, UpdateIntervall); tmElements_t TP; const char* Wochentag[8] = { "Fehler", "Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag" }; // Ende NTP ESP8266WebServer server(80); //Server on port 80 ESP8266HTTPUpdateServer serverUpdater; IPAddress ip, ClientIP; char HostIP[15]; time_t LastShow = 0, LastSync = 0, LastPing = 0, LastPub = 0; char MyTime[48]; struct EEData_t { int check; bool PumpeDa[8]; int PumpeZeit[8]; char Pflanzen[8][17]; }; time_t DaysLeft = 0; EEData_t Config; bool PumpeStatus[8] = {false, false, false, false, false, false, false, false}; int PublishOK = 0; // I2C Scan long LastScan; // Ende // ADC int Analog[8]; int AnalogRaw[8]; int Volt[8]; // Ende // Pumpentest int TestPumpe; bool DoTest = false; bool SayTestOnce = false; int TestZeit; unsigned long TestRunTime[8] = {0, 0, 0, 0, 0, 0, 0, 0}; // Ende void setup() { Serial.begin(115200); Serial.println(""); Serial.printf("Wasserwerk, Compilerzeit: %s %s\n",__DATE__,__TIME__); WiFiManager wifiManager; SPIFFS.begin(); EEPROM.begin(512); sensor.begin(); Wire.begin(sdaPIN, sclPIN); // hir die I2C-Schnittstellen // Parallel Expander mcp.begin(); // use default address 0 for (int i = 0; i < 8; i++) { mcp.pinMode(i, OUTPUT); mcp.digitalWrite(i, LOW); } // ADCs ads0.setGain(GAIN_ONE); ads0.begin(); ads1.setGain(GAIN_ONE); ads1.begin(); uint8_t macAddr[6]; char Hostname[15]; WiFi.macAddress(macAddr); sprintf(Hostname, "ottO-%02x-%02x-%02x", macAddr[3], macAddr[4], macAddr[5]); WiFi.hostname(Hostname); wifiManager.setDebugOutput(false); //wifiManager.resetSettings(); if (!wifiManager.autoConnect("Wasserwerk-AP")) { Serial.println("failed to connect, we should reset as see if it connects"); delay(3000); ESP.restart(); delay(5000); } ip = WiFi.localIP(); sprintf(HostIP, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); Serial.printf("IP-Adresse ist %s\n", HostIP); setSyncProvider(SyncTimeToNTP); setSyncInterval(1800); LastSync = now(); InitEE(); GetEE(); MQTT_Client.setServer(mqtt_server, 1883); DefServerFunctions(); serverUpdater.setup(&server); server.begin(); MDNS.addService("http", "tcp", 80); } void loop() { server.handleClient(); MDNS.update(); //DoPumpenTest(); RunPumpe(); ReadAnalog(); if (now() > LastPub) { sprintf(MyTime, "%02d-%02d-%04d %02d:%02d:%02d UTC", day(timeClient.getEpochTime()), month(timeClient.getEpochTime()), year(timeClient.getEpochTime()), \ hour(timeClient.getEpochTime()), minute(timeClient.getEpochTime()), second(timeClient.getEpochTime())); if (reconnectNB()) { if (PublishData()) { LastPub = now() + INTERVAL; PublishOK = 1; } else { LastPub = now() + RECOVER; PublishOK = 0; } } else { LastPub = now() + RECOVER; PublishOK = 2; } } } <file_sep>void DefServerFunctions(void) { server.on("/", handleRoot); //Which routine to handle at root location. This is display page server.on("/readJSON", sendJSON); server.on("/getJSON", readJSON); server.on("/TestPumpe", TestPumpen); server.on("/runPumpe", TestPumpen); server.on("/hostReboot", RebootHost); //Initialize Webserver server.on("/", handleRoot); server.onNotFound(handleWebRequests); //Set setver all paths are not found so we can handle as per URI } <file_sep>void handleRoot() { server.sendHeader("Location", "/index.html", true); //Redirect to our html web page server.send(302, "text/plane", ""); } bool loadFromSPIFFS(String path) { Serial.print("path ist "); String dataType = "text/plain"; if (path.endsWith("/")) path += "index.html"; if (path.endsWith(".src")) path = path.substring(0, path.lastIndexOf(".")); else if (path.endsWith(".html")) dataType = "text/html"; else if (path.endsWith(".htm")) dataType = "text/html"; else if (path.endsWith(".css")) dataType = "text/css"; else if (path.endsWith(".js")) dataType = "application/javascript"; else if (path.endsWith(".png")) dataType = "image/png"; else if (path.endsWith(".gif")) dataType = "image/gif"; else if (path.endsWith(".jpg")) dataType = "image/jpeg"; else if (path.endsWith(".ico")) dataType = "image/x-icon"; else if (path.endsWith(".xml")) dataType = "text/xml"; else if (path.endsWith(".pdf")) dataType = "application/pdf"; else if (path.endsWith(".zip")) dataType = "application/zip"; File dataFile = SPIFFS.open(path.c_str(), "r"); if (server.hasArg("download")) dataType = "application/octet-stream"; if (server.streamFile(dataFile, dataType) != dataFile.size()) { } dataFile.close(); Serial.println(path); return true; } void handleWebRequests() { //Serial.println(server.client().remoteIP()); if (loadFromSPIFFS(server.uri())) return; String message = "File Not Detected\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; for (uint8_t i = 0; i < server.args(); i++) { message += " NAME:" + server.argName(i) + "\n VALUE:" + server.arg(i) + "\n"; } server.send(404, "text/plain", message); Serial.println(message); } void sendJSON(void) { static int CallCounter = 0; const size_t capacity = JSON_OBJECT_SIZE(80); DynamicJsonDocument doc(capacity); char JSONBuffer[2048]; char OutputBuffer[20]; ClientIP = server.client().remoteIP(); GetEE(); doc["compile"] = __DATE__ " " __TIME__; sprintf(OutputBuffer, "%2.2f", Vcc); doc["vcc"] = OutputBuffer; sprintf(OutputBuffer, "%3.1f", Temperatur); doc["temperatur"] = OutputBuffer; doc["wochentag"] = Wochentag[weekday(now())]; doc["tag"] = MakeDateString(now()); doc["uhrzeit"] = MakeTimeString(now()); doc["hostIP"] = HostIP; sprintf(OutputBuffer, "%d.%d.%d.%d", ClientIP[0], ClientIP[1], ClientIP[2], ClientIP[3]); doc["clientIP"] = OutputBuffer; doc["mqtt"] = PublishOK; //Serial.println(OutputBuffer); JsonArray pumpenConfig = doc.createNestedArray("pumpenConfig"); JsonArray pumpeStatus = doc.createNestedArray("pumpeStatus"); JsonArray pflanzenNamen = doc.createNestedArray("pflanzenNamen"); JsonArray pumpeZeit = doc.createNestedArray("pumpeZeit"); JsonArray pflanzenFeuchte = doc.createNestedArray("pflanzenFeuchte"); JsonArray sensorFeuchte = doc.createNestedArray("sensorFeuchte"); for (int i = 0; i < 8; i++) { pumpenConfig.add(Config.PumpeDa[i]); pumpeStatus.add(PumpeStatus[i]); pflanzenNamen.add(Config.Pflanzen[i]); pumpeZeit.add(Config.PumpeZeit[i]); pflanzenFeuchte.add(Analog[i]); sensorFeuchte.add(Volt[i]); } serializeJson(doc, JSONBuffer); //Serial.println(JSONBuffer); server.send(200, "text/plane", JSONBuffer); //Send JSON Data to client ajax request } void readJSON() { DynamicJsonDocument doc(2048); if (server.hasArg("plain") == false) { //Check if body received server.send(200, "text/plain", "JSON not received"); Serial.println("Nix empfangen"); return; } server.send(200, "text/plain", "JSON received"); DeserializationError error = deserializeJson(doc, server.arg("plain")); if (error) { Serial.print(F("deserializeJson() failed: ")); Serial.println(error.f_str()); return; } for (int i = 0; i < 6; i++) { Config.PumpeDa[i] = doc["pumpenConfig"][i]; strcpy(Config.Pflanzen[i], doc["pflanzeName"][i]); Config.PumpeZeit[i] = doc["pumpeZeit"][i]; Serial.printf("Name: %s, Da: %d, Zeit; %d\n", Config.Pflanzen[i], Config.PumpeDa[i], Config.PumpeZeit[i]); } Serial.println("---+++---"); PutEE(); Serial.println("Daten gespeichert"); } void TestPumpen() { if (server.hasArg("pumpe") == false) { //Check if body received server.send(200, "text/plain", "kein Parameter empfangen"); Serial.println("Nix empfangen"); return; } /*if (DoTest) { server.send(200, "text/plain", "Test laeuft, warten"); Serial.println("Test laeuft, warten"); return; }*/ TestPumpe = server.arg("pumpe").toInt(); DoTest = true; TestRunTime[TestPumpe] = millis() + (Config.PumpeZeit[TestPumpe] * 1000); server.send(200, "text/plain", "Teste Pumpe"); } void RebootHost() { Serial.println("Reboot ping"); if (server.hasArg("reboot") == 1) { Serial.println("ESP Reboot"); server.send(200, "text/plain", "reboot ok"); delay(1000); ESP.restart(); delay(1000); } } <file_sep>/* MQTT reconnect-Routine */ bool reconnectNB() { if (!MQTT_Client.connected()) { MQTT_Client.connect(ClientName, "Batt", "OnOff"); if (MQTT_Client.connected()) Serial.println(F("MQTT Connected")); else Serial.println(F("MQTT NOT connected!")); return MQTT_Client.connected(); } } /* hier wird auf den MQTT-Broker veröffentlicht. */ bool PublishData (void) { const size_t capacity = JSON_OBJECT_SIZE(22); DynamicJsonDocument doc(capacity); char JSONBuffer[512]; bool PubState = false; doc["temperatur"] = Temperatur; doc["druck"] = 0.0; doc["feuchte"] = 0.0; doc["supply"] = ESP.getVcc(); doc["ip-address"] = HostIP; doc["messung_um"] = MyTime; doc["timestamp"] = timeClient.getEpochTime(); serializeJson(doc, JSONBuffer); PubState = MQTT_Client.publish(TOPIC_7, JSONBuffer, true); Serial.printf("JSON: %s\n\n", JSONBuffer); /*delay(500); MQTT_Client.disconnect(); delay(500);*/ return (PubState); } <file_sep># Wasserwerk Dieses Projekt dient der Bewässerung von max. sechs Pflanzen. In jeder Pflanze wird die Bodenfeuchte in Prozent gemessen. Der Messwert hat wenig mit den tatsächlichen Werten zu tun. Fest stehen die Eckwerte 0% (staubtrocken) und 100% (blankes Wasser). Die Steuerung erfolgt über ein Webseite, die das Projekt im lokalen Netz anbietet. Diese Webseite sollte NUR im lokalen Netz angeboten werden. Die Kommunikation zwischen Webclient und Server ist JSON-basiert. Es wird eine Update-Funktion angeboten, die allerdings NICHT Internet-fähig ist, da die Updates vollkommen ungeschützt übertragen werden. Als Nebeneffekt werden auf dem hauseigenen MQTT-Broker einige Daten publiziert. Alle I/Os gehen über I2C mit Ausnahme des Thermometers. Hier wird OneWire verwendet.
12b46f8256a33c688de5c47726e44e99b1f762b9
[ "Markdown", "C++" ]
7
C++
kfeger/Wasserwerk
0fdb37adfad74b08149aeb51b96de063874ac4f7
5ae61f37212b8447532d03095ed702581f02520b
refs/heads/master
<repo_name>kylejonson/Sudoku_Bot<file_sep>/Sudoku.java /** *Helper Class for the TwitterBot Class *@author <NAME> *@since 3/14/2017 *@version 1.0.0 */ import java.util.Random; public class Sudoku extends AbstractSudoku{ private int[] TestRow; public Sudoku(){ super(); this.TestRow = new int[]{1,2,3,4,5,6,7,8,9}; this.TestRow = shuffle(this.TestRow); } /** * @return a Sudoku solution */ public int[][] getSolution(){ generateSolution(); return this.board; } /** * Creates a solved Sudoku board */ private void generateSolution(){ explore(0,0); } /** * Recursive method to make a solve sudoku board * @param row changing row * @param col changing column * @return true when the first solution is found */ private boolean explore(int row, int col){ if(row < 0){ //row is given by AbstractSudoku.nextOpen() return true; //Base Case; board is full & everything placed is valid }else{ for(int i = 0; i < 9; i++){ if(isSafe(TestRow[i], row, col)){ board[row][col] = TestRow[i]; int NewRow = nextOpen()[0]; int NewCol = nextOpen()[1]; if(explore(NewRow,NewCol)){ return true; //If to stop everything when the first solution is found } board[row][col] = 0; //Remove / Backtrack } } return false; } } /** * @return a Sudoku Puzzle based on the already solved board */ public int[][] getPuzzle(){ int[][] temp = new int[9][9]; //I know this is bad for(int i = 0; i < 9; i++){ //But at the same time it works for(int j = 0; j < 9; j++){ //I'll fix it later temp[i][j] = board[i][j]; // -<NAME>, java haiku } } generatePuzzle(); for(int i = 0; i < 9; i++){ for(int j = 0; j < 9; j++){ puzzle[i][j] = board[i][j]; board[i][j] = temp[i][j]; } } return this.puzzle; } /** * Generates a new Sudoku Puzzle * Run this after the generateSolution() method */ private void generatePuzzle(){ int temp1; int temp2; Random rand = new Random(); while(count() >= 17){ int row = rand.nextInt(9); int col = rand.nextInt(9); if(count() > 40){ temp1 = board[row][col]; //Over 40 elements it removes with rotational symmetry /*TODO: This is symmetry along a path y=-x. Make this actual rotational symmetry*/ temp2 = board[col][row]; board[row][col] = 0; board[col][row] = 0; if(solutions() > 1){ board[row][col] = temp1; board[col][row] = temp2; } }else{ //Under 40 elements removes them one at a time temp1 = board[row][col]; board[row][col] = 0; if(solutions() > 1){ board[row][col] = temp1; if(count() < 28){ //28 is a good stopping point if a puzzle is complete break; //It will make puzzles with less than 28 however } } } } } /** *@return the number of solutions a given board has */ private int solutions(){ int count = 0; int[][] testboard = this.board; int row = nextOpen()[0]; int col = nextOpen()[1]; return search(row,col,count,testboard); } /** * Recursive helper method for Solutions */ private int search(int row, int col, int count, int[][] testboard){ if(row < 0){ //row is given by AbstractSudoku.nextOpen() return count + 1; }else{ for(int i = 0; i < 9; i++){ if(isSafe(TestRow[i], row, col)){ testboard[row][col] = TestRow[i]; int NewRow = nextOpen()[0]; int NewCol = nextOpen()[1]; count = search(NewRow,NewCol,count,testboard); board[row][col] = 0; } } return count; } } }
b8e56ae6c0472bcb1924d0df4f36ca3ab7c72fb6
[ "Java" ]
1
Java
kylejonson/Sudoku_Bot
d1d86bed6fa52b4f69a70a3f918016e6694fcab8
1ebfc10a77e2668dd2e04e394a9daa5d3a854fea
refs/heads/master
<file_sep># exercise_1 line = input('Enter accepted price: ') filepath = input('Enter filename : ') file = open(filepath, 'w+') file.write(line) file.close() # exercise_2 line = input('Enter accepted price: ') filepath = input('Enter filename : ') try: file = open(filepath, 'w+') file.write(line) file.close() except: print('SORRY WE HAVE AN ERROR. PLEASE TRY AGAIN') # exercise_3 line = input('Enter accepted price: ') filepath = input('Enter filename : ') try: file = open(filepath, 'w+') file.write(line) file.close() except FileNotFoundError as e: print('Error opening file', filepath, e) except: print('SORRY WE HAVE AN ERROR. PLEASE TRY AGAIN') # exercise_4 line = input('Enter accepted price: ') filepath = input('Enter filename : ') try: file = open(filepath, 'w+') file.write(line) value = int(line) file.close() print('The value saved in file is', value) except FileNotFoundError as e: print('Error opening file', filepath, e) except: print('SORRY WE HAVE AN ERROR. PLEASE TRY AGAIN') # exercise_5 line = input('Enter accepted price: ') filepath = input('Enter filename : ') try: file = open(filepath, 'w+') file.write(line) file.close() value = int(line) print('The value saved in file is', value) except FileNotFoundError as e: print('Error opening file', filepath, e) except ValueError as e: print('The value entered cannot be converted to a number', line, e) except: print('SORRY WE HAVE AN ERROR. PLEASE TRY AGAIN') else: print('Actions completed successfully')<file_sep>import os import time print("Current directory is:", os.getcwd()) current_dir = os.getcwd() filename = "results.txt" fullpath = os.path.join(current_dir, filename) print("\nThe constructed file path is: ", fullpath) relative_path = "output.txt" print("\nThe absolute path is: ", os.path.abspath(relative_path)) filepath = r"c:\temp\results.txt" print("\nThe file name part is: ", os.path.basename(filepath)) print("\nIs file existing? ", os.path.exists(filepath)) if os.path.exists(filepath): print("\nLast modify date is: ", os.path.getmtime(filepath)) print("Last modify date is: ", time.localtime(os.path.getmtime(filepath))) print("\nFile size is: ", os.path.getsize(filepath)) print("\nIs it a file?", os.path.isfile(filepath)) print("Is it a dir? ", os.path.isdir(filepath)) print("\nPath splitted: ", os.path.split(filepath)) print("Only file name part: ", os.path.split(filepath)[1]) print("\nPath splitted into drive: ", os.path.splitdrive(filepath)) print("Only drive: ", os.path.splitdrive(filepath)[0]) <file_sep>import os import time dir = input("Enter directory name: ") if not os.path.isdir(dir): print(f"{dir} must be a directory") else: file = input(f"Enter filename saved in directory {dir}: ") path = os.path.join(dir, file) if not os.path.isfile(path): print(f"{path} file does't exist!") else: print(f"displaying properties of file {path}") print("Last modify date is: ", time.localtime(os.path.getmtime(path))) print('Size in bytes', os.path.getsize(path)) print('Current directory is: ', os.getcwd()) print('Relative path to the file is', os.path.relpath(path)) <file_sep>def check_int(s): if s[0] in ('-', '+'): return s[1:].isdigit() return s.isdigit() print('This program solves equation ax^2+bx+c = 0') print('Enter the values for a, b and c:') a = input("a = ") b = input("b = ") c = input("c = ") if not (check_int(a) and check_int(b) and check_int(c)): print("a, b and c need to be int!") else: a = int(a) b = int(b) c = int(c) if a == 0: print("a cannot be a 0!") else: delta = b**2 - 4*a*c if delta < 0: print("there is no solution") elif delta == 0: x1 = -b/(2*a) print(f"there is one solution: {x1}") else: x1 = (-b-delta**0.5)/(2*a) x2 = (-b+delta**0.5)/(2*a) print(f"there are two solutions: {x1} and {x2}") <file_sep>filesize = input("Enter the max file size (MB): ") filesize = int(filesize) print(f"The max size is {filesize}") print(f"Size in KB is {filesize * 1024}")<file_sep>class Cake: def __init__(self, name, kind, taste, additives, filling): self.name = name self.kind = kind self.taste = taste self.additives = additives.copy() self.filling = filling cake01 = Cake('Vanilla Cake', 'cake', 'vanilla', ['chocolade', 'nuts'], 'cream') cake02 = Cake('Chocolade Muffin', 'muffin', 'chocolade', ['chocolade'], '') cake03 = Cake('Super Sweet Maringue', 'meringue', 'very sweet', [], '') bakery_offer = [] bakery_offer.append(cake01) bakery_offer.append(cake02) bakery_offer.append(cake03) print("Today in our offer:") for c in bakery_offer: print("{} - ({}) main taste: {} with additives of {}, filled with {}".format( c.name, c.kind, c.taste, c.additives, c.filling))
a4235d8daa992811c5de8c8161f24bac3d84cfe1
[ "Python" ]
6
Python
michalconrad/October-2019
fe256b4d151d27094feae8c808ac74becabbaa37
6eda3fae004fbb1f5cb4a7393624b5fa459af0ce
refs/heads/master
<repo_name>BoSmallEar/Anime-Face-Generator<file_sep>/Style-GAN/README.txt Code for Style-GAN The code is adapted from a github repo https://github.com/NVlabs/stylegan dataseet_tool.py is modified based on the code from the above repo train.py is modified based on the code from the above repo config.py is modified based on the code from the above repo generate_figures.py is modified based on the code from https://github.com/atelier-ritz/AnimeStyleGAN <file_sep>/README.txt Code for FID The code is adapted from a github repo https://github.com/mseitzer/pytorch-fid fid_score.py is reused from the above repo inception.py is reused from the above repo <file_sep>/Style-GAN/generate_figures.py import os import pickle import numpy as np import PIL.Image import dnnlib import dnnlib.tflib as tflib from metrics import metric_base import config def randomLatents(seed1,seed2,morphingFactor,shape): # 0 < morphingFactor < 1, 0->latents0, 1-> latents1 latents0 = np.random.RandomState(seed1).randn(1, shape) latents1 = np.random.RandomState(seed2).randn(1, shape) latents = latents0+(latents1-latents0)*morphingFactor return latents if __name__ == "__main__": # Initialize TensorFlow. tflib.init_tf() # Load pre-trained network. _G, _D, Gs = pickle.load(open("network-snapshot-003285.pkl", "rb")) # Print network details. Gs.print_layers() ''' TRUNCATION = 0.7 SEED1_1 = [4722,2111,3333,1357,2589] SEED1_2 = [5944,3111,3766,3421,4171] SEED2_1 = [3611,4111,1434,2267,4102] SEED2_2 = [4333,5111,3456,4588,4990] MORPH_FACTOR = 0.84615 for i in range(5): # Pick latent vector. latents_1 = randomLatents(SEED1_1[i],SEED1_2[i],MORPH_FACTOR,Gs.input_shape[1]) # Generate image. fmt = dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True) images = Gs.run(latents_1, None, truncation_psi=TRUNCATION, randomize_noise=True, output_transform=fmt) # Save image. result_dir = 'results/' os.makedirs(result_dir, exist_ok=True) png_filename = os.path.join(result_dir, 'photo-'+str(i)+'-1.png') PIL.Image.fromarray(images[0], 'RGB').save(png_filename) latents_2 = randomLatents(SEED2_1[i],SEED2_2[i],MORPH_FACTOR,Gs.input_shape[1]) # Generate image. fmt = dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True) images = Gs.run(latents_2, None, truncation_psi=TRUNCATION, randomize_noise=True, output_transform=fmt) # Save image. result_dir = 'results/' os.makedirs(result_dir, exist_ok=True) png_filename = os.path.join(result_dir, 'photo-'+str(i)+'-2.png') PIL.Image.fromarray(images[0], 'RGB').save(png_filename) latents_3 = latents_1 + latents_2 # Generate image. fmt = dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True) images = Gs.run(latents_3, None, truncation_psi=TRUNCATION, randomize_noise=True, output_transform=fmt) # Save image. result_dir = 'results/' os.makedirs(result_dir, exist_ok=True) png_filename = os.path.join(result_dir, 'photo-'+str(i)+'-3.png') PIL.Image.fromarray(images[0], 'RGB').save(png_filename) ''' for i in range(100): # Pick latent vector. TRUNCATION = 0.7 SEED1 = 1200 + 40 * i; SEED2 = 1000 + 50 * i; MORPH_FACTOR = 0.84615 latents_1 = randomLatents(SEED1,SEED2,MORPH_FACTOR,Gs.input_shape[1]) # Generate image. fmt = dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True) images = Gs.run(latents_1, None, truncation_psi=TRUNCATION, randomize_noise=True, output_transform=fmt) # Save image. result_dir = 'results/' os.makedirs(result_dir, exist_ok=True) png_filename = os.path.join(result_dir, 'photo-'+str(i)+'-1.jpg') PIL.Image.fromarray(images[0], 'RGB').save(png_filename)<file_sep>/DC-GAN/model.py import torch import torch.nn as nn import torch.nn.parallel def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: m.weight.data.normal_(0.0, 0.02) elif classname.find('BatchNorm') != -1: m.weight.data.normal_(1.0, 0.02) m.bias.data.fill_(0) class _netG_1(nn.Module): def __init__(self, ngpu, nz, nc , ngf, n_extra_layers_g): super(_netG_1, self).__init__() self.ngpu = ngpu main = nn.Sequential( nn.ConvTranspose2d( nz, ngf * 8, 4, 1, 0, bias=False), nn.BatchNorm2d(ngf * 8), nn.LeakyReLU(0.2, inplace=True), nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf * 4), nn.LeakyReLU(0.2, inplace=True), nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf * 2), nn.LeakyReLU(0.2, inplace=True), nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf), nn.LeakyReLU(0.2, inplace=True), ) for t in range(n_extra_layers_g): main.add_module('extra-layers-{0}-{1}-conv'.format(t, ngf), nn.Conv2d(ngf, ngf, 3, 1, 1, bias=False)) main.add_module('extra-layers-{0}-{1}-batchnorm'.format(t, ngf), nn.BatchNorm2d(ngf)) main.add_module('extra-layers-{0}-{1}-relu'.format(t, ngf), nn.LeakyReLU(0.2, inplace=True)) main.add_module('final_layer_deconv', nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False)) # 5,3,1 for 96x96 main.add_module('final_layer_tanh', nn.Tanh()) self.main = main def forward(self, input): gpu_ids = None if isinstance(input.data, torch.cuda.FloatTensor) and self.ngpu > 1: gpu_ids = range(self.ngpu) return nn.parallel.data_parallel(self.main, input, gpu_ids), 0 class _netD_1(nn.Module): def __init__(self, ngpu, nz, nc, ndf, n_extra_layers_d): super(_netD_1, self).__init__() self.ngpu = ngpu main = nn.Sequential( nn.Conv2d(nc, ndf, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 2), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 4), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 8), nn.LeakyReLU(0.2, inplace=True), ) for t in range(n_extra_layers_d): main.add_module('extra-layers-{0}.{1}.conv'.format(t, ndf * 8), nn.Conv2d(ndf * 8, ndf * 8, 3, 1, 1, bias=False)) main.add_module('extra-layers-{0}.{1}.batchnorm'.format(t, ndf * 8), nn.BatchNorm2d(ndf * 8)) main.add_module('extra-layers-{0}.{1}.relu'.format(t, ndf * 8), nn.LeakyReLU(0.2, inplace=True)) main.add_module('final_layers_conv', nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False)) main.add_module('final_layers_sigmoid', nn.Sigmoid()) self.main = main def forward(self, input): gpu_ids = None if isinstance(input.data, torch.cuda.FloatTensor) and self.ngpu > 1: gpu_ids = range(self.ngpu) output = nn.parallel.data_parallel(self.main, input, gpu_ids) return output.view(-1, 1)<file_sep>/DC-GAN/generate_figures.py from __future__ import print_function from PIL import Image import random import torch import torchvision.utils as vutils from torch.autograd import Variable import torchvision.transforms import matplotlib.pyplot as plt import models model_path = 'results/netG_epoch_50.pth' #model_path = 'results/netG_epoch_99.pth' netG = models._netG_1(2, 100, 3,64, 1) # ngpu, nz, nc, ngf, n_extra_layers netG.cuda() netG.load_state_dict(torch.load(model_path, map_location=lambda storage, loc: storage)) for i in range(1144): noise_batch = torch.FloatTensor(1, 100, 1, 1).normal_(0,1) noise_batch = Variable(noise_batch) fake_batch,_ = netG(noise_batch) img_tensor = fake_batch.data.cpu() grid = vutils.make_grid(img_tensor, nrow=1, padding=2) ndarr = grid.mul(0.5).add(0.5).mul(255).byte().transpose(0, 2).transpose(0, 1).numpy() im = Image.fromarray(ndarr,'RGB') im.save('results/dcgan-generate-'+str(i)+'.jpg')<file_sep>/DC-GAN/README.txt Code for DC-GAN The code is adapted from a github repo https://github.com/jayleicn/animeGAN build_face_dataset.py is reused from the above repo model.py is modified based on the code from the above repo generate_figures.py is modified based on the code from the above repo interpretation.ipynb is modified based on the code from the above repo main.py contains the training schedule and it is modified based on the above repo
e58e4b5397ec64ff9912796b0050f5f53d7479b2
[ "Python", "Text" ]
6
Text
BoSmallEar/Anime-Face-Generator
781cd9e11ba2925cb57b1befd95b8f508bf1c6f4
8500f64be6b79f9f8c36001edc978532b56ae869
refs/heads/master
<repo_name>GambuzX/MIEIC_aeda<file_sep>/Solved Tests/teste2_17_18/Hospital.cpp /* * Hospital.cpp */ #include "Hospital.h" // #include <algorithm> Hospital::Hospital(unsigned trayC):trayCapacity(trayC) { } void Hospital::addDoctor(const Doctor &d1) { doctors.push_back(d1); } list<Doctor> Hospital::getDoctors() const { return doctors; } void Hospital::addTrays(stack<Patient> tray1) { letterTray.push_back(tray1); } list<stack<Patient> > Hospital::getTrays() const { return letterTray; } unsigned Hospital::numPatients(string medicalSpecialty) const { unsigned total = 0; for (const auto & doctor: doctors){ if (doctor.getMedicalSpecialty() == medicalSpecialty){ total += doctor.getPatients().size(); } } return total; } void Hospital::sortDoctors() { vector<Doctor> ord; for (const auto & doc : doctors) ord.push_back(doc); for (unsigned int p = 1; p < ord.size(); p++) { Doctor tmp = ord[p]; int j; for (j = p; j > 0 && tmp < ord[j-1]; j--) ord[j] = ord[j-1]; ord[j] = tmp; } doctors.clear(); for (auto & ele : ord) doctors.push_back(ele); } bool Hospital::addDoctor(unsigned codM1, string medicalSpecialty1) { int nDocs = 0; for (const auto & doc : doctors) if (doc.getMedicalSpecialty() == medicalSpecialty1) nDocs++; if (nDocs >= 3) return false; doctors.push_back(Doctor(codM1, medicalSpecialty1)); return true; } queue<Patient> Hospital::removeDoctor(unsigned codM1) { list<Doctor>::iterator it; queue<Patient> p1; for (it = doctors.begin(); it != doctors.end(); it++) if (it->getCode() == codM1) { p1 = it->getPatients(); doctors.erase(it); return p1; } throw DoctorInexistent(); } bool Hospital::putInLessBusyDoctor(unsigned cod1, string medicalSpecialty1) { int stackSize = -1; Doctor * lessOcupied = NULL; for (auto & doctor: doctors) { if (doctor.getMedicalSpecialty() == medicalSpecialty1) { if ((int) doctor.getPatients().size() < stackSize || stackSize == -1) { stackSize = doctor.getPatients().size(); lessOcupied = &doctor; } } } if (stackSize == -1) return false; lessOcupied->addPatient(Patient(cod1, medicalSpecialty1)); return true; } void Hospital::processPatient(unsigned codM1) { for (Doctor & doc: doctors) { if(doc.getCode() == codM1) { Patient pat(1, ""); try { pat = doc.removeNextPatient(); } catch(Doctor::PatientInexistent & excp) { break; } bool inserted = false; for (auto & band : letterTray) { if (band.size() < trayCapacity) { band.push(pat); inserted = true; break; } } if (!inserted) { stack<Patient> newS; newS.push(pat); letterTray.push_back(newS); } break; } } } unsigned Hospital::removePatients(unsigned codP1) { unsigned total = 0; list<stack<Patient>>::iterator it; for (it = letterTray.begin(); it != letterTray.end(); it++) { if (it->top().getCode() == codP1){ it->pop(); total++; } if (it->size() == 0) letterTray.erase(it--); } return total; } <file_sep>/Practical Classes/TP03/animal.cpp #include "animal.h" #include <sstream> string Animal::getNome() const { return nome; } int Animal::getIdade() const { return idade; } Veterinario* Animal::getVet() const { return vet; } Animal::Animal(string nome, int idade) { this->nome = nome; this->idade = idade; vet = NULL; if (Animal::maisJovem == -1 || Animal::maisJovem > idade) Animal::maisJovem = idade; } int Animal::maisJovem = -1; string Animal::getInformacao() const { ostringstream oss; oss << nome << ", " << idade; if (vet != NULL) { oss << ", " << vet->getNome() << ", " << vet->getCodOrdem(); } return oss.str(); } bool Animal::alocaVet(Veterinario *vete) { if (vete == NULL) return 1; vet = vete; return 0; } Cao::Cao(string nome, int idade, string raca): Animal(nome,idade) { this->raca = raca; } bool Cao::eJovem() const { return idade<5; } string Cao::getInformacao() const { return (Animal::getInformacao() + ", " + raca); } Voador::Voador(int vmax, int amax) { velocidade_max = vmax; altura_max = amax; } string Voador::getInformacao() const { ostringstream oss; oss << velocidade_max << ", " << altura_max; return oss.str(); } Morcego::Morcego(string nome, int idade, int vmax, int amax): Animal(nome, idade), Voador(vmax, amax) { } bool Morcego::eJovem() const { return idade<4; } string Morcego::getInformacao() const { return (Animal::getInformacao() + ", " + Voador::getInformacao()); } <file_sep>/Practical Classes/TP08/Dicionario.h #ifndef _DIC #define _DIC #include <string> #include <fstream> #include "BST.h" class PalavraSignificado { string palavra; string significado; public: PalavraSignificado(string p, string s): palavra(p), significado(s) {} string getPalavra() const { return palavra; } string getSignificado() const { return significado; } void setSignificado(string sig) { significado = sig; } bool operator < (const PalavraSignificado &ps1) const; }; class Dicionario { BST<PalavraSignificado> palavras; public: Dicionario(): palavras(PalavraSignificado("","")){}; BST<PalavraSignificado> getPalavras() const; void lerDicionario(ifstream &fich); string consulta(string palavra) const; bool corrige(string palavra, string significado); void imprime() const; }; // a alterar class PalavraNaoExiste { string pantes, santes, pdepois, sdepois; public: PalavraNaoExiste(string a, string b, string c,string d): pantes(a), santes(b), pdepois(c), sdepois(d) {} string getPalavraAntes() const { return pantes; } string getSignificadoAntes() const { return santes; } string getPalavraApos() const { return pdepois; } string getSignificadoApos() const { return sdepois; } }; #endif <file_sep>/Practical Classes/TP01/Parque.cpp #include "Parque.h" #include <vector> using namespace std; ParqueEstacionamento::ParqueEstacionamento(unsigned int lot, unsigned int nMaxCli): lotacao(lot), numMaximoClientes(nMaxCli) { vagas = lot; } unsigned int ParqueEstacionamento::getNumLugares() const { return lotacao; } unsigned int ParqueEstacionamento::getNumMaximoClientes() const { return numMaximoClientes; } int ParqueEstacionamento::posicaoCliente(const string &nome) const { int index = -1; for (unsigned i = 0; i < clientes.size(); i++) if (clientes[i].nome == nome) index = i; return index; } bool ParqueEstacionamento::adicionaCliente(const string & nome) { bool success = false; if (posicaoCliente(nome) == -1 && clientes.size() < numMaximoClientes) { InfoCartao newCard; newCard.nome = nome; newCard.presente = false; clientes.push_back(newCard); success=true; } return success; } bool ParqueEstacionamento::entrar(const string & nome) { vector<InfoCartao>::iterator it; for (it = clientes.begin(); it != clientes.end(); it++) { if (it->nome == nome) { if (!it->presente && vagas > 0) { it->presente = true; vagas--; return true; } else return false; } } return false; } bool ParqueEstacionamento::retiraCliente(const string & nome) { vector<InfoCartao>::iterator it; for (it = clientes.begin(); it != clientes.end(); it++) { if (it->nome == nome) { if (!it->presente){ clientes.erase(it); return true; } else { return false; } } } return false; } bool ParqueEstacionamento::sair(const string & nome) { vector<InfoCartao>::iterator it; for (it = clientes.begin(); it != clientes.end(); it++) { if (it->nome == nome) { if (it->presente) { it->presente = false; vagas++; return true; } else return false; } } return false; } unsigned int ParqueEstacionamento::getNumLugaresOcupados() const { return lotacao-vagas; } unsigned int ParqueEstacionamento::getNumClientesAtuais() const { return clientes.size(); } <file_sep>/Practical Classes/TP07/StackExt.h # include <iostream> # include <stack> using namespace std; template <class T> class StackExt { private: stack<T> allValues; stack<T> minValues; public: StackExt() {}; bool empty() const; T& top(); void pop(); void push(const T& val); T& findMin(); }; template <class T> bool StackExt<T>::empty() const { return allValues.empty(); } template <class T> T& StackExt<T>::top() { return allValues.top(); } template <class T> void StackExt<T>::pop() { T val = allValues.top(); if (!allValues.empty()) allValues.pop(); if (!minValues.empty() && minValues.top() == val) minValues.pop(); } template <class T> void StackExt<T>::push(const T& val) { allValues.push(val); if (minValues.empty() || val <= minValues.top()) minValues.push(val); } template <class T> T& StackExt<T>::findMin() { return minValues.top(); } <file_sep>/Practical Classes/TP03/html/search/all_3.js var searchData= [ ['veterinario',['Veterinario',['../class_veterinario.html',1,'']]], ['voador',['Voador',['../class_voador.html',1,'']]] ]; <file_sep>/Practical Classes/TP08/Jogo.cpp #include "Jogo.h" #include <sstream> BinaryTree<Circulo> & Jogo::getJogo() { return jogo; } ostream &operator << (ostream &os, Circulo &c1) { // a alterar return os; } Jogo::Jogo(int niv, vector<int> &pontos, vector<bool> &estados) { jogo = criaJogo(0, niv, pontos, estados); } BinaryTree<Circulo> Jogo::criaJogo(int pos, int niv, vector<int> &pontos, vector<bool> &estados) { if (niv == 0) return Circulo(pontos[pos], estados[pos]); return BinaryTree<Circulo>(Circulo(pontos[pos], estados[pos]), criaJogo(2*pos+1, niv-1, pontos, estados), criaJogo(2*pos+2, niv-1, pontos, estados)); } string Jogo::escreveJogo() { BTItrLevel<Circulo> iter(jogo); string returnS = ""; while (!iter.isAtEnd()) { ostringstream oss(""); oss << iter.retrieve().getPontuacao() << '-'; if (iter.retrieve().getEstado()) oss << "true-"; else oss << "false-"; oss << iter.retrieve().getNVisitas() << '\n'; returnS += oss.str(); iter.advance(); } return returnS; } int Jogo::jogada() { int pos=1, score; BTItrLevel<Circulo> iter(jogo); if(iter.isAtEnd()) return -1; while(true) { Circulo &c1 = iter.retrieve(); bool state = c1.getEstado(); int n; if (!state) n = pos; else n = pos+1; c1.mudaEstado(); c1.incrementVisits(); score = c1.getPontuacao(); int i = 0; while (i<n && !iter.isAtEnd()) { iter.advance(); i++; } if (!iter.isAtEnd()) pos += n; else break; } return score; } int Jogo::maisVisitado() { int max = 0; BTItrLevel<Circulo> iter(jogo); iter.advance(); while(!iter.isAtEnd()) { if (iter.retrieve().getNVisitas() > max) max = iter.retrieve().getNVisitas(); iter.advance(); } return max;; } <file_sep>/Practical Classes/TP08/Dicionario.cpp #include <iostream> #include <string> #include <fstream> #include "Dicionario.h" #include "BST.h" using namespace std; BST<PalavraSignificado> Dicionario::getPalavras() const { return palavras; } bool PalavraSignificado::operator < (const PalavraSignificado &ps1) const { return palavra < ps1.getPalavra(); } void Dicionario::lerDicionario(ifstream &fich) { string savingString; while (getline(fich, savingString)) { string nome = savingString; getline(fich, savingString); string definition = savingString; palavras.insert(PalavraSignificado(nome, definition)); } return; } string Dicionario::consulta(string palavra) const { BSTItrIn<PalavraSignificado> iter(palavras); while (!iter.isAtEnd()) { if (iter.retrieve().getPalavra() == palavra) { return iter.retrieve().getSignificado(); } PalavraSignificado pantes = iter.retrieve(); iter.advance(); if (! iter.isAtEnd() && iter.retrieve().getPalavra() > palavra) { throw PalavraNaoExiste(pantes.getPalavra(), pantes.getSignificado(), iter.retrieve().getPalavra(), iter.retrieve().getSignificado()); } } throw PalavraNaoExiste("", "", "", ""); return ""; } bool Dicionario::corrige(string palavra, string significado) { try { consulta(palavra); BST<PalavraSignificado> newBST(PalavraSignificado("","")); BSTItrIn<PalavraSignificado> iter(palavras); while (!iter.isAtEnd()) { if (iter.retrieve().getPalavra() == palavra) { newBST.insert(PalavraSignificado(palavra, significado)); } newBST.insert(iter.retrieve()); iter.advance(); } palavras = newBST; } catch (PalavraNaoExiste & exc) { palavras.insert(PalavraSignificado(palavra, significado)); return false; } return true; } void Dicionario::imprime() const { BSTItrIn<PalavraSignificado> iter(palavras); while (!iter.isAtEnd()) { cout << iter.retrieve().getPalavra() << endl << iter.retrieve().getSignificado() << endl; iter.advance(); } return; } <file_sep>/Solved Tests/teste1_16_17/Postman.h /* * Postman.h */ #ifndef SRC_POSTMAN_H_ #define SRC_POSTMAN_H_ #include "Mail.h" #include <string> #include <vector> class Postman { static int currID; unsigned int id; string name; vector<Mail *> myMail; public: Postman(); Postman(string name); void setName(string nm); void addMail(Mail *m); void addMail(vector<Mail *> mails); string getName() const; vector<Mail *> getMail() const; unsigned int getID() const; bool operator<(const Postman &) const; }; class NoPostmanException { string name; public: NoPostmanException(string n) { name = n; } string getName() const { return name; } }; #endif /* SRC_POSTMAN_H_ */ <file_sep>/Practical Classes/TP03/zoo.cpp #include "zoo.h" #include <sstream> int Zoo::numAnimais() const { return animais.size(); } int Zoo::numVeterinarios() const { return veterinarios.size(); } void Zoo::adicionaAnimal(Animal *a1) { animais.push_back(a1); } string Zoo::getInformacao() const { string info = ""; vector<Animal *>::const_iterator it; for (it = animais.begin(); it != animais.end(); it++) { info += (*it)->getInformacao() + "; "; } return info; } bool Zoo::animalJovem(string nomeA) { vector<Animal *>::const_iterator it; for (it = animais.begin(); it != animais.end(); it++) { if ((*it)->getNome() == nomeA) return (*it)->eJovem(); } return false; } void Zoo::alocaVeterinarios(istream &isV) { string name, codeS; while(getline(isV, name)) { getline(isV, codeS); long code = stoi(codeS); Veterinario * vet = new Veterinario(name, code); veterinarios.push_back(vet); } size_t vetNum = veterinarios.size(); for (size_t i = 0; i < animais.size(); i++) { animais[i]->alocaVet(veterinarios[i%vetNum]); } } bool Zoo::removeVeterinario(string nomeV) { size_t vetIndex = -1; for (size_t i = 0; i < veterinarios.size(); i++) { if (veterinarios[i]->getNome() == nomeV) { vetIndex = i; break; } } if ((int) vetIndex == -1) return false; vector<Animal *>::const_iterator it; for (it = animais.begin(); it != animais.end(); it++) { if (veterinarios.size() <= 1) (*it)->alocaVet(NULL); else if ((*it)->getVet()->getNome() == nomeV) (*it)->alocaVet(veterinarios[(vetIndex + 1) % veterinarios.size()]); } veterinarios.erase(veterinarios.begin() + vetIndex); return true; } bool Zoo::operator<(Zoo& zoo2) const { int sum1 = 0, sum2 = 0; vector<Animal *>::const_iterator it; for (it = animais.begin(); it != animais.end(); it++) sum1 += (*it)->getIdade(); for (it = zoo2.animais.begin(); it != zoo2.animais.end(); it++) sum2 += (*it)->getIdade(); return sum1 < sum2 ? sum1 : sum2; } <file_sep>/Solved Tests/teste1_17_18/Garage.h /* * Garage.h * * Created on: 24/10/2017 * Author: hlc */ #ifndef SRC_GARAGE_H_ #define SRC_GARAGE_H_ #include <vector> template <class Vehicle> class Garage { std::vector<Vehicle *> vehicles; const unsigned int capacity; public: Garage(int size); ~Garage(); std::vector<Vehicle *> getVehicles() const; void setVehicles(std::vector<Vehicle *> vehicles); int getCapacity() const; bool addVehicle(Vehicle *vehicle); Vehicle* removeVehicle(std::string brand, std::string model); float avgPrice(std::string brand) const; void sortVehicles(); }; class NoSuchVehicleException { public: NoSuchVehicleException() { } }; class NoSuchBrandException { std::string brand; public: NoSuchBrandException(std::string b) { brand = b; } std::string getBrand() { return brand; } }; template <class Vehicle> Garage<Vehicle>::Garage(int size) : capacity(size) { } template <class Vehicle> Garage<Vehicle>::~Garage() { typename std::vector<Vehicle *>::const_iterator it; for (it=vehicles.begin(); it!=vehicles.end(); it++) { delete *it; } } template<class Vehicle> std::vector<Vehicle *> Garage<Vehicle>::getVehicles() const { return vehicles; } template<class Vehicle> void Garage<Vehicle>::setVehicles(std::vector<Vehicle*> vehicles) { this->vehicles = vehicles; } template<class Vehicle> int Garage<Vehicle>::getCapacity() const { return capacity; } template<class Vehicle> bool Garage<Vehicle>::addVehicle(Vehicle * vehicle) { if (vehicles.size() >= capacity) return false; for (size_t i = 0; i < vehicles.size(); i++) if (*vehicles[i] == *vehicle) return false; vehicles.push_back(vehicle); return true; } template<class Vehicle> void Garage<Vehicle>::sortVehicles() { for (unsigned i = 1; i < vehicles.size(); i++) { Vehicle * tmp = vehicles.at(i); int j; for (j = i; j > 0 && *tmp < *(vehicles[j-1]); j--) vehicles[j] = vehicles[j-1]; vehicles[j] = tmp; } } template<class Vehicle> Vehicle* Garage<Vehicle>::removeVehicle(std::string brand, std::string model) { int index = -1; for (size_t i = 0; i < vehicles.size(); i++) if (vehicles.at(i)->getBrand() == brand && vehicles.at(i)->getModel() == model) index = i; if (index == -1) throw NoSuchVehicleException(); Vehicle * vehicleToRemove = vehicles[index]; vehicles.erase(vehicles.begin()+index); return vehicleToRemove; } template<class Vehicle> float Garage<Vehicle>::avgPrice(std::string brand) const { float total = 0; int nV = 0; for (size_t i = 0; i < vehicles.size(); i++) { if (vehicles.at(i)->getBrand() == brand) { total += vehicles.at(i)->getPrice(); nV++; } } if (total == 0) throw NoSuchBrandException(brand); return total/nV; } #endif /* SRC_GARAGE_H_ */ <file_sep>/Practical Classes/TP10/Aposta.cpp #include "Aposta.h" #include <iostream> #include <sstream> using namespace std; bool Aposta::contem(unsigned num) const { tabHInt::const_iterator it = numeros.find(num); if (it != numeros.end()) return true; return false; } void Aposta::geraAposta(const vector<unsigned> & valores, unsigned n) { unsigned inserted = 0; for (unsigned i = 0; i < valores.size(); i++) { if (inserted >= n) break; pair<tabHInt::iterator, bool> ret = numeros.insert(valores[i]); if (ret.second) inserted ++; } } unsigned Aposta::calculaCertos(const tabHInt & sorteio) const { unsigned certos = 0; tabHInt::const_iterator it; for (it = sorteio.begin(); it != sorteio.end(); it++) { if (contem(*it)) certos++; } return certos; } <file_sep>/Practical Classes/TP02/Frota.cpp #include "Frota.h" #include "Veiculo.h" #include <string> using namespace std; void Frota::adicionaVeiculo(Veiculo * v1) { veiculos.push_back(v1); } int Frota::numVeiculos() const { return veiculos.size(); } int Frota::menorAno() const { int menor = 0; for (unsigned i = 0; i < veiculos.size(); i++) { int ano = (veiculos.at(i))->getAno(); if (ano < menor || menor == 0) { menor = ano; } } return menor; } vector<Veiculo *> Frota::operator() (int anoM) const { vector<Veiculo *> vehicles; for (const auto & veic : veiculos) { if (anoM == veic->getAno()) vehicles.push_back(veic); } return vehicles; } float Frota::totalImposto() const{ float total; for (const auto & veic: veiculos) { total += veic->calcImposto(); } return total; } <file_sep>/Practical Classes/TP03/html/search/all_1.js var searchData= [ ['cao',['Cao',['../class_cao.html',1,'']]] ]; <file_sep>/Practical Classes/TP02/Veiculo.cpp #include "Veiculo.h" #include <iostream> using namespace std; Veiculo::Veiculo(string mc, int m, int a) { marca = mc; mes = m; ano = a; } int Veiculo::getAno() const { return ano; } int Veiculo::getMes() const { return mes; } string Veiculo::getMarca() const { return marca; } int Veiculo::info() const { cout << "Marca: " << marca << endl; cout << "Mes: " << mes << endl; cout << "Ano: " << ano << endl; return 3; } bool Veiculo::operator<(const Veiculo & v) const { if (ano == v.getAno()) return mes > v.getMes() ? false : true; else return ano > v.getAno() ? false : true; } Motorizado::Motorizado(string mc, int m, int a, string c, int cil): Veiculo(mc, m, a) { combustivel = c; cilindrada = cil; } string Motorizado::getCombustivel() const { return combustivel; } int Motorizado::info() const { Veiculo::info(); cout << "Combustivel: " << combustivel << endl; cout << "Cilindrada: " << cilindrada << endl; return 5; } float Motorizado::calcImposto() const { float imposto = 0; string co = combustivel; int ci = cilindrada; if ((co == "gasolina" && ci <= 1000) || (co != "gasolina" && ci <= 1500)) { if (getAno() > 1995) imposto = 14.56; else imposto = 8.10; } else if ((co == "gasolina" && ci > 1000 && ci <= 1300) || (co != "gasolina" && ci > 1500 && ci <= 2000)) { if (getAno() > 1995) imposto = 29.06; else imposto = 14.56; } else if ((co == "gasolina" && ci > 1300 && ci <= 1750) || (co != "gasolina" && ci > 2000 && ci <= 3000)) { if (getAno() > 1995) imposto = 45.15; else imposto = 22.65; } else if ((co == "gasolina" && ci > 1750 && ci <= 2600) || (co != "gasolina" && ci > 3000)) { if (getAno() > 1995) imposto = 113.98; else imposto = 54.89; } else if (co == "gasolina" && ci > 2600 && ci <= 3500) { if (getAno() > 1995) imposto = 181.17; else imposto = 87.13; } else if (co == "gasolina" && ci > 3500) { if (getAno() > 1995) imposto = 320.89; else imposto = 148.37; } return imposto; } Automovel::Automovel(string mc, int m, int a, string c, int cil): Motorizado(mc,m,a,c,cil) {} int Automovel::info() const { return Motorizado::info(); } Camiao::Camiao(string mc, int m, int a, string c, int cil, int cm): Motorizado(mc,m,a,c,cil) { carga_maxima = cm; } int Camiao::info() const { Motorizado::info(); cout << "Carga maxima: " << carga_maxima << endl; return 6; } Bicicleta::Bicicleta(string mc, int m, int a, string t): Veiculo(mc, m ,a) { tipo = t; } int Bicicleta::info() const { Veiculo::info(); cout << "Tipo: " << tipo << endl; return 4; } float Bicicleta::calcImposto() const { return 0; } <file_sep>/Practical Classes/TP04/grafo.h #include <iostream> #include <vector> using namespace std; /** * Versao da classe generica Grafo usando a classe vector */ template <class N, class A> class Aresta; template <class N, class A> class No { public: N info; vector< Aresta<N,A> > arestas; No(N inf) { info = inf; } }; template <class N, class A> class Aresta { public: A valor; No<N,A> *destino; Aresta(No<N,A> *dest, A val) { valor = val; destino = dest; } }; template <class N, class A> class Grafo { vector< No<N,A> *> nos; public: Grafo(); ~Grafo(); Grafo & inserirNo(const N &dados); Grafo & inserirAresta(const N &inicio, const N &fim, const A &val); Grafo & eliminarAresta(const N &inicio, const N &fim); A & valorAresta(const N &inicio, const N &fim); int numArestas(void) const; int numNos(void) const; void imprimir(std::ostream &os) const; }; template <class N, class A> std::ostream & operator<<(std::ostream &out, const Grafo<N,A> &g); // excecao NoRepetido template <class N> class NoRepetido { public: N info; NoRepetido(N inf) { info=inf; } }; template <class N> std::ostream & operator<<(std::ostream &out, const NoRepetido<N> &no) { out << "No repetido: " << no.info; return out; } // excecao NoInexistente template <class N> class NoInexistente { public: N info; NoInexistente(N inf) { info = inf; } }; template <class N> std::ostream & operator<<(std::ostream &out, const NoInexistente<N> &ni) { out << "No inexistente: " << ni.info; return out; } // excecao ArestaRepetida template <class N> class ArestaRepetida { public: N start, end; ArestaRepetida(N s, N e) { start = s; end = e; } }; template <class N> std::ostream & operator<<(std::ostream &out, const ArestaRepetida<N> &ni) { out << "Aresta repetida: " << ni.start << " , " << ni.end;; return out; } // excecao ArestaInexistente template <class N> class ArestaInexistente { public: N start, end; ArestaInexistente(N s, N e) { start = s; end = e; } }; template <class N> std::ostream & operator<<(std::ostream &out, const ArestaInexistente<N> &ni) { out << "Aresta inexistente: " << ni.start << " , " << ni.end;; return out; } template <class N, class A> Grafo<N,A>::Grafo() {} template <class N, class A> Grafo<N,A>::~Grafo() { typename vector <No<N,A> *>::const_iterator it; for (it = nos.begin(); it!=nos.end(); it++) delete *it; } template <class N, class A> int Grafo<N,A>::numNos() const { return nos.size(); } template <class N, class A> int Grafo<N,A>::numArestas() const { int total = 0; for (size_t i = 0; i < nos.size(); i++) total += (*nos[i]).arestas.size(); return total; } template <class N, class A> Grafo<N, A> & Grafo<N,A>::inserirNo(const N &dados) { for (size_t i = 0; i < nos.size(); i++) { if ((*nos[i]).info == dados) throw NoRepetido<N>(dados); } No<N,A> * newNode = new No<N,A>(dados); nos.push_back(newNode); return *this; } template <class N, class A> Grafo<N, A> & Grafo<N, A>::inserirAresta(const N &inicio, const N &fim, const A &val) { No<N,A> * start = NULL; No<N,A> * end = NULL; for (size_t i = 0; i < nos.size(); i++) if ((*nos[i]).info == inicio) start = nos[i]; else if ((*nos[i]).info == fim) end = nos[i]; if (start == NULL) throw NoInexistente<N>(inicio); if (end == NULL) throw NoInexistente<N>(fim); for (auto it = start->arestas.begin(); it != start->arestas.end(); it++) { if (it->destino == end) throw ArestaRepetida<N>(inicio, fim); } Aresta<N, A> ar (end, val); start->arestas.push_back(ar); return *this; } template <class N, class A> A & Grafo<N, A>::valorAresta(const N &inicio, const N &fim) { No<N,A> * start = NULL; No<N,A> * end = NULL; Aresta<N,A> * edge = NULL; for (size_t i = 0; i < nos.size(); i++) { if ((*nos[i]).info == inicio) start = nos[i]; if ((*nos[i]).info == fim) end = nos[i]; } if (start == NULL) throw NoInexistente<N>(inicio); if (end == NULL) throw NoInexistente<N>(fim); for (auto it = start->arestas.begin(); it != start->arestas.end(); it++) if (it->destino == end) edge = &(*it); if (edge == NULL) throw ArestaInexistente<N>(inicio, fim); return edge->valor; } template <class N, class A> Grafo<N,A> & Grafo<N,A>::eliminarAresta(const N &inicio, const N &fim) { No<N,A> * start = NULL; No<N,A> * end = NULL; int index = -1; for (size_t i = 0; i < nos.size(); i++) { if ((*nos[i]).info == inicio) start = nos[i]; if ((*nos[i]).info == fim) end = nos[i]; } if (start == NULL) throw NoInexistente<N>(inicio); if (end == NULL) throw NoInexistente<N>(fim); for (size_t i = 0; i < start->arestas.size(); i++) { if (start->arestas[i].destino == end) index = i; } if (index == -1) throw ArestaInexistente<N>(inicio, fim); start->arestas.erase(start->arestas.begin()+index); return *this; } template <class N, class A> void Grafo<N,A>::imprimir(std::ostream &os) const { for (const auto & node: nos) { os << "( " << node->info; for (const auto & edge: node->arestas) { os << "[ " << edge.destino->info << " " << edge.valor << "] "; } os << ") "; } } template <class N, class A> std::ostream & operator<<(std::ostream &out, const Grafo<N,A> &g) { g.imprimir(out); return out; } <file_sep>/Practical Classes/TP06/Jogo.cpp /* * Jogo.cpp * */ #include "Jogo.h" using namespace std; unsigned Jogo::numPalavras(string frase) { if ( frase.length() == 0 ) return 0; int n=1; unsigned pos = frase.find(' '); while ( pos != string::npos ) { frase = frase.substr(pos+1); pos = frase.find(' '); n++; } return n; } Jogo::Jogo() { criancas.clear(); } Jogo::Jogo(list<Crianca>& lc2) { for (const auto & c : lc2) criancas.push_back(c); } void Jogo::insereCrianca(const Crianca &c1) { criancas.push_back(c1); } list<Crianca> Jogo::getCriancasJogo() const { return criancas; } string Jogo::escreve() const { string res = ""; for (const auto & c : criancas) res += c.escreve() + '\n'; return res; } Crianca& Jogo::perdeJogo(string frase) { int nP = numPalavras(frase); while(criancas.size() > 1) { int index = (nP-1) % criancas.size(); list<Crianca>::iterator it = criancas.begin(); for (int i = 0; i < index; i++) it++; criancas.erase(it); } return *(criancas.begin()); } list<Crianca>& Jogo::inverte() { list<Crianca> lista; int n = criancas.size(); for (int i = 0; i < n; i++) { lista.push_back(criancas.back()); criancas.pop_back(); } criancas.clear(); for (const auto & c: lista) criancas.push_back(c); // a alterar return criancas; } list<Crianca> Jogo::divide(unsigned id) { list<Crianca> lista; list<Crianca>::iterator it; for (it = criancas.begin(); it != criancas.end(); it++) { if (it->getIdade() > id) { lista.push_back(*it); it = criancas.erase(it); it--; } } return lista; } void Jogo::setCriancasJogo(const list<Crianca>& l1) { for (const auto & c : l1) criancas.push_back(c); } bool Jogo::operator==(Jogo& j2) { return criancas == j2.getCriancasJogo(); } list<Crianca> Jogo::baralha() const { list<Crianca> copy = criancas; list<Crianca> randomL; for (unsigned i = 0; i < criancas.size(); i++){ int index = rand() % copy.size(); list<Crianca>::iterator it = copy.begin(); for (int j = 0; j < index; j++) it++; randomL.push_back(*it); copy.erase(it); } return randomL; } <file_sep>/Practical Classes/TP03/veterinario.cpp #include "veterinario.h" Veterinario::Veterinario(string n, int c) { nome = n; codOrdem = c; } string Veterinario::getNome() const { return nome; } long Veterinario::getCodOrdem() const { return codOrdem; } <file_sep>/Practical Classes/TP10/Jogador.cpp #include "Jogador.h" void Jogador::adicionaAposta(const Aposta & ap) { apostas.insert(ap); } unsigned Jogador::apostasNoNumero(unsigned num) const { unsigned count = 0; tabHAposta::const_iterator it; for (it = apostas.begin(); it != apostas.end(); it++) { if (it->contem(num)) count++; } return count; } tabHAposta Jogador::apostasPremiadas(const tabHInt & sorteio) const { tabHAposta money; tabHAposta::const_iterator it; for (it = apostas.begin(); it != apostas.end(); it++) { int correct = 0; for (tabHInt::const_iterator it2 = sorteio.begin(); it2 != sorteio.end(); it2++) { if (it->contem(*it2)) correct++; } if (correct > 3) { money.insert(*it); } } return money; } <file_sep>/Practical Classes/TP07/Balcao.cpp #include <queue> #include <cstdlib> #include "Balcao.h" #include <random> using namespace std; Cliente::Cliente() { numPresentes = rand() % 5 + 1; } int Cliente::getNumPresentes() const { return numPresentes; } Balcao::Balcao(int te): tempo_embrulho(te) { tempo_atual = 0; prox_chegada = rand() % 20 + 1; prox_saida = 0; clientes_atendidos = 0; } void Balcao:: proximoEvento() { if (clientes.empty() || prox_chegada < prox_saida) { tempo_atual = prox_chegada; chegada(); } else { tempo_atual = prox_saida; saida(); } } void Balcao::chegada() { Cliente cl = Cliente(); clientes.push(cl); prox_chegada = rand() % 20 + 1; if (clientes.size() == 1) prox_saida = tempo_atual + cl.getNumPresentes() * tempo_embrulho; cout << "tempo= " << tempo_atual << "'\nchegou novo cliente com " << cl.getNumPresentes() << " presentes" << endl; } void Balcao::saida() { Cliente cl = getProxCliente(); clientes.pop(); clientes_atendidos++; if (clientes.size() == 0) prox_saida = tempo_atual; else prox_saida = tempo_atual + clientes.front().getNumPresentes() * tempo_embrulho; cout << "tempo= " << tempo_atual << "'\nsaiu cliente com " << cl.getNumPresentes() << " presentes" << endl; } int Balcao::getTempoAtual() const { return tempo_atual; } int Balcao::getProxChegada() const { return prox_chegada; } ostream & operator << (ostream & out, const Balcao & b1) { cout << "Numero de clientes atendidos: " << b1.clientes_atendidos << ", Numero de clientes em espera: " << b1.clientes.size() << endl; return out; } int Balcao::getTempoEmbrulho() const { return tempo_embrulho; } int Balcao::getProxSaida() const { return prox_saida; } int Balcao::getClientesAtendidos() const { return clientes_atendidos; } Cliente & Balcao::getProxCliente() { if (clientes.empty()) throw FilaVazia(); return clientes.front(); } <file_sep>/Solved Tests/teste1_16_17/Postman.cpp /* * Postman.cpp */ #include "Postman.h" template <class N> extern unsigned int numberDifferent(const vector<N> &); Postman::Postman(): id(0) {} Postman::Postman(string n) { name = n; id = currID; currID++; } int Postman::currID = 1; void Postman::setName(string nm){ name = nm; } string Postman::getName() const{ return name; } vector<Mail *> Postman::getMail() const { return myMail; } void Postman::addMail(Mail *m) { myMail.push_back(m); } void Postman::addMail(vector<Mail *> mails) { myMail.insert(myMail.end(),mails.begin(),mails.end()); } unsigned int Postman::getID() const{ return id; } bool Postman::operator<(const Postman &postman) const { int n1, n2; vector<string> zipCodes; for (const auto & mail : myMail) zipCodes.push_back(mail->getZipCode()); n1 = numberDifferent(zipCodes); zipCodes.clear(); for (const auto & mail : postman.getMail()) zipCodes.push_back(mail->getZipCode()); n2 = numberDifferent(zipCodes); return n1 < n2; } <file_sep>/Solved Tests/teste1_16_17/PostOffice.cpp /* * PostOffice.cpp */ #include "PostOffice.h" #include <string> PostOffice::PostOffice(string firstZCode, string lastZCode): firstZipCode(firstZCode), lastZipCode(lastZCode) {} PostOffice::PostOffice() {} void PostOffice::addMailToSend(Mail *m) { mailToSend.push_back(m); } void PostOffice::addMailToDeliver(Mail *m) { mailToDeliver.push_back(m); } void PostOffice::addPostman(const Postman &p){ postmen.push_back(p); } vector<Mail *> PostOffice::getMailToSend() const { return mailToSend; } vector<Mail *> PostOffice::getMailToDeliver() const { return mailToDeliver; } vector<Postman> PostOffice::getPostman() const { return postmen; } vector<Mail *> PostOffice::removePostman(string name) { vector<Mail *> mail; for (size_t i = 0; i < postmen.size(); i++) if (postmen.at(i).getName() == name) { mail = postmen.at(i).getMail(); postmen.erase(postmen.begin()+i); break; } return mail; } vector<Mail *> PostOffice::endOfDay(unsigned int &balance) { balance = 0; vector<Mail *> retVec; for (const auto & mail : mailToSend) { balance += mail->getPrice(); if (mail->getZipCode() >= firstZipCode && mail->getZipCode() <= lastZipCode) addMailToDeliver(mail); else retVec.push_back(mail); } mailToSend.clear(); return retVec; } Postman PostOffice::addMailToPostman(Mail *m, string name) { int index = -1; for (size_t i = 0 ; i < postmen.size(); i++) if (postmen.at(i).getName() == name) index = i; if (index == -1) throw NoPostmanException(name); postmen.at(index).addMail(m); return postmen.at(index); } <file_sep>/Solved Tests/teste2_16_17/Purchase.cpp /* * Purchase.cpp * * Created on: Nov 16, 2016 * Author: hlc */ #include "Purchase.h" using namespace std; Purchase::Purchase(long cli) : client (cli) { } long Purchase::getClient() const { return client; } list< stack<Article*> > Purchase::getBags() const { return bags; } /** * Create an Article associated with the client of this purchase. */ Article* Purchase::createArticle(long barCode, bool present, bool deliverHome) { Article * art = new Article(client, barCode); art->setPresent(present); art->setDeliverHome(deliverHome); return art; } /** * Add an Article to the bags of this purchase. A new bag is added when the last bag is full. */ void Purchase::putInBag(Article* article) { bool inserted = false; for (auto & bag : bags) { if (bag.size() < Purchase::BAG_SIZE) { inserted = true; bag.push(article); } } if (!inserted) { stack<Article*> newBag; newBag.push(article); bags.push_back(newBag); } } /** * Pop from the bags all articles that are presents. * All other articles are pushed back into the bags where they were, maintaining order. */ vector<Article*> Purchase::popPresents() { vector<Article*> presents; for (auto & bag : bags) { list<Article*> temp; while(bag.size() > 0) { if(bag.top()->getPresent()) { presents.push_back(bag.top()); } else { temp.push_back(bag.top()); } bag.pop(); } list<Article*>::reverse_iterator it; for (it = temp.rbegin(); it != temp.rend(); it++) bag.push(*it); } return presents; } <file_sep>/Solved Tests/teste2_17_18/Doctor.cpp /* * Doctor.cpp */ #include "Doctor.h" Patient::Patient(unsigned codP, string mS): codeP(codP), medicalSpecialty(mS) {} string Patient::getMedicalSpecialty() const { return medicalSpecialty; } unsigned Patient::getCode() const { return codeP; } Doctor::Doctor(unsigned codM, string mS): codeM(codM), medicalSpecialty(mS) {} Doctor::Doctor(unsigned codM, string mS, queue<Patient> patients1): codeM(codM), medicalSpecialty(mS), patients(patients1) {} unsigned Doctor::getCode() const { return codeM; } string Doctor::getMedicalSpecialty() const { return medicalSpecialty; } queue<Patient> Doctor::getPatients() const { return patients; } void Doctor::addPatient(const Patient &p1) { patients.push(p1); } Patient Doctor::removeNextPatient() { if (!patients.empty()) { Patient p1 = patients.front(); patients.pop(); return p1; } else throw PatientInexistent(); } void Doctor::moveToFront(unsigned codP1) { queue<Patient> temp = patients; queue<Patient> newQueue; while (temp.size() > 0) { Patient pat = temp.front(); temp.pop(); if (pat.getCode() == codP1) newQueue.push(pat); } while(patients.size() > 0) { Patient pat = patients.front(); patients.pop(); if (pat.getCode() != codP1) newQueue.push(pat); } patients = newQueue; } bool Doctor::operator<(Doctor & doc) { if (medicalSpecialty == doc.getMedicalSpecialty() && patients.size() == doc.getPatients().size()) return codeM < doc.getCode(); else if (patients.size() == doc.getPatients().size()) return medicalSpecialty < doc.getMedicalSpecialty(); return patients.size() < doc.getPatients().size(); } <file_sep>/Practical Classes/TP05/parque.cpp #include "parque.h" #include "insertionSort.h" #include "sequentialSearch.h" #include <vector> using namespace std; ParqueEstacionamento::ParqueEstacionamento(unsigned int lot, unsigned int nMaxCli): lotacao(lot), numMaximoClientes(nMaxCli) { numClientes = 0; vagas=lot; } ParqueEstacionamento::~ParqueEstacionamento() {} vector<InfoCartao> ParqueEstacionamento::getClientes() const { return clientes; } bool ParqueEstacionamento::adicionaCliente(const string & nome) { if ( numClientes == numMaximoClientes ) return false; if ( posicaoCliente(nome) != -1 ) return false; InfoCartao info; info.nome = nome; info.presente = false; info.frequencia = 0; // a fazer clientes.push_back(info); numClientes++; return true; } bool ParqueEstacionamento::retiraCliente(const string & nome) { for (vector<InfoCartao>::iterator it = clientes.begin(); it != clientes.end(); it++) if ( it->nome == nome ) { if ( it->presente == false ) { clientes.erase(it); numClientes--; return true; } else return false; } return false; } unsigned int ParqueEstacionamento::getNumLugares() const { return lotacao; } unsigned int ParqueEstacionamento::getNumLugaresOcupados() const { return lotacao-vagas; } int ParqueEstacionamento::getFrequencia(const string &nome) const { int index = posicaoCliente(nome); if (index == -1) throw ClienteNaoExistente(nome); return clientes[index].frequencia; } bool ParqueEstacionamento::entrar(const string & nome) { if ( vagas == 0 ) return false; int pos = posicaoCliente(nome); if ( pos == -1 ) return false; if ( clientes[pos].presente == true ) return false; clientes[pos].frequencia++; clientes[pos].presente = true; vagas--; return true; } bool ParqueEstacionamento::sair(const string & nome) { int pos = posicaoCliente(nome); if ( pos == -1 ) return false; if ( clientes[pos].presente == false ) return false; clientes[pos].presente = false; vagas++; return true; } int ParqueEstacionamento::posicaoCliente(const string & nome) const { InfoCartao ic; ic.nome = nome; return sequentialSearch(clientes, ic); } void ParqueEstacionamento::ordenaClientesPorFrequencia() { insertionSort(clientes); } void ParqueEstacionamento::ordenaClientesPorNome() { for(unsigned int j=clientes.size()-1; j>0; j--){ bool troca=false; for(unsigned int i = 0; i<j; i++) if(clientes[i+1].nome < clientes[i].nome) { swap(clientes[i],clientes[i+1]); troca = true; } if (!troca) return; } } vector<string> ParqueEstacionamento::clientesGamaUso(int n1, int n2) { vector<InfoCartao> v = clientes; vector<string> nomes; insertionSort(v); for (size_t i = 0; i < v.size(); i++) if (v.at(i).frequencia >= n1 && v.at(i).frequencia <= n2) nomes.push_back(v.at(i).nome); return nomes; } InfoCartao ParqueEstacionamento::getClienteAtPos(vector<InfoCartao>::size_type p) const { if (p > clientes.size()-1) throw PosicaoNaoExistente(p); return clientes.at(p); } bool InfoCartao::operator==(const InfoCartao &ic1) const { return ic1.nome == nome; } bool InfoCartao::operator<(const InfoCartao &ic1) const { if (ic1.frequencia == frequencia) { return nome < ic1.nome; } return ic1.frequencia < frequencia; } ostream & operator<<(ostream & os, const ParqueEstacionamento & pe) { for (const auto &cl : pe.clientes) { os << cl.nome << " " << cl.frequencia; if (cl.presente) os << " - Present" << endl; else os << " - Not Present" << endl; } return os; } <file_sep>/Practical Classes/TP03/animal.h #ifndef SRC_ANIMAL_H_ #define SRC_ANIMAL_H_ #include "veterinario.h" #include <string> using namespace std; class Animal { protected: string nome; int idade; Veterinario *vet; static int maisJovem; public: /** * Constructor for the Animal class * @param nome Animal name * @param idade Animal age */ Animal(string nome, int idade); /** * Animal class Destructor */ virtual ~Animal(){}; /** * Name getter method * @return Animal name */ string getNome() const; /** * Age getter method * @return Animal age */ int getIdade() const; /** * Assigned veterinary getter method * @return Animal assigned veterinary */ Veterinario* getVet() const; /** * Youngest animal getter method * @return Younger of the existent animal's age */ static int getMaisJovem() { return maisJovem; } /** * Verify if the animal is considered young * @return bool representing if the animal is young */ virtual bool eJovem() const = 0; /** * Get the attributes' information of the animal * @return string with the animal's information */ virtual string getInformacao() const; /** * Assign a veterinary to the animal * @param Veterinary to assign * @return bool representing operation success */ bool alocaVet(Veterinario *vet); }; class Cao: public Animal { string raca; public: /** * Constructor for the Cao class * @param nome Cao name * @param idade Cao age * @param raca Cao breed */ Cao(string nome, int idade, string raca); /** * Verify if the cao is considered young * @return bool representing if the cao is young */ bool eJovem() const; /** * Get the attributes' information of the Cao * @return string with the Cao's information */ string getInformacao() const; }; class Voador { int velocidade_max; int altura_max; public: /** * */ Voador(int vmax, int amax); virtual ~Voador(){}; virtual string getInformacao() const; }; class Morcego: public Animal, public Voador { public: Morcego(string nome, int idade, int vmax, int amax); bool eJovem() const; string getInformacao() const; }; #endif /* SRC_ANIMAL_H_ */ <file_sep>/README.md # Algorithms and Data Structures 2018-2019 :file_folder: Exercises solved during practical classes for the AEDA curricular unit, as well as tests from previous years. #### Project [https://github.com/GambuzX/Games_Library](https://github.com/GambuzX/Games_Library "GamesLibrary") <br> **Final Grade: 19** ### Technologies and Software Used * C++ * Doxygen * Visual Paradigm (UML diagram) * Eclipse ### Curricular Unit Info * **Date:** 2nd Year, 1st Semester, 2018/2019 * **Course:** [Algoritmos e Estruturas de Dados | Algorithms and Data Structures](https://sigarra.up.pt/feup/en/UCURR_GERAL.FICHA_UC_VIEW?pv_ocorrencia_id=419991 "AEDA") (AEDA) ### Disclaimer (Valid for any `MIEIC_course` repository) This repository was used for educational purposes and I do not take any responsibility for anything related to its content. You are free to use any code or algorithm you find, but do so at your own risk. <file_sep>/Practical Classes/TP11/MaquinaEmpacotar.cpp /* * Empacotador.cpp */ #include "MaquinaEmpacotar.h" #include <sstream> MaquinaEmpacotar::MaquinaEmpacotar(int capCaixas): capacidadeCaixas(capCaixas) {} unsigned MaquinaEmpacotar::numCaixasUsadas() { return caixas.size(); } unsigned MaquinaEmpacotar::addCaixa(Caixa& cx) { caixas.push(cx); return caixas.size(); } HEAP_OBJS MaquinaEmpacotar::getObjetos() const { return this->objetos; } HEAP_CAIXAS MaquinaEmpacotar::getCaixas() const { return this->caixas; } /* a implementar pelos estudantes */ unsigned MaquinaEmpacotar::carregaPaletaObjetos(vector<Objeto> &objs) { unsigned loaded = 0; vector<Objeto>::iterator it; for (it = objs.begin(); it != objs.end(); it++) { if (it->getPeso() > capacidadeCaixas) continue; loaded++; objetos.push(*it); it = objs.erase(it); it--; } return loaded; } Caixa MaquinaEmpacotar::procuraCaixa(Objeto& obj) { Caixa cx = Caixa(capacidadeCaixas); unsigned size = caixas.size(); vector<Caixa> vecCaixas; for (size_t i = 0; i < size; i++) { vecCaixas.push_back(caixas.top()); caixas.pop(); } vector<Caixa>::iterator it; for (it = vecCaixas.begin(); it != vecCaixas.end(); it++) { if (it->getCargaLivre() >= obj.getPeso()) { cx = *it; vecCaixas.erase(it); break; } } for (size_t i = 0; i < vecCaixas.size(); i++) caixas.push(vecCaixas[i]); return cx; } unsigned MaquinaEmpacotar::empacotaObjetos() { unsigned usedBoxes = 0; vector<unsigned> ids; unsigned n_objs = objetos.size(); for (unsigned i = 0; i < n_objs; i++) { Objeto obj = objetos.top(); objetos.pop(); Caixa box = procuraCaixa(obj); box.addObjeto(obj); caixas.push(box); bool repeatedBox = false; for (unsigned j = 0; j < ids.size(); j++) if (ids[j] == box.getID()) repeatedBox = true; if (!repeatedBox) { ids.push_back(box.getID()); usedBoxes++; } } return usedBoxes; } string MaquinaEmpacotar::imprimeObjetosPorEmpacotar() const { string retString = ""; if (objetos.size() == 0) return "Nao ha objetos!\n"; HEAP_OBJS copy = objetos; unsigned n_objs = copy.size(); for (unsigned i = 0; i < n_objs; i++) { Objeto obj = copy.top(); copy.pop(); ostringstream oss; oss << obj; retString += oss.str() + '\n'; } return retString; } Caixa MaquinaEmpacotar::caixaMaisObjetos() const { if (caixas.size() == 0) throw MaquinaSemCaixas(); HEAP_CAIXAS copy = caixas; unsigned n_boxes = copy.size(); unsigned maxObjs = 0; Caixa cx; for (unsigned i = 0; i < n_boxes; i++) { Caixa temp = copy.top(); copy.pop(); if (temp.getSize() > maxObjs) { maxObjs = temp.getSize(); cx = temp; } } return cx; }
90e6ad841f0b7388bdae1e901ba10d17fa10d296
[ "JavaScript", "C++", "Markdown" ]
28
C++
GambuzX/MIEIC_aeda
6e61710af090667cbc60796b38661666181ac26e
76cdeeab32abbc072b8bfb919f1ecbde98aad0a3
refs/heads/master
<file_sep>const qwertyID = document.querySelector('#qwerty'); const phraseID = document.querySelector('#phrase '); const ul = phraseID.querySelector('ul'); const divOL = document.querySelector('#scoreboard'); const ol = divOL.querySelector('ol'); let missed = 0; //player life let score = 0; const phrases = ['The Dark Knight', 'The Dark Knight Rises', 'Lord of the rings', 'interstellar', 'Joker', 'The Green mile', 'Inception']; //Hide overlay div on click .btn__reset const overlay = document.querySelector('#overlay'); const h2 = overlay.querySelector('h2'); const a = overlay.querySelector('a'); const start = document.querySelector('.btn__reset'); start.addEventListener('click', (e) => { overlay.style.display = 'none'; }); const getRandomPhraseAsArray = (arr) => { let randNumb = Math.floor(Math.random() * Math.floor(arr.length)); return arr[randNumb].split(''); } const addPhraseToDisplay = (arr) => { console.log(arr); for(let i=0; i<arr.length; i++){ const li = document.createElement('li'); li.className = 'space'; if(arr[i] !== " "){ li.className = 'letter'; } ul.appendChild(li); } } let praseArray = getRandomPhraseAsArray(phrases); addPhraseToDisplay(praseArray); const resetGame = () => { missed = 0; score = 0; ol.innerHTML = ''; for(let i=0; i<5; i++){ ol.innerHTML += `<li class="tries"><img src="images/liveHeart.png" height="35px" width="30px"></li>`; } const button = qwertyID.querySelectorAll('button'); for(let i=0; i<button.length; i++){ button[i].className = ''; button[i].disabled = false; } const li = ul.querySelectorAll('li'); for(let i=0; i<li.length; i++){ ul.removeChild(li[i]); } praseArray = getRandomPhraseAsArray(phrases); addPhraseToDisplay(praseArray); } const checkLetter = (button) => { let check = false; const li = ul.querySelectorAll('li'); for(let i=0; i<praseArray.length; i++){ if(button.textContent === praseArray[i].toLowerCase()){ check = true; score++; li[i].textContent = praseArray[i]; } check ? button.className = 'show' : button.className = 'chosen'; button.disabled = true; } return check ? button.textContent : null; } const checkWin = () => { const li = ul.querySelectorAll('li.letter').length; if(missed >= 5){ overlay.style.display = ""; overlay.className = 'lose'; h2.textContent = "GAME OVER!"; a.textContent = 'Try again.'; resetGame(); } else if(score === li){ overlay.style.display = ""; overlay.className = 'win'; h2.textContent = "Winner!"; a.textContent = 'Try again.'; resetGame(); } } qwertyID.addEventListener('click', (e) => { if(e.target.tagName === 'BUTTON'){ const button = e.target; const check = checkLetter(button); if(check === null) { const li = ol.firstElementChild; missed++; ol.removeChild(li); } checkWin(); } });
faf4abd27f8de5f894dc7f62cb89491c0a31417f
[ "JavaScript" ]
1
JavaScript
Bpetrushev/game-show-app
194a2233925353937f42a18e7d89d737c86c2fa3
b70a0dadf5e5fc5cee038b007724854adc216d64
refs/heads/master
<file_sep>package com.interesting; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; /** * @author libinghui * @date 2019/1/2 11:31 */ @EnableEurekaClient @SpringBootApplication public class InterestingApplication { public static void main(String[] args) { SpringApplication.run(InterestingApplication.class, args); } } <file_sep>package com.interesting.ticketgrabbing.controller; import com.interesting.ticketgrabbing.service.GrabRedService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author libinghui * @date 2019/1/23 13:37 */ @RestController public class GrabRedController { @Autowired GrabRedService grabRedService; @RequestMapping("/ticket-grabbing") public void grapRed() { //price 红包总金额 //person 红包个数 int price = 100; int person = 28; grabRedService.grapRed(price,person); } } <file_sep>package com.interesting.ticketgrabbing.service; /** * @author libinghui * @date 2019/1/23 13:38 */ public interface GrabRedService { /** * 抢红包实现 * @param price * @param person */ void grapRed(int price, int person); }
913b2bafe81412da3b5adc5e64529b1e0e76b0b5
[ "Java" ]
3
Java
binghuili/just-for-interesting
e04de47a3fc3967ae8ce5268825c4c4436e2b677
1ff40eff1bd76d14ed51569a322f04bf6d435b9f
refs/heads/master
<file_sep>import LivingThing from './LivingThing.js'; export default class Eukaryota extends LivingThing { constructor (name, uniCellular, asexual, mobile, heterotroph) { super(name, uniCellular, true, false, asexual, mobile, heterotroph); this._heterotroph = heterotroph; } get heterotroph () { return this._heterotroph; } set heterotroph (boolean) { this._heterotroph = boolean; } get autotroph () { return !this._heterotroph; } set autotroph (boolean) { this._heterotroph = !boolean; } }
5681f3fb477c9d500209f0e4bc2fd1139a17bc11
[ "JavaScript" ]
1
JavaScript
Hyperkind/Kingdom-of-OOP
a5a242dc02526304d7b33d7aeb56e06982a44f4e
7bf5373f1f0064d81350a7bb39b5e1ed93189ea0
refs/heads/master
<repo_name>PeterRichardsWA/DojoStoreEcommerce<file_sep>/website/application/views/cart.php <html> <head> <title>Shopping Cart</title> <style type="text/css"> *{ margin: 0px; padding: 0px; } #header{ background-color: black; color:white; width:100%; height:50px; font-size: 36px; margin-bottom: 50px; } #header a{ margin-left: 70%; color:white; } table{ margin: 0 auto; } #total{ <<<<<<< HEAD margin-left:50%; margin-top: 10px; margin-bottom: 100px; font-size: 24px; ======= margin-left:80%; margin-top: 10px; margin-bottom: 100px; >>>>>>> remotes/origin/master } th{ width:50px; border-bottom: 1px solid black; } <<<<<<< HEAD th, td{ font-size: 24px; text-align: center; } ======= >>>>>>> remotes/origin/master form{ margin-left: 50px; } p{ margin: 20px; } </style> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script type="text/javascript"> <<<<<<< HEAD // when the "same as shipping" box is checked, hide the form for billing info ======= >>>>>>> remotes/origin/master $('document').ready(function(){ $('#check').click(function(){ $('.duplicate').toggle('showOrHide'); }); }); </script> </head> <body> <div id="header"> <<<<<<< HEAD Dojo eCommerce <a href="/main/cart">View Cart<?php echo "(".$cart['items']."): $".$cart['total']; ?></a> </div> <!-- cart displays correctly and allows for deleting items correctly. --> <!-- need to add ability to update the quantities and have the page update with ajax--> ======= <NAME> <a href="/main/cart">View Cart</a> </div> >>>>>>> remotes/origin/master <table> <tr> <th>Item</th> <th>Price</th> <th>Quantity</th> <th>Total</th> <th>Remove Item</th> </tr> <?php $total=0; foreach ($cartInfo as $item) { $subtotal=$item['price']*$item['quantity']; $total=$total+$subtotal; <<<<<<< HEAD $id=$item['id']; echo "<tr><td>".$item['name']."</td><td>".$item['price']."</td><td>".$item['quantity']."</td><td>".$subtotal."</td><td><a href='/main/remove/".$id."'>X</a></td></tr>"; } ?> </table> <!-- display the total below the cart --> <div id="total"> <?php echo "<p>Total:$".$total."</p>"; ?> <a href="/main/delete"><button>Delete Cart</button></a> ======= echo "<tr><td>".$item['name']."</td><td>".$item['price']."</td></td>".$item['quantity']."</td><td>".$subtotal."</td><td><a href='/main/remove'>X</a></td></tr>"; } ?> </table> <div id="total"> <?php echo "Total:$".$total; ?> >>>>>>> remotes/origin/master <a href="/"><button>Continue Shopping</button></a> </div> <form action="/main/order" method="post"> <h2>Shipping Information</h2> <p>First Name:<input type="text" name="ship_first"></p> <p>Last Name:<input type="text" name="ship_last"></p> <p>Address:<input type="text" name="ship_street1"></p> <p>Address 2:<input type="text" name="ship_street2"></p> <p>City:<input type="text" name="ship_city"></p> <p>State:<input type="text" name="ship_state"></p> <p>Zip Code:<input type="text" name="ship_zip"></p> <h2>Billing Information</h2> <input id="check" type="checkbox" name="same_info" value="same_info">Same As Shipping Address <<<<<<< HEAD <!-- duplicate class gets hidden by jquery --> ======= >>>>>>> remotes/origin/master <p class="duplicate">First Name:<input type="text" name="bill_first"></p> <p class="duplicate">Last Name:<input type="text" name="bill_last"></p> <p class="duplicate">Address:<input type="text" name="bill_street1"></p> <p class="duplicate">Address 2:<input type="text" name="bill_street2"></p> <p class="duplicate">City:<input type="text" name="bill_city"></p> <p class="duplicate">State:<input type="text" name="bill_state"></p> <p class="duplicate">Zip Code:<input type="text" name="bill_zip"></p> <p>Card Number:<input type="text" name="bill_card"></p> <p>Security Code:<input type="text" name="bill_security"></p> <p>Expiration Date:<input type="month" name="bill_date"></p> <<<<<<< HEAD <!-- pass the total through the form to display on confirmation. --> <!-- this could instead be calculated when the order is processed --> <input type="hidden" name="total" value='<?php echo $total; ?>' /> ======= >>>>>>> remotes/origin/master <input type="submit" value="Pay"> </form> </body> </html><file_sep>/new-connection.php <?php //define constants for db_host, db_user, db_pass, and db_database //adjust the values below to match your database settings define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', '<PASSWORD>'); //set DB_PASS as '<PASSWORD>' if you're using mac define('DB_DATABASE', 'store'); //make sure to set your database //connect to database host $connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE); //make sure connection is good or die if ($connection->connect_errno) { die("Failed to connect to MySQL: (" . $connection->connect_errno . ") " . $connection->connect_error); } <<<<<<< HEAD ======= >>>>>>> 4729fe55dece6c1d9356d0ed120b4fd8ead7ec07 //used when expecting multiple results function fetch_all($query) { $data = array(); global $connection; $result = $connection->query($query); //while($row = $result->fetch_assoc()) while($row = mysqli_fetch_assoc($result)) { $data[] = $row; } return $data; } //use when expecting a single result function fetch_record($query) { global $connection; $result = $connection->query($query); return mysqli_fetch_assoc($result); //return $result->fetch_assoc(); } //use to run INSERT/DELETE/UPDATE, queries that don't return a value //notice this function returns a value. This value will be equal to the ID of the most recent query item //ran by your PHP code. function run_mysql_query($query) { global $connection; $result = $connection->query($query); return $connection->insert_id; } //This function will return an escaped string. IE the string "That's crazy!" Will be returned as: // "That\'s crazy!...This helps secure your database! function escape_this_string($string) { global $connection; return $connection->real_escape_string($string); } ?><file_sep>/website/application/models/CartData.php <?php // // MODEL for Cart Data while shopping. Kristy/Matt/Peter // this will manage the entries for the cart as users shop through the site. // class CartData extends CI_model { // model allows for methods to manipulate data: add/update/remove data // to view the data is: one record, many records // // ******************************************************************* // Get data files towards top of file as they will be used more than // write functions // public function get_all_data($cartid=0) { // get all data in the current cart return $this->db->query('')->result_array(); } public function get_data_id($id=0) { // get one item from cart. Not sure why this is here? return $this->db->query('', array($id))->row_array(); } // gets number of items in the cart through db public function get_cart_total($id=0) { $query = "SELECT COUNT(oid) AS numitems FROM orders WHERE oid = ?"; $values = array($id); // numitems is returned in this row_array return $this->db->query('', array($id))->row_array(); } // functions that change data in the database // // creates the blank order if it doesn't exist. Later we add items to cart. // public function create_order($data) { // this creates a blank order inserting session id into the database for the cart, // so we can tie to this in the future. $session_id = $this->session->userdata('session_id'); if($session_id) { $myDate = date('Y-m-d H:m'); // make a valid date for create and update // create the order, passing back the ID of the newly inserted item, then store in session for // shopping. $query = 'INSERT INTO orders (sessid,status,created_on,modified_on) VALUES (?,?,now(),now())'; // # values must match field count above. $values = array($session_id,0,$myDate,$myDate); $tmp = $this->db->query($query, $values); } else { die('no session!!! cannot create cart.'); } return $this->db->insert_id; // return id of record inserted. more useful. } public function add_to_cart($cartid=0, $prodid=0, $qty=0) { // first check to see if item exists in cart already. if so, than just add to qty // otherwise create a new entry in cart for this prodid. $query = "SELECT * FROM pivot_order-products WHERE order_id = ? AND product_id = ?"; $values = array($cartid,$prodid); $results = $this->db->query($query,$values); if($results) { $total = $results('quantity') + $qty; $query = "UPDATE pivot_order-products SET quantity = ?, SET modified_on = NOW() WHERE order_id = ? AND product_id = ?"; $values = array($total, $cartid, $prodid); } else { $query = "INSERT INTO pivot_order-products (order_id,product_id,quantity,created_on,modified_on) VALUES "; $query = "(?,?,?,NOW(),NOW())"; $values = array($cartid, $prodid, $qty); } return $this->db->query($query, $values); } // update items in cart. if qty = 0, then remove ALL public function remove_from_cart($qty=0, $oid=0, $proid=0) { if($qty) { $query = "UPDATE pivot_order-products SET quantity = ? WHERE order_id = ? AND product_id = ?"; $values = array($qty,$oid,$prodid); } else { $query = "DELETE FROM pivot_order-products WHERE order_id = ? AND product_id = ?"; $values = array($oid,$prodid); } return $this->db->query($query,$values); } public function clear_cart($cartid=0) { $query = "DELETE FROM pivot_order-products WHERE order_id = ?"; $values = array($cartid); return $this->db->query($query,$values); } } ?><file_sep>/website/application/views/dashboard.php <?php $this->load->view('adminheader'); ?> <div class="container"> <div class="row" id="dashheader"> <div class="col-sm-2"> <!-- search box --> <form role="form" action="adminordersearch" method="post"> <div class="form-group"> <input type="text" class="form-control" name="adminordersearch" placeholder="search"> </div> </form> </div> <!-- search box --> <div class="col-sm-2 col-sm-offset-8"> <!-- dropdown --> <form role="form" action="adminorderfilter" method="post"> <div class="form-group"> <select class="form-control" name="adminorderfilter"> <option value="showall">Show All</option> <option value="inprocess">Order In Process</option> <option value="shipped">Shipped</option> </select> </div> </form> </div> <!--dropdown --> </div> <!-- dashheader --> <div class="row" id="dashbody"> <table class="table table-striped"> <thead> <tr> <th>Order ID</th> <th>Name</th> <th>Date</th> <th>Billing Address</th> <th>Total</th> <th>Status</th> </tr> </thead> <tbody> <?php foreach($ordersindb as $row) { ?> <tr> <td><a href="showorder/<?= $row['oid'] ?>"><?= $row['oid'] ?></a></td> <td><?= $row['bill_name'] ?></td> <td><?= $row['created_at'] ?></td> <td><?= $row['bill_street']." ".$row['bill_street2']. ", ". $row['bill_city']. " ". $row['bill_state']." ". $row['bill_zip'] ?></td> <td><?= $totalarray[$row['oid']] ?></td> <TD> <!-- default value of order status needs to be set by jquery: .attr("selected","true") --> <form role="form" action="changeorderstatus" method="post"> <div class="form-group"> <select class="form-control" name="adminorderfilter" id="<?= $row['id'] ?>"> <option value="cancelled">Cancelled</option> <option value="inprocess">Order In Process</option> <option value="shipped">Shipped</option> </select> </div> </form> </TD> </tr> <?php } //foreach ?> </tbody> </table> </div> <!-- dashbody --> <div class="row" id="dashpagination"> <div class="col-sm-3 col-sm-offset-4"> <!-- how many pages will be determined by db data --> <ul class="pagination"> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> </ul> </div> </div> <!-- dashpagination --> </div> <!-- container--> </body> </html><file_sep>/README.md # DojoStoreEcommerce The dojo Store with DB and order admin with backend. Mount MAMP or WAMP at the /website folder for root. Other directories adjacent or above this directory contain files for the rest of the site. Database for My SQL, or readme dox, notes. etc. the ERD is there as well. -------------------------------------------------------------------- UPDATE: 2/8/2015 created EcomData model for the loading, changing and removal of products in the ecomm store. created CartData model for adding/editing/removing cart data for shopping. <file_sep>/website/application/controllers/admins.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Admins extends CI_Controller { public function __construct() { parent::__construct(); // $this->output->enable_profiler(); } public function index() { // if admin is logged in, take them to the dash, otherwise, to the login screen if (isset($this->session->adminid)) $this->dashboard(); else $this->load->view('admin'); } public function login() { $this->load->model('mydb'); $email = $this->input->post('email'); $password = $this->input->post('password'); //checks info against db $check = $this->mydb->get_admin_by_email($email); if($check && ($check['password']==$password)) { //good info: log in $this->dashboard(); } else { //bad info: bounce back with an error message. $this->session->set_flashdata('errors', "Credentials don't match. Try again."); $this->load->view('admin'); $this->dashboard(); } } public function logoff() { //destroy session data $this->session->sess_destroy(); //redirect to login page $this->index(); } public function dashboard() { $this->load->model('EcomData'); $adminid = $this->session->userdata('adminid'); $ordersindb = $this->EcomData->get_all_orders(); $numresults = count($ordersindb); //calculate total of order and add it to the data $totalarray = []; foreach ($ordersindb as $order) { $total = $this->EcomData->get_order_total($order['oid']); $totalarray[$order['oid']] = $total; } $this->load->view('dashboard', array('adminid' => $adminid, "ordersindb" => $ordersindb, 'numresults' => $numresults, 'totalarray' => $totalarray)); } public function showorder($id) { $this->load->model('EcomData'); $order = $this->EcomData->get_order_by_id($id); $this->load->view('showorder', array('order' => $order, 'adminid' => $this->session->userdata('adminid'))); } public function products() { $this->load->view('adminproductpage', array('adminid' => $this->session->userdata('adminid'))); } } //end of main controller<file_sep>/website/application/controllers/userData.php <?php // // MODEL for userData DB. Kristy/Matt/Peter // class userData extends CI_model { // admin functions. get data to login. // set last_login date. public function get_admin($uEmail,$uPassword) { return $this->db->query('SELECT * FROM admins WHERE email = ? AND password = ?', array($id))->row_array(); } public function update_login($id) { $this->db->query('UPDATE admins SET last_login = now() WHERE aid = ?'); return; } } ?><file_sep>/website/application/views/admin.php <?php $this->load->view('adminheader'); ?> <div class="container"> <div class="row"> <div class="col-sm-4" "col-sm-offset-2"> <h1>Admin Login Page</h1> </div> </div> <?php if (null !== ($this->session->flashdata('errors'))) { ?> <div class="row"> <div class="col-sm-10"> <h1 style="color:red"><?= $this->session->flashdata('errors') ?></h1> </div> </div> <?php } ?> <div class="row"> <div class="col-sm-4 col-sm-offset-2"> <form role="form" action="login" method="post"> <div class="form-group"> <label for="email">Email:</label> <input type="text" class="form-control" name="email"> </div> <div class="form-group"> <label for="<PASSWORD>">Password</label> <input type="<PASSWORD>" class="form-control" name="<PASSWORD>"> </div> <input class="btn btn-success" type="submit" value="log in"> </form> </div> </div> </body> </html><file_sep>/website/application/views/productinfo.php <html> <head> <title>Product Info</title> <style type="text/css"> *{ margin: 0px; padding: 0px; } #header{ background-color: black; color:white; width:100%; height:50px; font-size: 36px; } #header a{ margin-left: 70%; color:white; } #images,#description{ margin-top: 20px; display: inline-block; vertical-align: top; } #images{ width:20%; } .blowup{ height:200px; width:200px; display: block; } .thumbnail{ height:50px; width:50px; } #description{ width:70%; margin-left: 5%; } #similar div{ display: inline-block; } </style> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script type="text/javascript"> $('document').ready(function(){ $('.thumbnail').hover(function(){ $src=$(this).attr('src'); $('.blowup').attr('src',$src); }); }); </script> </head> <body> <div id="header"> <<<<<<< HEAD Dojo eCommerce <a href="/main/cart">View Cart<?php echo "(".$cart['items']."): $".$cart['total']; ?></a> ======= Dojo eCommerse <a href="/main/cart">View Cart</a> >>>>>>> remotes/origin/master </div> <a href="/">Go Back</a> <h1>(Product Name Here)</h1> <div id="info"> <div id="images"> <p>(Pictures Go Here)</p> <img class="blowup" src="front.png" alt="product image"> <img class="thumbnail" src="side.png" alt="product image"> <img class="thumbnail" src="front.png" alt="product image"> <img class="thumbnail" src="back.png" alt="product image"> </div> <div id="description"> description about the product...description about the product...description about the product...description about the product...description about the product...description about the product...description about the product...description about the product...description about the product...description about the product...description about the product...description about the product...description about the product...description about the product...description about the product...description about the product... <form action="/main/add" method="post"> <<<<<<< HEAD <input type="hidden" name="product_id" value=<?php $product['id'] ?> /> ======= >>>>>>> remotes/origin/master <input type="number" name="quantity" min="1"> <input type="submit" value="Add to Cart"> </form> </div> </div> <div id="similar"> <h3>Similar Items</h3> <?php foreach ($similar as $row) { echo "<div><a href='/main/info/".$row['id']."'><img src=".$row['src']." alt='product image'><p>".$row['name']."</p></a></div>"; } ?> </div> </body> </html><file_sep>/db/store.sql -- phpMyAdmin SQL Dump -- version 4.1.14 -- http://www.phpmyadmin.net -- -- Host: 1172.16.31.10 -- Generation Time: Feb 10, 2015 at 11:46 PM -- Server version: 5.6.17 -- PHP Version: 5.5.12 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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 utf8 */; -- -- Database: `store` -- -- -------------------------------------------------------- -- -- Table structure for table `admins` -- CREATE TABLE IF NOT EXISTS `admins` ( `aid` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT 'admin first name', `last_name` varchar(45) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT 'admin lastname', `email` varchar(120) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'email which is also the admins logon name - cannot be null', `password` varchar(15) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT '<PASSWORD>', `last_login` datetime DEFAULT NULL COMMENT 'date and time of last admin login. -- should we keep a file log as well?', `created_on` datetime DEFAULT NULL, `modified_on` datetime DEFAULT NULL, PRIMARY KEY (`aid`), KEY `prim` (`aid`) USING BTREE, KEY `logon` (`email`,`password`) USING BTREE, KEY `for logon trace` (`first_name`,`last_name`,`last_login`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ; -- -- Dumping data for table `admins` -- INSERT INTO `admins` (`aid`, `first_name`, `last_name`, `email`, `password`, `last_login`, `created_on`, `modified_on`) VALUES (1, 'Peter', 'Richards', '<EMAIL>', '', NULL, '2015-02-06 14:02:59', '2015-02-06 14:03:01'); -- -------------------------------------------------------- -- -- Table structure for table `carriers` -- CREATE TABLE IF NOT EXISTS `carriers` ( `cid` int(11) NOT NULL AUTO_INCREMENT, `Carrier` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'name of the carrier', PRIMARY KEY (`cid`), KEY `prim` (`cid`,`Carrier`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ; -- -- Dumping data for table `carriers` -- INSERT INTO `carriers` (`cid`, `Carrier`) VALUES (1, 'UPS'), (2, 'FedEx'), (3, 'USPS'), (4, 'Drone'); -- -------------------------------------------------------- -- -- Table structure for table `categories` -- CREATE TABLE IF NOT EXISTS `categories` ( `id` int(11) NOT NULL AUTO_INCREMENT, `active` int(11) DEFAULT '1' COMMENT 'defaults to 1 for active, 0 means we are disabling the active state of this category', `category` varchar(80) DEFAULT NULL COMMENT 'name of category (NOT PRODUCTS)', `created_on` datetime DEFAULT NULL, `modified_on` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `prim` (`id`) USING BTREE, KEY `show and where` (`active`,`category`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ; -- -- Dumping data for table `categories` -- INSERT INTO `categories` (`id`, `active`, `category`, `created_on`, `modified_on`) VALUES (1, 1, 'T-Shirts', '2015-02-06 14:07:25', '2015-02-06 14:07:27'), (2, 1, 'Shoes', '2015-02-06 14:07:40', '2015-02-06 14:07:42'), (3, 1, 'Cups', '2015-02-06 14:07:54', '2015-02-06 14:07:56'), (4, 1, 'Fruits', '2015-02-06 14:08:07', '2015-02-06 14:08:10'); -- -------------------------------------------------------- -- -- Table structure for table `orders` -- CREATE TABLE IF NOT EXISTS `orders` ( `oid` int(11) NOT NULL AUTO_INCREMENT, `status` int(11) DEFAULT NULL COMMENT 'status of order: pending, shipping, on carrier, delivered', `carrier_id` int(11) DEFAULT NULL COMMENT 'carrier id, table carriers will have fed ex, ups, etc.', `ship_name` varchar(50) NOT NULL, `ship_street` varchar(100) NOT NULL, `ship_street2` varchar(100) DEFAULT NULL, `ship_city` varchar(50) NOT NULL, `ship_state` varchar(2) DEFAULT NULL, `ship_zip` varchar(10) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'shipping zip. must be present', `bill_name` varchar(50) NOT NULL, `bill_street` varchar(100) NOT NULL, `bill_street2` varchar(100) DEFAULT NULL, `bill_city` varchar(50) NOT NULL, `bill_state` varchar(2) DEFAULT NULL, `bill_zip` varchar(10) NOT NULL, PRIMARY KEY (`oid`), KEY `prim` (`oid`) USING BTREE, KEY `statuscar` (`status`,`carrier_id`) USING BTREE, KEY `billing` (`bill_zip`) USING BTREE, KEY `shipping` (`ship_zip`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `photos` -- CREATE TABLE IF NOT EXISTS `photos` ( `phid` int(11) NOT NULL AUTO_INCREMENT, `prod_id` int(11) DEFAULT '0' COMMENT 'id of the product this belongs to', `sort` int(11) DEFAULT '0' COMMENT 'order the photo should show in, low to high. 0-9 type.', `file_path` varchar(300) DEFAULT NULL, `caption` varchar(150) DEFAULT NULL COMMENT 'caption or comment on photo', `created_on` datetime DEFAULT NULL, `modified_on` datetime DEFAULT NULL, PRIMARY KEY (`phid`), KEY `prim` (`phid`) USING BTREE, KEY `for filters` (`sort`,`modified_on`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ; -- -- Dumping data for table `photos` -- INSERT INTO `photos` (`phid`, `prod_id`, `sort`, `file_path`, `caption`, `created_on`, `modified_on`) VALUES (1, 1, 0, 'sweat-shirt_green.png', 'Green. Shirt. Yes.', '2015-02-09 00:00:00', '2015-02-09 00:00:00'), (2, 2, 0, 't-shirt_red.png', 'No really, an ice cream scoop.', '2015-02-03 00:00:00', '2015-02-03 00:00:00'); -- -------------------------------------------------------- -- -- Table structure for table `pivot_order-products` -- CREATE TABLE IF NOT EXISTS `pivot_order-products` ( `order_id` int(11) NOT NULL DEFAULT '0', `product_id` int(11) NOT NULL DEFAULT '0', `quantity` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`order_id`,`product_id`,`quantity`), KEY `main` (`order_id`,`product_id`,`quantity`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Table structure for table `pivot_related_cats` -- CREATE TABLE IF NOT EXISTS `pivot_related_cats` ( `ref_category` int(11) NOT NULL DEFAULT '0', `rel_category` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`ref_category`,`rel_category`), KEY `main` (`ref_category`,`rel_category`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Table structure for table `pivot_related_prods` -- CREATE TABLE IF NOT EXISTS `pivot_related_prods` ( `ref_prod_id` int(11) NOT NULL DEFAULT '0', `rel_prod_id` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`ref_prod_id`,`rel_prod_id`), KEY `main` (`ref_prod_id`,`rel_prod_id`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Table structure for table `products` -- CREATE TABLE IF NOT EXISTS `products` ( `pid` int(11) NOT NULL AUTO_INCREMENT, `catid` int(11) DEFAULT NULL, `inventory` int(11) DEFAULT '0' COMMENT 'simple inventory. could be in sep table with inventory :: qty, order date, suplier....', `added_by` int(11) DEFAULT NULL COMMENT 'the admin who added this product', `price` decimal(10,2) DEFAULT '0.00' COMMENT 'price per unit', `taxable` int(11) DEFAULT '0' COMMENT 'true or false for taxable item', `product` varchar(200) DEFAULT NULL, `format` varchar(30) DEFAULT NULL COMMENT 'for comes in packs of 12, or 3 to a pack, or any type of unit', `description` text COMMENT 'long description of item.', `created_on` datetime DEFAULT NULL, `modified_on` datetime DEFAULT NULL, PRIMARY KEY (`pid`), KEY `main index` (`pid`) USING BTREE, KEY `cat` (`catid`) USING BTREE, KEY `added_date` (`added_by`,`created_on`) USING BTREE, KEY `for filtering` (`inventory`,`price`,`taxable`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ; -- -- Dumping data for table `products` -- INSERT INTO `products` (`pid`, `catid`, `inventory`, `added_by`, `price`, `taxable`, `product`, `format`, `description`, `created_on`, `modified_on`) VALUES (1, 2, 13, 2, '24.99', 0, 'Upcycled Ninja Mask', NULL, 'Your very own ninja mask upcycled from discarded bike tires!', '2015-02-10 00:00:00', '2015-02-10 00:00:00'), (2, 3, 5, 2, '3.13', 0, 'Ice Cream Scoop', NULL, 'Cast iron artisanal ice cream scoop. Yum. ', '2015-02-03 00:00:00', '2015-02-03 00:00:00'); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/website/application/controllers/main.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Main extends CI_Controller { <<<<<<< HEAD // ALL MODELS ARE LOADED IN AUTOLOAD during config setup. // $this->output->enable_profiler(); // public function __construct() { parent::__construct(); } public function index() { // loads data for landing page - products, categories and cart totals data. $productInfo = $this->EcomData->get_all_products(); // return list of all products $categories = $this->EcomData->get_category_info(); // return list of all categories if($this->session->userdata('cartid')) { // should we just use session_id for the cartid?? $cartid = $this->session->userdata('cartid'); $cartTotalItems = $this->CartData->cartTotal($cartid); } else { $cartid = 0; $cartTotalItems = 0; } // get current cart info // by passing these record sets below, we don't have a way to traverse the list unless we use a associative array with a name for each of these. $values = array('productInfo'=>$productInfo,'cartItems' => $CartTotalItems, 'numproducts' => count($productInfo), 'categories' => $categories); $this->load->view('landing',$values); } public function showdetails($pid=0) { $results = $this->Ecomdata->get_data_id($pid); $this->load->view('product_info',array('data' => $results)); } public function cartTotal($cartid=0) { // must pass cart id in to this function so that database knows which items to pull, and use // for calculation. //this function calculates the cart info to be displayed in the header //Fully Functional $cartInfo = $this->CartData->get_all_data($cartid); ======= // public function __construct() // { // parent::__construct(); // $this->output->enable_profiler(); // } public function index() { $this->load->model('EcomData'); $productInfo = $this->EcomData->get_all_product_info(); $categories = $this->EcomData->get_category_info(); $cart=$this->cartTotal(); $this->load->view('landing',array('productInfo'=>$productInfo,/*'cart'=>$cart ,*/ 'numproducts' => count($productInfo), 'categories' => $categories)); } public function cartTotal() { //this function calculates the cart info to be displayed in the header //Fully Functional $this->load->model('CartData'); >>>>>>> 4729fe55dece6c1d9356d0ed120b4fd8ead7ec07 // $cartInfo=$this->CartData->get_all_data($cartid=0); $items=0; $total=0; foreach ($cartInfo as $item) { $items++; <<<<<<< HEAD $total = $total+$item['price']*$item['quantity']; } return array('items'=>$items,'total'=>$total); } public function cart($cartid) { //load necessary information and display the Cart page //Fully Functional $cartInfo = $this->CartData->get_all_data($cartid); $cart = $this->cartTotal($cartid); ======= $total=$total+$item['price']*$item['quantity']; } return array('items'=>$items,'total'=>$total); } public function cart() { //load necessary information and display the Cart page //Fully Functional $this->load->model('CartData'); $cartInfo=$this->CartData->get_all_data($cartid=0); $cart=$this->cartTotal(); >>>>>>> 4729fe55dece6c1d9356d0ed120b4fd8ead7ec07 $this->load->view('cart',array('cartInfo'=>$cartInfo,'cart'=>$cart)); } public function info() { //Load the view for the Product Info page. <<<<<<< HEAD $cart = $this->cartTotal($cartid); ======= $cart=$this->cartTotal(); >>>>>>> 4729fe55dece6c1d9356d0ed120b4fd8ead7ec07 $this->load->view('productinfo',array('cart'=>$cart)); } public function add(){ //from Product Info page. This will add an item to the cart, but not currently functional. <<<<<<< HEAD $product = $this->input->post('product_id'); $quantity = $this->input->post('quantity'); ======= $product=$this->input->post('product_id'); $quantity=$this->input->post('quantity'); >>>>>>> 4729fe55dece6c1d9356d0ed120b4fd8ead7ec07 } public function remove($id) { //deletes a single item from the cart. //Fully functional. <<<<<<< HEAD $this->load->CartData->remove_from_cart($id); redirect('/main/cart'); } public function delete($cartid) { //deletes the entire cart. //Fully Functional. $this->load->CartData->clear_cart($cartid); ======= $this->load->model('CartData'); $this->CartData->remove_data($id); redirect('/main/cart'); } public function delete() { //deletes the entire cart. //Fully Functional. $this->load->model('CartData'); $this->CartData->clear_cart(); >>>>>>> 4729fe55dece6c1d9356d0ed120b4fd8ead7ec07 redirect('/'); } public function order() { //when an order is placed, load the confirmation page. //Need to add form validation, Stripe API, and database interaction. $shipping=array('first'=>$this->input->post('ship_first'), 'last'=>$this->input->post('ship_last'), 'street1'=>$this->input->post('ship_street1'), 'street2'=>$this->input->post('ship_street2'), 'city'=>$this->input->post('ship_city'), 'state'=>$this->input->post('ship_state'), 'zip'=>$this->input->post('ship_zip') ); if ($this->input->post('same_info')=='same_info'){ $billing=$shipping; } else{ $billing=array('first'=>$this->input->post('bill_first'), 'last'=>$this->input->post('bill_last'), 'street1'=>$this->input->post('bill_street1'), 'street2'=>$this->input->post('bill_street2'), 'city'=>$this->input->post('bill_city'), 'state'=>$this->input->post('bill_state'), 'zip'=>$this->input->post('bill_zip') ); } $card=array('number'=>$this->input->post('bill_card'), 'ccv'=>$this->input->post('bill_security'), 'expiration'=>$this->input->post('bill_date') ); $this->session->set_userdata('shipping',$shipping); $this->session->set_userdata('billing',$billing); $this->session->set_userdata('card',$card); $this->session->set_userdata('total',$this->input->post('total')); echo $this->input->post('total'); echo $this->session->userdata('total'); redirect('/main/confirmation'); } public function confirmation(){ //Loads the confirmation page and then resets all session data and clears the cart. //Fully Functional. $shipping=$this->session->userdata('shipping'); $billing=$this->session->userdata('billing'); $card=$this->session->userdata('card'); $total=$this->session->userdata('total'); <<<<<<< HEAD unset($this->session->userdata); // does this work or do we use destroy_session?? $this->load->CartData->clear_cart($cartid); ======= unset($this->session->userdata); $this->load->model('CartData'); $this->CartData->clear_cart(); >>>>>>> 4729fe55dece6c1d9356d0ed120b4fd8ead7ec07 $this->load->view('confirmation',array('shipping'=>$shipping,'billing'=>$billing,'card'=>$card,'total'=>$total)); } public function admin() { <<<<<<< HEAD // show admin login ======= >>>>>>> 4729fe55dece6c1d9356d0ed120b4fd8ead7ec07 $this->load->view('login'); } } //end of main controller <file_sep>/website/application/controllers/filters.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Filters extends CI_Controller { // public function __construct() // { // parent::__construct(); // $this->output->enable_profiler(); // } public function search() { <<<<<<< HEAD // all search is partial match (perhaps do soundex search in future) //finds every product in the database containing the search term in any field $searchterm = $this->input->post('product'); // sanitize the searchterm $searchterm = escape_this_string($searchterm); $results = $this->EcomData->get_from_db_by_keyword($searchterm); if($this->session->userdata('cartid')) { // should we just use session_id for the cartid?? $cartid = $this->session->userdata('cartid'); $cartTotalItems = $this->CartData->cartTotal($cartid); // get total number of items based on current cart id } else { $cartid = 0; $cartTotalItems = 0; } // search term also gets categories that match as well. we can show the matching cats as well. $categories = $this->EcomData->get_select_category_info($searchterm); $values = array('productinfo' => $results, 'carttotal' => $cartTotalItems, 'categories' => $categories); // we don't need to pass count of $results as we can calculate on the fly easily during view. $this->load->view('landing',$values); } } ======= //finds every product in the database containing the search term in any field $searchterm = $this->input->post('product'); $this->load->model('EcomData'); $results = $this->EcomData->get_from_db_by_keyword($searchterm); //reloads the landing page with results as product info $categories = $this->EcomData->get_select_category_info($searchterm); $this->load->view('landing',array ('productInfo'=>$results,/*'cart'=>$cart ,*/ 'numproducts' => count($results), 'categories' => $categories)); } } >>>>>>> 4729fe55dece6c1d9356d0ed120b4fd8ead7ec07 //end of filters controller <file_sep>/website/application/views/landing.php <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <title>Products</title> <style type="text/css"> *{ margin: 0px; padding: 0px; } h6 a { float:right; text-decoration: none; color:silver; margin:60px; } #header{ background-color: black; color:white; width:100%; height:50px; font-size: 36px; margin-bottom: 50px; } #header a{ margin-left: 70%; color:white; } #sidebar, #content{ display: inline-block; vertical-align: top; border: 1px solid black; } #sidebar{ padding:20px; } #sidebar li{ margin: 10px; margin-left: 30px; } #content{ margin-left: 50px; width:70%; padding: 20px; } #nav{ margin-left: 85% } .cell { border: 1px solid black; height:150px; width:150px; margin:15px; display: inline-block; } .cell img { width:150px; height:150px; margin:0px; } .infobanner { border:1px solid black; height:36px; margin-top:-36px; background-color:#bbbbbb; opacity: 0.7; } .infocell { display: inline-block; width:45%; } </style> </head> <body> <div id="header"> Dojo eCommerce <a href="/main/cart">View Cart<?php echo "(".$cart['items']."): $".$cart['total']; ?></a> <a href="/main/cart">View Cart</a> </div> <div id="sidebar"> <form id="search" action="search" method="post"> <input type="text" name="product"> <input type="submit" value="Search"> </form> <h4>Categories:</h4> <ul> <li><a href='/'>All Products</a></li> <?php foreach ($categories as $category) { ?> <li><a href='#'><?=$category['category']?> (<?= $category['count(*)']?>)</a></li> <?php } ?> </ul> </div> <div id="content"> <h2>Products (Page $)</h2> <div id="nav"> <a href="#">Prev</a> <a href="#">Next</a> <form action="/main/sort" method="post"> <p>Sort By:<select><option>Price</option><option>Most Popular</option></select></p> </form> </div> <?php $this->load->view('productdisplay'); ?> <?php $pages=floor(count($productInfo)/15)+1; for($i=1;$i<=$pages;$i++){ echo "<a href='/main/page/".$i."'>".$i."</a>"; } ?> </div> </div></div> <div id="footer"> <h6><a href="admin">Admin Login</a></h6> </div> </body> </html><file_sep>/website/application/views/adminheader.php <!doctype html> <html> <head> <title>Admin</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script> <style> .navbar-default, nav li{ background-color: #990000; background-image:none; color:#ffffff; } .navbar-default .navbar-nav>li>a, .navbar-default .navbar-brand { color:#ffffff; } .navbar-default a { color:#ffffff; } body { padding-top:70px; } .bordered { border:1px solid black; } .navbar-right { padding-top:15px; } #orderinfotable div { padding:10px; } #statusbox, #totalpricebox { margin-top:20px; } img { height:50px; } </style> <script> $(document).on('click', '.modaltrigger', function(){ if($(this).attr('which')=="add") { $('#myModalLabel').html('Add Product'); } else { $('#myModalLabel').html('Edit Product - ID ##ID##'); } }); </script> </head> <body> <!-- if admin is logged in, show nav bar --> <?php if(isset($adminid)) { echo $adminid; ?> <nav id="adminnavbar" class="nav navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="nav navbar-header"> <div class="navbar-brand">Dashboard </div> </div> <div class="nav navbar-nav"> <ul class="nav navbar-nav"> <li><a href="/dashboard">Orders</a></li> <li><a href="/adminproducts">Products</a></li> </ul> </div> <div class="nav navbar-right navbar-nav"><a href="/logoff">log off</a> </div> </div> </nav> <?php } ?><file_sep>/website/application/views/product_info.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>The Store: Product Info</title> <link rel="stylesheet" type="text/css" href="/assets/css/details.css"> <script type="text/javascript" src="/assets/scripts/jquery-2.1.3.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#qty').on('keyup','',function() { var x = $('input[id=qty]').val(); var y = $('#qty').attr('valtag'); var z = x * y; $('#total').text('$'+z.toFixed(2)); }); $('img[class=picsmall]').hover(function() { var tmp = $(this).attr('src'); $('img[id=pic1]').fadeOut(200); $('img[id=pic1]').attr('src',tmp); $('img[id=pic1]').fadeIn(200); }, function() { }); $('#mainform').on('submit',function() { var form = $(this); // console.log('here'); $.post( form.attr('action'), form.serialize(), function(output) { // } ,"json"); return false; }); }); </script> </head> <body> <?php // echo "<pre>"; // var_dump($data); // echo "</pre>"; // // die(); $title = $data[0]['product']; $main_file = $data[0]['file_path']; $caption = $data[0]['caption']; // echo "****".$main_file; // exit; ?> <div id="container"> <div id="nav"> <a href="/">Go Back</a> </div> <div id="photos"> <h3><?= $title ?></h3> <div id="main-phot"> <img id="pic1" class="mainpic" src="/assets/images/<?= $main_file ?>" alt='Main photo' border=0 width=350 height=350> <br><span id="subtitle"><?= $caption ?></span> </div> <div id="smallpix"> <?php // echo "<pre>"; // var_dump($results); // echo "</pre>"; // exit; foreach($data as $row) { echo "<div class='divsmall'>"; echo "<img class='picsmall' src='/assets/images/".$row['file_path']."' border=0 height='50' width='50'>"; echo "</div>"; } ?> <div class='clear'></div> </div> </div> <div id="description"> <p><?= $data[0]['description'] ?></p> <div id="buyarea"> Qty: <input id='qty' valtag='<?=$data[0]['price']?>' type="text" size=3 name="qty" maxlength=3 class="qtyinput"> X <?=$data[0]['price'] ?> :: <label id='total' for='total'>$0.00</label> </div> </div> <div class="clear"></div> </div> </body> </html><file_sep>/website/application/controllers/EcomData.php <?php // // MODEL for Ecommerce Site. Kristy/Matt/Peter // class EcomData extends CI_model { // // ******************************************************************* // Get data files towards top of file as they will be used more than // write functions // // public function get_all_products() { // gets all products in database with their category and inventory. order by: category, product title, and category active is true $query = 'SELECT products.pid, products.catid, categories.id, categories.active, categories.category, products.inventory, '; $query = $query.'products.price, products.taxable, products.product, products.description, photos.sort, photos.file_path, '; $query = $query.'photos.caption FROM categories LEFT OUTER JOIN products ON categories.id = products.catid '; $query = $query.'LEFT OUTER JOIN photos ON products.pid = photos.prod_id WHERE pid IS NOT NULL AND categories.active = 1 '; $query = $query.'ORDER BY category, product'; return $this->db->query($query)->result_array(); // return ALL products organized by category, products and all photos. } public function get_category_info() { $query = 'SELECT categories.cid, categories.active, categories.category '; $query = $query.'FROM categories WHERE active=1 ORDER BY category'; return $this->db->query($query)->result_array(); // return ALL products organized by category, products and all photos. } // get an individual row of products from this productid. public function get_data_id($pid = 0) { $query = 'SELECT photos.main, photos.file_path, photos.caption, products.price, '; $query = $query.'products.taxable, products.product, products.description, products.inventory, categories.active, '; $query = $query.'categories.category, products.pid FROM categories RIGHT OUTER JOIN products ON categories.cid = products.catid '; $query = $query.'RIGHT OUTER JOIN photos ON products.pid = photos.prod_id '; $query = $query.'WHERE products.pid = ? AND price is not null ORDER BY photos.main DESC'; // echo $query; // exit; return $this->db->query($query, array($pid))->result_array(); // array of this row! } // show all related products to this product id. public function get_related_prod($pid=0) { $query = 'SELECT products.catid, products.product, products.pid, pivot_related_prods.ref_prod_id '; $query = $query.'FROM pivot_related_prods LEFT OUTER JOIN products ON pivot_related_prods.rel_prod_id = products.pid '; $query = $query.'WHERE pivot_related_prods.ref_prod_id = ?'; $values = array($pid); return $this->db->query($query, $values)->result_array(); // give us a result array back } // All related categories based on this products category id. public function get_related_cats($cid=0) { $query = 'SELECT pivot_related_cats.ref_category, categories.cid, categories.active, categories.category '; $query = $query.'FROM pivot_related_cats RIGHT OUTER JOIN categories ON pivot_related_cats.rel_category = categories.cid '; $query = $query.'WHERE pivot_related_cats.ref_category = ?'; $values = array($id); return $this->db->query($query, $values)->result_array(); //give a result set back } // // ************************************************************************* public function add_product($values) { // do we need this? perhaps to update price, taxable product description, etc. $query = 'INSERT INTO products (catid, inventory, added_by, price, taxable, product, description, created_on, modified_on) '; $query = $query.'VALUES (?,?,?,?,?,?,?,now(),now())'; $tmp = $this->db->query($query, $values); return $this->db->$insert_id; // passback the row id for this insertion } // // ************************************************************************* public function update_product($id, $values) { // do we need this? perhaps to update price, taxable product description, etc. $query = 'UPDATE products SET carid = ?, inventory = ?, add_by = ?, price = ?, taxable = ?, product = ?, description = ?, modified_on = now() WHERE pid = ?'; // ****** we need to add the id onto the values before we execute $values = array($id); // push id of this record onto array for update. return $this->db->query($query, $values); } public function remove_data($id) { // only put in title and desc since we are doing triggers for auto updates on timestamp and created $query = 'DELETE FROM products WHERE pid = ?'; $values = array('id' => $id); // doesn't return anything but a value to show it succeeded. if 0 then broke. return $this->db->query($query, $values); } } ?><file_sep>/website/application/views/confirmation.php <html> <head> <title>Order Confirmation</title> </head> <body> <!-- this page simply displays the information that was entered in the order form. --> <!-- Does not require any further processing or database interaction --> <h1>Thank you for your order!</h1> <h2>Shipping Address</h2> <?php echo "<p>First Name: ".$shipping['first']."</p> <p>Last Name: ".$shipping['last']."</p> <p>Street Address: ".$shipping['street1']." ".$shipping['street2']."</p> <p>City: ".$shipping['city']."</p> <p>State: ".$shipping['state']."</p> <p>Zip Code: ".$shipping['zip']."</p>"; ?> <h2>Billing Address</h2> <?php echo "<p>First Name: ".$billing['first']."</p> <p>Last Name: ".$billing['last']."</p> <p>Street Address: ".$billing['street1']." ".$billing['street2']."</p> <p>City: ".$billing['city']."</p> <p>State: ".$billing['state']."</p> <p>Zip Code: ".$billing['zip']."</p>"; ?> <h2>Credit Card Information</h2> <?php echo "<p>Card Number: ".$card['number']."</p> <p>Expiration Date: ".$card['expiration']."</p> <p>Total:".$total."</p>"; ?> <a href="/"><button>Back to Home</button></a> </body> </html><file_sep>/website/application/views/productdisplay.php <!-- generate product info area make 5x3 from db, pull image, name, price --> <?php for($j = 0;$j<3;$j++){ ?> <div class="row"> <?php for($i=0;$i<5;$i++){ if($i+($j*5) < $numproducts) { ?> <div class="cell"> <?php echo img("assets/images/".$productInfo[$i+($j*5)]['file_path']); ?> <div class="infobanner"> <div class="infocell"> <h6><?=$productInfo[$i+$j]['product'] ?></h6> </div> <div class="infocell"> <h4><?= $productInfo[$i+$j]['price'] ?></h4> </div> </div> </div> <?php } //if } //for-i } //for-j ?> </div><file_sep>/website/application/views/showorder.php <?php $this->load->view('adminheader'); ?> <div class="container"> <div class="row"> <div class="col-sm-3 bordered" id="orderinfotable"> <div class="row"> <p>Order ID:<?= $order[0]['oid'] ?></p> </div> <div class="row"> <p>Customer Shipping Info:</p> </div> <div class="row"> <p>Name:<?= $order[0]['ship_name'] ?></p> <p>Address: <?= $order[0]['ship_street']." ".$order[0]['ship_street2'] ?> <p>City: <?= $order[0]['ship_city'] ?></p> <p>State:<?= $order[0]['ship_state'] ?></p> <p>Zip:<?= $order[0]['ship_zip'] ?></p> </div> <div class="row"> <p>Customer Billing Info:</p> </div> <div class="row"> <p>Name:<?= $order[0]['bill_name'] ?></p> <p>Address: <?= $order[0]['bill_street']. " ".$order[0]['bill_street2'] ?></p> <p>City: <?= $order[0]['bill_city'] ?></p> <p>State:<?= $order[0]['bill_state'] ?></p> <p>Zip:<?= $order[0]['bill_zip'] ?></p> </div> </div> <div class="col-sm-8 col-sm-offset-1"> <div class="row bordered"> <table class="table table-striped"> <thead> <tr> <th>ID</th> <th>Item</th> <th>Price</th> <th>Quantity</th> <th>Total</th> </tr> </thead> <tbody> <?php foreach ($order as $item) { ?> <tr> <TD><?= $item['pid'] ?></TD> <TD><?= $item['product'] ?></TD> <TD>$<?= $item['price'] ?></TD> <TD><?= $item['quantity'] ?></TD> <TD>$<?= $item['price']*$item['quantity'] ?></TD> </tr> <?php } ?> </tbody> </table> </div> <div class="row"> <div class="col-sm-5 bordered" id="statusbox"> <!-- use jquery to set background color basen on status. --> <h2>Status: <?= $order[0]['status'] ?></h2> </div> <div class="col-sm-2"> </div> <div class="col-sm-5 bordered" id="totalpricebox"> <h3>Subtotal: $ <?= $subtotal ?></h3> <h3>Shipping: $Where do we get this from? <?= $shipping ?></h3> <h3>Total Price: $<?= $subtotal + $shipping ?></h3> </div> </div> </div> </div> </div> <!-- container--> </body> </html><file_sep>/add_admins.php <?php require_once('new-connection.php'); // temporary too to create encrypted passwords for the admins function AddToDatabase($salt,$fname,$lname,$email,$pass) { $e_password = crypt($salt,$pass); $e_email = crypt($salt,$email); $query = "INSERT INTO admins (first_name, last_name, email, password, created_on, modified_on) "; $query = $query."VALUES ('".$fname."','".$lname."','".$e_email."','".$e_password."',NOW(),NOW() )"; // echo $query; // die('here'); run_mysql_query($query); } echo "STARTING TO ADD...."; $salt = bin2hex(openssl_random_pseudo_bytes(22)); $password = '<PASSWORD>'; $first_name = 'Matt'; $last_name = 'McCullough'; $email = '<EMAIL>'; AddToDatabase($salt, $first_name, $last_name, $email, $password); $password = '<PASSWORD>'; $first_name = 'Kristy'; $last_name = 'Overton'; $email = '<EMAIL>'; AddToDatabase($salt, $first_name, $last_name, $email, $password); $password = '<PASSWORD>'; $first_name = 'Peter'; $last_name = 'Richards'; $email = '<EMAIL>'; AddToDatabase($salt, $first_name, $last_name, $email, $password); echo "<p>DONE!"; ?><file_sep>/website/application/views/adminproductpage.php <?php $this->load->view('adminheader'); ?> <div class="container"> <div class="row" id="dashheader"> <div class="col-sm-6"> <!-- search box --> <form role="form" action="adminproductsearch" method="post"> <div class="form-group"> <input type="text" name="adminproductsearch" class="form-control" placeholder="search"> </div> </form> </div> <!-- search box --> <div class="col-sm-2 col-sm-offset-8"> <!-- add new product button --> <button type="button" class="btn btn-primary modaltrigger" data-toggle="modal" data-target="#editproduct" which="add">Add New Product</button> </div> <!--dropdown --> </div> <!-- dashheader --> <div class="row" id="dashbody"> <table class="table table-striped"> <thead> <tr> <th>Picture</th> <th>Product ID</th> <th>Name</th> <th>Inventory Count</th> <th>Quantity Sold</th> <th>Action</th> </tr> </thead> <tbody> <?php // foreach($productsindb as $row) { ?> <tr> <TD><img src="#"></TD> <td><?= $row['id'] ?></td> <td><?= $row['name'] ?></td> <td><?= $row['inventory'] ?></td> <td><?= $row['totalqtysold'] ?></td> <td><a href="addproduct" class="modaltrigger" data-toggle="modal" data-target="#editproduct" which="edit">edit</a> <a href="deleteproduct">delete</a></td> </tr> <?php // } //foreach ?> </tbody> </table> </div> <!-- dashbody --> <div class="row" id="dashpagination"> <div class="col-sm-3 col-sm-offset-4"> <!-- how many pages will be determined by db data --> <ul class="pagination"> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> </ul> </div> </div> <!-- dashpagination --> </div> <!-- container--> <div class="modal fade" id="editproduct" tabindex="-1" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel"><!--supplied by jquery --></h4> </div> <div class="modal-body"> <?php $this->load->view('editproduct'); ?> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-success" id="previewproduct">Preview</button> <button type="submit" class="btn btn-primary">Save changes</button> </form> </div> </div> </div> </div> </div> </body> </html>
b7589311c19c312a1122de0a85b8b8aa8b9fa18a
[ "Markdown", "SQL", "PHP" ]
21
PHP
PeterRichardsWA/DojoStoreEcommerce
a85a4cbfcbf1f6a9a11488d9df75634fc7b19aba
97478d0db3df2560d503bdfa9d3774d9bc6ceb06
refs/heads/master
<file_sep>from __future__ import print_function import os from apiclient import discovery import oauth2client import httplib2 from apiclient.discovery import build from httplib2 import Http from commands import getstatusoutput as terminal from oauth2client import file, client, tools import time try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None SCOPES = 'https://www.googleapis.com/auth/drive' CLIENT_SECRET_FILE = 'client_secret.json' def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'drive-python-quickstart.json') store = oauth2client.file.Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.params['access_type'] = 'offline' flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials up_directory='~/Desktop/hey' #add directory address which is to be uploaded def get_files(): file_names=terminal('ls '+up_directory)[1].split('\n') if len(file_names)==1 and file_names[0]=='': return None for i in range(len(file_names)): terminal('cp '+up_directory+'/'+file_names[i]+' ./') #file_names[i]=names=os.path.join(up_directory, file_names[i]) FILES=tuple(file_names) return FILES def upload(): FILES= get_files() #get file list and mimetype #return if no file to be uploaded if not FILES: return credentials=get_credentials() http = credentials.authorize(httplib2.Http()) DRIVE = discovery.build('drive', 'v3', http=http) for filename in FILES: metadata = {'name': filename} try: res = DRIVE.files().create(body=metadata, media_body=filename).execute() except: continue if res: print('Uploaded "%s"' % (filename)) terminal('rm '+filename) terminal('rm '+up_directory+'/'+filename) while True: upload() delay=10 #refresh time "delay" in seconds time.sleep(delay)
227548f38628ebf0ade95c228f02e61640a19bed
[ "Python" ]
1
Python
mridulgupta369/google-drive-upload
34f53a17b1f960771bb8705c73c462f16c38af8e
5afb2b27ec81b4c59b5e30269ed42a27065411fa
refs/heads/master
<file_sep># Portland Transit Animating GTFS data in Portland, Oregon This repository contains the code and data used to create the below animation: ![img](https://media.giphy.com/media/3o7bu6LaJBftC8TOuI/giphy.gif) (It runs more smoothly in video format). 1) The `Data Wrangling` python notebook is used to download and manipulate the GTFS data into a form necessary for animation 2) The `gtfs` folder contains the raw gtfs that was downloaded using the python notebook 3) The `data.zip` file contains the clean csv that was generated by the python notebook 4) The `sketch` folder contains the Processing code used to create the animation To run this locally: * Download the repo * Unzip the data.zip file * Open the processing sketch and click play. You will need to have [Processing](https://processing.org/) and [Unfolding Maps](http://unfoldingmaps.org/) installed to play sketch. For the steps taken to download and manipulate the data, see `Data_Wrangling.ipynb`. <file_sep> ###### Load libraries ------------ library(data.table) library(magrittr) library(dplyr) library(sf) library(sp) library(rgdal) library(ggplot2) library(ggthemes) library(gganimate) ###### Load GTFS data ------------ # Indicate GTFS file gtfs_file <- "./data.zip" # read GTFS text files routes <- fread(unzip (gtfs_file, "routes.txt")) # get route_id trips <- fread(unzip (gtfs_file, "trips.txt")) # get trip_id stop_times <- fread(unzip (gtfs_file, "stop_times.txt")) # get stop_id stops <- fread(unzip (gtfs_file, "stops.txt")) # get stop_id + lat long shapes <- fread(unzip (gtfs_file, "shapes.txt")) # get stop_id + lat long # convert coordinates to numeric shapes[, shape_pt_lat := as.numeric(shape_pt_lat) ][, shape_pt_lon := as.numeric(shape_pt_lon) ] stops[, stop_lon := as.numeric(stop_lon) ][, stop_lat := as.numeric(stop_lat) ] ###### Find locations of stop_id along route shapes ------------ # Convert stops and shapes into sf format # stops coordinates(stops) = ~stop_lon+stop_lat stops_sf = st_as_sf(stops) # shapes coordinates(shapes) = ~shape_pt_lon+shape_pt_lat shapes_sf = st_as_sf(shapes) # assign CRS / spatial projection st_crs(stops_sf) <- st_crs("+proj=longlat +ellps=WGS84") st_crs(shapes_sf) <- st_crs("+proj=longlat +ellps=WGS84") # change projection to utm meters stops_sf <- st_transform(stops_sf, "+proj=utm +ellps=WGS84 +units=m") shapes_sf <- st_transform(shapes_sf, "+proj=utm +ellps=WGS84 +units=m") # Creater a 10 meter buffer around each stop stops_buffer <- st_buffer(stops_sf, dist=10 ) # Overlay stop buffers with lat/long points of route shapes ###### Bind all datasets together ------------ total_df <- left_join(stop_times, stops, by="stop_id") total_df <- left_join(total_df, trips, by="trip_id") total_df <- left_join(total_df, routes, by="route_id") %>% setDT() ###### Interpolate time between arrival times for each route/trip/direction ------------ data.table
ca72430c592b664b28aa00f88379be0b1036935f
[ "Markdown", "R" ]
2
Markdown
stevepepple/PortlandTransit
7ad7e9b4100145db36886268a28dca2737a849f1
982018ea0f40506b40c94436f24ad024c25b2b58
refs/heads/master
<file_sep>package test.java; import main.java.ParkingLot; import org.junit.*; import static org.junit.Assert.*; /** * ParkingLot Tester. * * @author <Authors name> * @since <pre>Aug 18, 2015</pre> * @version 1.0 */ public class ParkingLotTest { private ParkingLot parkingLot; @Before public void before() throws Exception { parkingLot = new ParkingLot(10); } @After public void after() throws Exception { parkingLot = null; } /** * * Method: parkCar() * */ @Test public void testParkCar() throws Exception { System.out.println("Testing parkCar()"); parkingLot.parkCar(); parkingLot.parkCar(); assertEquals(parkingLot.getMaxSpots(), 10); assertEquals(parkingLot.getTakenSpots(), 2); } /** * * Method: unparkCar() * */ @Test public void testUnparkCar() throws Exception { System.out.println("Testing unParkCar()"); parkingLot.parkCar(); parkingLot.parkCar(); parkingLot.parkCar(); parkingLot.parkCar(); parkingLot.unparkCar(); assertEquals(parkingLot.getMaxSpots(), 10); assertEquals(parkingLot.getTakenSpots(), 3); } } <file_sep># Class4 Using Gradle to Build and Test java App
089075754d0a16bc134c2653613ac26a6e0c6425
[ "Markdown", "Java" ]
2
Java
glookogeorge/Class4
2978a0e7b8e156ff57c6ee9414b30967bfc46957
697f94bc2147a0af64053ab3e61ac2f3e3b0b563
refs/heads/master
<file_sep>#!/bin/sh Xsetup - run as root before the login dialog appears /usr/bin/xrandr --current | grep -E "^DP-1 connected " if [ $? -eq 0 ]; then echo "DP-1 found" sleep 1s /usr/bin/xrandr --output "$(xrandr -q|grep -Eo 'eDP-[0-9]')" --off /usr/bin/xrandr --output 'DP-1' --auto --primary fi <file_sep># Systemwide Config Files ### _This repo supplements my dotfile repo. It contains configuration files and binaries that should not be user-writable for security's sake._ NOTE: As it is now, the structure of this repo as well as it's accompanying scripts are just provisional. This might or might not be transfered to Chef or a custom solution in the future. <file_sep>#!/bin/bash STORE=$HOME/.localSysConfStore echo $(dirname $1) >> $STORE/.__META__$(basename $1) cp $1 $STORE/ <file_sep>#! /usr/bin/bash export DISPLAY=:0 export XAUTHORITY=/home/dan/.Xauthority function connect(){ xrandr --output "$(xrandr -q|grep -Eo 'eDP-[0-9]')" --off xrandr --output 'DP-1' --auto --primary } function disconnect(){ xrandr --auto } xrandr | grep -E "^DP-1 connected" &> /dev/null && connect || disconnect <file_sep>/home/fabian/bin
e8f2df6aab19a4fdce3910386112512451c34028
[ "Markdown", "Shell" ]
5
Shell
Ozymandias42/My-Linux-Config
a5af7d7f2ae3e0ecc7de71550294ee1fc52b61ba
49c1ba0627ecb2bd949130e6069461b9d38a0a55
refs/heads/master
<file_sep>#include "Time.h" #include <ctime> Time::Time() { time_t now ; struct tm *now_tm; int hr,min; now = time(NULL); now_tm = localtime(&now); hr = now_tm->tm_hour; min = now_tm->tm_min; hours=hr; minutes=min; cout<<hours<<endl<<minutes<<endl; } /*Time operator+ (int shDur) //Shopping Duration { Time t; t.hours=hours+shDur ; t.minutes=minutes+shDur ; return t ; }*/ /*Time operator+ (int shDur) //Shopping Duration { hours=hours+shDur ; minutes=minutes+shDur ; return *this ; }*/ <file_sep>#include <Person.h> #include <Time.h> class Customer : public Person { int id; Time arrivalTime; public: Customer(); }; <file_sep>#include "Stock.cpp" #include <iostream> #include <unordered_map> using namespace std; int main(){ Stock s1; Item *t1; s1.sortStock(); s1.addItem("potato", "Drinking", 2515, 222); t1 = s1.findItemWithName("potato"); cout << t1->getName(); s1.printStock(); } <file_sep>#include "Administrator.h" Administrator::Administrator() { } void Administrator::ReportAvailableItems(int) const { } void Administrator::AddNewItem(int, string, type, amount) { } void Administrator::UpdateExistingItem(int) { } void Administrator::ReportTotalRevenue() { } int Administrator::TotalCustomer() { return customerList.size(); } double Administrator::MaxReceipt() { return maxReceipt; } void Administrator::SaveStock() { } void Administrator::AddCustomer( Customer c ) { double total = c.getTotal(); if (total > maxReceipt) { maxReceipt = total } customerList.push_back(c); }<file_sep>#include <string> using namespace std; class Person //BaseClass For Admin & Customer { string name,address; public: Person(); }; <file_sep>#include <ctime> using namespace std; class Time { int hours , minutes ; public: Time(); Time operator + (int) ; }; <file_sep>#include "Item.cpp" #include "Time.cpp" #include <iostream> #include <unordered_map> using namespace std; int main(){ Time t; // hash<string> hashItem; // string str; // cin >> str; // int hashedItem = hashItem(str); // cout << hashedItem << endl; } <file_sep>#include <Person.h> #include "Stock.h" #include "Customer.h" #include <vector> using namespace std; class Administrator : public Person { Stock stock; vector<Customer> customerList; double totalRevenue; double maxReceipt; public: Administrator(); void ReportAvailableItems(int) const; void AddNewItem(int, string, type, amount); void UpdateExistingItem(int); void ReportTotalRevenue(); int TotalCustomer(); double MaxReceipt(); void SaveStock(); void AddCustomer(Customer); };
c41464de2c068d34d2a89ef8e69e31b4148cad3e
[ "C++" ]
8
C++
hazem3500/SuperMarket
bba6696e749dfe47231a974f17452e3d17f84992
16ba2e25af9298e689e7919968c28b9edffe1ef6
refs/heads/master
<repo_name>diegofs01/prjPOODiegoValter<file_sep>/src/fatec/poo/model/Candidato.java package fatec.poo.model; import java.util.ArrayList; /** * * @author 0030481421048 */ public class Candidato extends Pessoa { private String inscricao; private double media; private ArrayList<Prova> provas = new ArrayList<Prova>(); public Candidato(String inscricao, String cpf, String nome, String endereco) { super(cpf,nome,endereco); this.inscricao = inscricao; } public String getInscricao() { return inscricao; } public double getMedia() { return media; } public void setMedia(double media) { this.media = media; } public void calcularMedia() { double tempMed = 0, tempPeso = 0; for(int x = 0; x < provas.size(); x++) { tempMed += (provas.get(x).getPeso() * provas.get(x).getNota()); tempPeso += provas.get(x).getPeso(); } media = tempMed / tempPeso; } public void addProva(Prova p) { provas.add(p); p.setCandidato(this); } } <file_sep>/src/fatec/poo/view/GuiMontarProva.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package fatec.poo.view; /** * * @author Massashi */ public class GuiMontarProva extends javax.swing.JFrame { /** * Creates new form GuiMontarProva */ public GuiMontarProva() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { grbtGabaritos = new javax.swing.ButtonGroup(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); txtMateria = new javax.swing.JTextField(); txtQtdeQuest = new javax.swing.JTextField(); lblPeso = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextAreaEnun = new javax.swing.JTextArea(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); txtAlterA = new javax.swing.JTextField(); txtAlterB = new javax.swing.JTextField(); txtAlterC = new javax.swing.JTextField(); txtAlterD = new javax.swing.JTextField(); jPanel3 = new javax.swing.JPanel(); rbtnA = new javax.swing.JRadioButton(); rbtnB = new javax.swing.JRadioButton(); rbtnC = new javax.swing.JRadioButton(); rbtnD = new javax.swing.JRadioButton(); btnAdicionar = new javax.swing.JButton(); btnIncluir = new javax.swing.JButton(); btnAlterar = new javax.swing.JButton(); btnExcluir = new javax.swing.JButton(); btnSair = new javax.swing.JButton(); btnConsult = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Montar Prova"); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Prova")); jPanel1.setName("Prova"); // NOI18N jLabel1.setText("Matéria:"); jLabel2.setText("Qtde. de Questões:"); jLabel3.setText("Peso:"); txtQtdeQuest.setEnabled(false); lblPeso.setEnabled(false); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addGap(3, 3, 3) .addComponent(txtMateria, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtQtdeQuest) .addGap(18, 18, 18) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblPeso, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(txtMateria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtQtdeQuest, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblPeso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(36, Short.MAX_VALUE)) ); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Questões")); jLabel4.setText("Número: 1"); jLabel5.setText("Enunciado:"); jTextAreaEnun.setColumns(20); jTextAreaEnun.setRows(5); jScrollPane1.setViewportView(jTextAreaEnun); jLabel6.setText("Alternativa A:"); jLabel7.setText("Alternativa B:"); jLabel8.setText("Alternativa C:"); jLabel9.setText("Alternativa D:"); txtAlterA.setEnabled(false); txtAlterB.setEnabled(false); txtAlterC.setEnabled(false); txtAlterD.setEnabled(false); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Gabarito")); grbtGabaritos.add(rbtnA); rbtnA.setText("A"); rbtnA.setEnabled(false); grbtGabaritos.add(rbtnB); rbtnB.setText("B"); rbtnB.setEnabled(false); grbtGabaritos.add(rbtnC); rbtnC.setText("C"); rbtnC.setEnabled(false); grbtGabaritos.add(rbtnD); rbtnD.setText("D"); rbtnD.setEnabled(false); rbtnD.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rbtnDActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(rbtnA) .addComponent(rbtnC) .addComponent(rbtnD) .addComponent(rbtnB)) .addGap(0, 36, Short.MAX_VALUE)) ); jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {rbtnA, rbtnB, rbtnC, rbtnD}); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(rbtnA) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(rbtnB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(rbtnC) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(rbtnD) .addContainerGap()) ); btnAdicionar.setText("Adicionar"); btnAdicionar.setEnabled(false); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jScrollPane1) .addContainerGap()) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(btnAdicionar, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel5) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtAlterC)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel9) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtAlterD, javax.swing.GroupLayout.PREFERRED_SIZE, 492, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtAlterB, javax.swing.GroupLayout.PREFERRED_SIZE, 531, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtAlterA, javax.swing.GroupLayout.PREFERRED_SIZE, 571, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(0, 34, Short.MAX_VALUE)))) ); jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {txtAlterA, txtAlterB, txtAlterC, txtAlterD}); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel4) .addGap(18, 18, 18) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(txtAlterA, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(txtAlterB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(txtAlterC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(txtAlterD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addComponent(btnAdicionar) .addContainerGap(19, Short.MAX_VALUE)) ); btnIncluir.setText("Incluir"); btnIncluir.setEnabled(false); btnAlterar.setText("Alterar"); btnAlterar.setEnabled(false); btnExcluir.setText("Excluir"); btnExcluir.setEnabled(false); btnSair.setText("Sair"); btnSair.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSairActionPerformed(evt); } }); btnConsult.setText("Consultar"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(32, 32, 32) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(btnConsult) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnIncluir) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnAlterar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnExcluir) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnSair))) .addContainerGap()) ); layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAlterar, btnConsult, btnExcluir, btnIncluir, btnSair}); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnIncluir) .addComponent(btnAlterar) .addComponent(btnExcluir) .addComponent(btnSair) .addComponent(btnConsult)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void rbtnDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbtnDActionPerformed // TODO add your handling code here: }//GEN-LAST:event_rbtnDActionPerformed private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed dispose(); }//GEN-LAST:event_btnSairActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(GuiMontarProva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GuiMontarProva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GuiMontarProva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GuiMontarProva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new GuiMontarProva().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAdicionar; private javax.swing.JButton btnAlterar; private javax.swing.JButton btnConsult; private javax.swing.JButton btnExcluir; private javax.swing.JButton btnIncluir; private javax.swing.JButton btnSair; private javax.swing.ButtonGroup grbtGabaritos; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextAreaEnun; private javax.swing.JTextField lblPeso; private javax.swing.JRadioButton rbtnA; private javax.swing.JRadioButton rbtnB; private javax.swing.JRadioButton rbtnC; private javax.swing.JRadioButton rbtnD; private javax.swing.JTextField txtAlterA; private javax.swing.JTextField txtAlterB; private javax.swing.JTextField txtAlterC; private javax.swing.JTextField txtAlterD; private javax.swing.JTextField txtMateria; private javax.swing.JTextField txtQtdeQuest; // End of variables declaration//GEN-END:variables }
af86fade77bc322643b8eba9d4a5316e58e94830
[ "Java" ]
2
Java
diegofs01/prjPOODiegoValter
35ef8e2cad40daba91c9595817889e461ddf3499
984046ea53954b61b48079269ca7fde38e26a285
refs/heads/master
<file_sep>#!/usr/bin/env bash export FLASK_APP=server.py flask run<file_sep>import requests import json from server import DATABASE_NAME sample_post = { "userId": "<KEY>", "sessionId": "XYZ456ABC", "actions": [ { "time": "2018-10-18T21:37:28-06:00", "type": "CLICK", "properties": { "locationX": 52, "locationY": 11 } }, { "time": "2018-10-18T21:37:30-06:00", "type": "VIEW", "properties": { "viewedId": "FDJKLHSLD" } }, { "time": "2018-10-18T21:37:30-06:00", "type": "NAVIGATE", "properties": { "pageFrom": "communities", "pageTo": "inventory" } } ] } r = requests.post('http://localhost:5000/add-log', json=json.dumps(sample_post)) assert (r.json()['message'] == 'added log to database') NUMBER_OF_USERS = 100 for i in range(0, NUMBER_OF_USERS): sample_post['userId'] = str(i) r = requests.post('http://localhost:5000/add-log', json=json.dumps(sample_post)) assert (r.json()['message'] == 'added log to database') <file_sep>from flask import Flask, request, jsonify, app import json import sqlite3 app = Flask(__name__) DATABASE_NAME = 'openhouse-ai.db' def setup_database(): connection = sqlite3.connect(DATABASE_NAME) cursor = connection.cursor() cursor.execute( 'CREATE TABLE IF NOT EXISTS logs (' 'userId varchar(9) NOT NULL, ' 'sessionId varchar(9) NOT NULL, ' 'time datetime NOT NULL, ' 'type varchar NOT NULL, ' 'properties varchar NOT NULL' ')' ) cursor.close() connection.commit() connection.close() @app.route('/add-log', methods=['POST']) def add_log(): try: data = json.loads(request.json) connection = sqlite3.connect(DATABASE_NAME) cursor = connection.cursor() for action in data['actions']: cursor.execute( "INSERT INTO logs (userId, sessionId, time, type, properties) VALUES (?, ?, ?, ?, ?)", (data['userId'], data['sessionId'], action['time'], action['type'], json.dumps(action['properties'])) ) cursor.close() connection.commit() connection.close() return jsonify({'message': 'added log to database'}), 200 except (KeyError, TypeError) as e: app.logger.error(e) return jsonify({"message": "error: please pass a json request in the format specified in the documentation."}), 400 @app.route('/get-logs', methods=['GET']) def get_logs(): try: data = request.data connection = sqlite3.connect(DATABASE_NAME) cursor = connection.cursor() cursor.execute( "SELECT * FROM logs WHERE userId=? AND time<=? AND time>=? and type=?", (data['userId'], data['startTime'], data['endTime'], data['type']) ) rows = cursor.fetchall() output = jsonify(rows) cursor.close() connection.close() return output except (KeyError, TypeError) as e: app.logger.error(e) return jsonify({"message": "error: please pass a request in the format specified in the documentation."}), 400 setup_database() <file_sep># Openhouse AI Challenge This application takes a request made by a front end and stores it in a database. Calls can then be made to the application to get data from the database. # To test Please install [Python 3](python.org/downloads/) and add it to your terminal path. After installing, run: ```bash pip install -r requirements.txt ``` To run server, run: ```bash ./run-server.sh ``` After the server is running, to run tests, run: ```bash python tests.py ``` # REST API POST /add-log Posting to /add-log adds the log to the database. It returns a JSON string object with a message. The format of the request must be: ```json { "userId": <string>, "sessionId": <string>, "actions": [ ..., { "time": <iso-datetime as a string>, "type": <string>, "properties": <json object> }, ... ] } ``` GET /get-logs?userId=<userId>&startTime=<startTime>&endTime=<endTime>&type<type> Making a get request to the above URL will get the logs with the desired userId and type between the startTime and the endTime. # How to make application scalable There are a few ways I could make this application scalable: 1. Use a different database. Sqlite is good for testing, but it only allows for one write at a time. Currently, this is a bottleneck as Sqlite will block on concurrent writes. Other SQL servers, like MSSQL, PostgreSQL or MySQL support multi-threaded writes. 2. Make Flask support asynchronous requests. Python is synchronous by default. This is can be done by using celery or some other multi-threaded queueing methods. 3. Launch multiple instances of the application. This could be done with AWS lambda or with multiple machines running multiple instances of the application. This would all be put behind a load balancer to route incoming requests to various machines.
5eb96516558bc5134482fad6438fe84cc483dc23
[ "Markdown", "Python", "Shell" ]
4
Shell
masonbrothers/openhouse-ai
f165dc98fcf1817717b4e0ebc30482e9ab346db0
c1f9f464ee288413be73cc7a62f0805ef4649087
refs/heads/master
<repo_name>mszygenda/govuk_single_page_pdk<file_sep>/src/modules/components/navigation/start-bar/start-bar.demo.ts import { Component } from '@govuk/angularjs-devtools'; @Component({ template: require('./start-bar.demo.html') }) export class StartBarDemo { items = [ { description: 'Give remand advice', action: 'Start', click: function () { console.log('clicked'); } } ]; }<file_sep>/src/modules/components/data-visualisation/tab/tab.component.ts import { Component } from '@govuk/angularjs-devtools'; @Component({ bindings: { heading: '@' }, transclude: true, template: ` <div ng-if="$ctrl.active" class="tabs-panel" id="before-you-start" role="tabpanel"> <div class="tabs-panel-inner" tabindex="0" ng-transclude> </div> </div> `, require: { tabsetCtrl: '^govTabset' } }) export class TabComponent { heading: string; tabsetCtrl: any; get active(): boolean { return this.tabsetCtrl.isActive(this); } $onInit(): void { this.tabsetCtrl.add(this); } $onDestroy(): void { this.tabsetCtrl.remove(this); } }<file_sep>/src/modules/components/media/image/image.component.ts import { Component } from '@govuk/angularjs-devtools'; @Component({ bindings: { image: '<' }, template: require('./image.component.html') }) export class ImageComponent {}<file_sep>/src/modules/components/data-visualisation/show-hide-pane/show-hide-pane.demo.html <h3 class="heading-medium">Show/Hide Pane</h3> <gov-tabset> <gov-tab heading="Angular Markup"> <docs-example language="markup"> <!--with default optiones--> <gov-show-hide-pane> <always-visible> This content will always be visible </always-visible> <hideable> this content can bi hidden/shown using the show/hide button </hideable> </gov-show-hide-pane> <!--with custom options--> <gov-show-hide-pane show-text="$ctrl.show" hide-text="$ctrl.hide" open="$ctrl.open"> <always-visible> This content will always be visible </always-visible> <hideable> this content can bi hidden/shown using the show/hide button </hideable> </gov-show-hide-pane> </docs-example> </gov-tab> <gov-tab heading="Data"> <prismify language="javascript"> This component does not require any data. However, The following attributes are optional: open: boolean showText: string hideText: string Example: open = false; show = 'Open'; hide = 'Close'; </prismify> </gov-tab> </gov-tabset> <discuss-component issue="28"></discuss-component><file_sep>/src/modules/components/data-visualisation/summary-item/summary-item.component.ts import { Component } from '@govuk/angularjs-devtools'; @Component({ bindings: { value: '<', itemDescription: '<', action: '&?' }, template: require('./summary-item.component.html') }) export class SummaryItemComponent { value: any; isNumber(): boolean { return angular.isNumber(this.value); } isBoolean(): boolean { return typeof(this.value) === 'boolean'; } }<file_sep>/src/modules/components/media/image/image.demo.ts import {Component} from '@govuk/angularjs-devtools'; @Component({ template: require('./image.demo.html') }) export class ImageDemoComponent { image = { src: 'assets/images/justice.jpg', title: 'Test image title', metadata: [ { key: 'date taken', value: '2016 05 19' }, { key: 'copyright', value: 'none' } ] }; }<file_sep>/src/modules/components/data-visualisation/digit-box/digit-box.component.ts import { Component } from '@govuk/angularjs-devtools'; @Component({ bindings: { digit: '<' }, template: `<div class="gov-digit-box" ng-bind="$ctrl.digit"></div>` }) export class DigitBoxComponent {}<file_sep>/src/modules/components/navigation/completed-bar/completed-bar.demo.ts import { Component } from '@govuk/angularjs-devtools'; @Component({ template: require('./completed-bar.demo.html') }) export class CompletedBarDemo { items = [ { description: 'Provided plea issues', subDescription: 'Acceptable for a guilty plea to s.20 wounding or inflicitng grievous bodily..', action: 'Amend', state: '', click: function () { console.log('clicked'); } }, { description: 'Proposed charge authorised', subDescription: '', action: 'Amend', state: 'Saved', click: function () { console.log('clicked'); } } ]; }<file_sep>/src/modules/components/navigation/breadcrumbs/breadcrumbs.demo.ts import { Component } from '@govuk/angularjs-devtools'; @Component({ template: require('./breadcrumbs.demo.html') }) export class BreadcrumbsDemo {}<file_sep>/src/modules/components/data-visualisation/tab/tab.demo.ts import { Component } from '@govuk/angularjs-devtools'; @Component({ template: require('./tab.demo.html') }) export class TabDemo {}<file_sep>/src/modules/components/data-visualisation/tab/tabset.component.ts import { Component } from '@govuk/angularjs-devtools'; import { TabComponent } from './tab.component'; @Component({ template: ` <div class="tabs"> <ul class="tabs-list" role="tablist"> <li role="presentation" ng-repeat="tab in $ctrl.tabs"> <a ng-click="$ctrl.select(tab)" role="tab" tabindex="{{ tab.active ? '0':'-1'}}" aria-selected="{{ tab.active ? 'true':'false'}}" aria-controls="{{tab.heading}}" ng-bind="tab.heading"></a> </li> </ul> </div> <div class="tabs-content" ng-transclude></div>`, transclude: true }) export class TabsetComponent { tabs: TabComponent[] = []; selected: TabComponent; add(tab: TabComponent): void { this.tabs.push(tab); if (!this.selected) { this.select(tab); } } isActive(tab: TabComponent): boolean { return tab === this.selected; } remove(tab: TabComponent): void { const idx = this.tabs.indexOf(tab); if (idx > -1) { this.tabs.splice(idx, 1); } this.select(this.tabs[0]); } select(tab: TabComponent): void { this.selected = tab; } }<file_sep>/src/modules/components/navigation/next-previous-navigation/next-previous-navigation.component.ts import { Component } from '@govuk/angularjs-devtools'; @Component({ bindings: { navigation: '<' }, template: require('./next-previous-navigation.component.html') }) export class NextPreviousNavigationComponent {}<file_sep>/src/modules/components/banners/notification/notification.component.ts import { Component } from '@govuk/angularjs-devtools'; @Component({ bindings: { type: '@', showIcon: '<' }, transclude: true, template: ` <div class="gov-notification {{$ctrl.type}}"> <i class="gov-icon" ng-if="$ctrl._showIcon"></i> <div class="gov-notification-body" ng-transclude> </div> </div> ` }) export class NotificationComponent { showIcon: boolean; _showIcon: boolean; $onChanges() { this._showIcon = this.showIcon === undefined ? true : this.showIcon; } }<file_sep>/src/modules/components/navigation/navigation.ts import { ActionPaneComponent } from './action-pane/action-pane.component'; import { ArrowComponent } from './arrow/arrow.component'; import { BadgeItemComponent} from './badge-item/badge-item.component'; import { BreadcrumbsComponent } from './breadcrumbs/breadcrumbs.component'; import { CompletedBarComponent} from './completed-bar/completed-bar.component'; import { NextPreviousNavigationComponent } from './next-previous-navigation/next-previous-navigation.component'; import { SideMenuComponent} from './menus/side-menu/side-menu.component'; import { TopMenuComponent} from './menus/top-menu/top-menu.component'; import { StartBarComponent} from './start-bar/start-bar.component'; const module = angular.module('govuk-single-page-pdk.components.navigation', []) .component('govActionPane', ActionPaneComponent) .component('govArrow', ArrowComponent) .component('govBadgeItem', BadgeItemComponent) .component('govBreadcrumbs', BreadcrumbsComponent) .component('govCompletedBar', CompletedBarComponent) .component('govNextPreviousNavigation', NextPreviousNavigationComponent) .component('govSideMenu', SideMenuComponent) .component('govTopMenu', TopMenuComponent) .component('govStartBar', StartBarComponent); export default module.name;
845e1b0eaca9e81adf7351384b076ac7a8708e3c
[ "TypeScript", "HTML" ]
14
TypeScript
mszygenda/govuk_single_page_pdk
dd159ad35dec441719e9ba4ebab2f5ed8a1db30d
f17b075e9257f98eca6651f1fd499f4064976c52
refs/heads/main
<repo_name>Dwarakh347/macham<file_sep>/main.js player1_name = localStorage.getItem("player1_name"); player2_name = localStorage.getItem("player2_name");
333ec2ad69b62bbd12989d0fdc43bad56fa174fb
[ "JavaScript" ]
1
JavaScript
Dwarakh347/macham
cd5395e3df79d54ed0b0a1f65038c039319946ff
9cf5ee1bd5249de2a53e0e0cd98985e5359ac559
refs/heads/master
<repo_name>ShuaiGuo95/SRPA<file_sep>/web/Dockerfile FROM python:3.5 MAINTAINER youchen <<EMAIL>> USER root RUN apt-get update RUN apt-get install -y gettext RUN git clone https://github.com/Time1ess/SRPA VOLUME ["/SRPA/static", "/SRPA/media"] RUN chmod a+x /SRPA/web/entrypoint.sh EXPOSE 8000 ENV SRPA_SETTINGS production ENTRYPOINT ["/SRPA/web/entrypoint.sh"] <file_sep>/authentication/views/info_detail.py #!/usr/bin/env python3 # coding: UTF-8 # Author: David # Email: <EMAIL> # Created: 2017-09-08 20:06 # Last modified: 2017-10-14 15:08 # Filename: info_detail.py # Description: from django.contrib.auth.mixins import UserPassesTestMixin from django.views.generic import DetailView from guardian.mixins import PermissionRequiredMixin from authentication import USER_IDENTITY_STUDENT, USER_IDENTITY_TEACHER from authentication.models import StudentInfo, TeacherInfo class InfoDetailBase(PermissionRequiredMixin, DetailView): """ A base view for displaying detail info. """ http_method_names = ['get'] slug_field = 'uid' slug_url_kwarg = 'uid' raise_exception = True class StudentInfoDetail(UserPassesTestMixin, InfoDetailBase): """ A view for displaying student info. """ model = StudentInfo fields = ['student_id', 'institute'] template_name = 'authentication/student_info_detail.html' permission_required = 'view_studentinfo' raise_exception = True def test_func(self): user = self.request.user return user.is_authenticated and \ user.user_info.identity == USER_IDENTITY_STUDENT class TeacherInfoDetail(UserPassesTestMixin, InfoDetailBase): """ A view for displaying teacher info. """ model = TeacherInfo fields = ['title'] template_name = 'authentication/teacher_info_detail.html' permission_required = 'view_teacherinfo' raise_exception = True def test_func(self): user = self.request.user return user.is_authenticated and \ user.user_info.identity == USER_IDENTITY_TEACHER <file_sep>/SRPA/development_settings.py #!/usr/bin/env python3 # coding: UTF-8 # Author: David # Email: <EMAIL> # Created: 2017-10-01 15:15 # Last modified: 2017-10-14 13:56 # Filename: development_settings.py # Description: # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<KEY>' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'SRPA', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '192.168.3.95', 'PORT': '3307', 'OPTIONS': { 'sql_mode': 'STRICT_TRANS_TABLES', } } }
60f0c7066d9a95b388a8c3df93f1e59c38c5fad5
[ "Python", "Dockerfile" ]
3
Dockerfile
ShuaiGuo95/SRPA
78c4a27a2f54b8ae7262559a602ed1a09cc5c052
4c41790063a1aa9e2b2e01305bd1240a56b2d6b2
refs/heads/master
<repo_name>lizongkai-big/LeetCode<file_sep>/src/TAG/LinkedList/LRU.java package TAG.LinkedList; import java.util.HashMap; /** * 双向链表 */ class DLinkedNode { public int val; // 用于hash表查找、删除 public String key; public DLinkedNode pre, post; public DLinkedNode(int v) { val = v; key = ""; pre = null; post = null; } } /** * 使用hash表 + 双向链表模拟实现的LRU,使得放入和移除都是 O(1), * 参考:https://blog.csdn.net/hopeztm/article/details/79547052 * hash表:保证查找的时间复杂度是O(1) * 链表:保证删除、插入的时间复杂度是O(1) * 双向:方便删除节点之后链表的恢复 * * 缺点:如果LRU链表本身很短,双向链表的双指针会显得浪费空间 */ public class LRU { private HashMap<String, DLinkedNode> cache; private int count; private int capacity; private DLinkedNode head, tail; public LRU(int capacity) { this.count = 0; this.capacity = capacity; this.cache = new HashMap<>(); head = new DLinkedNode(-1); tail = new DLinkedNode(-1); head.pre = null; head.post = tail; tail.pre = head; tail.post = null; } public int get(int value) { DLinkedNode node = cache.get(value + ""); if (node == null) { return -1; // should raise exception here. } // move the accessed node to the head; this.moveToHead(node); return node.val; } public void set(int value) { DLinkedNode node = cache.get(value + ""); if (node == null) { DLinkedNode newNode = new DLinkedNode(value); newNode.key = value + ""; this.cache.put(value + "", newNode); this.insertHead(newNode); ++count; if (count > capacity) { // pop the tail DLinkedNode tail = this.popTail(); this.cache.remove(tail.key); --count; } } else { this.moveToHead(node); } } /** * 双向链表中插入表头 * * @param node */ private void insertHead(DLinkedNode node) { DLinkedNode next = head.post; head.post = node; node.pre = head; node.post = next; next.pre = node; } /** * 双向链表中删除节点 * * @param node */ private void removeNode(DLinkedNode node) { DLinkedNode pre = node.pre; DLinkedNode post = node.post; pre.post = post; post.pre = pre; node.post = null; node.pre = null; } /** * 将某个节点移动到双向链表表头 * * @param node */ private void moveToHead(DLinkedNode node) { this.removeNode(node); this.insertHead(node); } /** * 删除表尾 * * @return */ private DLinkedNode popTail() { DLinkedNode pre = tail.pre; this.removeNode(pre); return pre; } public DLinkedNode getTail() { return tail; } public DLinkedNode getHead() { return head; } public void print() { DLinkedNode tmp = head.post; while (tmp != null && tmp != tail) { System.out.printf(tmp.val + " "); tmp = tmp.post; } System.out.println(); } public void printRvsOrder() { DLinkedNode tmp = tail.pre; while (tmp != null && tmp != head) { System.out.printf(tmp.val + " "); tmp = tmp.pre; } System.out.println(); } public static void main(String[] args) { LRU lru = new LRU(4); for (int i = 0; i < 200; i++) { int rand = (int) (Math.random() * 10); System.out.print("set: " + rand + "\n"); lru.set(rand); lru.print(); rand = (int) (Math.random() * 10); System.out.print("get: " + rand + "\n"); int find = lru.get(rand); System.out.println(find); if(find != -1) lru.print(); } } } <file_sep>/src/Ordered/_24__Swap_Nodes_in_Pairs.java package Ordered; import utils.ListNode; public class _24__Swap_Nodes_in_Pairs { public ListNode swapPairs_Iteration_Mine01(ListNode head) { if(head == null) return null; // dummy 节点 ListNode res = new ListNode(0); res.next = head; ListNode slow = head; ListNode fast = head.next; ListNode front = res; while(fast != null) { slow.next = fast.next; fast.next = slow; front.next = fast; front = slow; if(slow.next != null && slow.next.next != null) { fast = slow.next.next; slow = slow.next; } else{ slow = null; fast = null; } } return res.next; } public ListNode swapPairs_Iteration_Others(ListNode head) { // 对于空链表或只有一个节点的链表,无需swap if(head == null || head.next == null) return head; // dummy Node ListNode res = new ListNode(0); res.next = head; // 要有前节点 ListNode front = res; // 如果链表的剩余部分为空或只有一个节点,无需swap while(front.next != null && front.next.next != null) { // 草纸上模拟下就晓得了 ListNode slow = front.next; ListNode fast = front.next.next; slow.next = fast.next; fast.next = slow; front.next = fast; front = slow; } return res.next; } public ListNode swapPairs_Iteration(ListNode head) { // 对于空链表和只有一个节点的链表,不做交换直接返回 if(head == null || head.next == null) return head; // n 表示第二个节点 ListNode n = head.next; // 交换前两个节点,现在的头结点就成了n n.next = head; // 把第二个节点之后的链表当成一个新的链表 head.next = swapPairs_Iteration(head.next.next); return n; } } <file_sep>/src/TAG/LinkedList/_234__Palindrome_Linked_List.java package TAG.LinkedList; import utils.ListNode; /** * 判断一个单链表是否为回文的 */ public class _234__Palindrome_Linked_List { /** * https://github.com/andavid/leetcode-java/blob/master/note/234/README.md * 利用快慢指针,让slow指向链表的中点,并倒置前半个链表,最后比较中点两侧的链表是否相等 * @param head * @return */ public boolean isPalindrome(ListNode head) { // zero node or only one node if(head == null || head.next == null) return true; ListNode pre = null; // pre初始化不能是head,不然在倒置时会有head.next = pre(head),而head.next本身指向head,形成一个循环! ListNode slow = head; ListNode fast = head; while(fast != null && fast.next != null) { // 倒置结点,需要一个临时结点,仅靠slow,fast不能实现倒置 ListNode tmp = slow; /*-------slow和fast的向后移动,要在倒置结点之前----------*/ slow = slow.next; fast = fast.next.next; tmp.next = pre; pre = tmp; } /*让slow指向链表的后半部分的开始*/ /**设链表长度为len, 因为fast走了奇数(1+2*x)步,slow走了1+x步。 * 如果链表长度是偶数,则循环的跳出条件是fast==null,fast.next!==null, * 此时fast走了len+1步,根据len+1=1+2*x,slow走了len/2+1步,已经指向链表的后一半的第一个元素; * 如果链表长度为奇数,循环跳出条件为fast.next==null,fast!=null, * 此时fast走了len步,根据len+1=1+2*x,此时slow走了(len-1)/2+1,也就是(len+1)/2步,正指向链表的中间元素, * 所以要后移一位 * */ if(fast != null) slow = slow.next; while(slow != null) { if(slow.val != pre.val) { return false; } slow = slow.next; pre = pre.next; } // 恢复现场 return true; } public void two_points_practice(ListNode head) { if(head == null || head.next == null) return; ListNode slow = head, fast = head; while(fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } if(fast != null) slow = slow.next; } } <file_sep>/src/TAG/StringMatching/Trie.java package TAG.StringMatching; class TrieNode { char c; final int SIZE = 26; TrieNode[] children = new TrieNode[SIZE]; boolean isEndingChar = false; public TrieNode(char c) { this.c = c; } } public class Trie { private TrieNode root = new TrieNode('/'); public void insert(char[] text) { TrieNode node = root; for(char c: text) { int inx = c - 'a'; if(node.children[inx] == null) { node.children[inx] = new TrieNode(c); } node = node.children[inx]; } node.isEndingChar = true; } public boolean find(char[] pattern) { TrieNode node = root; for (char c: pattern) { int inx = c - 'a'; if(node.children[inx] == null) return false; node = node.children[inx]; } return node.isEndingChar; } public static void main(String[] args) { Trie trie = new Trie(); char[][] words = new char[][]{{'h','e','l','l','o'}, {'e','e','l','l','o'}, {'h','e','l','o','o'}, {'h','e','l','l','e'}, }; System.out.println("对空的Trie树进行查找------------------"); for(char[] w: words) { System.out.println(trie.find(w)); } System.out.println("先插入,再查找------------------"); for(char[] w: words) { trie.insert(w); } for(char[] w: words) { System.out.println(trie.find(w)); } System.out.println("再插入,再查找------------------"); for(char[] w: words) { trie.insert(w); } for(char[] w: words) { System.out.println(trie.find(w)); } System.out.println("查找一个不存在的字符串------------------"); System.out.println(trie.find(new char[]{'l', 'o', 'o'})); } } <file_sep>/src/TAG/DP/Longest_Common_Subsequence.java package TAG.DP; import java.util.Arrays; // 最长公共子序列 /** * 0 i = 0 || j == 0 * LCS[i, j] = LCS[i-1, j-1] + 1 i,j > 0 && Xi == Yj * Max{LCS[i-1,j], i,j > 0 && Xi != Yj * LCS[i,j-1]} */ public class Longest_Common_Subsequence { public String lcs(String s, String t) { int m = s.length(); int n = t.length(); int[][] dp = new int[m + 1][n + 1]; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (s.charAt(i - 1) == t.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } } // return dp[m][n]; StringBuilder sb = new StringBuilder(); for (int i = m, j = n; i >= 1 && j >= 1;) { if (s.charAt(i - 1) == t.charAt(j - 1)) { sb.append(s.charAt(i - 1)); j --; i --; } else { if (dp[i][j - 1] >= dp[i - 1][j]) { sb.append(s.charAt(j - 1)); j --; } else { sb.append(s.charAt(i - 1)); i --; } } } return sb.reverse().toString(); } public static void main(String[] args) { Longest_Common_Subsequence longest_common_subsequence = new Longest_Common_Subsequence(); String s = "abababa"; System.out.println(longest_common_subsequence.lcs(s, s)); } } <file_sep>/src/Ordered/_30__Substring_with_Concatenation_of_All_Words.java package Ordered; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * 如果是把words重新组合,则没有考虑到words中字符串都是相同长度的条件 * 感觉这道题比较没营养,可以学到map 的使用、越界的判断、break的条件 */ public class _30__Substring_with_Concatenation_of_All_Words { public List<Integer> findSubstring(String s, String[] words) { List<Integer> res = new LinkedList<>(); int wordNum = words.length; int slen = s.length(); if(slen == 0 || wordNum == 0) return res; int wordLen = words[0].length(); Map<String ,Integer> wordMap = new HashMap<>(); for (int i = 0; i < wordNum; i++) { if(words[i].length() != wordLen) { return res; } wordMap.put(words[i], wordMap.getOrDefault(words[i], 0) + 1); } for (int i = 0; i < slen - wordLen * wordNum + 1; i++) { Map<String, Integer> tmpMap = new HashMap<>(); int j = 0; for (; j < wordNum; j++) { String tmp = s.substring(i + j * wordLen, i + (j+1) * wordLen); if(!wordMap.containsKey(tmp)) { break; } tmpMap.put(tmp, tmpMap.getOrDefault(tmp, 0) + 1); if(tmpMap.get(tmp) > wordMap.get(tmp)) { break; } } if(j == wordNum) { res.add(i); } } return res; } public static void main(String[] args) { _30__Substring_with_Concatenation_of_All_Words substringWithConcatenationOfAllWords = new _30__Substring_with_Concatenation_of_All_Words(); String s = "barfoothefoobarman"; String[] words = {"foo","bar"}; System.out.println(substringWithConcatenationOfAllWords.findSubstring(s, words)); } } <file_sep>/src/TAG/BackTracking/_46__Permutations.java package TAG.BackTracking; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class _46__Permutations { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<>(); Arrays.sort(nums); backtrack(res, new ArrayList<Integer>(), nums); return res; } public void backtrack(List<List<Integer>> res, List<Integer> tmpList, int[] nums) { if (tmpList.size() == nums.length) { res.add(new ArrayList<>(tmpList)); } else { for (int i = 0; i < nums.length; i++) { if (tmpList.contains(nums[i])) continue; tmpList.add(nums[i]); backtrack(res, tmpList, nums); tmpList.remove(tmpList.size() - 1); } } } public static void main(String[] args) { _46__Permutations permutations = new _46__Permutations(); List<List<Integer>> lists = (permutations.permute(new int[]{1, 2, 3, 4, 7})); for (List<Integer> list : lists) System.out.println(list); } } <file_sep>/src/TAG/DP/_91__Decode_Ways.java package TAG.DP; public class _91__Decode_Ways { public static void main(String[] args) { } } <file_sep>/src/TAG/String/DelContinuouslyChar.java package TAG.String; import java.util.Stack; // #stack public class DelContinuouslyChar { // 删除str中连续的字符 如AAABA->BA,返回字符串最终的长度 public int del_Recur(String str) { int len = str.length(); int lent; if (len == 0) return 0; StringBuilder stringBuilder = new StringBuilder(); str += "#"; int l = 0; for (int i = 1; i <= len; i++) { if (str.charAt(i) != str.charAt(i - 1)) { if (l == i - 1) stringBuilder.append(str.charAt(i - 1)); l = i; } } if ((lent = stringBuilder.length()) == len) return 0; return len - lent + del_Recur(stringBuilder.toString()); } public int del_Iter(String str) { int len = str.length(); if (len == 0) return 0; Stack<Character> stack = new Stack<>(); int i = 0; while (i < len) { if (stack.isEmpty()) { stack.push(str.charAt(i)); i++; continue; } while (!stack.isEmpty() && i < len) { char c = str.charAt(i); char peek = stack.peek(); if (peek == c) { stack.pop(); i++; } else { stack.push(c); i++; break; } } } return stack.size(); } public int del_Iter_optimize(String str) { int len = str.length(); if (len == 0) return 0; Stack<Character> stack = new Stack<>(); int i = 0; while (i < len) { // 栈不空 && 字符串下标不越界 && 满足一定条件 while (!stack.isEmpty() && i < len && str.charAt(i) == stack.peek()) { stack.pop(); i++; } stack.push(str.charAt(i)); i++; } return stack.size(); } } <file_sep>/src/Ordered/_59__Spiral_Matrix_II.java package Ordered; public class _59__Spiral_Matrix_II { public int[][] generateMatrix(int n) { int[][] res = new int[n][n]; int top = 0, bottom = n-1, left = 0, right = n-1; for (int i = 1; i <= n*n; ) { for (int j = left; j <= right; j++) { res[top][j] = i; i ++; } top ++; for (int j = top; j <= bottom; j++) { res[j][right] = i; i ++; } right --; for (int j = right; j >= left; j--) { res[bottom][j] = i; i ++; } bottom --; for (int j = bottom; j >= top; j--) { res[j][left] = i; i ++; } left ++; } return res; } } <file_sep>/src/TAG/Brainteaser/WhenOneMeetZero.java package TAG.Brainteaser; import java.util.Scanner; import java.util.Stack; /** * 给定一个字符串,字符串中1,0相遇会互相抵消,抵消之后的字符串长度 * 如10101 --> 1 长度为1 * 0000 --》 0000 长度为4 * 1010 --》 "" 长度为0 */ public class WhenOneMeetZero { public static int solveWithStack(int m, String str) { Stack<Character> stack = new Stack<>(); int i = 0; while (i < m) { if(stack.isEmpty()) { stack.push(str.charAt(i)); i++; continue; } while (!stack.isEmpty() && i < m) { char c = str.charAt(i); char top = stack.peek(); if(top == '0' && c == '1' || top == '1' && c == '0') { stack.pop(); i ++; } else { stack.push(str.charAt(i)); i ++; break; } } } return stack.size(); } public static int solveWithTrick(int m, String str) { int ones = 0; int zeros = 0; for (int i = 0; i < m; i++) { if(str.charAt(i) == '0') zeros ++; else if(str.charAt(i) == '1') ones ++; } return Math.abs(ones-zeros); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { int m = Integer.parseInt(sc.nextLine()); String str = sc.nextLine(); System.out.println(solveWithStack(m, str) == solveWithTrick(m, str)); } } } <file_sep>/src/Easy/_26__Remove_Duplicates_from_Sorted_Array.java package Easy; public class _26__Remove_Duplicates_from_Sorted_Array { /** * elegant, and a little * @param nums * @return */ public int removeDuplicates(int[] nums) { int len = nums.length; if(len < 2) return len; int id = 1; for(int i = 1; i < len; i ++) { if(nums[i] != nums[i-1]) { nums[id++] = nums[i]; } } return id; } public int strStr(String haystack, String needle) { int lenStack = haystack.length(); int lenNeedle = needle.length(); int res = -1; for (int i = 0; i < lenStack; i++) { int j = 0; for (; j < lenNeedle; j++) { if(!((i+j) < lenStack && haystack.charAt(i+j) == needle.charAt(j))) { break; } } if(j == lenNeedle) { res = i; break; } } return res; } } <file_sep>/src/Ordered/_11__Container_With_Most_Water.java package Ordered; public class _11__Container_With_Most_Water { /** * https://leetcode.com/problems/container-with-most-water/discuss/6099/Yet-another-way-to-see-what-happens-in-the-O(n)-algorithm * 容器容积计算公式:Math.min(height[i], height[j]) * (j-i) * @param height * @return */ public int maxArea(int[] height) { int len = height.length; int res = 0; // 两个指针,分别代表容器的两边;初始状态使底长最大 int i=0, j = len-1; while(i < j) { // 高度 * 底长 res = Math.max(res, Math.min(height[i], height[j]) * (j-i)); // 为了Math.min(height[i], height[j])更大些,就让小的边寻求大些 // 如果高度一致,就都向内靠拢咯 if (height[i] == height[j]) {i++; j--;} else if (height[i] < height[j]) i ++; else j--; } return res; } } <file_sep>/src/Ordered/_41__First_Missing_Positive.java class _41__First_Missing_Positive { public int firstMissingPositive(int[] nums) { int n = nums.length; // first, put nums[i] into right place. for(int i = 0; i < nums.length; i++) { // nums[i]'s right place is in (0, n] while(nums[i] > 0 && nums[i] <= n && nums[nums[i]-1] != nums[i]) { // use temparory inx, because nums[i] will change, so nums[i]-1 also change. int inx = nums[i]-1; int t = nums[i]; nums[i] = nums[inx]; nums[inx] = t; } } // find the one not in right place. for(int i = 0; i < n; i++) { if(nums[i] != i+1) { return i+1; } } return n+1; } } <file_sep>/src/TAG/DP/_62__Unique_Paths.java package TAG.DP; import java.util.Arrays; /** * 精进案例 */ public class _62__Unique_Paths { public int uniquePaths_mine(int m, int n) { if(m == 0 || n == 0) return 0; int[][] pathNums = getPaths(m, n); return pathNums[m-1][n-1]; } /** * 事实上,getPaths(m, n)计算pathNums时,只用到了上一行和本行的前一列,所以只需要两行就行了 * O(2*min(m, n)) space complexity * @param m * @param n * @return */ public int uniquePaths_optimization_1(int m, int n) { /*好评,以前总想着要交换n, m*/ if (m > n) return uniquePaths_optimization_1(n, m); int[] cur = new int[n]; Arrays.fill(cur, 1); int[] pre = new int[n]; Arrays.fill(pre, 1); for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { cur[j] = cur[j - 1] + pre[j]; } // swap cur-pre pre = cur; } return cur[n-1]; } /** * 两行,本质上就是一行嘛 * @param m * @param n * @return */ public int uniquePaths_optimization_2(int m, int n) { if(m == 0 || n == 0) return 0; if (m > n) return uniquePaths_optimization_2(n, m); int[] dp = new int[n]; Arrays.fill(dp, 1); for(int i = 1; i < m; i ++) { // 从第二行开始 for(int j = 1; j < n; j ++) { dp[j] += dp[j-1]; } } return dp[n-1]; } /** * 函数依据P[i][j] = P[i - 1][j] + P[i][j - 1]的特点,但是需要O(n^2)的空间 * @param m * @param n * @return */ public int[][] getPaths(int m, int n) { int[][] pathNums = new int[m][n]; pathNums[0][0] = 1; for(int i = 0; i < m; i ++) { for(int j = 0; j < n; j ++) { if(i == 0 || j == 0) { pathNums[i][j] = 1; } else { pathNums[i][j] = pathNums[i][j-1] + pathNums[i-1][j]; } } } return pathNums; } } <file_sep>/src/TAG/BinarySearch/_74__Search_a_2D_Matrix.java package TAG.BinarySearch; public class _74__Search_a_2D_Matrix { public boolean searchMatrix(int[][] matrix, int target) { if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return false; int m = matrix.length, n = matrix[0].length; int lo = 0, hi = m-1; int row = 0, col = 0; // 最后一个小于等于target的元素 while (lo <= hi) { int mid = lo + ((hi-lo) >> 1); if(matrix[mid][0] <= target) { if(matrix[mid][0] == target) return true; if(matrix[mid+1][0] > target) row = target; lo = mid + 1; } else { hi = mid - 1; } } lo = 0; hi = n - 1; while (lo < hi) { int mid = lo + ((hi-lo) >> 1); if(matrix[row][mid] <= target) { if(matrix[row][mid] == target) return true; if(matrix[row][mid] > target) ; lo = mid + 1; } else { hi = mid - 1; } } return false; } } <file_sep>/src/TAG/Tree/_101_Symmetric_Tree.java package TAG.Tree; import utils.TreeNode; /** * Given a binary tree, * check whether it is a mirror of itself (ie, symmetric around its center). */ public class _101_Symmetric_Tree { public boolean isSymmetric(TreeNode root) { if(root == null) return true; return isSymmetricHelper(root.left, root.right); } public boolean isSymmetricHelper(TreeNode node1, TreeNode node2) { if(node1 == null || node2 == null) return node1 == node2; if(node1.val != node2.val) return false; return isSymmetricHelper(node1.left, node2.right) && isSymmetricHelper(node1.right, node2.left); } } <file_sep>/src/Ordered/_88__Merge_Sorted_Array.java package Ordered; public class _88__Merge_Sorted_Array { // 使用插入排序的思想,往已知有序的nums1中插入nums2中的数字; // 涉及到nums1中数字的后移,时间复杂度是O(mn) public void merge_Mine(int[] nums1, int m, int[] nums2, int n) { int i = 0, j = 0; for(; j < n && i < m;) { for(; i < m; i++) { if(nums1[i] > nums2[j]) { for(int k = m-1; k >= i; k--) nums1[k+1] = nums1[k]; nums1[i] = nums2[j]; m ++; j++; break; } } } while(j < n) { nums1[i ++] = nums2[j++]; } } // 按顺序从后往前加入混合之后的数组末尾,时间复杂度是O(m+n) public void merge_optimization(int[] nums1, int m, int[] nums2, int n) { int length = m+n-1; m --; n --; while (m >= 0 && n >= 0) { if(nums1[m] > nums2[n]) { nums1[length --] = nums1[m--]; } else { nums1[length --] = nums2[n--]; } } while (n >= 0) nums1[length--] = nums2[n--]; } } <file_sep>/src/TAG/Recrusion/_687__Longest_Univalue_Path.java package TAG.Recrusion; import utils.TreeNode; public class _687__Longest_Univalue_Path { int max = 0; public int longestUnivaluePath(TreeNode root) { getPath(root); return max; } public int getPath(TreeNode root) { if(root == null || root.left == null && root.right == null) return 0; int left = getPath(root.left); int right = getPath(root.right); // 以当前节点为根的子树的longestUnivaluePath,Longest-Univalue-Path-Across - node int maxLength = 0; // 以当前节点为根的子树,单向最长路径,对父节点而言 int pathLen = 0; if(root.left != null && root.val == root.left.val) { maxLength += (left+1); pathLen = left+1; } if(root.right != null && root.val == root.right.val) { maxLength += (right+1); if(right+1>pathLen) pathLen = right + 1; } if(maxLength > max) max = maxLength; return pathLen; } } <file_sep>/src/Ordered/_6__ZigZag_Conversion.java package Ordered; public class _6__ZigZag_Conversion { /** * 硬扛的裱糊匠!啰嗦、不够优雅 * @param s * @param numRows * @return */ public String convert_stupid(String s, int numRows) { int diff = numRows + numRows - 2; // i: row num // diff: 两个元素的下标的差值 int len = s.length(); if(numRows <= 1 || len <= 1) { return s; } char[] res = new char[len]; // point to res's subscript int point = 0; // 第一行 for(int i = 0, j = diff; i < len; i += diff) { res[point ++] = s.charAt(i); } // 第二行至倒数第二行 for(int i = 1, j = diff; i < numRows-1; i++, j -= 2) { if(i < len) res[point ++] = s.charAt(i); int firstDiff = j - 2; int secondDiff = diff - firstDiff; while(i + firstDiff < len) { res[point ++] = s.charAt(i + firstDiff); i += firstDiff; if(numRows != 3 && i + secondDiff < len){ res[point ++] = s.charAt(i + secondDiff); } if(numRows != 3) { i += secondDiff; } } } // 最后一行 for(int i = numRows - 1, j = diff; i < len; i += diff) { res[point ++] = s.charAt(i); } return new String(res); } /** * elegant approach * 另一个角度看待 zigzag pattern * @param s * @param numRows * @return */ public String convert_elegant(String s, int numRows) { if(numRows == 1) return s; int len = s.length(); StringBuilder[] res = new StringBuilder[numRows]; for(int i = 0; i < numRows; i ++) { /*init every res element **important step!!!!*/ // if not, res[i] is null res[i] = new StringBuilder(); } int direction = 1; int inx = 0; for(int i = 0; i < len; i ++) { res[inx].append(s.charAt(i)); // change the direction **important step!!!! if(inx == 0) direction = 1; if(inx == numRows - 1) direction = -1; inx += direction; // attention to outOfBounds, new test cases if(inx >= numRows) inx = numRows-1; if(inx < 0) inx = 0; } for(int i = 1; i < numRows; i ++) { res[0].append(res[i]); } return res[0].toString(); } public static void main(String[] args) { _6__ZigZag_Conversion zigZagConversion = new _6__ZigZag_Conversion(); System.out.println(zigZagConversion.convert_stupid("PAYPALISHIRING", 4)); } } <file_sep>/src/TAG/Brainteaser/_319__Bulb_Switcher.java package TAG.Brainteaser; /** * 2015盏灯,一开始全部熄灭,序号分别是1-2015,先把1的倍数序号的灯的开关全部按一次,然后把2的倍数的灯的开关全部按一次, * 然后把3的倍数的开关按一次,以此类推,最后把2015的倍数灯的开关按一次。问最后亮着的灯有多少盏? * * 最后亮着的灯都被按了奇数次,也就是那些约数个数是奇数个的灯,约数有奇数个的数都是完全平方数(整数自乘) * 证明,假设一个数m有奇数个约数,其中一个约数是n,则有另一个约数为m/n,如果n!=m/n则它的约数是以n, m/n成对出现的, * 应该有偶数个约数,不符合!所以n==m/n,则该数为n^2,即为完全平方数 * * 一个数中完全平方数的个数为sqrt(n)向下取整。如44^2<2015<45^2,所以2015中有44个完全平方数(1,2,3...44) */ public class _319__Bulb_Switcher { public int bulbSwitch(int n) { return (int)Math.sqrt(n); } } <file_sep>/src/Ordered/_56__Merge_Intervals.java package Ordered; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; public class _56__Merge_Intervals { public class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } } /** * 不算优点的优点:在原有的ArrayList中做处理 * 缺点:List.remove(int index); 涉及大量的数组复制操作,效率很低;不如直接新建一个List * @param intervals * @return */ public List<Interval> merge_mine(List<Interval> intervals) { bubbleSort(intervals); int inx = 0; for(int i = 1; i < intervals.size();) { if(intervals.get(inx).start == intervals.get(i).start || intervals.get(inx).start < intervals.get(i).start && intervals.get(inx).end >= intervals.get(i).start || intervals.get(inx).start > intervals.get(i).start && intervals.get(i).end >= intervals.get(inx).start ) { intervals.get(inx).start = Math.min(intervals.get(inx).start, intervals.get(i).start); intervals.get(inx).end = Math.max(intervals.get(inx).end, intervals.get(i).end); intervals.remove(i); } else { i++; inx ++; } } return intervals; } public List<Interval> merge_optimization1(List<Interval> intervals) { List<Interval> list=new ArrayList<>(); int []start=new int[intervals.size()]; int []end=new int[intervals.size()]; for(int i=0;i<intervals.size();i++){ start[i]=intervals.get(i).start; end[i]=intervals.get(i).end; } Arrays.sort(start); Arrays.sort(end); for(int i=0,j=0;i<intervals.size();i++){ /* 到了最后一个元素或者不再有重叠*/ if(i==intervals.size()-1 || start[i+1]>end[i]){ list.add(new Interval(start[j],end[i])); j=i+1; } } return list; } public List<Interval> merge_optimization2(List<Interval> intervals) { if (intervals.size() <= 1) return intervals; // Sort by ascending starting point using an anonymous Comparator intervals.sort((i1, i2) -> Integer.compare(i1.start, i2.start)); /*线性单链表 好评!*/ List<Interval> result = new LinkedList<Interval>(); int start = intervals.get(0).start; int end = intervals.get(0).end; Interval last = new Interval(0,0); for (Interval interval : intervals) { /*if (interval.start > end){ last = new Interval(start, end); result.add(last); } else { last.end = Math.max(last.end, interval.end); }*/ if (interval.start <= end) // Overlapping intervals, move the end if needed end = Math.max(end, interval.end); else { // Disjoint intervals, add the previous one and reset bounds result.add(new Interval(start, end)); start = interval.start; end = interval.end; } } // Add the last interval result.add(new Interval(start, end)); return result; } public void bubbleSort(List<Interval> intervals) { boolean swap = false; for(int i = 0; i < intervals.size(); i++) { for(int j = 0; j <= intervals.size()-i-1-1; j++) { if(intervals.get(j).start > intervals.get(j+1).start) { Interval temp = intervals.get(j); intervals.set(j, intervals.get(j+1)); intervals.set(j+1, temp); swap = true; } } // if(!swap) break; } } } <file_sep>/src/TAG/TwoPointers/_345__Reverse_Vowels_of_a_String.java package TAG.TwoPointers; // Two pointers public class _345__Reverse_Vowels_of_a_String { public String reverseVowels(String s) { char[] vowels = new char[]{'a','e','i','o','u','A','E','I','O','U'}; char[] array = s.toCharArray(); int len = array.length; int i = 0; int j = len-1; while(i < j) { while(i < j && !isVowels(vowels, array[i])) i++; while(i < j && !isVowels(vowels, array[j])) j--; char c = array[i]; array[i] = array[j]; array[j] = c; i ++; j --; } return new String(array); } private boolean isVowels(char[] vowels, char c) { for(char v: vowels) { if(v == c) return true; } return false; } } <file_sep>/src/Ordered/_54__Spiral_Matrix.java package Ordered; import java.util.ArrayList; import java.util.List; public class _54__Spiral_Matrix { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<>(); int row = matrix.length; if(row == 0) return res; int col = matrix[0].length; int top = 0, left = 0, bottom = row - 1, right = col - 1; while(true) { // r row for(int j = left; j <= right; j++) { res.add(matrix[top][j]); } top++; if(left>right || top>bottom) break; // col-c-1 colum for(int i = top; i <= bottom; i++) { res.add(matrix[i][right]); } right--; if(left>right || top>bottom) break; // row-r-1 row for(int j = right; j >= left; j--) { res.add(matrix[bottom][j]); } bottom--; if(left>right || top>bottom) break; // c colum for(int i = bottom; i >= top; i--) { res.add(matrix[i][left]); } left++; if(left>right || top>bottom) break; } return res; } } <file_sep>/src/TAG/Greedy/_870__Advantage_Shuffle.java package TAG.Greedy; import java.util.Arrays; /** * 田忌赛马 * 利用贪心思想,首先对自己的马的性能进行排序(方便二分查找),对于对方的任何一匹马A,找出自己的马群中第一个性能大于A的马, * 如果没有大于A的马,则用最小的那匹马 * 因为有数组移动的操作,时间复杂度为 O(n^2) * * https://leetcode.com/problems/advantage-shuffle/discuss/149822/JAVA-Greedy-6-lines-with-Explanation * 换个思路,使用大顶堆存储B的数字和对应下标,尽量满足大顶堆的堆顶,能满足就使用A中的最大值,不能满足就使用A中的最小值 * 因为存储了下标,时间复杂度为O(nlogn) * */ public class _870__Advantage_Shuffle { public int[] advantageCount(int[] A, int[] B) { Arrays.sort(A); int[] res = new int[A.length]; int len = A.length; for (int i = 0; i < B.length; i++) { int inx = binarySearch(A, B[i], len); if(inx == -1) { res[i] = A[0]; coverInx(A, 0, len); } else { res[i] = A[inx]; coverInx(A, inx, len); } len --; } return res; } public void coverInx(int[] array, int inx, int len) { for (int i = inx; i < len-1; i++) { array[i] = array[i+1]; } } /** * 使用二分查找的思想,找到array中第一个大于target的值 * @param array * @param target * @return */ public int binarySearch(int[] array, int target, int len) { int lo = 0, hi = len-1; while (lo <= hi) { int mid = lo + ((hi-lo) >> 1); if(array[mid] <= target) { lo = mid + 1; } else { if(mid == 0 || array[mid-1] <= target) { return mid; } hi = mid-1; } } return -1; } } <file_sep>/src/TAG/Tree/searchBST_Solution.java package TAG.Tree; /** * Given the root node of a binary search tree (BST) and a value. * You need to find the node in the BST that the node's value equals the given value. * Return the subtree rooted with that node. If such node doesn't exist, you should return NULL. */ public class searchBST_Solution { class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public TreeNode searchBST(TreeNode root, int val) { /*1. iteration*/ /* while(true) { if(root == null) { return null; } if(root.val == val) { return root; } else if(root.val < val) { root = root.right; } else { root = root.left; } } */ /*2. recrusion*/ if(root == null) { return null; } TreeNode res; if(root.val == val) { res = root; } else if(root.val < val) { res = searchBST(root.right, val); } else { res = searchBST(root.left, val); } return res; } } <file_sep>/src/TAG/Tree/leafSimilar_Solution.java package TAG.Tree; import utils.TreeNode; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class leafSimilar_Solution { // 1.分别先序遍历得到序列,比较序列 public boolean leafSimilar1(TreeNode root1, TreeNode root2) { List<Integer> leaves1 = getLeaves(root1); List<Integer> leaves2 = getLeaves(root2); int size = leaves1.size(); if(size != leaves2.size()){ return false; } /* 判断两个长度相同的list是否完全相等 // solution 1 for(int i = 0; i < size; i++){ if(leaves1.get(i) != leaves2.get(i)) return false; } return true; */ // solution 2 return leaves1.equals(leaves2); } // 2.分别遍历得到一个叶子节点,判断是否相等;利用栈可以做到 public boolean leafSimilar2(TreeNode root1, TreeNode root2) { // if(root1 == null && root2 == null) // return true; // else if(root1 != null && root2 == null || root2 != null && root1 == null) // return false; Stack<TreeNode> s1 = new Stack<>(), s2 = new Stack<>(); s1.push(root1); s2.push(root2); while(!s1.isEmpty() && !s2.isEmpty()) { if(dfs(s1) != dfs(s2)) return false; } return s1.isEmpty() && s2.isEmpty(); } public int dfs(Stack<TreeNode> s) { while(true) { TreeNode root = s.pop(); if(root.left != null) s.push(root.left); if(root.right != null) s.push(root.right); // 返回叶子节点 if(root.left == null && root.right == null) return root.val; } } List getLeaves(TreeNode root) { List<Integer> leaves = new ArrayList<>(); if(root != null){ forEach(root, leaves); } Integer[] xx = leaves.toArray(new Integer[leaves.size()]); return leaves; } void forEach(TreeNode root, List leaves){ if(root.left == null && root.right == null) { leaves.add(root.val); return; } if(root.left != null) { forEach(root.left, leaves); } if(root.right != null) { forEach(root.right, leaves); } } TreeNode listToTree(List<Integer> list) { if(list == null) { return null; } TreeNode res = new TreeNode(list.get(0)); for (int i = 1; i < list.size(); i++) { if(list.get(i) != null) { } } return res; } public static void main(String[] args) { } } <file_sep>/src/Ordered/_5__Longest_Palindromic_Substring.java package Ordered; /** * 寻找最长的回文数,回文数长度可能为偶数,可能是奇数 */ public class _5__Longest_Palindromic_Substring { static int startInx = 0, validLen = 0; static int left = 0, right = 0; /** * 中心扩展算法 时间复杂度O(n^2) 空间复杂度O(n) * @param s * @return */ public static String longestPalindrome_CenterExtend(String s) { int len = s.length(); char[] c = s.toCharArray(); int i = 0; /*循环记得要自增,不然就是死循环咯*/ while(i < len - 1) { // assume even length. if(c[i] == c[i + 1]) { left = i; right = i + 1; findMaxPalindromic(c, left, right); } // assume odd length, try to extend Palindrome as possible left = right = i; findMaxPalindromic(c, left, right); i++; } /*substring(beginIndex, endInx)*/ return s.substring(startInx, startInx+validLen); } /** * 以left、right为起点,向两侧寻找最长的回文数,并记录startInx, validLen * 左右起点可能相同 * @param c 数组 * @param left 左起点 * @param right 右起点 */ public static void findMaxPalindromic(char[] c, int left, int right) { int len = c.length; // 向左右延伸,判断是否认为回文数 while(left >= 0 && right < len && c[left] == c[right]) { // 变化left\right即可,不需要一个step left --; right ++; } /*此时的left, right正好指向回文数之外的位置,所以有效的wide为right-left-1*/ int wide = right - left - 1; // 更新validLen, startInx if(wide > validLen) { validLen = wide; startInx = left + 1; } } /** * dp[j][i]表示s区间[j,i]是否回文字符串,j,i指向一个字符串的首尾 * when j == i, dp[j][i] == true * when j<i, if s[j]==s[i](字符串的首尾不相等必然不是回文字符串) * && * (i - j < 3 (字符串的首尾相邻(i-j==1)或者首尾之间只隔了一个元素(i-j==2)) * || * dp[j+1][i-1]) (看首尾各减1形成的字符串是否为回文字符串;如果是的话,就相当于回文字符串得到了扩展) * @param s * @return */ public static String longestPalindrome_DP(String s) { int len = s.length(); /* 特例判断 */ if(len == 0) return s; /*len>=1的情况,dp算法就可以执行,而且substring可以剪切出一个子串*/ char[] c = s.toCharArray(); boolean[][] dp = new boolean[len][len]; for(int i = 0; i < len; i ++) { for(int j = 0; j < i; j ++) { // j+1, i-1不怕越界吗? // because j<i && max(j+1)==i,而i<len; min(j+1)==1 ;所以1 <= j+1 <= len 不会越界 // min(i) == 1, max(i) == len -1, so 0 <= i-1 <= len-2 不会越界 /**/ dp[j][i] = (c[i] == c[j] && (i - j < 3 || dp[j + 1][i - 1])); // 更新right, left // 当len==2时候真正的长度,并不是validLen,所以为了使代码更为简洁,validLen只是为了长度的比较, // 并不是真正的长度,该if语句是为了更新left,right,真正的长度=right-left+1 if(dp[j][i] && i-j+1 > validLen) { validLen = i - j + 1; left = j; right = i; } } /*放在j的循环前后都无所谓啦*/ dp[i][i] = true; } return s.substring(left, right + 1); } /** * 马拉车算法 O(n) * 最长回文字符串的字符个数 = resLen - 1 * 起始位置 = (resCenter-resLen) / 2 * @param s * @return */ public static String longestPalindrome_Manacher(String s) { StringBuilder t = new StringBuilder("$#"); for(char c: s.toCharArray()) { t.append(c+"#"); } int len = t.length(); // p[i] 表示以s[i]为字符中心的回文子串的半径 int[] p = new int[len]; for(int i = 0; i < len; i ++) { p[i] = 0; } char[] c = t.toString().toCharArray(); // mx表示已知回文字符串的最靠右的位置,id表示mx对应回文字符串的中心位置; // resLen最长的回文字符串长度,resCenter是最长的回文字符串的中心位置在c中的下标 int mx = 0, id = 0, resLen = 0, resCenter = 0; // 从第一个 # 开始 for(int i = 1; i < len; i ++) { // 根据mx和i的关系,得到一个回文字符串半径的经验值 p[i] = mx > i ? Math.min(mx - i, p[id + id - i]) : 1; /*在下标不越界的情况下,向两侧延伸回文字符串*/ while(i + p[i] < len && i - p[i] >= 0 && c[i + p[i]] == c[i - p[i]]) p[i] ++; // 更新mx和id if(mx < i + p[i]) { mx = i + p[i]; id = i; } // 更新resLen 和 resCenter if(resLen < p[i]) { resLen = p[i]; resCenter = i; } } return s.substring((resCenter-resLen)/2, (resCenter-resLen)/2 + resLen - 1); } public static void main(String[] args) { System.out.println(longestPalindrome_Manacher("babadada")); } } <file_sep>/Readme.md 对于一道题,要有一个模型、要能发现它的特征 超过半小时想不出则看答案,看下别人的思路,自己的盲点,千万不要死抠!! 写链表代码还是主要为了*锻炼写代码的能力*,倒不是思考解决办法 不是完全想不出,而是想出来的思路不能解决问题;多做题,把思路整理好;在草纸上多演算 如果报错,记下来你的错误,第二次提交,记下错误,以此类推。 第二天,第三天接着做,一直做到一提交就bugfree 切忌盲目刷题,要记思路不记题目 心态:坚持刷、看题解、思考 不要怪题目太刁钻,是你没想出解决办法啦 tag: 精进案例,bit two points: i, j 快慢指针(链表) bit manipulation 滑动窗口 二分查找:旋转的有序数组中查找特定值,旋转的有序数组中求最小值 链表:判断有无环、判断环入口、环长度、链表长度、环中节点的对面节点、两个无环链表是否相交并判断相交点<file_sep>/src/TAG/Stack/_155__Min_Stack.java package TAG.Stack; import java.util.Stack; /** * 以O(1)的时间获取栈中的最小值, * 最朴素的想法是getMin()方法调用时,遍历栈来获得最小值,getMin()时间复杂度为O(n); * 为了让getMin()时间复杂度是O(1),可以用两个栈,一个存储数据,另一个存储当前数据集下的最小值,两个栈大小相同, * 缺点是空间复杂度为O(n); * 还可以用一个栈,如果新值是最小值,栈会记录一个之前的最小值,再记录新值,时间和空间复杂度分别是O(1)和O(n); */ public class _155__Min_Stack { } /** * 该类使用一个栈来实现 */ class MinStack { Stack<Integer> stack; int min = Integer.MAX_VALUE; /** initialize your data structure here. */ public MinStack() { stack = new Stack<>(); } public void push(int x) { // why =?因为对于栈顶是最小值的情况,pop()会弹出两次,如果新值等于最小值,如果只放如入栈一次,则pop()会出错 if(x <= min) { stack.push(min); min = x; } stack.push(x); } public void pop() { if(min == stack.pop()) min = stack.pop(); } public int top() { return stack.peek(); } public int getMin() { return min; } } class MinStack_TwoStack { Stack<Integer> stack; Stack<Integer> min; /** initialize your data structure here. */ public MinStack_TwoStack() { stack = new Stack<>(); min = new Stack<>(); } public void push(int x) { if(min.isEmpty() || x <= min.peek()) { min.push(x); } else { min.push(min.peek()); } stack.push(x); } public void pop() { min.pop(); stack.pop(); } public int top() { return stack.peek(); } public int getMin() { return min.peek(); } } class MinStack_Worst { private int[] items; private int n = 20; private int count = 0; /** initialize your data structure here. */ public MinStack_Worst() { items = new int[n]; } public void push(int x) { if(count == n) { int[] newItems = new int[n * 2]; for(int i = 0; i < n; i ++) { newItems[i] = items[i]; } items = newItems; n *= 2; } items[count ++] = x; } public void pop() { if(count == 0) return; count --; } public int top() { if(count == 0) return 0; return items[count - 1]; } public int getMin() { int min = items[count - 1]; for(int i = 0; i < count; i ++) { if(items[i] < min) min = items[i]; } return min; } }<file_sep>/src/Ordered/_75__Sort_Colors.java package Ordered; public class _75__Sort_Colors { public void sortColors(int[] nums) { int second = nums.length, zero = 0; for (int i = 0; i < second; ) { if(nums[i] == 2) { swap(nums[i], nums[second --]); i ++; } if(nums[i] == 0) { swap(nums[i], nums[zero ++]); } } } public void swap(int n, int m) { int t = n; n = m; m = t; } } <file_sep>/src/TAG/Tree/averageOfLevels_Solution.java package TAG.Tree; import utils.TreeNode; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * 要知道每层的个数,和值才能求平均 * 可以使用BFS DFS两种方法 */ public class averageOfLevels_Solution { /** * BFS:利用队列按层遍历 * @param root * @return */ public List<Double> averageOfLevels1(TreeNode root) { if(root == null) return null; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int preLevelCount = 1; List<Double> res = new ArrayList<>(); // 按层遍历队列 while(!queue.isEmpty()) { int curLevelCount = 0; double sum = 0; // 从队列中取出上一层的元素;求和,取平均,加入res;更新preLevelCount for(int i = 0; i < preLevelCount; i ++) { TreeNode node = queue.poll(); sum += node.val; if(node.left != null) { curLevelCount ++; queue.offer(node.left); } if(node.right != null) { curLevelCount ++; queue.offer(node.right); } } res.add(sum / preLevelCount); preLevelCount = curLevelCount; } return res; } class Node { double sum; int count; Node (double d, int c) { sum = d; count = c; } } /** * DFS:利用 * @param root * @return */ public List<Double> averageOfLevels2(TreeNode root) { List<Node> temp = new ArrayList<>(); helper(root, temp, 0); List<Double> result = new LinkedList<>(); for (int i = 0; i < temp.size(); i++) { result.add(temp.get(i).sum / temp.get(i).count); } return result; } public void helper(TreeNode root, List<Node> temp, int level) { if (root == null) return; // temp中每个值是Node,对应的是Tree中每层节点的总和以及个数 if (level == temp.size()) { Node node = new Node((double)root.val, 1); temp.add(node); } else { temp.get(level).sum += root.val; temp.get(level).count++; } helper(root.left, temp, level + 1); helper(root.right, temp, level + 1); } } <file_sep>/src/SwordOffer/_1.java package SwordOffer; public class _1 { // 二维数组array中,每一行都从左到右递增排序, // 每一列都从上到下递增排序 public boolean Find(int target, int [][] array) { if(array == null) return false; int row = array.length; int col = array[0].length; if(col == 0) return false; int i = 0, j = col - 1; boolean found = false; while(i < row && j >= 0) { if(array[i][j] == target) { found = true; break; } else if(array[i][j] < target) { i ++; } else { j --; } } return found; } } <file_sep>/src/Ordered/_904__Fruit_Into_Baskets.java package Ordered; /** * 往两个篮子里放水果,每个篮子里水果的种类是相同的; * 面对新的种类的水果,要么停止搜索,要么放进某个篮子中一个; * 那么对于一行树,求两个篮子最多能放的水果数目 */ public class _904__Fruit_Into_Baskets { public int totalFruit(int[] tree) { int max = 0; int len = tree.length; /*按照一种模型:...aaabbbc... * 对于一种新的类型c,分为三种情况 * 1. c == a * 2. c == b * 3. c != a && c != b * */ int a = -1, b = -1; // 笼统地知道a,b的数目是没有用的,因为题目虽然要求a, b可以不连续,但是一旦出现一个新的type(c),你根本不知到a和c之间的b有多少, // 所以,要有一个统计b的数目的变量 int cur = 0, cb = 0; for(int i = 0; i < len; i ++) { if(tree[i] == a) { a = b; b = tree[i]; cb = 1; cur ++; } else if(tree[i] == b) { cur ++; cb ++; } else if(tree[i] != a && tree[i] != b) { a = b; b = tree[i]; cur = cb + 1; cb = 1; } max = cur > max ? cur : max; } return max; } public static void main(String[] args) { _904__Fruit_Into_Baskets fruit_into_baskets = new _904__Fruit_Into_Baskets(); fruit_into_baskets.totalFruit(new int[]{1,0,1,4,1,4,1,2,3}); } } <file_sep>/src/TAG/TwoPointers/_443__String_Compression.java package TAG.TwoPointers; public class _443__String_Compression { public int compress(char[] chars) { if(chars.length < 2) return chars.length; int i = 0, j = 0, num = 0; for (j = 0; j < chars.length; j++) { num++; if(j == chars.length-1 || chars[j] != chars[j+1]) { chars[i++] = chars[j]; if(num != 1) { String s = String.valueOf(num); for (int k = 0; k < s.length(); k++) { chars[i++] = s.charAt(k); } } num = 0; } } return i; } } <file_sep>/src/TAG/BackTracking/_22__Generate_Parentheses.java package TAG.BackTracking; import java.util.*; public class _22__Generate_Parentheses { /** * 遍历所有情况,通过剪枝来减少无效情况的发生 * 通过判断左右括号的个数,以及是有效括号字符串来加入结果集 * * @param n * @return */ public List<String> generateParenthesis_Mine(int n) { List<String> res = new ArrayList<>(); // find all situations, keep valid parenthes findAllParenthes(res, "", 0, 0, n); return res; } // 剪枝 public void findAllParenthes(List<String> res, String s, int leftParenthesNum, int rightParenthesNum, int total) { /*递归的返回条件放在第一行,说明需要多一次递归;可以把判断条件放在内部,减少一次递归*/ // if(leftParenthesNum > total || rightParenthesNum > total) return; if (leftParenthesNum == total && rightParenthesNum == total && isValid(s)) { // res.add(s); return; } /************************************KEY DIFFERENCE*************************************/ // 只限制左右括号的个数,而忽略两者之间的关系,就需要另外判断形成的字符串是否有效 if (leftParenthesNum < total) findAllParenthes(res, s + "(", leftParenthesNum + 1, rightParenthesNum, total); if (rightParenthesNum < total) findAllParenthes(res, s + ")", leftParenthesNum, rightParenthesNum + 1, total); } public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); int len = s.length(); for (int i = 0; i < len; i++) { if (s.charAt(i) == '(') stack.push(s.charAt(i)); else { // ')' if (stack.isEmpty() || stack.pop() != '(') { return false; } } } if (stack.isEmpty()) return true; return false; } /** * 回溯,带有剪枝 * * @param n * @return */ public List<String> generateParenthesis_Others(int n) { List<String> list = new ArrayList<String>(); backtrack(list, "", 0, 0, n); return list; } public void backtrack(List<String> list, String str, int open, int close, int max) { if (str.length() == max * 2) { // equal to (open == max && close == max) list.add(str); return; } /************************************KEY DIFFERENCE*************************************/ // 既考虑左右括号的个数,也考虑两者之间的关系,就能够保证最终形成的字符串是有效的 if (open < max) // str要和“(”相加,以对带(的情况进行回溯,同时又要保持本色,以对别的情形进行回溯,所以str + "("正合适;open+1同理 backtrack(list, str + "(", open + 1, close, max); if (close < open) backtrack(list, str + ")", open, close + 1, max); } public static void main(String[] args) { _22__Generate_Parentheses generateParentheses = new _22__Generate_Parentheses(); System.out.println(generateParentheses.generateParenthesis_Mine(2)); System.out.println(generateParentheses.generateParenthesis_Others(2)); } } <file_sep>/src/TAG/Tree/_236__Lowest_Common_Ancestor_of_a_Binary_Tree.java package TAG.Tree; import utils.TreeNode; import java.util.ArrayList; import java.util.List; /** * 最近公共祖先 */ public class _236__Lowest_Common_Ancestor_of_a_Binary_Tree { /** * If the current (sub)tree contains both p and q, then the function result is their LCA. * If only one of them is in that subtree, then the result is that one of them. * If neither are in that subtree, the result is null/None/nil. * @param root * @param p * @param q * @return */ public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || root == p || root == q) return root; TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); return left == null ? right : right == null ? left : root; } /** * 将寻找最近公共祖先转换为两个数组找公共节点。时间复杂度是O(n) * 分别找到p,q的公共祖先序列,然后找到最近的公共祖先 * @param root * @param p * @param q * @return */ public TreeNode lowestCommonAncestor_MINE(TreeNode root, TreeNode p, TreeNode q) { List<TreeNode> pAncestor = new ArrayList<>(); List<TreeNode> qAncestor = new ArrayList<>(); isAncestor(root, p, pAncestor); isAncestor(root, q, qAncestor); int len1 = pAncestor.size(); int len2 = qAncestor.size(); int i = len1-1, j = len2-1; for(; i>=0 && j>= 0;) { if(pAncestor.get(i) == qAncestor.get(j)) { i --; j --; } else { break; } } return pAncestor.get(i+1); } /** * Is node p's ancester? * 将p的祖先节点保存在list中 * @param node * @param p * @param list * @return */ public boolean isAncestor(TreeNode node, TreeNode p, List<TreeNode> list) { if(node == null) return false; if(node == p) { // 把p节点放进list list.add(node); return true; } boolean found = false; if(isAncestor(node.left, p, list) || isAncestor(node.right, p, list)) { found = true; // 把p的祖先节点放进list list.add(node); } return found; } } <file_sep>/src/TAG/Tree/_114__Flatten_Binary_Tree_to_Linked_List.java package TAG.Tree; import utils.TreeNode; public class _114__Flatten_Binary_Tree_to_Linked_List { public void flatten(TreeNode root) { if(root == null) return; if(root.left != null) flatten(root.left); if(root.right != null) flatten(root.right); TreeNode node = root.right; root.right = root.left; root.left = null; // nessesary? yes! because it maybe has TreeNode before, need to be set null. while(root.right != null) root = root.right; root.right = node; } } <file_sep>/src/SwordOffer/_4_ReConstructBinaryTree.java package SwordOffer; import utils.TreeNode; import java.util.Arrays; /** * 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 * 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。 * */ public class _4_ReConstructBinaryTree { public TreeNode reConstructBinaryTree(int [] pre, int [] in) { TreeNode dummy = new TreeNode(0); dummy.left = recru(pre, in); return dummy.left; } private TreeNode recru(int[] pre, int[] in) { if(pre.length == 0 && in.length ==0)return null; // 树顶点 int i = 0; for(; i < in.length; i ++) { if(in[i] == pre[0]) break; } TreeNode node = new TreeNode(pre[0]); if(i <= 0) // i+1>pre.length || i >in.length node.left = null; else node.left = recru(Arrays.copyOfRange(pre, 1, i+1), Arrays.copyOfRange(in, 0, i)); if(pre.length - i - 1 <= 0) // i+1>=pre.length || i+1 >=in.length node.left = null; else node.right = recru(Arrays.copyOfRange(pre, i+1, pre.length), Arrays.copyOfRange(in, i+1, in.length)); return node; } public TreeNode reConstructBinaryTreeIterative(int [] pre, int [] in) { if(pre == null || pre.length == 0) return null; int j = 0; while(in[j] != pre[0]) {j ++;} TreeNode node = new TreeNode(pre[0]); node.left = reConstructBinaryTreeIterative(Arrays.copyOfRange(pre, 1, j+1), Arrays.copyOfRange(in, 0, j)); node.right = reConstructBinaryTreeIterative(Arrays.copyOfRange(pre, j+1, pre.length), Arrays.copyOfRange(in, j+1, in.length)); return node; } } <file_sep>/src/utils/ListNode.java package utils; public class ListNode { public int val; public ListNode next; public ListNode(int x) {val = x;} public static ListNode buildListNode(int[] num) { ListNode dummy = new ListNode(-1); ListNode head = dummy; for (int i: num) { dummy.next = new ListNode(i); dummy = dummy.next; } return head.next; } public static void printListNode(ListNode head) { if(head == null) { System.out.println("This ListNode is NULL!"); return; } while (head != null) { System.out.print(head.val + " "); head = head.next; } System.out.println(); } public static ListNode reverseIterative(ListNode head) { ListNode pre = null; ListNode cur = head; while (cur != null) { ListNode tmp = cur; cur = cur.next; tmp.next = pre; pre = tmp; } return pre; } public static ListNode reverseRecursive(ListNode head) { return reverseListRecursive(head, null); } private static ListNode reverseListRecursive(ListNode cur, ListNode pre) { if(cur == null) return pre; ListNode tmp = cur; cur = cur.next; tmp.next = pre; pre = tmp; return reverseListRecursive(cur, pre); } public static void main(String[] args) { int[] num = new int[]{3,4,5,0,1,2}; ListNode head = ListNode.buildListNode(num); ListNode.printListNode(head); head = ListNode.reverseIterative(head); ListNode.printListNode(head); head = ListNode.reverseRecursive(head); ListNode.printListNode(head); } } <file_sep>/src/TAG/Tree/_437_PathSumIII.java package TAG.Tree; import utils.TreeNode; public class _437_PathSumIII { /** * 双重递归 * pathSum递归选择root point(起始结点) * pathSumHelper 拿着root point递归遍历这条树,直到leaf * @param root * @param sum * @return */ public int pathSum(TreeNode root, int sum) { if(root == null) return 0; return pathSumHelper(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum); } public int pathSumHelper(TreeNode root, int sum) { if(root == null) return 0; int count = 0; if(root.val == sum) count++; count += pathSumHelper(root.left, sum - root.val); count += pathSumHelper(root.right, sum - root.val); return count; } } <file_sep>/src/TAG/Math/Bit_Manipulation/_136__Single_Number.java package TAG.Math.Bit_Manipulation; public class _136__Single_Number { public int singleNumber(int[] nums) { int x = 0; for(int i: nums) { x ^= i; } return x; } public static void main(String[] args) { _136__Single_Number single_number = new _136__Single_Number(); System.out.println(single_number.singleNumber(new int[]{1,1,2})); } } <file_sep>/src/Ordered/_73__Set_Matrix_Zeroes.java package Ordered; /** * Given a m x n matrix, if an element is 0, set its entire row and column to 0. * 精进案例 * 1. A straight forward solution using O(mn) space is probably a bad idea. * 新建一个与matrix同样大小的数组newArray,以matrix为参照操作newArray * 2. A simple improvement uses O(m + n) space, but still not the best solution. * 问题本身是设置某行和列为0,so, 新建一个一行大小和一个一列大小的数组,分别表示该列和行是否要置零 * 3. Could you devise a constant space solution? * 直接使用matrix的首行和首列来标识该列和行是否置零,至于首行和首列是否置零单独用变量标识 */ public class _73__Set_Matrix_Zeroes { public void setZeroes(int[][] matrix) { if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return; boolean fr = false, fc = false; int m = matrix.length; int n = matrix[0].length; // 如果matrix[i,j]==0,就让列首、行首为0(标记),如果行首、列首存在为0的情形,则让fr,fc为true for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(matrix[i][j] == 0) { if(i == 0) fr = true; if(j == 0) fc = true; matrix[0][j] = 0; matrix[i][0] = 0; } } } for(int i = 1; i < m; i ++) { for(int j = 1; j < n; j ++) { if(matrix[i][0] == 0 || matrix[0][j] == 0) { matrix[i][j] = 0; } } } if(fr) for(int j = 0; j < n; j ++) { matrix[0][j] = 0; } if(fc) for(int i = 0; i < m; i ++) { matrix[i][0] = 0; } } } <file_sep>/src/TAG/Math/One_Num_Binary.java package TAG.Math; /** * 一个数的二进制中1的个数 */ public class One_Num_Binary { /** * 移位 + 计数 * 与n的二进制位数有关,最多循环32次 * @param n * @return */ public int BitCount_Normal(int n) { int c = 0; // 计数器 while (n > 0) { if ((n & 1) == 1) // 当前位是1 ++c; // 计数器加1 n >>= 1; // 移位 } return c; } public int BitCount_Normal_Ahead(int n) { int c = 0; for (; n > 0; n >>= 1) { c += n & 1; } return c; } /** * 通过 n &= (n-1) 清除n的二进制数中的最低位的1,正负数都适用 * @param n * @return */ public int BitCount_Quick_Negative(int n) { int c = 0; // n中1的个数 for (; n != 0; c ++) { // 清除 n 的最低位的 1 n &= (n - 1); } return c; } public int BitCount_Dynamic_Table(int n) { char[] bitsSetTable256 = new char[256]; for (int i = 0; i < bitsSetTable256.length; i++) { bitsSetTable256[i] = 0; } for (int i = 0; i < bitsSetTable256.length; i++) { // ((i & 1) == 0 ? '0' : '1') // function BitCount(i) 指的是 i 的二进制中 1 的个数 // 如果i是偶数,i二进制最后1位是0,BitCount(i)==BitCount(i>>1); // 如果i是奇数,i二进制最后1位是1,BitCount(i)==BitCount(i>>1) + 1; // 综上得出以下计算公式 bitsSetTable256[i] = (char)(bitsSetTable256[i / 2] + (i & 1)); } int c = 0; // 把n按8位分成4份,分别求其中1的个数 c = bitsSetTable256[(n & 0xFF000000) >> 24] + bitsSetTable256[(n & 0x00FF0000) >> 16] + bitsSetTable256[(n & 0x0000FF00) >> 8] + bitsSetTable256[(n & 0x000000FF)]; return c; } public int BitCount_Static_Table(int n) { int[] table = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; int c = 0; while(n > 0) { c += table[n & 0xF]; n >>= 4; } return c; } public int BitCount_Static_Table_2(int n) { // 数字0, 1, 2, 3对应的二进制数的个数 int[] table = { 0, 1, 1, 2 }; int c = 0; while(n > 0) { c += table[n & 0x3]; n >>= 2; } return c; } public int BitCount_negative(int n) { if(n == 0 ) return 0; int i = 1; int count = 0; while (i != 0) { if((n & i) == i) { count ++; } i >>= 1; } return count; } public static void main(String[] args) { int i = 100; Long c = Long.valueOf(-2147483648); System.out.println(false ^ true); One_Num_Binary one_numDecimal = new One_Num_Binary(); int num = -217; System.out.println(Integer.toBinaryString(num)); System.out.println(one_numDecimal.BitCount_Quick_Negative(num)); if(num < 0) return; System.out.println(one_numDecimal.BitCount_Normal(num)); System.out.println(one_numDecimal.BitCount_Normal_Ahead(num)); System.out.println(one_numDecimal.BitCount_Dynamic_Table(num)); System.out.println(one_numDecimal.BitCount_Static_Table(num)); System.out.println(one_numDecimal.BitCount_Static_Table_2(num)); } }
03fc9d3bef953774f4c0f3e0e562b73904d27d45
[ "Markdown", "Java" ]
44
Java
lizongkai-big/LeetCode
80eaee31f1c40d9e6042118d0b5bad0e9e7fe359
bbe693f2b6dc0e8f6e0b717c13e0f8ac092d3373
refs/heads/master
<repo_name>tfogal/simvis<file_sep>/raw.cpp #include <algorithm> #include <cassert> #include <cerrno> #include <cstdlib> #include <fstream> #include <iostream> #include <numeric> #include <stdexcept> #include <tr1/array> #include <vector> #include <sys/inotify.h> #include <unistd.h> #include "uvf.h" // grabbed these from agent.inp... const std::tr1::array<float, 27> zdist = {{ 3, 3, 3, 3, 3, 4, 4, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 6, 2, 2, 2, 2, 2 }}; std::tr1::array<float, 27> zmemo; const size_t NUM_COLUMNS = 11; // miserably inefficient way to do this. void read_column(std::istream& is, size_t col, std::vector<float>& into) { float tmp, garbage; into.clear(); do { for(size_t i=0; i < col; ++i) { is >> garbage; } is >> tmp; for(size_t i=col; i < NUM_COLUMNS; ++i) { is >> garbage; } if(is) { into.push_back(tmp); } } while(is); } // each column in the input file is a different variable. this maps the column // index to the name of the variable. std::string variable_name(size_t column) { switch(column) { case 0: return "x-coord"; case 1: return "y-coord"; case 2: return "flux 1"; case 3: return "flux 2"; case 4: return "flux 3"; case 5: return "flux 4"; case 6: return "flux 5"; case 7: return "flux 6"; case 8: return "flux 7"; case 9: return "absorption"; case 10: return "fission"; default: return "unknown"; } } void gen_raw(std::vector<std::string> files, size_t column, const size_t dims[3], std::ostream& bin) { std::vector<float> d; std::cout << "Generating RAW data for variable '" << variable_name(column) << "' ...\n"; d.reserve(files.size() * 360000); for(std::vector<std::string>::const_iterator f = files.begin(); f != files.end(); ++f) { std::cout << " .. from file " << *f << "... "; std::vector<float> tmp; std::ifstream ifs(f->c_str(), std::ios::in); read_column(ifs, column, tmp); d.insert(d.end(), tmp.begin(), tmp.end()); std::cout << d.size() << " elems thus far.\n"; } assert(d.size() == std::accumulate(dims, dims+3, static_cast<size_t>(1), std::multiplies<size_t>())); bin.write(reinterpret_cast<char*>(&d[0]), d.size()*sizeof(float)); } class IterationUnchanged : public std::runtime_error { public: IterationUnchanged(std::string s) : std::runtime_error(s) {} }; void read_parameters(const char* metadata, size_t& iteration, size_t dims[3], std::vector<std::string>& files) { files.clear(); std::ifstream is(metadata, std::ios::in); if(!is) { throw std::runtime_error("Could not open metadata file!"); } { size_t iter; is >> iter; if(is.fail()) { throw std::runtime_error("Could not read iteration number."); } if(iter == iteration) { throw IterationUnchanged("Iteration has not changed."); } iteration = iter; } { is >> dims[0] >> dims[1] >> dims[2]; if(is.fail()) { throw std::runtime_error("Could not read dimensions."); } } do { std::string file; is >> file; if(is) { files.push_back(file); } } while(is); is.close(); } static void wait_for_event(int fd) { struct inotify_event event; std::cout << "Waiting until metadata file changes...\n"; read(fd, &event, sizeof(struct inotify_event)); } static void convert_to_binary(const std::vector<std::string>& files, const size_t dims[3], const char* rawfn) { std::ofstream bin(rawfn, std::ios::binary | std::ios::trunc); gen_raw(files, 2, dims, bin); // 3rd column (index 2) == flux_1 bin.close(); } int main(int argc, char *argv[]) { if(argc == 1) { std::cerr << "Need metadata file.\n"; exit(EXIT_FAILURE); } int inotify = inotify_init1(IN_CLOEXEC); int watch = inotify_add_watch(inotify, argv[1], IN_CLOSE_WRITE); size_t iteration; size_t dims[3]; std::vector<std::string> files; const char* tmpraw = ".out.raw"; do { wait_for_event(inotify); try { read_parameters(argv[1], iteration, dims, files); convert_to_binary(files, dims, tmpraw); uvf_convert(tmpraw, "in-place.uvf", dims); unlink(tmpraw); } catch(const IterationUnchanged&) { std::cout << "Iteration variable did not change. Skipping this event.\n"; } catch(const std::runtime_error& err) { std::cerr << "error: " << err.what() << "\nSkipping this event.\n"; } } while(1); if(inotify_rm_watch(inotify, watch) != 0) { std::cerr << "Error deleting watch: " << errno << "\n"; } close(watch); close(inotify); return 0; } <file_sep>/uvf.h #ifndef SIM_UVF_H #define SIM_UVF_H // assumes floating point fata void uvf_convert(const char*input, const char* uvf, const size_t dimensions[3]); #endif /* SIM_UVF_H */ <file_sep>/makefile UVF_ROOT=./imagevis3d/Tuvok UVF_CF=-I$(UVF_ROOT) UVF_LDFLAGS=$(UVF_ROOT)/Build/libTuvok.a \ $(UVF_ROOT)/IO/expressions/libtuvokexpr.a UVF_LD_REQS=-lz -lGLU -lGL -lQtOpenGL -lQtCore CXXFLAGS=-g -Wextra -Wall -O3 $(UVF_CF) OBJ=raw.o uvf.o all: $(OBJ) ascii-to-uvf ascii-to-uvf: uvf.o raw.o $(CXX) $(CXXFLAGS) $^ -o $@ $(UVF_LDFLAGS) $(UVF_LD_REQS) clean: rm -f ascii-to-uvf $(OBJ) <file_sep>/uvf.cpp #include "Controller/Controller.h" #include "IO/RAWConverter.h" // RAII for adding/removing a debug channel from the controller. class AddADebugOut { public: AddADebugOut(tuvok::MasterController& ctl) : ctlr(ctl), debugOut(NULL) { this->debugOut = new ConsoleOut(); this->debugOut->SetOutput(true, true, true, false); this->ctlr.AddDebugOut(this->debugOut); } ~AddADebugOut() { this->ctlr.RemoveDebugOut(this->debugOut); // controller will clean up the debugOut automagically; we don't need to // delete it. } private: tuvok::MasterController& ctlr; ConsoleOut* debugOut; }; // assumes floating point fata void uvf_convert(const char* input, const char* uvf, const size_t dimensions[3]) { const std::string temp_dir = "."; const uint64_t skip_bytes = 0; const uint64_t component_size = 32; const uint64_t component_count = 1; const uint64_t timesteps = 1; const bool convert_endianness = false; const bool is_signed = true; const bool is_float = true; UINT64VECTOR3 dims = UINT64VECTOR3(dimensions[0], dimensions[1], dimensions[2]); const FLOATVECTOR3 aspect = FLOATVECTOR3(1.0, 1.0, 1.0); const uint64_t brick_size = 256; const uint64_t overlap = 4; AddADebugOut dbgout(tuvok::Controller::Instance()); if(RAWConverter::ConvertRAWDataset(std::string(input), std::string(uvf), temp_dir, skip_bytes, component_size, component_count, timesteps, convert_endianness, is_signed, is_float, dims, aspect, std::string("In-progress simulation"), std::string("AGENT"), brick_size, overlap)) { MESSAGE("Success!"); } else { T_ERROR("Conversion failed!"); } } <file_sep>/bld-iv3d.sh #!/bin/sh if ! test -d imagevis3d ; then iv3d="https://gforge.sci.utah.edu/svn/imagevis3d" env -i svn --non-interactive --trust-server-cert co ${iv3d} fi (cd imagevis3d && svn update) VIS="-fvisibility=hidden" INL="-fvisibility-inlines-hidden" CF="-g -Wall -Wextra -O3 -U_DEBUG -DNDEBUG" CXF="-Werror" if test -n "${QT_BIN}" ; then echo "Using custom qmake..." qm="${QT_BIN}/qmake" else qm="qmake" fi for d in imagevis3d ; do pushd ${d} &>/dev/null ${qm} \ CONFIG+="release" \ QMAKE_CONFIG="release" \ QMAKE_CFLAGS="${VIS} ${CF}" \ QMAKE_CXXFLAGS="${VIS} ${INL} ${CF} ${CXF}" \ -recursive nice make -j8 popd &>/dev/null done
5f0f740383472986cea9d1a692ba00e07ad47359
[ "C", "Makefile", "C++", "Shell" ]
5
C++
tfogal/simvis
d50b538910e6c1bd9eb0ff037f5dfe551a6033e0
806ca79ba065274a506127ed7789ca104f0c3e12
refs/heads/master
<file_sep>package com.neo4j.todo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; @SpringBootApplication(exclude={DataSourceAutoConfiguration.class}) @EnableNeo4jRepositories public class TodoWithNeoApplication { public static void main(String[] args) { SpringApplication.run(TodoWithNeoApplication.class, args); } } <file_sep>package com.neo4j.todo.controller; import com.neo4j.todo.entity.TodoDAO; import org.springframework.web.bind.annotation.*; @RequestMapping("/todo") public interface ITodoController { @PostMapping void createTodo(TodoDAO todo); @GetMapping("/{id}") TodoDAO getTodo(@PathVariable Long id); @DeleteMapping("/{id}") void deleteTodo(@PathVariable Long id); @PutMapping("/{id}") void updateTodo(@PathVariable Long id, TodoDAO updateTodo); } <file_sep>package com.neo4j.todo.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import org.springframework.data.neo4j.core.schema.GeneratedValue; import org.springframework.data.neo4j.core.schema.Id; import org.springframework.data.neo4j.core.schema.Node; @Node("Todo") @Data @NoArgsConstructor @AllArgsConstructor public class TodoDAO { @Id @GeneratedValue private Long id; private String name; private String description; private Boolean done; } <file_sep>package com.neo4j.todo.Service; import com.neo4j.todo.entity.TodoDAO; public interface ITodoService { void creatTodo(TodoDAO todo); void deleteTodo(Long id); void updateTodo(Long id, TodoDAO updatedTodo); TodoDAO getTodo(Long id); } <file_sep># Java with Neo4j ## Default prerequisites * Neo4j server run on default port: `bolt://localhost:7687` * Username set to: `neo4j` * Password set to: `<PASSWORD>` ## Example requests To run using postman use this file: `src/test/resources/TodoCollection.json`
947cc202ac95b0d4293323c5d44f03e2fc466dd8
[ "Markdown", "Java" ]
5
Java
StrikerSK/java-neo4j
97870ecc2fef1997c3ea078b2da23797bf335c84
461d3d2f1bf01d2ad6fdc7b72a43e03b83020a07
refs/heads/master
<repo_name>tyrelh/kattis-skeletons<file_sep>/README.md # Kattis Skeleton Projects for Various Languages Well, like the title says. <file_sep>/sol.js "use strict"; process.stdin.resume(); process.stdin.resume(); let inputString = ""; let currentLine = 0; process.stdin.on("data", inputStdin => { inputString += inputStdin; }); process.stdin.on("end", _ => { inputString = inputString.trim().split("\n").map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } function main() { const values = readLine().split(" "); const w = parseInt(values[0]); } //digit = parseInt(digit) //const nums = line.split("") //for (let digit of nums) {}<file_sep>/sol.py import sys input = sys.stdin.readline().rstrip().split(' ') w = int(input[0])
d682846b6658b1f2c09f2ab544eebd8f6c452f0c
[ "Markdown", "Python", "JavaScript" ]
3
Markdown
tyrelh/kattis-skeletons
8e8efe36cdaeb1061a7922757b275a097ba64c00
9774e56e7198e7d0ee137ed3d3799b273d02ca38
refs/heads/master
<file_sep># android-sensor-feed Cloud Computing Assignment - Web Sockets "<NAME>" University of Iași, Romania Faculty of Computer Science <NAME> <EMAIL> ## Description This is a minimal client-server application used to receive sensor readings from android devices via web sockets. ## Observations * Just like my [Python3 REST Api](https://github.com/Bogdan-Stefan/python3-rest-api), this project has been created for educational purposes. It's not perfect and I'm learning from my mistakes. * The server is written in python3 using [CherryPy](http://cherrypy.org/) and [ws4py](https://github.com/Lawouach/WebSocket-for-Python). * The client is a native android app. The only external library used is [Java-WebSocket](https://github.com/TooTallNate/Java-WebSocket). * Server supports multiple connected clients. ## Useful Links [websocket.org](http://websocket.org/) [What are web sockets?](https://pusher.com/websockets) [WebSocket - Why, what, and - can I use it?](http://crossbario.com/blog/Websocket-Why-What-Can-I-Use-It/) <file_sep>package com.example.bogdan_stefan.sensorfeed; interface WebSocketEventHandler { void connectionOpened(); void connectionClosed(); void exceptionRaised(String errorMessage, Exception e); } <file_sep>package com.example.bogdan_stefan.sensorfeed; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import java.net.URI; class SensorFeedClient extends WebSocketClient { private WebSocketEventHandler webSocketEventHandler; SensorFeedClient(URI serverUri, WebSocketEventHandler webSocketEventHandler) { super(serverUri); this.webSocketEventHandler = webSocketEventHandler; } @Override public void onOpen(ServerHandshake serverHandshake) { webSocketEventHandler.connectionOpened(); } @Override public void onMessage(String s) { System.out.println("Received: " + s); } @Override public void onClose(int i, String s, boolean b) { webSocketEventHandler.connectionClosed(); } @Override public void onError(Exception e) { e.printStackTrace(); webSocketEventHandler.exceptionRaised("Web Socket Error!", e); } } <file_sep>import cherrypy from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool from ws4py.websocket import WebSocket cherrypy.server.socket_host = 'server-ip' cherrypy.config.update({'server.socket_port': 9000}) WebSocketPlugin(cherrypy.engine).subscribe() cherrypy.tools.websocket = WebSocketTool() class FeedPrinter(WebSocket): def received_message(self, message): """Prints the values received from client.""" values = str(message).split(',') print(values[0]) print("X Axis -> ", values[1]) print("Y Axis -> ", values[2]) print("Z Axis -> ", values[3]) print("\n") class Root(object): @cherrypy.expose def index(self): return 'some HTML with a websocket javascript connection' @cherrypy.expose def ws(self): # you can access the class instance through handler = cherrypy.request.ws_handler cherrypy.quickstart(Root(), '/', config={'/ws': {'tools.websocket.on': True, 'tools.websocket.handler_cls': FeedPrinter}})
b6655ac7f20e37aa8aed061461ce4feb03a8377a
[ "Markdown", "Java", "Python" ]
4
Markdown
Bogdan-Stefan/android-sensor-feed
474358ff256603245609f135c6deaa31b8b0e8f7
6727045af2d3eb01b2d95eac0d4cc99dd3e0a459
refs/heads/master
<file_sep># in dress agent create one that is your player name # without spaces and a 1 at the end. # Example: "Player Name" needs to be playername1 msgcolor = 62 wep1 = Player.Name.lower().replace(' ', '') + '1' Player.HeadMessage(msgcolor, "Weapon 1") Dress.ChangeList(wep1) Dress.DressFStart() <file_sep># ButlerHelper by Spatchel & Matsamilla # use with ButlerProfiles.py for best results, update butlerID with butler serial below # Last updated 6/2/22 ########################################################### # Add your butlers serial below # ########################################################### butlerID = 0x0029C3D1 #add your butler serial here ########################################################### # Option to equip armor, bag regs & bag pots below # ########################################################### from System.Collections.Generic import List import sys # 4 = equip armor, 5 = bag regs, 6 = bag pots (switch = List[int]([0,4,5,6]) would do all switch = List[int]([0,4]) ########################################################### # If you dont run ButlerProfiles.py, this will load # ########################################################### regs = 30 # default reg count if not profile armor = 0 # default armor, 0=no 1=yes cap = 0 # cap in default profile, 0=no 1=yes bandies = 0 # default bandage count arrows = 0 bolts = 0 cure = 10 heal = 10 refresh = 10 ######## NO TOUCHY BELOW THIS ############################# butler = Mobiles.FindBySerial(butlerID) randomPause = 150 player_bag = Items.FindBySerial(Player.Backpack.Serial) if butler == None: Player.HeadMessage(33, 'Butler not found, stoppling') sys.exit() while Player.DistanceTo(butler) > 2.5: if Timer.Check('butler') == False: Mobiles.Message(butler,33, 'Come closer to restock.') Timer.Create('butler',2500) #moss count if Misc.CheckSharedValue('moss'): moss6 = Misc.ReadSharedValue('moss') else: moss6 = regs #ash count if Misc.CheckSharedValue('ash'): ash7 = Misc.ReadSharedValue('ash') else: ash7 = regs # root count if Misc.CheckSharedValue('root'): root8 = Misc.ReadSharedValue('root') else: root8 = regs # pearl count if Misc.CheckSharedValue('pearl'): pearl9 = Misc.ReadSharedValue('pearl') else: pearl9 = regs #nightshade count if Misc.CheckSharedValue('shade'): shade10 = Misc.ReadSharedValue('shade') else: shade10 = regs # Ginseng count if Misc.CheckSharedValue('ginseng'): ginseng11 = Misc.ReadSharedValue('ginseng') else: ginseng11 = regs # Garlic Count if Misc.CheckSharedValue('garlic'): garlic12 = Misc.ReadSharedValue('garlic') else: garlic12 = regs # Silk Count if Misc.CheckSharedValue('silk'): silk13 = Misc.ReadSharedValue('silk') else: silk13 = regs # Armor if Misc.CheckSharedValue('armor'): armorS = Misc.ReadSharedValue('armor') if cap: cap0 = armorS elif Player.CheckLayer('Helm'): cap0 = 0 else: cap0 = 0 gorget1 = armorS sleeves2 = armorS gloves3 = armorS if Player.CheckLayer("InnerTorso"): tunic4 = 0 else: tunic4 = armorS if Player.CheckLayer("Pants"): legs5 = 0 else: legs5 = armorS else: if cap: cap0 = armor elif Player.CheckLayer('Helm'): cap0 = 0 else: cap0 = 0 gorget1 = armor sleeves2 = armor gloves3 = armor if Player.CheckLayer("InnerTorso"): tunic4 = 0 else: tunic4 = armorS if Player.CheckLayer("Pants"): legs5 = 0 else: legs5 = armorS # Agility Pots Count if Misc.CheckSharedValue('agil'): agiImput = Misc.ReadSharedValue('agil') else: agiImput = 5 # Cure Pots Count if Misc.CheckSharedValue('cure'): cureImput = Misc.ReadSharedValue('cure') else: cureImput = 5 # Explode Pots Count if Misc.CheckSharedValue('exp'): expImput = Misc.ReadSharedValue('exp') else: expImput = 0 # Heal Pots Count if Misc.CheckSharedValue('heal'): healImput = Misc.ReadSharedValue('heal') else: healImput = 5 # Deadlypoison Pots Count if Misc.CheckSharedValue('deadlypoison'): dpImput = Misc.ReadSharedValue('deadlypoison') else: dpImput = 0 # Refresh Pots Count if Misc.CheckSharedValue('refresh'): refreshImput = Misc.ReadSharedValue('refresh') else: refreshImput = 5 # Strength Pots Count if Misc.CheckSharedValue('str'): strImput = Misc.ReadSharedValue('str') else: strImput = 5 # Bandages Count if Misc.CheckSharedValue('bandies'): bandages21 = Misc.ReadSharedValue('bandies') else: bandages21 = bandies # Arrows if Misc.CheckSharedValue('arrows'): arrows25 = Misc.ReadSharedValue('arrows') else: arrows25 = arrows # Bolts if Misc.CheckSharedValue('bolts'): bolts26 = Misc.ReadSharedValue('bolts') else: bolts26 = bolts def dumpBottles(): for i in player_bag.Contains: if i.ItemID == 0x0F0E: Items.Move(i, butlerID, 0) Misc.Pause(600) def butler(): global saveSwitch Mobiles.UseMobile(butlerID) Gumps.WaitForGump(989312372, 2000) if Gumps.LastGumpTextExist( 'Remove Leather Tub?' ): Misc.SendMessage('Leather Tub Detected') saveSwitch = 5 withdrawSwitch = 8 else: saveSwitch = 3 withdrawSwitch = 6 #################### Armor ####################################### textid = List[int]([0]) text = List[str]([str(cap0)]) saveProfile(textid, text) textid = List[int]([1]) text = List[str]([str(gorget1)]) saveProfile(textid, text) textid = List[int]([2]) text = List[str]([str(sleeves2)]) saveProfile(textid, text) textid = List[int]([3]) text = List[str]([str(gloves3)]) saveProfile(textid, text) textid = List[int]([4]) text = List[str]([str(tunic4)]) saveProfile(textid, text) textid = List[int]([5]) text = List[str]([str(legs5)]) saveProfile(textid, text) #################### REGS ####################################### # Moss textid = List[int]([6]) text = List[str]([str(moss6)]) saveProfile(textid, text) #Ash textid = List[int]([7]) text = List[str]([str(ash7)]) saveProfile(textid, text) #Root textid = List[int]([8]) text = List[str]([str(root8)]) saveProfile(textid, text) #Pearl textid = List[int]([9]) text = List[str]([str(pearl9)]) saveProfile(textid, text) #Nightshade textid = List[int]([10]) text = List[str]([str(shade10)]) saveProfile(textid, text) #Ginseng textid = List[int]([11]) text = List[str]([str(ginseng11)]) saveProfile(textid, text) #garlic textid = List[int]([12]) text = List[str]([str(garlic12)]) saveProfile(textid, text) #SpidersSilk textid = List[int]([13]) text = List[str]([str(silk13)]) saveProfile(textid, text) #################### Potions ################################### # Cure textid = List[int]([14]) text = List[str]([str(cureImput)]) saveProfile(textid, text) # Agility textid = List[int]([15]) text = List[str]([str(agiImput)]) saveProfile(textid, text) #Strength textid = List[int]([16]) text = List[str]([str(strImput)]) saveProfile(textid, text) #Deadlypoison textid = List[int]([17]) text = List[str]([str(dpImput)]) saveProfile(textid, text) #Heal textid = List[int]([19]) text = List[str]([str(healImput)]) saveProfile(textid, text) #Refresh textid = List[int]([18]) text = List[str]([str(refreshImput)]) saveProfile(textid, text) #Explode textid = List[int]([20]) text = List[str]([str(expImput)]) saveProfile(textid, text) #################### Bandages ################################### textid = List[int]([21]) text = List[str]([str(bandages21)]) saveProfile(textid, text) #################### Petals ##################################### textid = List[int]([23]) text = List[str]([str(0)]) saveProfile(textid, text) textid = List[int]([25]) text = List[str]([str(arrows25)]) saveProfile(textid, text) #################### Arrows/Bolts ############################### textid = List[int]([26]) text = List[str]([str(bolts26)]) saveProfile(textid, text) Gumps.WaitForGump(989312372, 2000) #Gumps.SendAction(989312372, withdrawSwitch) Gumps.SendAdvancedAction(989312372, withdrawSwitch, switch) def saveProfile(textid, text): if Gumps.CurrentGump() != 989312372: tempGump = Gumps.CurrentGump() Gumps.CloseGump(tempGump) Mobiles.UseMobile(butlerID) Gumps.WaitForGump(989312372, 2000) Gumps.SendAdvancedAction(989312372, saveSwitch, switch, textid, text) Misc.Pause(randomPause) dumpBottles() butler() <file_sep># Bandage script by Matsamilla # Relys on Bandage_Timer.py, without it it will not stop applying bandages. # Pause at start for skill check, # Script stops if no healing on toon. import sys Misc.Pause( 5000 ) if Player.GetRealSkillValue( 'Healing' ) < 50: Misc.SendMessage( 'No Healing, stopping script',33) Misc.Pause( 200 ) sys.exit() def BandageSelf(): if Misc.ReadSharedValue('bandageDone') == True: lastTarget = Target.GetLast() while Target.HasTarget(): Misc.Pause(10) Items.UseItemByID(0x0E21, 0) Target.WaitForTarget(1500, False) Target.Self() Misc.Pause (500) Target.SetLast(lastTarget) Timer.Create( 'outOfBandageWarningIncrement', 1 ) while True: # make sure Bandage_Timer.py is running, script will not run # correctly if timer is not running. if not Misc.ScriptStatus('Bandage_Timer.py'): Misc.ScriptRun('Bandage_Timer.py') if Player.IsGhost: # Player died, wait until Player is resurrected while Player.IsGhost: Misc.Pause( 100 ) # Checks for bandages if Items.BackpackCount( 0x0E21 ,-1 ): # only apply bandage if player is not hidden, damaged or poisoned and not one already applying. if Player.Visible == True and Player.Hits < Player.HitsMax or Player.Poisoned and Misc.CheckSharedValue('bandageDone') == True: BandageSelf() # if no bandages, warn player. elif Timer.Check( 'outOfBandageWarningIncrement' ) == False: Player.HeadMessage( 1100, 'Out of bandages!' ) Timer.Create( 'outOfBandageWarningIncrement', 5000 ) Misc.Pause( 50 ) <file_sep># Drag-Drop organizer by Mourn # contributions by MatsaMilla # adjust to your servers drag delay in ms dragDelay = 600 import sys startX = 0 startY = 0 verticalIncrement = 0 horizontalIncrement = 5 endX = 0 endY = 0 item = Items.FindBySerial( Target.PromptTarget( 'Choose type' )) container = Items.FindBySerial( item.Container ) itemID = item.ItemID itemHue = item.Hue destPrompt = Target.PromptTarget( 'Chose Destination' ) itemsToMove = [] # gems gems = [0x0F19, 0x0F25, 0x0F13, 0x0F16, 0x0F21, 0x0F26, 0x0F15, 0x0F2D, 0x0F10] #glowing runes glowingRunes = [0x483b, 0x483e, 0x4841, 0x4844, 0x4847, 0x484a, 0x484d, 0x4850, 0x4853, 0x4856, 0x4859, 0x485c, 0x485f, 0x4862, 0x4865, 0x4868, 0x486b, 0x486e, 0x4871, 0x4874, 0x4877, 0x487a, 0x487d, 0x4880, 0x4883] #Regs regs = [0x0F86, 0x0F88, 0x0F8D, 0x0F85,0x0F7B, 0x0F84, 0x0F8C, 0x0F7A] #Misc.SendMessage(str(dest)) def getSize(container): global startX global startY global endX global endY global verticalIncrement global horizontalIncrement if "backpack" in container.Name: Misc.SendMessage("Setting size to Backpack or a Pouch") startX = 45 startY = 75 endX = 160 endY = 150 verticalIncrement = 20 elif "pouch" in container.Name: Misc.SendMessage("Setting size to Pouch") startX = 45 startY = 75 endX = 160 endY = 150 verticalIncrement = 20 elif "bag" in container.Name: Misc.SendMessage("Setting size to Bag") startX = 30 startY = 40 endX = 115 endY = 120 verticalIncrement = 20 elif "ornate" in container.Name: Misc.SendMessage("Setting size to Box") startX = 15 startY = 50 endX = 155 endY = 120 verticalIncrement = 20 elif "wooden box" in container.Name: Misc.SendMessage("Setting size to Box") startX = 15 startY = 50 endX = 155 endY = 120 verticalIncrement = 20 elif "metal chest" in container.Name: Misc.SendMessage("Setting size to Metal Chest") startX = 20 startY = 105 endX = 135 endY = 150 verticalIncrement = 10 else: Misc.SendMessage("Setting size to Unknown") startX = 50 startY = 50 endX = 115 endY = 120 verticalIncrement = 20 if destPrompt == Player.Serial: dest = Player.Backpack.Serial Misc.SendMessage("Setting size to Backpack") startX = 45 startY = 75 endX = 160 endY = 150 verticalIncrement = 20 else: dest = Items.FindBySerial( destPrompt ) getSize(dest) if item.ItemID in gems: for items in container.Contains: if items.ItemID in gems: Items.Move(items,dest,0) Misc.Pause(600) sys.exit() elif item.ItemID in glowingRunes: for items in container.Contains: if items.ItemID in glowingRunes: Items.Move(items,dest,0) Misc.Pause(600) sys.exit() elif item.ItemID in regs: for items in container.Contains: if items.ItemID in regs: Items.Move(items,dest,0) Misc.Pause(600) sys.exit() else: for items in container.Contains: if items.ItemID == itemID and items.Hue == itemHue : itemsToMove.append( items.Serial ) x = startX y = startY total = len( itemsToMove ) timeToMove = ( total * dragDelay ) / 1000 Player.HeadMessage( 66, "Moving " + str( total ) + ' Items' ) Misc.Pause( 200 ) Player.HeadMessage( 66, str( timeToMove ) + ' Seconds' ) Journal.Clear() for items in itemsToMove: if x > endX: x = startX y = y + verticalIncrement if y >= endY: y = startY + verticalIncrement Items.Move( items , dest , 0 , x , y ) Misc.Pause( dragDelay ) x = x + horizontalIncrement if Journal.Search('That container cannot hold more items.'): Player.HeadMessage( 66, "Container full, stopping" ) Journal.Clear() sys.exit() Player.HeadMessage( 76 ,'Items have been moved' ) <file_sep># Trains Magery to GM # Change resistTrain to True if you are training resist and/or # don't want to take damage # False will make it cast dmg spells on yourself, which use less regs. # but require someone healing you, or you to have healing. # By MatsaMilla resistTrain = True # ------------------------------------ self = Player.Serial pearl = 0x0F7A root = 0x0F86 shade = 0x0F88 silk = 0x0F8D moss = 0x0F7B ginseng = 0x0F85 garlic = 0x0F84 ash = 0x0F8C import sys def trainMageryNoResist(): while Player.Hits < 45: Misc.Pause(100) if Player.GetRealSkillValue('Magery') < 35: Misc.SendMessage('Go buy Magery skill!!') sys.exit() elif Player.GetRealSkillValue('Magery') < 65: Spells.CastMagery('Mind Blast') Target.WaitForTarget(2500) Target.TargetExecute(self) Misc.Pause(2500) elif Player.GetRealSkillValue('Magery') < 85: Spells.CastMagery('Energy Bolt') Target.WaitForTarget(2500) Target.TargetExecute(self) Misc.Pause(2500) elif Player.GetRealSkillValue('Magery') < 100: Spells.CastMagery("Flamestrike") Target.WaitForTarget(2500) Target.TargetExecute(self) Misc.Pause(2500) if Player.Mana < 40: Player.UseSkill('Meditation') while Player.Mana < Player.ManaMax: if (not Player.BuffsExist('Meditation') and not Timer.Check('skillTimer')): Player.UseSkill('Meditation') Timer.Create('skilltimer', 11000) Misc.Pause(100) def trainMage(): if Player.GetRealSkillValue('Magery') < 35: Misc.SendMessage('Go buy Magery skill!!') sys.exit() elif Player.GetRealSkillValue('Magery') < 55: Spells.CastMagery('Mana Drain') Target.WaitForTarget(2500) Target.TargetExecute(self) Misc.Pause(2500) elif Player.GetRealSkillValue('Magery') < 75: Spells.CastMagery('Invisibility') Target.WaitForTarget(2500) Target.TargetExecute(self) Misc.Pause(2500) elif Player.GetRealSkillValue('Magery') < 100: Spells.CastMagery('Mana Vampire') Target.WaitForTarget(2500) Target.TargetExecute(self) Misc.Pause(2500) if Player.Mana < 40: Player.UseSkill('Meditation') while Player.Mana < Player.ManaMax: if (not Player.BuffsExist('Meditation') and not Timer.Check('skillTimer')): Player.UseSkill('Meditation') Timer.Create('skilltimer', 11000) Misc.Pause(100) def checkRegs(): if Items.BackpackCount(pearl, -1) < 2: Misc.SendMessage('Low on Pearl!') sys.exit() elif Items.BackpackCount(root, -1) < 2: Misc.SendMessage('Low on Root!') sys.exit() elif Items.BackpackCount(shade, -1) < 2: Misc.SendMessage('Low on Shade!') sys.exit() elif Items.BackpackCount(silk, -1) < 2: Misc.SendMessage('Low on Silk!') sys.exit() elif Items.BackpackCount(garlic, -1) < 2: Misc.SendMessage('Low on Garlic!') sys.exit() elif Items.BackpackCount(ash, -1) < 2: Misc.SendMessage('Low on Ash!') sys.exit() elif Items.BackpackCount(silk, -1) < 2: Misc.SendMessage('Low on Silk!') sys.exit() elif Items.BackpackCount(ginseng, -1) < 2: Misc.SendMessage('Low on Ginseng!') sys.exit() Journal.Clear() while Player.GetRealSkillValue('Magery') < 100: if resistTrain: trainMage() else: trainMageryNoResist() checkRegs() Player.ChatSay(33, 'GM Magery') <file_sep>def writeautofill(x): f = open('C:/Users/Jason/PycharmProjects/BodBot/smithautofill.txt', 'a') f.write(str(x)) f.close() def writegarbo(x): f = open('C:/Users/Jason/PycharmProjects/BodBot/smithgarbo.txt', 'a') f.write(str(x)) f.close() def stringtest(x): bodList = Items.GetPropStringList(x) f = open('C:/Users/Jason/PycharmProjects/BodBot/test.txt', 'a') f.write(str(bodList)) f.close() def getstringofbod(bod): result= "" bodList = Items.GetPropStringList(bod) for i in range(0, len(bodList)): result = result + bodList[i] result = result.replace("[","") result = result.replace("]","") result = result.replace(" deedBlessed<BASEFONT COLOR=#585868> Hue: 1102 <BASEFONT COLOR=#FFFFFF>Weight: 1 stone","") result = result.replace("bulk orderAll items must be","") result = result.replace(".All items must be made with","") result = result.replace(".amount to make:","") result = result.replace("a bulk order","") result = result + '\n' return result def comparetolist(input): filepath = 'C:/Users/Jason/PycharmProjects/BodBot/' + input + ".txt" f = open(filepath, 'r') allinlist = f.readlines() f.close() #Player.HeadMessage(54, str(len(allinlist))) for i in range(0, len(allinlist)): #Player.HeadMessage(54, str(allinlist[i])) #Player.HeadMessage(54, str(getstringofbod(0x44D90146))) if getstringofbod(0x44D90146) == allinlist[i]: Player.HeadMessage(54, "yes") else: Player.HeadMessage(54, "No") #writeautofill(getstringofbod(0x444785C5)) #bod = 0x47842EEF #lbod #bod = 0x479CFE6D #bod = 0x47079787 #femail plate bod = Target.PromptTarget("select bod to trash") #bod =0x41104ADC #writeautofill(getstringofbod(bod)) #adds to autofill writegarbo(getstringofbod(bod)) #adds to garbo list #stringtest(bod) #prints raw string to test.txt <file_sep># Runebook copy by Wardoctor. Upated by MatsaMilla # Last update: 12/9/21 # If copying a locked down book, DO THIS BEFORE STARTING # Mark a rune for a location close to runebook being copied # # Put this rune into a book for safe keeping (runes are not blessed, runebooks are) # Set the rune as the default location for the book # Select the correct book when the target comes up for Select item to recall off of to return to runebook being copied def PromptRunebook( promptString ): runebookSerial = Target.PromptTarget( promptString ) runebook = Items.FindBySerial( runebookSerial ) if runebook == None or runebook.ItemID != 0x22C5: Player.HeadMessage( 33, 'That is not a runebook!' ) return None else: return runebook def GetNamesOfRunesInBook( runebook ): Items.UseItem( runebook ) # Pause here since the next part goes pretty quick Misc.Pause( 650 ) Gumps.WaitForGump( 1431013363, 5000 ) while Gumps.CurrentGump() != 1431013363: Player.HeadMessage( 33, 'Too far from runebook to copy, please move closer.' ) Misc.Pause( 1000 ) Items.UseItem( runebook ) Gumps.WaitForGump( 1431013363, 5000 ) runeNames = [] lineList = Gumps.LastGumpGetLineList() # Remove the default 3 lines from the top of the list lineList = lineList[ 3 : ] # Remove the items before the names of the runes endIndexOfDropAndDefault = 0 for i in range( 0, len( lineList ) ): if lineList[ i ] == 'Set default' or lineList[ i ] == 'Drop rune': endIndexOfDropAndDefault += 1 else: break # Add two for the charge count and max charge numbers endIndexOfDropAndDefault += 2 runeNames = lineList[ endIndexOfDropAndDefault : ( endIndexOfDropAndDefault + 16 ) ] runeNames = [ name for name in runeNames if name != 'Empty' ] return runeNames def GetNumberOfRunesInBook( runebook ): return len( GetNamesOfRunesInBook( runebook ) ) def CopyRunebookName( runebookToCopy, runebookToPlaceIn, runebookMoveable ): Journal.Clear() if Gumps.CurrentGump() == 1431013363: Gumps.WaitForGump( 1431013363, 1000 ) Gumps.SendAction( 1431013363, 0 ) Items.SingleClick( runebookToCopy.Serial ) Misc.Pause( 200 ) runebookName = None if runebookMoveable: for line in Journal.GetTextByType( 'Label' ): if '[' in line: bracketIndex = line.find( '[' ) runebookName = line[ 0 : ( bracketIndex - 1 ) ] else: journalText = Journal.GetTextByType( 'Label' ) journalText.Reverse() runebookName = journalText[ 0 ] if runebookName != None and runebookName != '': Items.UseItem( runebookToPlaceIn ) Gumps.WaitForGump( 1431013363, 10000 ) Misc.Pause( 200 ) Gumps.SendAction( 1431013363, 1 ) Misc.WaitForPrompt( 1000 ) Misc.ResponsePrompt( runebookName ) Gumps.WaitForGump( 1431013363, 1000 ) Gumps.SendAction( 1431013363, 0 ) def CopyRunebook(): global runebookToCopy global runebookToPlaceIn runebookToCopy = PromptRunebook( 'Select the runebook to copy from' ) if runebookToCopy == None: return runebookToPlaceIn = PromptRunebook( 'Select the runebook to copy to' ) if runebookToPlaceIn == None: return # Test if the runebook is locked down or not Journal.Clear() runebookMoveable = True recallRunebook = None if runebookToCopy.RootContainer != Player.Serial: Items.Move( runebookToCopy, Player.Backpack, 0 ) Misc.Pause( 650 + 100 ) # plus 100 to be extra safe runebookToCopy = Items.FindBySerial( runebookToCopy.Serial ) if runebookToCopy.RootContainer != Player.Backpack.Serial: runebookMoveable = False recallRunebook = Target.PromptTarget( 'Select item to recall off of to return to runebook being copied' ) numberOfRunesInOldBook = GetNumberOfRunesInBook( runebookToCopy ) numberOfRunesInNewBook = GetNumberOfRunesInBook( runebookToPlaceIn ) runeNames = GetNamesOfRunesInBook( runebookToCopy ) Misc.SendMessage( '# of runes to copy: %i' % numberOfRunesInOldBook ) Misc.SendMessage( '# of runes already copied: %i' % numberOfRunesInNewBook ) numberOfRunesToBeMarked = numberOfRunesInOldBook - numberOfRunesInNewBook # Make sure we have enough runes to be marked blankRuneBagSerial = Target.PromptTarget( 'Select bag with empty runes' ) blankRuneBag = Items.FindBySerial( blankRuneBagSerial ) if blankRuneBag == None or not blankRuneBag.IsContainer: Player.HeadMessage( 33, 'Invalid item selection!' ) return numberOfBlankRunes = 0 for item in blankRuneBag.Contains: if item.ItemID == 0x1F14: numberOfBlankRunes += 1 if numberOfRunesToBeMarked > numberOfBlankRunes: Player.HeadMessage( 33, 'You don\'t have enough blank runes to copy this book! You need %i more runes' % ( numberOfRunesToBeMarked - numberOfBlankRunes ) ) return # Copy the runebook for i in range( numberOfRunesInNewBook, numberOfRunesInOldBook ): Items.UseItem( runebookToCopy ) Misc.Pause( 650 ) Gumps.WaitForGump( 1431013363, 5000 ) if i == 0: Gumps.SendAction( 1431013363, 5 ) else: Gumps.SendAction( 1431013363, ( 5 + ( i * 6 ) ) ) Timer.Create( 'spellCooldown', 2500 ) Misc.Pause( 100 ) playerPosition = Player.Position runeToMark = Items.FindByID( 0x1F14, -1, blankRuneBag.Serial ) while Timer.Check( 'spellCooldown' ): Misc.Pause( 50 ) markScrolls = Items.FindByID( 0x1F59, 0x0000, Player.Backpack.Serial ) if markScrolls != None: Items.UseItem( markScrolls ) Timer.Create( 'markScrollDragDelay', 650 ) else: Spells.CastMagery( 'Mark' ) Target.WaitForTarget( 2000, True ) Target.TargetExecute( runeToMark ) if markScrolls != None and Timer.Check( 'markScrollDragDelay' ): while Timer.Check( 'markScrollDragDelay' ): Misc.Pause( 20 ) elif markScrolls == None: Timer.Create( 'spellCooldown', 1800 ) Items.UseItem( runeToMark ) Misc.WaitForPrompt( 1000 ) Misc.ResponsePrompt( runeNames[ i ] ) Misc.Pause( 650 ) Items.Move( runeToMark, runebookToPlaceIn, 0 ) Misc.Pause( 650 ) if runebookMoveable: if Player.Mana < 41: Player.UseSkill( 'Meditation' ) while Player.Mana < ( Player.ManaMax - 3 ): Misc.Pause( 50 ) while Timer.Check( 'spellCooldown' ): Misc.Pause( 50 ) else: while Timer.Check( 'spellCooldown' ): Misc.Pause( 50 ) Spells.CastMagery( 'Recall' ) Target.WaitForTarget( 15000, False ) Target.TargetExecute( recallRunebook ) Player.HeadMessage( 44, 'Move within recall range of the runebook being copied' ) Timer.Create( 'messageCooldown', 2000 ) while not Player.InRangeItem( runebookToCopy, 1 ): Misc.Pause( 100 ) if not Timer.Check( 'messageCooldown' ): Player.HeadMessage( 44, 'Move within recall range of the runebook being copied' ) Timer.Create( 'messageCooldown', 2000 ) if Player.Mana < 42: # 42 = 11 for 2 Recalls and 20 for one Mark Player.HeadMessage( 44, 'Meditating' ) Player.UseSkill( 'Meditation' ) while Player.Mana < ( Player.ManaMax - 3 ): if not Player.BuffsExist( 'Meditation' ): Player.UseSkill( 'Meditation' ) Misc.Pause( 50 ) Misc.Pause( 650 ) CopyRunebookName( runebookToCopy, runebookToPlaceIn, runebookMoveable ) Player.HeadMessage( 33, 'Done copying runebook!' ) Misc.Beep() runebookToCopy = None runebookToPlaceIn = None CopyRunebook() <file_sep># Bent Rod Crafter by MatsaMilla # Last edit: Matsamilla 6/4/19 # Moves bent rods to beetle from System.Collections.Generic import List import winsound import sys #***************SETUP SECTION********************************** #ItemSerials beetle = 0x00215F22 keepGM = False # true to keep all GM rods too keepCount = 30 # how many GM rods to keep #************************************************************** error = "Sounds2\error.wav" dragTime = 600 saw = 0x1034 tink = 0x1EB8 cloth = 0x1766 wood = 0x1BD7 logs = 0x1BDD ignot = 0x1BF2 pole = 0x0DBF noColor = 0x0000 self_pack = Player.Backpack.Serial self = Player.Serial gmCount = 0 # Use neraby trashcan trashBarrelFilter = Items.Filter() trashBarrelFilter.OnGround = 1 trashBarrelFilter.Movable = False trashBarrelFilter.RangeMin = 0 trashBarrelFilter.RangeMax = 2 trashBarrelFilter.Graphics = List[int]( [ 0x0E77 ] ) trashBarrelFilter.Hues = List[int]( [ 0x03B2 ] ) trashcanhere = Items.ApplyFilter( trashBarrelFilter ) if trashcanhere: global trashcan for t in trashcanhere: trashcan = t else: Misc.SendMessage('No trashcan nearby, stopping',33) sys.exit() if keepGM: Mobiles.UseMobile(self) Misc.Pause(dragTime) Mobiles.SingleClick(beetle) Misc.WaitForContext(beetle, 1500) Misc.ContextReply(beetle, "Open Backpack") Misc.Pause(dragTime) gmBag = Target.PromptTarget('Select Bag for GM Rods') def moveToBeetle(): global gmCount if keepGM: if gmRod: gmCount = gmCount +1 Misc.SendMessage(gmCount) if Player.Mount: Mobiles.UseMobile(self) Misc.Pause(dragTime) Items.Move(bentRod, gmBag, 1) Misc.Pause(dragTime) Mobiles.UseMobile(beetle) Misc.Pause(dragTime) if gmCount == keepCount: Misc.SendMessage('GM Rod Count Reached, stopping.',33) winsound.PlaySound(error, winsound.SND_FILENAME) sys.exit() else: if Player.Mount: Mobiles.UseMobile(self) Misc.Pause(dragTime) Items.Move(bentRod, beetle, 1) Misc.Pause(dragTime) Mobiles.UseMobile(beetle) Misc.Pause(dragTime) else: if Player.Mount: Mobiles.UseMobile(self) Misc.Pause(dragTime) Items.Move(bentRod, beetle, 1) Misc.Pause(dragTime) Mobiles.UseMobile(beetle) Misc.Pause(dragTime) def trashPole(): if trashcan: Items.Move(bentRod, trashcan.Serial, 1) Misc.Pause(dragTime) else: Misc.SendMessage('No trashcan nearby, stopping',33) sys.exit() def hide(): if not Player.BuffsExist('Hiding'): Player.UseSkill('Hiding') def checkMats(): if Items.BackpackCount(cloth, -1) < 5: Misc.SendMessage('Out of Cloth',33) winsound.PlaySound(error, winsound.SND_FILENAME) sys.exit() if Items.BackpackCount(wood, -1) < 5 and Items.BackpackCount(logs, -1) < 5: Misc.SendMessage('Out of Wood',33) winsound.PlaySound(error, winsound.SND_FILENAME) sys.exit() if Items.BackpackCount(saw, noColor) < 1: craftTools() def craftTools(): currentTink = Items.FindByID(tink, -1, -1) if Items.BackpackCount(ignot, noColor) < 10: Misc.SendMessage('Out of Ignots',33) winsound.PlaySound(error, winsound.SND_FILENAME) sys.exit() if Items.BackpackCount(tink, noColor) < 2: Items.UseItem(currentTink.Serial) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, 8) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, 23) if Items.BackpackCount(saw, noColor) < 1: Items.UseItem(currentTink.Serial) Gumps.WaitForGump(949095101,1500) Gumps.SendAction(949095101, 8) Gumps.WaitForGump(949095101,1500) Gumps.SendAction(949095101, 51) def craftPole(): if not Player.Mount: Mobiles.UseMobile(beetle) Misc.Pause(dragTime) currentSaw = Items.FindByID(saw, -1, -1) if currentSaw: Items.UseItem(currentSaw) Gumps.WaitForGump(949095101,1500) Gumps.SendAction(949095101, 22) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, 37) Misc.Pause(2000) def bentRodCheck(): global bentRod global gmRod bentRod = Items.FindByID(pole, -1, self_pack) gmRod = False if bentRod: if keepGM: Items.SingleClick(bentRod.Serial) Misc.Pause(dragTime) if Journal.Search('a bent rod'): moveToBeetle() Journal.Clear() elif Journal.Search('Exceptional'): gmRod = True moveToBeetle() Journal.Clear() else: trashPole() else: Items.SingleClick(bentRod.Serial) Misc.Pause(dragTime) if Journal.Search('a bent rod'): moveToBeetle() Journal.Clear() else: trashPole() while True: Journal.Clear() if Player.GetRealSkillValue('Hiding') > 30: hide() checkMats() craftPole() while Items.BackpackCount(pole, -1) > 0: bentRodCheck() <file_sep>Player.ChatSay(5, "Right One")<file_sep>restockBeetle = False amountToMake = 10000 restockChestSerial = 0x43510513 dragTime = 600 bp = 0x0F7A bm = 0x0F7B mr = 0x0F86 pen = 0x0FBF scroll = 0x0EF3 recall = 0x1F4C noColor = 0x0000 pack = Player.Backpack.Serial beetle = 0x0023F0A0 beetleContainer = 0x439F1BD4 # Inspect item in beetle to get container restockChest = Items.FindBySerial(restockChestSerial) import sys def craftRecall(): #pens = Items.FindByID(0x0FBF,-1,pack) pens = FindItem(0x0FBF, Player.Backpack) Items.UseItem(pens) Gumps.WaitForGump(949095101, 2000) Gumps.SendAction(949095101, 22) Gumps.WaitForGump(949095101, 2000) Gumps.SendAction(949095101, 51) Gumps.WaitForGump(949095101, 2000) if Player.Mana < 20: med() def med(): Player.UseSkill('Meditation') Timer.Create('med', 7000) Misc.Pause(dragTime) while Player.Mana < Player.ManaMax: if not Player.BuffsExist('Meditation') and Timer.Check('med') == False: Misc.Pause(2000) Player.UseSkill('Meditation') Timer.Create('med', 7000) Misc.Pause(100) def unload(): recalls = Items.FindByID(recall, -1, pack) if recalls: if restockBeetle: if Player.Mount: Mobiles.UseMobile(self) Misc.Pause(dragTime) Items.Move(recalls, beetle, 0) Misc.Pause(dragTime) if not Player.Mount: Mobiles.UseMobile(beetle) Misc.Pause(dragTime) else: Items.Move(recalls, restockChest.Serial, 0) Misc.Pause(dragTime) def FindItem( itemID, container, color = -1, ignoreContainer = [] ): ''' Searches through the container for the item IDs specified and returns the first one found Also searches through any subcontainers, which Misc.FindByID() does not ''' ignoreColor = False if color == -1: ignoreColor = True if isinstance( itemID, int ): foundItem = next( ( item for item in container.Contains if ( item.ItemID == itemID and ( ignoreColor or item.Hue == color ) ) ), None ) elif isinstance( itemID, list ): foundItem = next( ( item for item in container.Contains if ( item.ItemID in itemID and ( ignoreColor or item.Hue == color ) ) ), None ) else: raise ValueError( 'Unknown argument type for itemID passed to FindItem().', itemID, container ) if foundItem != None: return foundItem subcontainers = [ item for item in container.Contains if ( item.IsContainer and not item.Serial in ignoreContainer ) ] for subcontainer in subcontainers: foundItem = FindItem( itemID, subcontainer, color, ignoreContainer ) if foundItem != None: return foundItem def restock(): recalls = Items.FindByID(recall, -1, pack) if restockBeetle: if Items.BackpackCount(scroll, -1) < 1 or Items.BackpackCount(bp, -1) < 1 or Items.BackpackCount(bm, -1) < 1 or Items.BackpackCount(mr, -1) < 1: if Player.Mount: Mobiles.UseMobile(Player.Serial) Misc.Pause(dragTime) backpackscrolls = Items.FindByID(scroll, noColor, pack) backpackBp = Items.FindByID(bp, noColor, pack) backpackBm = Items.FindByID(bm, noColor, pack) backpackMr = Items.FindByID(mr, noColor, pack) if backpackscrolls: Items.Move(backpackscrolls, beetle, beetleContainer) Misc.Pause(dragTime) if backpackBp: Items.Move(backpackBp, beetle, 0) Misc.Pause(dragTime) if backpackBm: Items.Move(backpackBm, beetle, 0) Misc.Pause(dragTime) if backpackMr: Items.Move(backpackMr, beetle, 0) Misc.Pause(dragTime) if recalls: Items.Move(recalls, beetle, 0) Misc.Pause(dragTime) Mobiles.SingleClick(beetle) Misc.WaitForContext(beetle, 1500) Misc.ContextReply(beetle, "Open Backpack") Misc.Pause(dragTime) beetleScrolls = Items.FindByID(scroll, noColor, beetleContainer) bps = Items.FindByID (bp , noColor, beetleContainer) bms = Items.FindByID (bm , noColor, beetleContainer) mrs = Items.FindByID (mr , noColor, beetleContainer) if beetleScrolls: Items.Move(beetleScrolls, pack, 100) Misc.Pause(dragTime) if bps: Items.Move(bps, pack, 100) Misc.Pause(dragTime) if bms: Items.Move(bms, pack, 100) Misc.Pause(dragTime) if mrs: Items.Move(mrs, pack, 100) Misc.Pause(dragTime) if not Player.Mount: Mobiles.UseMobile(beetle) Misc.Pause(dragTime) else: if Items.BackpackCount(scroll, -1) < 1: Items.UseItem(restockChest) Misc.Pause(dragTime) scrolls = Items.FindByID (scroll ,-1,restockChest.Serial) Items.Move(scrolls, pack, 100) Misc.Pause(dragTime) unload() if Items.BackpackCount(bp, -1) < 1: Items.UseItem(restockChest) Misc.Pause(dragTime) bps = Items.FindByID (bp ,-1,restockChest.Serial) Items.Move(bps, pack, 100) Misc.Pause(dragTime) unload() if Items.BackpackCount(bm, -1) < 1: Items.UseItem(restockChest) Misc.Pause(dragTime) bms = Items.FindByID (bm ,-1,restockChest.Serial) Items.Move(bms, pack, 100) Misc.Pause(dragTime) unload() if Items.BackpackCount(mr, -1) < 1: Items.UseItem(restockChest) Misc.Pause(dragTime) mrs = Items.FindByID (mr ,-1,restockChest.Serial) Items.Move(mrs, pack, 100) Misc.Pause(dragTime) unload() if Items.BackpackCount(pen, -1) < 1: restockPen = FindItem(pen, restockChest) Items.Move(restockPen, pack, 0) Misc.Pause(dragTime) if Items.BackpackCount(scroll, -1) < 1 or Items.BackpackCount(bp, -1) < 1 or Items.BackpackCount(bm, -1) < 1 or Items.BackpackCount(mr, -1) < 1: sys.exit() if Items.BackpackCount(pen, -1) < 1: Misc.SendMessage('Out of pens', 33) sys.exit() for i in range(0,amountToMake): restock() craftRecall() if i % 10 == 0: Misc.SendMessage ( 'Recalls made: %i' % ( i ) , 33) #Misc.SendMessage(i) <file_sep># Recall Home by MatsaMilla # version 2.1 - overhead message for using charges, and remaining charges # # Enter in player name (case sensitive!), runebook and runeNumber (posotion of rune in book, 1-16) # True = Mage will not open book, home rune set to default targetBook = True if Player.Name == "MetaMilla": runebook = 0x43286FAE runeNumber = 1 elif Player.Name == "MGD": runebook = 0x402F6431 runeNumber = 1 elif Player.Name == "MatsaMilla": runebook = 0x40c0aa9a runeNumber = 2 elif Player.Name == "Matsa-": runebook = 0x40c0aa9a runeNumber = 2 #***************************************************************# def recallMagery(book, rune): if targetBook: Spells.CastMagery('Recall') Target.WaitForTarget(3500,False) Target.TargetExecute(book) else: rune = rune -1 rune = 5 + (6 * rune) if Gumps.CurrentGump() != 1431013363: Items.UseItem(book) Gumps.WaitForGump(1431013363, 1000) Gumps.SendAction(1431013363, rune) def recallCharge(book, rune): rune = rune -1 rune = 2 + (6 * rune) if Gumps.CurrentGump() != 1431013363: Items.UseItem(book) Misc.Pause(100) Gumps.WaitForGump(1431013363, 1000) Gumps.SendAction(1431013363, rune) Items.WaitForProps(book,500) charges = Items.GetPropValue(book,'Charges') Player.HeadMessage(66, str(int(charges)) + ' charges left' ) def FindItem( itemID, container, color = -1, ignoreContainer = [] ): ''' Searches through the container for the item IDs specified and returns the first one found Also searches through any subcontainers, which Misc.FindByID() does not ''' ignoreColor = False if color == -1: ignoreColor = True if isinstance( itemID, int ): foundItem = next( ( item for item in container.Contains if ( item.ItemID == itemID and ( ignoreColor or item.Hue == color ) ) ), None ) elif isinstance( itemID, list ): foundItem = next( ( item for item in container.Contains if ( item.ItemID in itemID and ( ignoreColor or item.Hue == color ) ) ), None ) else: raise ValueError( 'Unknown argument type for itemID passed to FindItem().', itemID, container ) if foundItem != None: return foundItem subcontainers = [ item for item in container.Contains if ( item.IsContainer and not item.Serial in ignoreContainer ) ] for subcontainer in subcontainers: foundItem = FindItem( itemID, subcontainer, color, ignoreContainer ) if foundItem != None: return foundItem def checkRegs(): if (FindItem(0x0F7A , Player.Backpack) and FindItem(0x0F86 , Player.Backpack) and FindItem(0x0F7B , Player.Backpack) ): return True else: return False if runebook != None: if Player.GetRealSkillValue('Magery') > 50 and checkRegs(): recallMagery(runebook, runeNumber) else: Player.HeadMessage(66,"-Using Charge-") recallCharge(runebook, runeNumber) else: Player.HeadMessage(33,'No Runebook Set') <file_sep>Player.ChatSay(5, "Turn Around")<file_sep>#buff pots leftHand = Player.GetItemOnLayer('LeftHand') chugtime = 650 journalTimeout = 100 msgColor = 66 noBow = True bows = [0x13B2,0x26C2,0x0F50,0x13FD,0x0A12,0x0F6B] # 0x0A12,0x0F6B = torch if not leftHand: noBow = True elif leftHand.ItemID in bows: noBow = False elif leftHand: noBow = True def str(): Player.ChatSay( 1 , '[drink GreaterStrengthPotion ') Misc.Pause( journalTimeout ) if Journal.Search( 'You do not have any of those potions.'): Player.HeadMessage(msgColor, "No Strength pots!") Journal.Clear() else: Misc.Pause(chugtime) def strPot(): whitePot = Items.FindByID(0x0F09,0,Player.Backpack.Serial,True) if whitePot: Items.UseItem(whitePot) Misc.Pause(chugtime) else: Player.HeadMessage(msgColor, "No Strength pots!") def agil(): Player.ChatSay( 1 , '[drink GreaterAgilityPotion') Misc.Pause( journalTimeout ) if Journal.Search( 'You do not have any of those potions.'): Player.HeadMessage(msgColor, "No Agility pots!") Journal.Clear() else: Misc.Pause(chugtime) def agilPot(): bluePot = Items.FindByID(0x0F08,0,Player.Backpack.Serial,True) if bluePot: Items.UseItem(bluePot) Misc.Pause(chugtime) else: Player.HeadMessage(msgColor, "No Agility pots!") def refresh(): Player.ChatSay( 1 , '[drink totalrefreshpotion') Misc.Pause(100) if Journal.Search( 'You do not have any of those potions.'): Player.HeadMessage(msgColor, "No Refresh pots!") Journal.Clear() # else: # Misc.Pause(chugtime) def refreshPot(): redPot = Items.FindByID(0x0F0B,0,Player.Backpack.Serial,True) if redPot: Items.UseItem(redPot) else: Player.HeadMessage(msgColor, "No Refresh pots!") def clearHands(): if leftHand and noBow: Player.UnEquipItemByLayer('LeftHand') Misc.Pause(chugtime) return True else: return False def reArm(): Player.EquipItem(leftHand) Misc.Pause(50) def buffUp(): if Player.Str <= 100: if clearHands(): disarmed = True else: disarmed = False str() agil() refresh() if disarmed: reArm() elif Player.Dex <= 100: if clearHands(): disarmed = True else: disarmed = False str() agil() refresh() if disarmed: reArm() elif Player.Stam <= Player.StamMax: if clearHands(): disarmed = True else: disarmed = False refresh() if disarmed: reArm() else: Player.HeadMessage(msgColor, 'Buffed and full stam') def buffUpPots(): if Player.Str <= 100: if clearHands(): disarmed = True else: disarmed = False strPot() agilPot() refreshPot() if disarmed: reArm() elif Player.Dex <= 100: if clearHands(): disarmed = True else: disarmed = False strPot() agilPot() refreshPot() if disarmed: reArm() elif Player.Stam <= Player.StamMax: if clearHands(): disarmed = True else: disarmed = False refreshPot() if disarmed: reArm() else: Player.HeadMessage(msgColor, 'Buffed and full stam') if Misc.ShardName() == "Ultima Forever" or Misc.ShardName() == "UOForever": buffUp() else: buffUpPots() <file_sep>Player.ChatSay(5, "Embark") Misc.Pause(400) Player.ChatSay(5, "Raise Anchor")<file_sep># T-Map ID & Pull by MatsaMilla # Last Edit 3/18322 # Disable auto-open corpses to run smoother # Uses wands if ID skill below 80. Set idAllItems to false to not ID at all. # Must use tooltips #*********** SETUP SECTION********************************************* # Replace with beetle serial if you have one beetle = 0x0006EB2A # False if you don not have beetle beetleBag = True # True if you want to keep scrolls sortScrolls = False # True to ID & Pull, false to just pull weps & armor idAllItems = True # Modify for item delay of server or to slow down / speed up script dragTime = 800 #********** Wep Mods To KEEP ******************************************* # modify list to keep armor matching strings below, must match in both keepArmorMods & keepArmorHPMods keepArmorMods = ['Invulnerability','Exceptional'] #'Fortification', 'Hardening', 'Guarding', 'Defence' keepArmorHPMods = ['Indestructible','Fortified','Massive'] # 'Substantial' , 'Durable' # always keep wep mods keepProps = ['Vanquishing'] # keep wep mods if matching keepWepDmgMods or keepWepAccuracyMods keepWepDmgMods = ['Power'] # 'Force', 'Might', 'Ruin' keepWepAccuracyMods = ['Supremely Accurate','Exceedingly Accurate'] # 'Eminently Accurate', 'Surpassingly Accurate', 'Accurate' # keep slayers if matching in this list slayerProps = ['Silver','Undead','Snake','Lizardman','Dragon','Reptile','Terathan', 'Orc Slaying','Ogre','Water','Earth','Elemental','Repond','Fey','Daemon','Exorcism','Poison','Arachnid'] # 'Scorpion','Flame','Vacuum','Gargoyle','Spider' # useless items no matter how good they are, aka bad shields & ringmail sellItems = [ 0x1B72,0x13DB,0x13D5,0x13DA,0x1B7B,0x1DB9,0x13BB,0x1B79,0x13EB,0x1B7A,0x13F0,0x1C02,0x1C0C, 0x13EC,0x1B73,0x13DC,0x13BE,0x13EE,0x13D6,0x13BF ] #*********************NO TOUCH BELOW************************************* import sys Misc.SendMessage('Starting TMap Pull and ID', 33) skillTimer = 0 msgColor = 68 self = Mobiles.FindBySerial(Player.Serial) heavy = Player.MaxWeight - 10 # Will use ID Wand if skill Item ID below 80 if Player.GetRealSkillValue('Item ID') < 80: idWand = True else: idWand = False #loot includes gate, recall & lvl 8 summoning scrolls loot = [0x2260,0x1f4c,0x1f60,0x1f66,0x1f68,0x1f69,0x1f6a,0x1f6b,0x1f6c] perk = [0x2dd5,0x1f18,0x2da3,0x166e,0x26BB,0x139B] gold = [0xeed] gems = [0xf16,0xf15,0xf19,0xf25,0xf21,0xf10,0xf26,0xf2d,0xf13] wands = [0xdf5,0xdf3,0xdf4,0xdf2] boneArmor = [0x1450,0x1f0b,0x1452,0x144f,0x1451,0x144e] regs= [0xf7a,0xf7b,0xf86,0xf84,0xf85,0xf88,0xf8d,0xf8c] scrolls = [0x1f2d,0x1f2e,0x1f2f,0x1f30,0x1f31,0x1f32,0x1f33,0x1f34,0x1f35,0x1f36,0x1f37,0x1f38,0x1f39, 0x1f3a,0x1f3b,0x1f3c,0x1f3d,0x1f3e,0x1f3f,0x1f40,0x1f41,0x1f42,0x1f43,0x1f44,0x1f45,0x1f46,0x1f47,0x1f48, 0x1f49,0x1f4a,0x1f4b,0x1f4d,0x1f4e,0x1f4f,0x1f50,0x1f51,0x1f52,0x1f53,0x1f54,0x1f55,0x1f56,0x1f57,0x1f58, 0x1f59,0x1f5a,0x1f5b,0x1f5c,0x1f5d,0x1f5e,0x1f5f,0x1f60,0x1f61,0x1f62,0x1f63,0x1f64,0x1f65,0x1f66,0x1f67, 0x1f68,0x1f69,0x1f6a,0x1f6b,0x1f6c] trash = [0x1717,0x1718,0x1544,0x1540,0x1713,0x1715,0x1714,0x1716,0x1717,0x1718,0x1719,0x171a,0x171b, 0x171c,0x2306,0x13f6,0xec4,0x1716,0xe81,0xe86,] boneArmor = [0x1450,0x1f0b,0x1452,0x144f,0x1451,0x144e] weps = [0xf62,0x1403,0xe87,0x1405,0x1401,0xf52,0x13b0,0xdf0,0x1439,0x1407,0xe89,0x143d,0x13b4,0xe81,0x13f8, 0xf5c,0x143b,0x13b9,0xf61,0x1441,0x13b6,0xec4,0x13f6,0xf5e,0x13ff,0xec3,0xf43,0xf45,0xf4d,0xf4b,0x143e, 0x13fb,0x1443,0xf47,0xf49,0xe85,0xe86,0x13fd,0xf50,0x13b2,] armor = [0x1b72,0x1b73,0x1b7b,0x1b74,0x1b79,0x1b7a,0x1b76,0x1408,0x1410,0x1411,0x1412,0x1413,0x1414,0x1415, 0x140a,0x140c,0x140e,0x13bb,0x13be,0x13bf,0x13ee,0x13eb,0x13ec,0x13f0,0x13da,0x13db,0x13d5,0x13d6,0x13dc, 0x13c6,0x13cd,0x13cc,0x13cb,0x13c7,0x1db9,0x1c04,0x1c0c,0x1c02,0x1c00,0x1c08,0x1c06,0x1c0a,] # check / set bags. Idea from Wardoc (thanks!) def GetBag ( sharedValue, promptString ): if Misc.CheckSharedValue( sharedValue ): bag = Misc.ReadSharedValue( sharedValue ) if not Items.FindBySerial( bag ): Player.HeadMessage(66,promptString) bag = Target.PromptTarget( promptString ) Misc.SetSharedValue( sharedValue, bag ) else: Player.HeadMessage(66,promptString) bag = Target.PromptTarget( promptString ) Misc.SetSharedValue( sharedValue, bag ) return bag regBag = GetBag( 'regBag', 'Select Bag for Regs' ) gemBag = GetBag( 'gemBag', 'Select Bag for Gems' ) trashCan = GetBag( 'trashCan', 'Select corpse to dump on') if idAllItems: sellBag = GetBag( 'sellBag', 'Select Bag for BAD weps and armor' ) keepBag = GetBag( 'keepBag', 'Select Bag for GOOD weps and armor' ) else: armorBag = GetBag( 'armorBag', 'Select Bag for armor' ) wepBag = GetBag( 'wepBag', 'Select Bag for weapons' ) if sortScrolls: scrollBag = GetBag( 'scrollBag', 'Select Bag for Scrolls' ) Player.HeadMessage(66,"Select Treasure Chest") chest = Target.PromptTarget('Select Treasure Chest') mapChest = Items.FindBySerial(chest) Items.UseItem(mapChest) Misc.Pause(dragTime) def checkWeight(): if Player.Weight >= heavy: Player.ChatSay(msgColor, 'Overweight, stopping!') sys.exit() def checkDistance(): reopenChest = False while mapChest.DistanceTo(self) > int(1): Misc.Pause(1000) reopenChest = True if not Timer.Check('Distance'): Player.HeadMessage(msgColor, 'Too Far Away') Timer.Create('Distance', 2500) if reopenChest == True: Items.UseItem(mapChest) Misc.Pause(dragTime) reopenChest = False def goldToBeetle(): #moves gold to beetle if beetleBag: for s in mapChest.Contains: checkDistance() if s.ItemID in gold: if Player.Mount: Mobiles.UseMobile(Player.Serial) Misc.Pause(dragTime) Items.Move(s, beetle, 0) Misc.Pause(dragTime) if not Player.Mount: Mobiles.UseMobile(beetle) Misc.Pause(dragTime) def idStuffToolTips(container, type): if type == 'weps': idItems = weps tier1 = keepWepDmgMods tier2 = keepWepAccuracyMods worthlessBag = sellBag elif type == 'armor': idItems = armor tier1 = keepArmorMods tier2 = keepArmorHPMods worthlessBag = sellBag elif type == 'bone': idItems = boneArmor tier1 = keepArmorMods tier2 = ['Indestructible'] worthlessBag = trashCan for i in container.Contains: worldSave() if i.ItemID in idItems: checkWeight() Journal.Clear() idTarget() Target.WaitForTarget(1500) Target.TargetExecute(i.Serial) Misc.Pause(dragTime) Items.WaitForProps(i,2000) props = Items.GetPropStringList(i) if any(elem in keepProps for elem in props): #** Good Stuff Move ** Items.Move(i, keepBag, 0) Misc.Pause(dragTime) elif any(elem in tier1 for elem in props): #moves items if in sell ids if i.ItemID in sellItems: #** Sell Stuff Move ** Items.Move(i, worthlessBag, 0) Misc.Pause(dragTime) elif any(elem in tier2 for elem in props): #** Good Stuff Move ** Items.Move(i, keepBag, 0) Misc.Pause(dragTime) else: #** Sell Stuff Move ** Items.Move(i, worthlessBag, 0) Misc.Pause(dragTime) else: #** Sell Stuff Move ** Items.Move(i, worthlessBag, 0) Misc.Pause(dragTime) def itemID(container): if idAllItems: idStuffToolTips(container, 'weps') idStuffToolTips(container, 'armor') idStuffToolTips(container, 'bone') else: for i in container.Contains: if i.ItemID in armor: Items.Move(i,armorBag,0) Misc.Pause(dragTime) elif i.ItemID in weps: Items.Move(i,wepBag,0) Misc.Pause(dragTime) elif i.ItemID in boneArmor: Items.Move(i,wepBag,0) Misc.Pause(dragTime) def pullGems(): for i in mapChest.Contains : checkDistance() checkWeight() if i.ItemID == 0x0F21 and i.Hue == 0x0489: Player.ChatEmote(1,'[e woohoo') Misc.Pause(200) Player.ChatParty('FRAG, GET OUT OF HERE!') Misc.Pause(200) Player.ChatSay(66, 'FRAG, GET OUT OF HERE!') Items.Move(i, gemBag, 0) Misc.Pause(dragTime) if i.ItemID in gems: Items.Move(i, gemBag, 0) Misc.Pause(dragTime) def pull(): for i in mapChest.Contains : checkDistance() checkWeight() if i.ItemID in gold: Items.Move(i, Player.Backpack.Serial, 0) Misc.Pause(dragTime) elif i.ItemID in loot: Items.Move(i, Player.Backpack.Serial, 0) Misc.Pause(dragTime) elif i.ItemID in perk: Items.Move(i, Player.Backpack.Serial, 0) Misc.Pause(dragTime) elif i.ItemID in regs: Items.Move(i, regBag, 0) Misc.Pause(dragTime) elif i.ItemID in wands: Items.Move(i, Player.Backpack.Serial, 0) Misc.Pause(dragTime) elif i.ItemID in scrolls: if sortScrolls: Items.Move(i, scrollBag, 0) Misc.Pause(dragTime) def trashStuff(): for i in mapChest.Contains : checkDistance() checkWeight() if i.ItemID in scrolls: Items.Move(i, trashCan, 0) Misc.Pause(dragTime) elif i.ItemID in trash: Items.Move(i, trashCan, 0) Misc.Pause(dragTime) def worldSave(): if Journal.SearchByType('The world is saving, please wait.', 'Regular' ): Misc.SendMessage('Pausing for world save', 33) while not Journal.SearchByType('World save complete.', 'Regular'): Misc.Pause(1000) Misc.SendMessage('Continuing', 33) Journal.Clear() def equipWand(): global wandSerial player_bag = Items.FindBySerial(Player.Backpack.Serial) rightHand = Player.CheckLayer('RightHand') leftHand = Player.CheckLayer('LeftHand') if leftHand: Player.UnEquipItemByLayer('LeftHand') if not rightHand: Player.ChatSay(66,'[equip idwand') Misc.Pause(dragTime) if Player.GetItemOnLayer('RightHand').ItemID in wands: wandSerial = Player.GetItemOnLayer('RightHand').Serial else: Player.ChatSay(33, "No Wands Found, Stopping Script") sys.exit() def idTarget(): if idWand: equipWand() Items.UseItem(wandSerial) else: Player.UseSkill('Item ID') Misc.Pause(100) if not Target.HasTarget(): idTarget() goldToBeetle() while mapChest: pullGems() pull() itemID(mapChest) trashStuff() mapChest = Items.FindBySerial(chest) Player.HeadMessage(msgColor, 'Chest Cleared, Thanks MatsaMilla!') <file_sep>Player.ChatSay(5, "Turn Right")<file_sep># XP tracker by SilentNox, imporoved by MatsaMilla # Version 2.6: Fixed error with rogue while using tooltips # Tracks XP of talisman, or meta pet, just start it up and enjoy # *leave talisman gump open if NOT using tooltips # *leave meta stone gump open regardless # Displays XP gained every 10 seconds, total every 60s & grand total # true if using tooltips (works better) toolTipsOn = True # True = will track XP only while running the script # False = will track XP since Enhanced, if you stop/restart script it will still track starting xp trackOnScript = False # put name in here if you never want to track (maxxed talismans) and will only open tali gump noTrackList = ['mgdexxer', 'viernadourden', 'metamilla'] minxp = 0 currentxp = 0 counter = 0 name = Player.Name.lower().replace(' ', '') import sys def setupToolTips(): global startingxp global temp global currentxp temp = Items.GetPropStringByIndex(Talli, propLine) if temp == 'MAX': Misc.SendMessage('Talisman Maxxed, stopping', 33) sys.exit() else: temp = temp.split(": ", 1)[1] temp = temp.split("/", 1)[0] if hasInt(temp): currentxp = int(temp) else: setup() if trackOnScript: startingxp = currentxp Misc.SendMessage('Starting XP: ' + startingxp, 33) else: if Misc.CheckSharedValue( pname + 'xp' ): startingxp = Misc.ReadSharedValue( pname + 'xp' ) Misc.SendMessage('Starting XP: ' + str(startingxp) , 33) Misc.Pause(200) gainedXP = currentxp - startingxp if gainedXP > 0: Player.HeadMessage(66,'XP since run: ' + str(gainedXP)) elif gainedXP == 0: Misc.NoOperation() else: Player.HeadMessage(44, 'You leveled up!' ) Player.ChatSay(66, '[e woohoo') Misc.RemoveSharedValue( pname + 'xp' ) setup() else: startingxp = currentxp Misc.SetSharedValue( pname + 'xp', startingxp ) Misc.SendMessage('Starting XP: ' + str(startingxp) , 33) def talismanXpToolTips(): global counter global currentxp global minxp Misc.Pause(10000) temp = Items.GetPropStringByIndex(Talli, propLine) if temp == 'MAX': Misc.SendMessage('Talisman Maxxed, stopping', 33) sys.exit() else: temp = temp.split(": ", 1)[1] temp = temp.split("/", 1)[0] if hasInt(temp): newxp = int(temp) else: newxp = currentxp difference = newxp - currentxp Misc.Pause(120) if difference > 0: Player.HeadMessage(54, '+' + str(difference) + ' xp') currentxp = newxp elif difference == 0: Misc.NoOperation() else: Player.HeadMessage(44, 'You leveled up!' ) Misc.Pause(200) Player.ChatSay(66, '[e woohoo') Misc.RemoveSharedValue( pname + 'xp' ) #startingxp = 0 Misc.SetSharedValue( pname + 'xp', 0 ) #Misc.SendMessage('Starting XP: ' + str(startingxp) , 33) Misc.Pause(10000) minxp = difference + minxp counter = counter + 1 if counter >= 6: overallxp = currentxp - startingxp if minxp > 0: Player.HeadMessage(54, '+' + str(minxp) + ' xp last 60s') Misc.Pause(200) if overallxp > 0: Player.HeadMessage(44, str(overallxp) + 'xp total.') elif overallxp == 0: Misc.NoOperation() else: Player.HeadMessage(44, 'You leveled up!' ) Player.ChatSay(66, '[e woohoo') Misc.RemoveSharedValue( pname + 'xp' ) setup() counter = 0 minxp = 0 Misc.Pause(50) def hasInt(s): try: int(s) return True except ValueError: return False def talismanXp(): global counter global currentxp global minxp if Gumps.CurrentGump() == gumpid: Misc.Pause(10000) temp = Gumps.LastGumpGetLine(gumpLine) temp = temp.split("/", 1)[0] if hasInt(temp): newxp = int(temp) else: newxp = currentxp difference = newxp - currentxp Misc.Pause(120) if difference > 0: Player.HeadMessage(54, '+' + str(difference) + ' xp') currentxp = newxp elif difference == 0: Misc.NoOperation() else: Player.HeadMessage(44, 'You leveled up!' ) Player.ChatSay(66, '[e woohoo') Misc.RemoveSharedValue( pname + 'xp' ) setup() minxp = difference + minxp counter = counter + 1 if counter >= 6: overallxp = currentxp - startingxp if minxp > 0: Player.HeadMessage(54, '+' + str(minxp) + ' xp last 60s') Misc.Pause(200) if overallxp > 0: Player.HeadMessage(44, str(overallxp) + 'xp total.') elif overallxp == 0: Misc.NoOperation() else: Player.HeadMessage(44, 'You leveled up!' ) Player.ChatSay(66, '[e woohoo') Misc.RemoveSharedValue( pname + 'xp' ) setup() counter = 0 minxp = 0 else: tempGump = Gumps.CurrentGump() Gumps.CloseGump(tempGump) Misc.Pause(50) def setup(): global startingxp global temp global currentxp Gumps.WaitForGump(gumpid, 10000) temp = Gumps.LastGumpGetLine(gumpLine) if temp == 'MAX': Misc.SendMessage('Talisman Maxxed, stopping', 33) sys.exit() temp = temp.split("/", 1)[0] #Misc.SendMessage(str(temp)) if hasInt(temp): currentxp = int(temp) #Misc.SendMessage('OK') else: Misc.Pause(600) Misc.SendMessage('retrying read') setup() if trackOnScript: startingxp = currentxp Misc.SendMessage('Starting XP: ' + str(startingxp), 33) else: if Misc.CheckSharedValue( pname + 'xp' ): startingxp = Misc.ReadSharedValue( pname + 'xp' ) Misc.SendMessage('Starting XP: ' + str(startingxp) , 33) Misc.Pause(200) gainedXP = currentxp - startingxp if gainedXP > 0: Player.HeadMessage(66,'XP since run: ' + str(gainedXP)) elif gainedXP == 0: Misc.NoOperation() else: Player.HeadMessage(44, 'You leveled up!' ) Player.ChatSay(66, '[e woohoo') Misc.RemoveSharedValue( pname + 'xp' ) setup() else: startingxp = currentxp Misc.SetSharedValue( pname + 'xp', startingxp ) Misc.SendMessage('Starting XP: ' + str(startingxp) , 33) Misc.Pause(200) pname = Player.Name.lower().replace(' ', '') Talli = Player.GetItemOnLayer('Talisman') if Talli: Tallyserial = Items.FindBySerial(Talli.Serial) Tallyserial = Items.FindBySerial(Talli.Serial) if Talli.Hue == 0x078c: propLine = 6 else: propLine = 5 gumpLine = 4 gumpid = 463091633 else: Talli = Items.FindByID( 0x3679 , -1 , Player.Backpack.Serial) if Talli: Items.UseItem(Talli) Misc.Pause(600) Tallyserial = Items.FindBySerial(Talli.Serial) gumpLine = 4 gumpid = 3527528070 Misc.SendMessage('Using Meta Stone', 33) else: Misc.SendMessage('Talisman Not Found, Stopping', 33) sys.exit() #setup() try: if toolTipsOn: if Talli.ItemID == 0x3679: setup() while True: talismanXp() else: setupToolTips() if pname in noTrackList: Items.UseItem(Tallyserial) Misc.Pause(200) sys.exit() while True: talismanXpToolTips() else: Items.UseItem(Tallyserial) Misc.Pause(200) if pname in noTrackList: sys.exit() setup() while True: talismanXp() except: print("An exception occurred") <file_sep>Player.ChatSay(5, "Forward Left")<file_sep># Recursive, fast steal script by ATHL33T # Updated by MatsaMilla 4/2/22 if Player.GetRealSkillValue('Snooping') < 100: Misc.SendMessage('You\'re not a theif', 33) sys.exit() escapeRunebook = 0x414D8007 recallAfterSteal = False psHue = 0x0481 blazeHue = 1161 #0x0489 short_delay = 20 journal_delay = 120 snoop_delay = 600 ignoreList = [] trap_hues = [0x0489, 0x0026] containers = [0xe76, 0xe75, 0xe74, 0xe78, 0xe7d, 0xe77] bags = [0x0E76, 0xE75, 0xE74, 0xE78, 0xE77, 0x0E79] # 0x0E7D trap box # 0x0E79 pouch # 0x0E75 backpack # 0x0E76 bag relic = 0x2AA4 eventFrag = 0x35DA portalFrag = 0x0F21 powerScroll = 0x14F0 skillScroll = 0x2260 dragonEgg = 0x47E6 head = 0x1CE1 garlic = 0x0F84 root = 0x0F86 bandages = 0x0E21 cure_pots = 0x0F07 arrows = 0x0F3F #bags = [] steal_priorities_Hues = [ powerScroll, portalFrag, skillScroll ] steal_priorities = [ relic, eventFrag, dragonEgg, portalFrag, skillScroll, powerScroll, head ] stealHues = [ blazeHue, psHue ] def is_steal_success(): Misc.Pause(journal_delay) if Journal.Search('You fail to steal the item.'): Player.HeadMessage(33, 'FAILED') elif Journal.Search('You successfully steal the item.'): Player.HeadMessage(66, '└[∵┌]└[ ∵ ]┘[┐∵]┘') Player.HeadMessage(66, 'GOT EM') Player.ChatSay(52, "[organizeme") if recallAfterSteal: escape() sys.exit() else: Player.HeadMessage(66, 'third thing') def escape(): runebook = Items.FindByID( 0x22C5 , -1 , Player.Backpack.Serial ) Spells.CastMagery('Recall') Target.WaitForTarget(1500) Target.TargetExecute( runebook ) def steal(item, mark): Journal.Clear() attempted = False Items.WaitForProps(item,500) while not attempted: if Items.GetPropValue(item, 'Blessed'): Player.HeadMessage(66 , 'Blessed Item') ignoreList.append(item.Serial) break #Player.HeadMessage(66,'Attempting') Player.UseSkill('Stealing') Misc.Pause(journal_delay) if Journal.SearchByType('You must wait a few moments to use another skill.', 'Regular'): Player.HeadMessage(66 , 'Skill Timer') Misc.Pause(journal_delay) Journal.Clear() elif Journal.SearchByType('You can\'t steal that.', 'System'): Player.HeadMessage(66 , 'Blessed Item') ignoreList.append(item) Journal.Clear() attempted = True else: Target.WaitForTarget(1500) while Player.DistanceTo(mark) > 1: Misc.Pause(short_delay) Target.TargetExecute(item) attempted = True is_steal_success() def snoop_recursive(container, mark): Items.UseItem(container) contents = container.Contains stealThis = [] #steal_target_bags = [item for item in contents if item.IsContainer and item.Hue not in trap_hues] steal_target_bags = [item for item in contents if item.ItemID in bags and item.Hue not in trap_hues] #items_to_steal = [item.Serial for item in contents if (item.ItemID in steal_priorities_Hues and item.Hue in stealHues)] items_to_steal = [item.Serial for item in contents if (item.ItemID in steal_priorities)] for i in items_to_steal: ok = Items.FindBySerial(i) if ok.Serial in ignoreList: Misc.NoOperation() elif ok.ItemID in steal_priorities_Hues: if ok.Hue in stealHues: stealThis.append(i) else: stealThis.append(i) if len(stealThis) > 0: #stealItem = Items.FindBySerial(items_to_steal[0]) stealItem = Items.FindBySerial(stealThis[0]) Player.HeadMessage(66,stealItem.Name) return steal(stealItem, mark) if len(steal_target_bags) == 0: return True else: for bag in steal_target_bags: Misc.Pause(snoop_delay) snoop_recursive(bag, mark) return True def run_continuously(): while Player.Hits > 0: mark = Target.GetTargetFromList("stealtarget") if mark != None and Player.DistanceTo(mark) < 2: snoop_recursive(mark.Backpack, mark) Misc.Pause(short_delay) Misc.Pause(600) # filter def find(): fil = Mobiles.Filter() fil.Enabled = True fil.RangeMax = 1 fil.IsHuman = True fil.IsGhost = False fil.Friend = False fil.Notorieties = List[Byte](bytes(1,3,4,5,6)) list = Mobiles.ApplyFilter(fil) return list def run_once(): mark = Mobiles.Select(find(),'Next') # Target.GetTargetFromList("stealtarget") if mark != None and Player.DistanceTo(mark) < 2: snoop_recursive(mark.Backpack, mark) Misc.Pause(short_delay) Misc.Pause(600) Player.HeadMessage(66, 'sticky fingers time') run_continuously() <file_sep>Player.ChatSay(5, "Right")<file_sep># Version 2.0 - updated 12/30/20 # recharges blaze pouches in pack. MUST HAVE TOOL TIPS ENABLED # By MatsaMilla for i in Player.Backpack.Contains: if i.ItemID == 0x0E79 and i.Hue == 0x0489: Items.WaitForProps( i , 1000 ) charges = Items.GetPropValue(i,"Charges") if charges: if charges < 30: while charges < 30: Spells.CastMagery('Magic Trap') Target.WaitForTarget(10000, False) Target.TargetExecute(i) Misc.Pause(800) Items.WaitForProps( i , 1000 ) charges = Items.GetPropValue(i,"Charges") if Player.Mana < 20: Player.UseSkill("Meditation") while Player.Mana < Player.ManaMax: Misc.Pause(100) # blazePouch = Items.FindBySerial( Target.PromptTarget('Target Pouch') ) # trapcharges = 1 # Journal.Clear() # while trapcharges < 30: # Spells.CastMagery('Magic Trap') # Target.WaitForTarget(10000, False) # Target.TargetExecute(blazePouch) # Misc.Pause(800) # Misc.SendMessage(trapcharges) # trapcharges = trapcharges +1 # if Journal.Search('This pouch can only hold 30 charges.'): # Stop # if Player.Mana < 20: # Player.UseSkill("Meditation") # while Player.Mana < Player.ManaMax: # Misc.Pause(100) <file_sep># Dexxer trainer by MatsaMilla # Will train Healing , Anatomy, Hiding & Alchemy dummy = None dragTime = 600 bows = [0x13B2,0x26C2,0x0F50,0x13FD] leftHand = Player.GetItemOnLayer('LeftHand') import sys def trainingDummy(): global dummy training = Target.PromptTarget("Target training dummy") dummy = Mobiles.FindBySerial(training) def kegPots(): if Journal.Search('hold any more'): Misc.SendMessage('Empty Keg!!') sys.exit() keg = Items.FindByID(0x1940,-1,Player.Backpack.Serial) tr = Items.FindByID(0xf0b,-1,Player.Backpack.Serial) ga = Items.FindByID(0xf08 ,-1,Player.Backpack.Serial) gs = Items.FindByID(0xf09 ,-1,Player.Backpack.Serial) gh = Items.FindByID(0xf0c ,-1,Player.Backpack.Serial) gc = Items.FindByID(0xf07 ,-1,Player.Backpack.Serial) if tr: Items.Move(tr, keg, 0) Misc.Pause(dragTime) elif ga: Items.Move(ga, keg, 0) Misc.Pause(dragTime) elif gs: Items.Move(gs, keg, 0) Misc.Pause(dragTime) elif gh: Items.Move(gh, keg, 0) Misc.Pause(dragTime) elif gc: Items.Move(gc, keg, 0) Misc.Pause(dragTime) def trainAlchy(): if Player.GetRealSkillValue('Alchemy') < 100: if Player.GetRealSkillValue('Alchemy') < 60: mortar = Items.FindByID(0x0E9B , -1 , Player.Backpack.Serial) Items.UseItem(mortar) Gumps.WaitForGump(0x38920abd, 1500) Gumps.SendAction(0x38920abd ,1) Gumps.WaitForGump(0x38920abd, 1500) Gumps.SendAction(0x38920abd ,9) Gumps.WaitForGump(0x38920abd, 1500) kegPots() elif Player.GetRealSkillValue('Alchemy') < 70: mortar = Items.FindByID(0x0E9B , -1 , Player.Backpack.Serial) Items.UseItem(mortar) Gumps.WaitForGump(0x38920abd, 1500) Gumps.SendAction(0x38920abd ,8) Gumps.WaitForGump(0x38920abd, 1500) Gumps.SendAction(0x38920abd ,9) Gumps.WaitForGump(0x38920abd, 1500) kegPots() elif Player.GetRealSkillValue('Alchemy') < 80: mortar = Items.FindByID(0x0E9B , -1 , Player.Backpack.Serial) Items.UseItem(mortar) Gumps.WaitForGump(0x38920abd, 1500) Gumps.SendAction(0x38920abd ,29) Gumps.WaitForGump(0x38920abd, 1500) Gumps.SendAction(0x38920abd ,9) Gumps.WaitForGump(0x38920abd, 1500) kegPots() elif Player.GetRealSkillValue('Alchemy') < 90: mortar = Items.FindByID(0x0E9B , -1 , Player.Backpack.Serial) Items.UseItem(mortar) Gumps.WaitForGump(0x38920abd, 1500) Gumps.SendAction(0x38920abd ,22) Gumps.WaitForGump(0x38920abd, 1500) Gumps.SendAction(0x38920abd ,9) Gumps.WaitForGump(0x38920abd, 1500) kegPots() elif Player.GetRealSkillValue('Alchemy') < 100: mortar = Items.FindByID(0x0E9B , -1 , Player.Backpack.Serial) Items.UseItem(mortar) Gumps.WaitForGump(0x38920abd, 1500) Gumps.SendAction(0x38920abd ,43) Gumps.WaitForGump(0x38920abd, 1500) Gumps.SendAction(0x38920abd ,9) Gumps.WaitForGump(0x38920abd, 3500) kegPots() def trainHide(): if not Timer.Check('hideTimer'): Player.UseSkill('Hiding') Timer.Create('hideTimer', 11000) elif Player.GetRealSkillValue('Hiding') == 100: if not Player.BuffsExist('Hidden'): Player.UseSkill('Hiding') def trainHealing(): if dummy == None: trainingDummy() if (Journal.Search('resurrect your patient.') or not Timer.Check('bandie')): Journal.Clear() bandage = Items.FindByID(0x0E21,-1,Player.Backpack.Serial) Items.UseItem(bandage) Target.WaitForTarget(10000, False) Target.TargetExecute(dummy) Timer.Create('bandie', 11000) def trainResist(): if dummy == None: trainingDummy() if not Timer.Check ('casttime')and Player.DistanceTo(dummy) < 12: Spells.CastMagery("Mana Vampire") Target.WaitForTarget(1500, False) Target.TargetExecute(dummy) Timer.Create('casttime', 3000) Player.SetWarMode(False) def equipBow(): #Misc.Pause( config.dragDelayMilliseconds ) if Player.GetRealSkillValue('Archery') > 80: player_bag = Items.FindBySerial(Player.Backpack.Serial) if not leftHand: for i in player_bag.Contains: if i.ItemID in bows: Player.EquipItem(i.Serial) Misc.Pause( 600 ) def trainAnat(): if dummy == None: trainingDummy() if Timer.Check('anat') == False: Player.UseSkill('Anatomy') Target.WaitForTarget(10000, False) Target.TargetExecute(dummy) Timer.Create('anat', 5000) def attkHealTarget(): if dummy == None: trainingDummy() if dummy.Hits < 25 and Misc.ReadSharedValue('bandageDone') == True: Items.UseItemByID(0x0E21, 0) Target.WaitForTarget(10000, False) Target.TargetExecute(dummy) Misc.Pause (500) if dummy.Hits < 10: Player.SetWarMode(False) while dummy.Hits < 25: Misc.Pause(100) Player.SetWarMode(True) Player.Attack(dummy) def BandageSelf(): if Misc.ReadSharedValue('bandageDone') == True: Items.UseItemByID(0x0E21, 0) Target.WaitForTarget(1500, False) Target.Self() Misc.Pause (500) Journal.Clear() while True: if Player.GetRealSkillValue('Healing') > 30 and (Player.Hits < 50 or Player.Poisoned): BandageSelf() if Player.GetRealSkillValue('Anatomy') > 30 and Player.GetRealSkillValue('Anatomy') < 100: trainAnat() if Player.GetRealSkillValue('Hiding') > 30 and Player.GetRealSkillValue('Hiding') < 100: trainHide() if Player.GetRealSkillValue('Healing') > 30 and Player.GetRealSkillValue('Healing') < 100: trainHealing() if Player.GetRealSkillValue('Alchemy') > 30 and Player.GetRealSkillValue('Alchemy') < 100: trainAlchy() Misc.Pause(100) if Target.HasTarget( ) == True: Target.Cancel() <file_sep>Player.ChatSay(5, "Forward Left One")<file_sep># Adding an extra 200 ms in case of latency issues hidingTimerMilliseconds = 10200 stealthTimerMilliseconds = 10200 Misc.SendMessage( 'Beginning Stealth training', 90 ) Timer.Create( 'hidingTimer', 1 ) Timer.Create( 'stealthTimer', 1 ) moveNorth = True # while skill can increase and player is not dead while Player.GetRealSkillValue( 'Stealth' ) < 80.0 and not Player.IsGhost: #Player.GetSkillCap( 'Stealth' ) if Player.GetSkillValue( 'Hiding' ) < 80.0: if not Timer.Check( 'hidingTimer' ): Player.UseSkill( 'Hiding' ) Timer.Create( 'hidingTimer', hidingTimerMilliseconds ) Timer.Create( 'stealthTimer', stealthTimerMilliseconds ) continue if not Player.BuffsExist( 'Hiding' ): if not Timer.Check( 'hidingTimer' ): Player.UseSkill( 'Hiding' ) Timer.Create( 'hidingTimer', hidingTimerMilliseconds ) Timer.Create( 'stealthTimer', stealthTimerMilliseconds ) elif Player.BuffsExist( 'Hiding' ) and not Timer.Check( 'stealthTimer' ): Player.UseSkill( 'Stealth' ) Timer.Create( 'stealthTimer', stealthTimerMilliseconds ) Timer.Create( 'hidingTimer', hidingTimerMilliseconds ) if Player.GetSkillValue( 'Stealth' ) > 40.0: # After skill reaches 50, start walking to trigger stealth more often for i in range( 0, 5 ): if moveNorth: Player.Walk( 'North' ) else: Player.Walk( 'South' ) Misc.Pause( 200 ) moveNorth = not moveNorth Misc.Pause( 500 ) # Pause to ease CPU usage Misc.Pause( 500 ) Misc.SendMessage( 'Stealth training complete!' ) <file_sep># Lightning Wand by MatsaMilla # equips and uses Lightning wand, then unequips after #[equip spellwand lightning wandType = "Lightning" wands = [0xdf5,0xdf3,0xdf4,0xdf2] msgColor = 33 dragTime = 600 import sys def getWands( itemID , container = Player.Backpack ): ''' Recursively looks through backpack for any wands in the wands list Returns a list with wand serials ''' # Create the list wandList = [] if isinstance( itemID, int ): # add wand serials to list for item in container.Contains: if item.ItemID == itemID: wandList.append(item.Serial) elif isinstance( itemID, list ): # add wand serials to list for item in container.Contains: if item.ItemID in itemID: wandList.append(item.Serial) else: raise ValueError( 'Unknown argument type for itemID passed to FindItem().', itemID, container ) subcontainers = [ item for item in container.Contains if item.IsContainer ] # Iterate through each item in the given list for subcontainer in subcontainers: wandsInSubContainer = getWands( itemID, subcontainer ) for i in wandsInSubContainer: wandList.append(i) return wandList def findAndEquipWand (wandType): wandsInPack = getWands( wands ) for i in wandsInPack: wand = Items.FindBySerial(i) Items.WaitForProps( wand, 500 ) propList = Items.GetPropStringList( wand ) charges = Items.GetPropValue(wand,"Charges") if any( wandType in s for s in propList ): Player.HeadMessage(78,"{} charges".format(int(charges))) #Misc.SendMessage(wandType + " found") Player.EquipItem( wand ) Misc.Pause( dragTime ) Items.UseItem( wand ) Target.WaitForTarget( 2500 ) while Target.HasTarget(): Misc.Pause( 50 ) Misc.Pause( dragTime ) Player.UnEquipItemByLayer('RightHand') sys.exit() Player.HeadMessage( msgColor, "No wands found!" ) def checkHands(wandType): leftHand = Player.GetItemOnLayer('LeftHand') rightHand = Player.GetItemOnLayer('RightHand') if leftHand: Misc.SendMessage('lefthand') Player.UnEquipItemByLayer('LeftHand') Misc.Pause( dragTime ) return False if rightHand: if rightHand.ItemID in wands: Items.WaitForProps(rightHand,500) propList = Items.GetPropStringList( rightHand ) charges = Items.GetPropValue(rightHand,"Charges") if any( wandType in s for s in propList ): Player.HeadMessage(78,"{} charges".format(int(charges))) Items.UseItem( rightHand ) Target.WaitForTarget( 2500 ) while Target.HasTarget(): Misc.Pause( 50 ) Misc.Pause( dragTime ) Player.UnEquipItemByLayer('RightHand') return True else: Player.UnEquipItemByLayer('RightHand') Misc.Pause( dragTime ) return False if checkHands(wandType): Misc.NoOperation() else: findAndEquipWand (wandType) <file_sep># Target Closest, Attack and DROP Target on nearest target # aka sallos target aquire # by MatsaMilla & contributions by <NAME> # Last Update: 8/2/21 from System.Collections.Generic import List from System import Byte import sys # true to attack, false will only set as last target attack = True # true for humanoid only, false excludes humaniods humanoid = True # true to also target red targets. (I keep false to not auto target bosses) redTargets = True # true to send target message to party sendMessage = False # true to display target overhead & over mobile displayTarget = False # range at which target will aquire targetRange = 12 # filter def find(notoriety, humanoid): fil = Mobiles.Filter() fil.Enabled = True fil.RangeMax = targetRange fil.IsHuman = humanoid fil.IsGhost = False fil.Friend = False fil.Notorieties = List[Byte](bytes(notoriety)) list = Mobiles.ApplyFilter(fil) return list # Possible Selections: # 1 blue, 2 green, 3 grey, 4 grey(agro), 5 orange, 6 red, 7 invul # Random, Nearest,Farthest, Weakest, Strongest, Next # if your toon is blue, green, or gray or militia if (Player.Notoriety == 1 or Player.Notoriety == 2 or Player.Notoriety == 3 or Player.Notoriety == 4): greyMobile = Mobiles.Select(find([3,4],humanoid),'Nearest',) orangeMobile = Mobiles.Select(find([5],humanoid),'Nearest') if redTargets: redMobile = Mobiles.Select(find([6],humanoid),'Nearest') else: redMobile = None if orangeMobile: if sendMessage: Player.ChatParty('Changing last target to ' + orangeMobile.Name) Target.SetLast(orangeMobile) Target.TargetExecute(orangeMobile) if attack: Player.Attack(orangeMobile) if displayTarget: Player.HeadMessage(47, "Target: " + orangeMobile.Name) Mobiles.Message(orangeMobile, 15, "*Target*") elif redMobile: if sendMessage: Player.ChatParty('Changing last target to ' + redMobile.Name) Target.SetLast(redMobile) Target.TargetExecute(redMobile) if attack: Player.Attack(redMobile) if displayTarget: Player.HeadMessage(33, "Target: " + redMobile.Name) Mobiles.Message(redMobile, 15, "*Target*") elif greyMobile: if sendMessage: Player.ChatParty('Changing last target to ' + greyMobile.Name) Target.SetLast(greyMobile) Target.TargetExecute(greyMobile) if attack: Player.Attack(greyMobile) if displayTarget: Player.HeadMessage(902, "Target: " + greyMobile.Name) Mobiles.Message(greyMobile, 15, "*Target*") else: Misc.SendMessage('No Targets', 33) # if your toon is red elif Player.Notoriety == 6: blueMobile = Mobiles.Select(find([1],humanoid),'Nearest') greyMobile = Mobiles.Select(find([3,4],humanoid),'Nearest') orangeMobile = Mobiles.Select(find([5],humanoid),'Nearest') if redTargets: redMobile = Mobiles.Select(find([6],humanoid),'Nearest') else: redMobile = None if blueMobile: if sendMessage: Player.ChatParty('Changing last target to ' + blueMobile.Name) Target.SetLast(blueMobile) Target.TargetExecute(blueMobile) if attack: Player.Attack(blueMobile) if displayTarget: Player.HeadMessage(1266, "Target: " + blueMobile.Name) Mobiles.Message(blueMobile, 15, "*Target*") elif greyMobile: if sendMessage: Player.ChatParty('Changing last target to ' + greyMobile.Name) Target.SetLast(greyMobile) Target.TargetExecute(greyMobile) if attack: Player.Attack(greyMobile) if displayTarget: Player.HeadMessage(902, "Target: " + greyMobile.Name) Mobiles.Message(greyMobile, 15, "*Target*") elif orangeMobile: if sendMessage: Player.ChatParty('Changing last target to ' + orangeMobile.Name) Target.SetLast(orangeMobile) Target.TargetExecute(orangeMobile) if attack: Player.Attack(orangeMobile) if displayTarget: Player.HeadMessage(47, "Target: " + orangeMobile.Name) Mobiles.Message(orangeMobile, 15, "*Target*") elif redMobile: if sendMessage: Player.ChatParty('Changing last target to ' + redMobile.Name) Target.SetLast(redMobile) Target.TargetExecute(redMobile) if attack: Player.Attack(redMobile) if displayTarget: Player.HeadMessage(33, "Target: " + redMobile.Name) Mobiles.Message(redMobile, 15, "*Target*") else: Misc.SendMessage('No Targets', 33)<file_sep># Use this to cast Mana Vampire on someone (or yourself) until you run out of regs. # By MatsaMilla #---------------------------------------------------- training = Target.PromptTarget("Target training dummy") dummy = Mobiles.FindBySerial(training) bows = [0x13B2,0x26C2,0x0F50,0x13FD] leftHand = Player.GetItemOnLayer('LeftHand') import sys def equipBow(): #Misc.Pause( config.dragDelayMilliseconds ) if Player.GetRealSkillValue('Archery') > 80: player_bag = Items.FindBySerial(Player.Backpack.Serial) if not leftHand: for i in player_bag.Contains: if i.ItemID in bows: Player.EquipItem(i.Serial) Misc.Pause( 600 ) while True: dummy = Mobiles.FindBySerial(training) if Player.DistanceTo(dummy) < 12: Player.SetWarMode(False) Spells.CastMagery("Mana Vampire") Target.WaitForTarget(1500, False) Target.TargetExecute(dummy) Player.SetWarMode(True) Player.SetWarMode(False) Misc.Pause(2500) Player.SetWarMode(False) if Player.Mana < 40: Player.UseSkill('Meditation') while Player.Mana < Player.ManaMax: if not Player.BuffsExist('Meditation') and Timer.Check('med') == False: Misc.Pause(2000) Player.UseSkill('Meditation') Timer.Create('med', 7000) Misc.Pause(100) if Items.BackpackCount( 0x0F8D, -1) < 1: sys.exit() if Journal.Search('Did it, got it') == 50: sys.exit() <file_sep># This will use a moongate within 2 tiles, and accept the gump if there is one. # By MatsaMilla, updated 4/25/20 # must import list to use it in the filters from System.Collections.Generic import List # Items filter for finding moongate gate = Items.Filter() gate.Enabled = True gate.OnGround = True gate.Movable = False gate.RangeMax = 1 gate.Graphics = List[int]( [ 0x0F6C ] ) moongate = Items.ApplyFilter(gate) # if a moongate is found, continue if moongate: # select the nearest item from list m = Items.Select( moongate , 'Nearest' ) # Double click on the moongate found Items.UseItem(m) # wait for gump pop up Gumps.WaitForGump(3716879466, 1500) # click yes Gumps.SendAction(3716879466, 1) else: # if not gates in range send message Misc.SendMessage('No Gate In Range',33) <file_sep>from System.Collections.Generic import List import sys # Empty Potion Keg Maker by MatsaMilla Version 1.1 # Target restock container, then container for empty potion kegs # will make as many as maxToMake, or until mats run out maxToMake = 120 journalPause = 120 dragTime = 600 kegGump1 = 15 kegGump2 = 163 lidGump1 = 1 lidGump2 = 9 stavesGump1 = 1 stavesGump2 = 2 hoopGump1 = 15 hoopGump2 = 37 barrelTap1 = 15 barrelTap2 = 16 potionKegGump1 = 43 potionKegGump2 = 44 tinkKitGump1 = 8 tinkKigGump2 = 23 sawGump1 = 8 sawGump2 = 51 ignot = 0x1BF2 wood = 0x1BD7 tink = 0x1EB8 saw = 0x1034 bottle = 0x0F0E hoop = 0x1DB7 stave = 0x1EB1 lid = 0x1DB8 tap = 0x1004 def tinkCraft (gump1, gump2): Gumps.CloseGump(949095101) currentTink = FindItem(tink,Player.Backpack) if Gumps.CurrentGump() != 949095101: Items.UseItem(currentTink) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, gump1) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, gump2) Gumps.WaitForGump(949095101, 1500) Misc.Pause(journalPause) def carpCraft (gump1, gump2): Gumps.CloseGump(949095101) currentsaw = FindItem(saw,Player.Backpack) if Gumps.CurrentGump() != 949095101: Items.UseItem(currentsaw) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, gump1) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, gump2) Gumps.WaitForGump(949095101, 1500) Misc.Pause(journalPause) def craftKegs(i): for i in range( 0, i ): craftKeg() def craftKeg(): checkMats () while Items.BackpackCount(stave,-1) < 3: carpCraft(stavesGump1, stavesGump2) checkMats () while Items.BackpackCount(lid,-1) < 2: carpCraft(lidGump1, lidGump2) checkMats () if Items.BackpackCount(hoop,-1) < 1: tinkCraft(hoopGump1, hoopGump2) checkMats () if Items.BackpackCount(tap,-1) < 1: tinkCraft(barrelTap1, barrelTap2) checkMats () carpCraft(kegGump1, kegGump2) checkMats () tinkCraft(potionKegGump1, potionKegGump2) moveKegs(potionKegContainer) def restock(container): restockWood = FindItem(wood, container,0x0000) if Items.BackpackCount(wood, -1) < 19: if restockWood: Items.Move(restockWood, Player.Backpack, 500) Misc.Pause(dragTime) restockIgnots = FindItem(ignot, container) if Items.BackpackCount(ignot, -1) < 10: if restockIgnots: Items.Move(restockIgnots, Player.Backpack, 100) Misc.Pause(dragTime) restockBottle = FindItem(bottle, container) if Items.BackpackCount(bottle, -1) < 10: if restockBottle: Items.Move(restockBottle, Player.Backpack, 100) Misc.Pause(dragTime) def moveKegs(container): potionKeg = FindItem(0x1940, Player.Backpack) while potionKeg: Items.Move(potionKeg, container, 0) Misc.Pause(dragTime) potionKeg = FindItem(0x1940, Player.Backpack) if Journal.Search('That container cannot hold more weight.'): Player.HeadMessage(33, 'Potion container full, stopping') sys.exit() def checkMats (): # Stop if low on iron if Items.BackpackCount(ignot, -1) < 10: restock(restockContainer) Misc.Pause(journalPause) if Items.BackpackCount(ignot, -1) < 10: Misc.SendMessage('Out of Ignots',33) sys.exit() # Stop if low on wood if Items.BackpackCount(wood, -1) < 19: restock(restockContainer) Misc.Pause(journalPause) if Items.BackpackCount(wood, -1) < 19: Misc.SendMessage('Out of Wood',33) sys.exit() # Stop if low on bottles if Items.BackpackCount(bottle, -1) < 10: restock(restockContainer) Misc.Pause(journalPause) if Items.BackpackCount(bottle, -1) < 10: Misc.SendMessage('Out of Bottles',33) sys.exit() # always have 2 tinker kits if Items.BackpackCount(tink, -1) < 2: tinkCraft (tinkKitGump1, tinkKigGump2) # craft saw if Items.BackpackCount(saw, -1) < 1: tinkCraft (sawGump1, sawGump2) def FindItem( itemID, container, color = -1, ignoreContainer = [] ): ''' Searches through the container for the item IDs specified and returns the first one found Also searches through any subcontainers, which Misc.FindByID() does not ''' ignoreColor = False if color == -1: ignoreColor = True if isinstance( itemID, int ): foundItem = next( ( item for item in container.Contains if ( item.ItemID == itemID and ( ignoreColor or item.Hue == color ) ) ), None ) elif isinstance( itemID, list ): foundItem = next( ( item for item in container.Contains if ( item.ItemID in itemID and ( ignoreColor or item.Hue == color ) ) ), None ) else: raise ValueError( 'Unknown argument type for itemID passed to FindItem().', itemID, container ) if foundItem != None: return foundItem subcontainers = [ item for item in container.Contains if ( item.IsContainer and not item.Serial in ignoreContainer ) ] for subcontainer in subcontainers: foundItem = FindItem( itemID, subcontainer, color, ignoreContainer ) if foundItem != None: return foundItem restockContainer = Items.FindBySerial( Target.PromptTarget('Target Restock Container') ) potionKegContainer = Items.FindBySerial( Target.PromptTarget('Target Bag for Potion Kegs')) Items.UseItem(restockContainer) Misc.Pause(dragTime) Journal.Clear() craftKegs(maxToMake) <file_sep>''' Author: TheWarDoctor95 Other Contributors: Last Contribution By: MatsaMilla - May 22, 2020 Description: Uses the instruments from the player's backpack to train Musicianship to GM ''' musichianshipTimerMilliseconds = 6500 def FindItem( itemsToLookFor, items ): ''' Recursively looks through a container for any items in the provided list Returns the first item found from the list ''' # Iterate through each item in the given list for item in items: if item.ItemID in itemsToLookFor: return item elif item.IsContainer: # If the list of items contains a container, look in that container for the item too itemToReturn = FindItem( itemsToLookFor, item.Contains ) if itemToReturn != None: return itemToReturn return None def FindInstrument(): ''' Uses FindItem to find an instrument in the player's backpack Returns the first instrument found ''' instruments = [ 0xe9c, # Drum 0x2805, # Flute 0xeb3, # Lute # Harps 0xeb2, # Lap Harp 0xeb1, # Standing Harp # Tambourines 0xe9e, # Tambourine 0xe9d # Tambourine with red tassle ] instrument = FindItem( instruments, Player.Backpack.Contains ) return instrument def TrainMusicianship(): ''' Trains Musicianship by using the instruments in the player's bag Transitions to a new instrument if the one being used runs out of uses ''' global instrument global musichianshipTimerMilliseconds Misc.SendMessage( 'Training with: %s' % instrument ) Items.UseItem( instrument ) Timer.Create( 'musichianshipTimer', musichianshipTimerMilliseconds ) while instrument != None and Player.GetSkillValue( 'Musicianship' ) < 100 and not Player.IsGhost: if not Timer.Check( 'musichianshipTimer' ): Items.UseItem( instrument ) Timer.Create( 'musichianshipTimer', musichianshipTimerMilliseconds ) instrument = Items.FindBySerial( instrument.Serial ) if instrument == None: # Our instrument broke, we need to find a new one if possible instrument = FindInstrument() if instrument != None: Misc.SendMessage( 'Training with: %s' % instrument ) if instrument == None: Misc.SendMessage( 'Ran out of instruments to train with', 1100 ) instrument = FindInstrument() if instrument == None: Player.HeadMessage( 1100, 'No instrument found' ) else: TrainMusicianship() <file_sep># train meditation to GM by Mastamilla # purchase magical wizard hat from mage shop #check backpack for wizard hat wizardHat = Items.FindByID( 0x1718 , -1 , Player.Backpack.Serial ) # not in pack? Check head layer if not wizardHat: wizardHat = Player.GetItemOnLayer('Head') # hat found if wizardHat: #loop until GM while Player.GetRealSkillValue("Meditation") < 100: if Player.Mana >= Player.ManaMax: Items.Move(wizardHat, Player.Backpack.Serial, 0) Misc.Pause(2000) Player.EquipItem(wizardHat) Misc.Pause(600) # no hat found else: Player.HeadMessage(33,'No wizard hat found.') <file_sep># Sort selected runebook alphabetically # By MatsaMilla # must have ToolTips enabled # don't have any other runes in back, bag them before starting runebook = Items.FindBySerial(Target.PromptTarget('target book')) runelist = [] def GetNamesOfRunesInBook( runebook ): Items.UseItem( runebook ) # Pause here since the next part goes pretty quick Misc.Pause( 600 ) Gumps.WaitForGump( 1431013363, 5000 ) while Gumps.CurrentGump() != 1431013363: Player.HeadMessage( 33, 'Too far from runebook to copy, please move closer.' ) Misc.Pause( 1000 ) Items.UseItem( runebook ) Gumps.WaitForGump( 1431013363, 5000 ) runeNames = [] lineList = Gumps.LastGumpGetLineList() # Remove the default 3 lines from the top of the list lineList = lineList[ 3 : ] # Remove the items before the names of the runes endIndexOfDropAndDefault = 0 for i in range( 0, len( lineList ) ): if lineList[ i ] == 'Set default' or lineList[ i ] == 'Drop rune': endIndexOfDropAndDefault += 1 else: break # Add two for the charge count and max charge numbers endIndexOfDropAndDefault += 2 runeNames = lineList[ endIndexOfDropAndDefault : ( endIndexOfDropAndDefault + 16 ) ] runeNames = [ name for name in runeNames if name != 'Empty' ] return runeNames def GetNumberOfRunesInBook( runebook ): return len( GetNamesOfRunesInBook( runebook ) ) def dropRunes(): numberOfRunesInBook = GetNumberOfRunesInBook( runebook ) +1 Items.UseItem(runebook) for i in range( 0 , numberOfRunesInBook): # drop runebook runes #Items.UseItem(runebook) Gumps.WaitForGump(1431013363, 1000) Gumps.SendAction(1431013363, 3) Misc.Pause(600) Gumps.WaitForGump(1431013363, 1000) Gumps.SendAction(1431013363, 0) def getSortKey(list): return list[0] def compileRunes(): for i in Player.Backpack.Contains: if i.ItemID == 0x1F14: Items.WaitForProps(i, 1000) runeName = Items.GetPropStringByIndex(i, 0) if runeName: #Misc.SendMessage(runeName) runelist.append((runeName,i.Serial)) #Misc.Pause(200) #Misc.SendMessage('____', 33) runelist.sort(key=getSortKey) for l in runelist: Items.Move(l[1], runebook.Serial, 0) #Misc.SendMessage(l[0]) Misc.Pause(600) dropRunes() compileRunes() <file_sep># Automatic Potion Butler Filler by MatsaMilla # - Version 3, updated 4/10/21 - Can fill if not Owner or CoOwner of house # NEED: Restock Chest (containing BARBED leather / tailor kits (or ignots if you have tinkering)) # False if not owner or co-owned to house houseOwner = True #*******************************************************************# Player.HeadMessage(66,'Target Butler') butler = Target.PromptTarget('Target Butler') Player.HeadMessage(66,'Target Restock Chest') restockChest = Items.FindBySerial( Target.PromptTarget('Target Restock Chest') ) fillStopNumber = 50 dragTime = 800 butlerGump = 989312372 import sys def setValues( armorValue , gump ): global armorID global gumpAction armorID = armorValue gumpAction = gump def FindItem( itemID, container, color = -1, ignoreContainer = [] ): ''' Searches through the container for the item IDs specified and returns the first one found Also searches through any subcontainers, which Misc.FindByID() does not ''' ignoreColor = False if color == -1: ignoreColor = True if isinstance( itemID, int ): foundItem = next( ( item for item in container.Contains if ( item.ItemID == itemID and ( ignoreColor or item.Hue == color ) ) ), None ) elif isinstance( itemID, list ): foundItem = next( ( item for item in container.Contains if ( item.ItemID in itemID and ( ignoreColor or item.Hue == color ) ) ), None ) else: raise ValueError( 'Unknown argument type for itemID passed to FindItem().', itemID, container ) if foundItem != None: return foundItem subcontainers = [ item for item in container.Contains if ( item.IsContainer and not item.Serial in ignoreContainer ) ] for subcontainer in subcontainers: foundItem = FindItem( itemID, subcontainer, color, ignoreContainer ) if foundItem != None: return foundItem def craftArmor(armor, amount): sewKit = FindItem( 0x0F9D , Player.Backpack ) if not sewKit: restock() if armor == 'cap': setValues( 0x1DB9 , 9 ) elif armor == 'gorget': setValues( 0x13C7 , 2) elif armor == 'arms': setValues( 0x13CD , 23 ) elif armor == 'gloves': setValues( 0x13C6 , 16 ) elif armor == 'chest': setValues( 0x13CC , 37 ) elif armor == 'legs': setValues( 0x13CB , 30 ) else: Misc.SendMessage('potType not defined, stopping', 33) sys.exit() while amount > 0: worldSave() restock() if Gumps.CurrentGump() != 949095101: sewKit = FindItem( 0x0F9D , Player.Backpack ) Items.UseItem(sewKit) Gumps.WaitForGump(949095101, dragTime) # change to barbed Gumps.WaitForGump(949095101, dragTime) Gumps.SendAction(949095101, 7) Gumps.WaitForGump(949095101, dragTime) Gumps.SendAction(949095101, 27) Gumps.WaitForGump(949095101, dragTime) Gumps.SendAction(949095101, 36) Gumps.WaitForGump(949095101, dragTime) Gumps.SendAction(949095101, gumpAction) Gumps.WaitForGump(949095101, dragTime) Misc.Pause(200) restock() # move crafted armor to butler craftedArmor = FindItem( armorID , Player.Backpack) while craftedArmor: Items.Move(craftedArmor, butler, 0) Misc.Pause(dragTime) craftedArmor = FindItem( armorID , Player.Backpack) amount = amount - 1 if amount < 1: break if amount < 1: break def restock(): leather = FindItem( 0x1081 , Player.Backpack, 0x059d ) if not leather or leather.Amount < 12: leatherRestock = FindItem( 0x1081 , restockChest, 0x059d) if leatherRestock: Items.Move( leatherRestock , Player.Backpack , 200 ) Misc.Pause(dragTime) else: Misc.SendMessage( 'No more leather' , 33 ) sys.exit() sewKit = FindItem( 0x0F9D , Player.Backpack ) if sewKit == None: if Player.GetRealSkillValue('Tinkering') > 80: tinkTool = FindItem( 0x1EB8 , Player.Backpack ) if tinkTool: Items.UseItem(tinkTool) Gumps.WaitForGump(949095101, dragTime) Gumps.SendAction(949095101, 8) Gumps.WaitForGump(949095101, dragTime) Gumps.SendAction(949095101, 44) Gumps.WaitForGump(949095101, dragTime) Misc.Pause(200) Gumps.CloseGump(949095101) else: restockSewKit = FindItem( 0x0F9D , restockChest ) if restockSewKit: Items.Move( restockSewKit , Player.Backpack , 200 ) Misc.Pause(dragTime) else: Misc.SendMessage( 'No more sewing kits' , 33 ) sys.exit() def worldSave(): if Journal.SearchByType('The world is saving, please wait.', 'Regular' ): Misc.SendMessage('Pausing for world save', 33) while not Journal.SearchByType('World save complete.', 'Regular'): Misc.Pause(1000) Misc.SendMessage('Continuing', 33) Journal.Clear() Journal.Clear() Misc.Pause(1000) Mobiles.UseMobile(butler) Misc.Pause(1000) if houseOwner: fillList = [('cap',4),('gorget',5),('arms',6),('gloves',7),('chest',8),('legs',9)] else: fillList = [('cap',5),('gorget',7),('arms',9),('gloves',11),('chest',13),('legs',15)] while True: # verify its butler gump if Gumps.CurrentGump() == butlerGump: # iterate through fillList for i in fillList: # read gump line fillNumber = fillStopNumber - int(float(Gumps.LastGumpGetLine(i[1]))) while fillNumber > 0: #int(float(Gumps.LastGumpGetLine(i[1]))) < fillStopNumber: if Gumps.CurrentGump() == butlerGump: Gumps.CloseGump(butlerGump) Misc.SendMessage('Filling ' + str(i[0])+ ', ' + str(fillNumber) + ' left', 66) Misc.Pause(dragTime) craftArmor (i[0], fillNumber) Mobiles.UseMobile(butler) Misc.Pause(dragTime) fillNumber = fillStopNumber - int(float(Gumps.LastGumpGetLine(i[1]))) Misc.SendMessage('Butler is as full as we can get it!', 66) Gumps.CloseGump(butlerGump) sys.exit() else: Mobiles.UseMobile(butler) Misc.Pause(dragTime) <file_sep># Simple mount macro by MatsaMilla # must set mount every time Enhanced is opened, on each toon on account if needed if Misc.CheckSharedValue('mount'+ str(Player.Serial)): mountSerial = Misc.ReadSharedValue('mount'+ str(Player.Serial)) else: mountSerial = None if Player.Mount: Mobiles.UseMobile(Player.Serial) else: if mountSerial != None: mount = Mobiles.FindBySerial(mountSerial) while Player.DistanceTo(mount) > 1: if Timer.Check('MountTimer') == False: Player.ChatSay(66, mount.Name + ' Come') Timer.Create('MountTimer', 500) Misc.Pause(50) Mobiles.UseMobile(mount) else: Player.HeadMessage(66,"Target Mount") mountSerial = Target.PromptTarget("Target Mount",33) mount = Mobiles.FindBySerial( mountSerial ) if mount: Misc.SetSharedValue('mount'+ str(Player.Serial),mountSerial) while Player.DistanceTo(mount) > 1: if Timer.Check('MountTimer') == False: Player.ChatSay(66, mount.Name + ' Come') Timer.Create('MountTimer', 500) Misc.Pause(50) Mobiles.UseMobile(mount) else: Player.HeadMessage(33, 'Not Valid') <file_sep>setTarget = Mobiles.FindBySerial( Target.PromptTarget() ) msgColor = 1 if setTarget: Target.SetLast(setTarget.Serial) Player.ChatParty('Changing last target to ' + setTarget.Name) if setTarget.Notoriety == 1: msgColor = 1266 #blue elif setTarget.Notoriety == 2: msgColor = 77 #green elif setTarget.Notoriety == 3 or setTarget.Notoriety == 4: msgColor = 902 #grey elif setTarget.Notoriety == 5: msgColor = 47 #orange elif setTarget.Notoriety == 6: msgColor = 33 #red Mobiles.Message( setTarget, 15 , '*Target*' ) Player.HeadMessage( msgColor , 'Target: ' + setTarget.Name )<file_sep>Player.ChatSay(5, "Left")<file_sep>Player.ChatSay(5, "Stop")<file_sep># ItemID GM # Targets dagger in bag until GM ItemID # By MatsaMilla def hide(): if Player.GetRealSkillValue('Hiding') > 50: if Timer.Check('skill' + Player.Name) == False and not Player.BuffsExist('Hiding'): Player.UseSkill('Hiding') Timer.Create('skill' + Player.Name,11000) def itemID(): if Timer.Check('skill' + Player.Name) == False and Player.BuffsExist('Hiding'): dagger = Items.FindByID( 0x0F52 , -1 , Player.Backpack.Serial ) Player.UseSkill( "Item ID" ) Target.WaitForTarget( 10000 , True ) Target.TargetExecute( dagger ) Timer.Create('skill' + Player.Name,1000) while Player.GetRealSkillValue( "Item ID" ) < 100: itemID() hide() <file_sep># Craft Summon Water Elemental Scrolls, by MatsaMilla # - updated 3/10/22 # Put all crafting materials in a secured chest in your house, then target it. # it will make as many as it can from the materials in the chest. Player.HeadMessage(66,'Target the OPENED Restock Chest') restockChest = Target.PromptTarget() dragTime = 600 bp = 0x0F7A bm = 0x0F7B mr = 0x0F86 ss = 0x0F8D scroll = 0x0EF3 waterScroll = 0x1F6C import sys if Player.GetRealSkillValue('Inscription') < 100: Player.HeadMessage(33,"Wait, you arent even GM scribe? Git Gud") sys.exit() def craftWaterEle(): if not Gumps.CurrentGump() == 949095101: pen = Items.FindByID(0x0FBF,-1,Player.Backpack.Serial) if pen: Items.UseItem(pen) else: restock() Gumps.WaitForGump(949095101, 2000) Gumps.SendAction(949095101, 50) Gumps.WaitForGump(949095101, 2000) Gumps.SendAction(949095101, 51) Gumps.WaitForGump(949095101, 5000) # mana check if Player.Mana < 50: Player.UseSkill('Meditation') # dont do anything until full mana while Player.Mana < Player.ManaMax: Misc.Pause(100) def unload(): if Items.BackpackCount(waterScroll,-1) > 100: elescrolls = Items.FindByID(waterScroll, -1, Player.Backpack.Serial) if elescrolls: Items.Move(elescrolls, restockChest, 0) Misc.Pause(dragTime) def restock(): # restock pen, stop if out if Items.BackpackCount(0x0FBF, -1) < 1: restockPen = Items.FindByID (0x0FBF ,-1,restockChest, True) if restockPen: Items.Move(restockPen,Player.Backpack.Serial,1) Misc.Pause(dragTime) else: Player.HeadMessage(33,'Out of pens') sys.exit() # restock scrolls, stop if out if Items.BackpackCount(scroll, -1) < 1: scrolls = Items.FindByID (scroll ,-1,restockChest, True) if scrolls: Items.Move(scrolls, Player.Backpack.Serial, 100) Misc.Pause(dragTime) else: Player.HeadMessage(33,'Out of blank scrolls') sys.exit() # restock silk, stop if out if Items.BackpackCount(ss, -1) < 1: silk = Items.FindByID (ss ,-1,restockChest, True) if silk: Items.Move(silk, Player.Backpack.Serial, 100) Misc.Pause(dragTime) else: Player.HeadMessage(33,'Out of silk') sys.exit() # restock moss, stop if out if Items.BackpackCount(bm, -1) < 1: bloodmoss = Items.FindByID (bm ,-1,restockChest, True) if bloodmoss: Items.Move(bloodmoss, Player.Backpack.Serial, 100) Misc.Pause(dragTime) else: Player.HeadMessage(33,'Out of blood moss') sys.exit() # restock root, stop if out if Items.BackpackCount(mr, -1) < 1: root = Items.FindByID (mr ,-1,restockChest, True) if root: Items.Move(root, Player.Backpack.Serial, 100) Misc.Pause(dragTime) else: Player.HeadMessage(33,'Out of mandrake root') sys.exit() unload() unload() while True: restock() craftWaterEle() <file_sep>Player.ChatSay(5, "Turn Left")<file_sep># Trap Box Maker by MatsaMilla # make sure to have plenty of wood and some ignots on crafter # place as many explostion pots on crafter as boxes you want to make from System.Collections.Generic import List type = 2 # 2 for box, 9 for crate dragTime = 600 saw = 0x1034 tink = 0x1EB8 wood = 0x1BD7 ignot = 0x1BF2 expPot = 0x0F0D amountToMake = Items.BackpackCount(expPot, -1) trapBox = [0x9aa,0x9a9,0xe3e,0xe3c,0xe42,0xe43,0x280b,0xe7d,0xe7e,0xe3f,0xe3d,0x280c] def craftTools(): currentTink = Items.FindByID(tink, -1, -1) if Items.BackpackCount(ignot, -1) < 10: Misc.SendMessage('Out of Ignots',33) winsound.PlaySound(error, winsound.SND_FILENAME) sys.exit() if Items.BackpackCount(tink, -1) < 2: Items.UseItem(currentTink.Serial) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, 8) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, 23) if Items.BackpackCount(saw, -1) < 1: Items.UseItem(currentTink.Serial) Gumps.WaitForGump(949095101,1500) Gumps.SendAction(949095101, 8) Gumps.WaitForGump(949095101,1500) Gumps.SendAction(949095101, 51) Gumps.CloseGump(949095101) # 2 for box, 9 for crate def craftBox(amount, type): i = 0 while i < amount: currentSaw = Items.FindByID(saw, -1, -1) if currentSaw: if Gumps.CurrentGump != 949095101: Items.UseItem(currentSaw) Gumps.WaitForGump(949095101, 3000) Gumps.SendAction(949095101, 15) Gumps.WaitForGump(949095101, 3000) Gumps.SendAction(949095101, type) Gumps.WaitForGump(949095101, 3000) i = i + 1 else: craftTools() Gumps.CloseGump(949095101) # trap def trapBoxes(): trapList = [] for i in Player.Backpack.Contains: if i.ItemID in trapBox: trapList.append( i.Serial ) for t in trapList: currentTink = Items.FindByID( tink , -1 , -1 ) if currentTink: if Gumps.CurrentGump != 949095101: Items.UseItem(currentTink) Gumps.WaitForGump(949095101, 3000) Gumps.SendAction(949095101, 50) Gumps.WaitForGump(949095101, 3000) Gumps.SendAction(949095101, 16) Target.WaitForTarget(8000, False) Target.TargetExecute(t) craftBox(amountToMake, type) trapBoxes() <file_sep>while not Player.IsGhost: Player.ChatSay(5, "Scan The Horizons") Misc.Pause(12500)<file_sep>Player.ChatSay(5, "Fire Right")<file_sep>while Player.GetRealSkillValue('Tracking') < 100: Player.UseSkill("Tracking") Gumps.WaitForGump(2976808305, 10000) Gumps.SendAction(2976808305, 4) Misc.Pause(500) Gumps.CloseGump(993494147) Misc.Pause(10500) <file_sep># This script relys on Bandage_Timer.py, if you do not have it, it will not work # Add the serials of pets you want to heal to the petList from System.Collections.Generic import List from System import Byte import sys #Pet list you can add to it by putting the Serial of the pet in the list. petList = [ 0x00120786,# Winged Snek 0x003FAA39,# Kuzco 0x00049A23,# Water Wyrm 0x0016D74B,# Pacha 0x001BF91B,# Matsa- Mare 0x0028E693,# Crab 0x000A1896,# Spida 0x000263C0,# aragog - getold 0x0014E207,# chicken test 0x0011DB49,# roddy piper - donovan wolf 0x000600B6,# TJ 0x00190593,# gizmo - Draven 0x001FA4BC,# rando mare ] # quits if you have less than 80 HP if Player.GetRealSkillValue('Veterinary') < 80: Misc.SendMessage('Not enough vet skill, stopping',33) sys.exit() healing = None while True: init = 0 plist = [] for i in petList: healPet = Mobiles.FindBySerial(i) if healPet: if healPet.Hits != int(0) and Player.InRangeMobile(healPet, int(1.5)): plist.append(healPet.Serial) for j in plist: if init == 0: healing = Mobiles.FindBySerial(j) init = 1 healPet = Mobiles.FindBySerial(j) if healPet: if healPet.Hits <= healing.Hits or healPet.Poisoned: healing = Mobiles.FindBySerial(healPet.Serial) if healing: pet2Heal = Mobiles.FindBySerial(healing.Serial) if pet2Heal: if (pet2Heal.Hits < int(23) or pet2Heal.Poisoned) and Player.InRangeMobile(pet2Heal, int(1.5)): if Misc.ReadSharedValue('bandageDone') == True and Player.Visible: prevTarget = Target.Last() if Target.HasTarget( ) == False: Misc.SendMessage("Healing " + pet2Heal.Name, 33) Items.UseItemByID(0x0E21, -1) Target.WaitForTarget(1500) Target.TargetExecute(pet2Heal) Misc.Pause(600) Misc.Pause(10) <file_sep>Player.ChatSay(5, "Back Right One")<file_sep>if not Target.HasTarget(): if Player.Poisoned: Spells.CastMagery('Cure') Target.WaitForTarget(1500) Target.Self() else: Spells.CastMagery('Heal') Target.WaitForTarget(1500) Target.Self() <file_sep>#para pouch popper if Player.Paralized: Player.ChatSay (20, "[pouch") pouch = Items.FindByID( 0x0E79 , 0x0489 , Player.Backpack.Serial ) if pouch: Items.WaitForProps(pouch, 500) Misc.Pause(120) charges = Items.GetPropValue(pouch, 'Charges') if charges > 0: Player.HeadMessage(0x0489,"{} charges".format(int(charges))) <file_sep># Simple script to attack a target from a list and set it to last target # Set up a targeting filter on the Targeting tab named enemy, example here https://imgur.com/a/f9rvEPe # The example above will target the nearest grey non humanoid non friended mob within 12 tiles. # set enemy variable from the targeting list 'enemy' enemy = Target.GetTargetFromList('enemy') # check if there is an enemy, if there is continue if enemy: Player.ChatSay(44,"All Kill") Target.WaitForTarget(1500) # this will target the enemy variable obtained from the list in the first line Target.TargetExecute(enemy) # if no enemies, alert the player with a head message else: Player.HeadMessage(44,"No Enemies") <file_sep># Move big item to trap box & announce in party what drop is by MatsaMilla # if key is in box, key gets locked in box... # version 2.2 - fixed if you get drop after locked #standard imports from System.Collections.Generic import List from System import Byte import sys lockBoxAfterDrop = True # will not box item if serial in this list, like blessed relics ignoreSerials = [0x402E5274] # delay for login Misc.Pause(2500) msgColor = 66 dragtime = 600 backpack = Items.FindBySerial(Player.Backpack.Serial) key = 0x100E box = False #dragon egg eggList = [0x2a7c,0x47E6] #meta relics relicsList = [0x2AA4] #power scrolls ps = 0x14F0 #skulls skullList = [0x1AE1] #crystals crystalsList = [ 0x35DA, #event crystal 0x0F21, #portal frag ] perks = [ 0x2dd5,0x1f18,0x2da3,0x166e,0x26BB,0x139B,0x0FBE ] # only boxes tame SSs, blaze color ss = [ 0x2260 ] #box types trapBox = [0x9aa,0x9a9,0xe3e,0xe3c,0xe42,0xe43,0x280b,0xe7d,0xe7e,0xe3f,0xe3d,0x280c] for b in backpack.Contains: if b.ItemID in trapBox: box = b Player.HeadMessage(msgColor, 'Trap Box Set to ' + box.Name) break moveList = [] def dropWatch(): for i in backpack.Contains: if i.ItemID in eggList: moveList.append(i.Serial) elif i.ItemID in relicsList: moveList.append(i.Serial) elif (i.ItemID == ps and i.Hue == 0x0481): moveList.append(i.Serial) elif i.ItemID in skullList and i.Hue == 0x0000: moveList.append(i.Serial) elif i.ItemID in crystalsList: if i.Hue == 0x0489 or i.ItemID == 0x35DA: moveList.append(i.Serial) elif i.ItemID in perks: moveList.append(i.Serial) elif i.Hue == 0x0489 and i.ItemID in ss: moveList.append(i.Serial) for m in moveList: if m in ignoreSerials: moveList.remove(m) if len(moveList) > 0: boxItems() if lockBoxAfterDrop: lockBox() def boxItems(): Journal.Clear() for i in moveList: Items.Move(i, box, 0) Misc.Pause(dragtime) hotItem = Items.FindBySerial(i) Items.WaitForProps(hotItem, 500) itemName = Items.GetPropStringByIndex(hotItem, 0) if itemName: Player.HeadMessage(msgColor, itemName) hotItem = Items.FindBySerial(i) Misc.Pause(50) if hotItem.Container != box.Serial: Player.HeadMessage(33,'NOT IN BOX') if Journal.Search('It appears to be locked.'): unlockBox() else: Player.ChatParty(itemName + ' In Box') del moveList[:] def lockBox(): Journal.Clear() boxKey = Items.FindByID(key,-1,Player.Backpack.Serial,True) if boxKey: Items.UseItem(boxKey) Target.WaitForTarget(1500) Target.TargetExecute(box) Misc.Pause(200) if Journal.Search('You lock it.'): Player.HeadMessage(msgColor, 'Box Locked!!') Player.ChatParty('Box Locked!!') else: lockBox() else: Player.HeadMessage(msgColor, 'No Key!\n!!NOT LOCKED!!') def unlockBox(): Journal.Clear() boxKey = Items.FindByID(key,-1,Player.Backpack.Serial,True) if boxKey: Items.UseItem(boxKey) Target.WaitForTarget(1500) Target.TargetExecute(box) Misc.Pause(dragtime) if Journal.Search('You unlock it.'): Player.HeadMessage(msgColor, 'Box unLocked!!') Player.ChatParty('Box unLocked!!') else: Player.HeadMessage(msgColor, 'No Key!\n!!Still UnLOCKED!!') boxItems() Journal.Clear() while True: if not box: Misc.Pause(500) Misc.SendMessage('No trap box, stopping script', 33) sys.exit() Misc.Pause(50) dropWatch() <file_sep># in dress agent create one that is your player name # without spaces and all lowercase. # Example: "Player Name" needs to be playername msgcolor = 62 dresslist = Player.Name.lower().replace(' ', '') #Player.HeadMessage(msgcolor, "Dressing") Dress.ChangeList(dresslist) Dress.DressFStart()<file_sep>leftHand = Player.GetItemOnLayer('LeftHand') chugtime = 650 msgColor = 66 noBow = True bows = [ 0x13B2,0x26C2,0x0F50,0x13FD,0x0A12,0x0F6B] # 0x0A12,0x0F6B = torch if not leftHand: noBow = True elif leftHand.ItemID in bows: noBow = False elif leftHand: noBow = True def cureDrink(): Journal.Clear() if Player.Poisoned: if leftHand and noBow: Player.UnEquipItemByLayer('LeftHand') Misc.Pause(chugtime) Player.ChatSay( 1 , '[drink greatercurepotion') Misc.Pause(100) if Journal.Search( 'You do not have any of those potions.'): Player.HeadMessage(msgColor, "No Cure pots!") Misc.Pause(chugtime) Player.EquipItem(leftHand) Misc.Pause(50) else: Player.ChatSay( 1 , '[drink greatercurepotion') Misc.Pause(100) if Journal.Search( 'You do not have any of those potions.'): Player.HeadMessage(msgColor, "No Cure pots!") else: Misc.NoOperation() else: Player.HeadMessage(msgColor, "Not Poisoned") def curePot(): if Player.Poisoned: orangePot = Items.FindByID(0x0F07,0,Player.Backpack.Serial,True) if orangePot: if leftHand and noBow: Player.UnEquipItemByLayer('LeftHand') Misc.Pause(chugtime) Items.UseItem(orangePot) Misc.Pause(chugtime) Player.EquipItem(leftHand) Misc.Pause(50) else: Items.UseItem(orangePot) else: Player.HeadMessage(msgColor, "No Cure pots!") else: Player.HeadMessage(msgColor, "Not Poisoned") if Misc.ShardName() == "Ultima Forever" or Misc.ShardName() == "UOForever": cureDrink() else: curePot() <file_sep># OG from AbelGoodwin https://github.com/hampgoodwin/razorenhancedscripts # Modified by Matsamilla # # Last updated: 12/2/21 if Player.GetRealSkillValue('Lumberjacking') < 40: Misc.SendMessage('No skill, stopping',33) Stop #******************** # serial of your beetle, logs go here when full beetle = 0x00285C67 # Attack nearest grey script name (must be exact) autoFightMacroName = 'pvm_AttackGrey.py' # you want boards or logs? logsToBoards = False # Trees where there is no longer enough wood to be harvested will not be revisited until this much time has passed treeCooldown = 1200000 # 1,200,000 ms is 20 minutes # Want this script to alert you for humaniods? alert = False #******************** # Parameters scanRadius = 15 treeStaticIDs = [ 0x0C95, 0x0C96, 0x0C99, 0x0C9B, 0x0C9C, 0x0C9D, 0x0C8A, 0x0CA6, 0x0CA8, 0x0CAA, 0x0CAB, 0x0CC3, 0x0CC4, 0x0CC8, 0x0CC9, 0x0CCA, 0x0CCB, 0x0CCC, 0x0CCD, 0x0CD0, 0x0CD3, 0x0CD6, 0x0CD8, 0x0CDA, 0x0CDD, 0x0CE0, 0x0CE3, 0x0CE6, 0x0CF8, 0x0CFB, 0x0CFE, 0x0D01, 0x0D25, 0x0D27, 0x0D35, 0x0D37, 0x0D38, 0x0D42, 0x0D43, 0x0D59, 0x0D70, 0x0D85, 0x0D94, 0x0D96, 0x0D98, 0x0D9A, 0x0D9C, 0x0D9E, 0x0DA0, 0x0DA2, 0x0DA4, 0x0DA8, ] if Misc.ShardName() == 'Ultima Forever': treeStaticIDsToRemove = [ 0x0C99, 0x0C9A, 0x0C9B, 0x0C9C, 0x0C9D, 0x0CA6, 0x0CC4, ] for treeStaticIDToRemove in treeStaticIDsToRemove: if treeStaticIDToRemove in treeStaticIDs: treeStaticIDs.remove( treeStaticIDToRemove ) #axeSerial = None EquipAxeDelay = 1000 TimeoutOnWaitAction = 4000 ChopDelay = 1000 runebookBank = 0x41EA8DEE # Runebook for bank runebookTrees = 0x41EA8DEE # Runebook for tree spots recallPause = 3000 dragDelay = 600 logID = 0x1BDD boardID = 0x1BD7 otherResourceID = [ 0x318F, 0x3199, 0x2F5F, 0x3190, 0x3191, ] logBag = 0x401FA597 # Serial of log bag in bank otherResourceBag = 0x40191C19 # Serial of other resource in bank weightLimit = Player.MaxWeight - 10 bankX = 2051 bankY = 1343 axeList = [ 0x0F49, 0x13FB, 0x0F47, 0x1443, 0x0F45, 0x0F4B, 0x0F43 ] rightHand = Player.CheckLayer( 'RightHand' ) leftHand = Player.CheckLayer( 'LeftHand' ) # System Variables from System.Collections.Generic import List from System import Byte from math import sqrt import clr clr.AddReference('System.Speech') from System.Speech.Synthesis import SpeechSynthesizer tileinfo = List[Statics.TileInfo] trees = [] treeCoords = None blockCount = 0 lastRune = 5 onLoop = True class Tree: x = None y = None z = None id = None def __init__ ( self, x, y, z, id ): self.x = x self.y = y self.z = z self.id = id def RecallNextSpot(): global lastRune Gumps.ResetGump() Misc.SendMessage('--> Recall to Spot', 77) Items.UseItem( runebookTrees ) Gumps.WaitForGump( 1431013363, TimeoutOnWaitAction ) Gumps.SendAction( 1431013363, lastRune ) Misc.Pause( recallPause ) lastRune = lastRune + 6 if lastRune > 95: lastRune = 5 EquipAxe() def RecallBack(): global lastRune Items.UseItem( runebookTrees ) Gumps.WaitForGump( 1431013363, TimeoutOnWaitAction ) Gumps.SendAction( 1431013363, lastRune ) Misc.Pause( recallPause ) EquipAxe() def DepositInBank(): global bankX global bankY while Player.Weight >= weightLimit: Gumps.ResetGump() Items.UseItem( runebookBank ) Gumps.WaitForGump( 1431013363, 10000 ) Gumps.SendAction( 1431013363, 71 ) Misc.Pause( recallPause ) Player.ChatSay( 77, 'bank' ) Misc.Pause( 300 ) if Items.BackpackCount( logID, -1 ) > 0: while Items.BackpackCount( logID, -1 ) > 0: Misc.SendMessage( '--> Moving Log', 77 ) Items.Move( item, logBag, 0 ) Misc.Pause( dragDelay ) if Items.BackpackCount( boardID, -1 ) > 0: while Items.BackpackCount( boardID, -1 ) > 0: Misc.SendMessage( '--> Moving Log', 77 ) Items.Move( item, logBag, 0 ) Misc.Pause( dragDelay ) for otherid in otherResourceID: if item.ItemID == otherid: Misc.SendMessage( '--> Moving Other', 77 ) Items.Move( item, otherResourceBag, 0 ) Misc.Pause( dragDelay ) else: Misc.NoOperation() def ScanStatic(): global treenumber global trees Misc.SendMessage('--> Scan Tile Started', 77) minX = Player.Position.X - scanRadius maxX = Player.Position.X + scanRadius minY = Player.Position.Y - scanRadius maxY = Player.Position.Y + scanRadius x = minX y = minY while x <= maxX: while y <= maxY: staticsTileInfo = Statics.GetStaticsTileInfo( x, y, Player.Map ) if staticsTileInfo.Count > 0: for tile in staticsTileInfo: for staticid in treeStaticIDs: if staticid == tile.StaticID and not Timer.Check( '%i,%i' % ( x, y ) ): #Misc.SendMessage( '--> Tree X: %i - Y: %i - Z: %i' % ( minX, minY, tile.StaticZ ), 66 ) trees.Add( Tree( x, y, tile.StaticZ, tile.StaticID ) ) y = y + 1 y = minY x = x + 1 trees = sorted( trees, key = lambda tree: sqrt( pow( ( tree.x - Player.Position.X ), 2 ) + pow( ( tree.y - Player.Position.Y ), 2 ) ) ) Misc.SendMessage( '--> Total Trees: %i' % ( trees.Count ), 77 ) def RangeTree(): playerX = Player.Position.X playerY = Player.Position.Y treeX = trees[ 0 ].x treeY = trees[ 0 ].y if ( ( treeX >= playerX - 1 and treeX <= playerX + 1 ) and ( treeY >= playerY - 1 and treeY <= playerY + 1 ) ): return True else: return False def MoveToTree(): global trees global treeCoords pathlock = 0 Misc.SendMessage( '--> Moving to TreeSpot: %i, %i' % ( trees[ 0 ].x, trees[ 0 ].y ), 77 ) Misc.Resync() treeCoords = PathFinding.Route() treeCoords.MaxRetry = 5 treeCoords.StopIfStuck = False treeCoords.X = trees[ 0 ].x treeCoords.Y = trees[ 0 ].y + 1 #Items.Message(trees[0], 1, "Here") if PathFinding.Go( treeCoords ): #Misc.SendMessage('First Try') Misc.Pause( 1000 ) else: Misc.Resync() treeCoords.X = trees[ 0 ].x + 1 treeCoords.Y = trees[ 0 ].y if PathFinding.Go( treeCoords ): Misc.SendMessage( 'Second Try' ) else: treeCoords.X = trees[ 0 ].x - 1 treeCoords.Y = trees[ 0 ].y if PathFinding.Go( treeCoords ): Misc.SendMessage( 'Third Try' ) else: treeCoords.X = trees[ 0 ].x treeCoords.Y = trees[ 0 ].y - 1 Misc.SendMessage( 'Final Try' ) if PathFinding.Go( treeCoords ): Misc.NoOperation() else: return Misc.Resync() while not RangeTree(): CheckEnemy() Misc.Pause( 100 ) pathlock = pathlock + 1 if pathlock > 350: Misc.Resync() treeCoords = PathFinding.Route() treeCoords.MaxRetry = 5 treeCoords.StopIfStuck = False treeCoords.X = trees[ 0 ].x treeCoords.Y = trees[ 0 ].y + 1 if PathFinding.Go( treeCoords ): #Misc.SendMessage('First Try') Misc.Pause( 1000 ) else: treeCoords.X = trees[ 0 ].x + 1 treeCoords.Y = trees[ 0 ].y if PathFinding.Go( treeCoords ): Misc.SendMessage( 'Second Try' ) else: treeCoords.X = trees[ 0 ].x - 1 treeCoords.Y = trees[ 0 ].y if PathFinding.Go( treeCoords ): Misc.SendMessage( 'Third Try' ) else: treeCoords.X = trees[ 0 ].x treeCoords.Y = trees[ 0 ].y - 1 Misc.SendMessage( 'Final Try' ) PathFinding.Go( treeCoords ) pathlock = 0 return Misc.SendMessage( '--> Reached TreeSpot: %i, %i' % ( trees[ 0 ].x, trees[ 0 ].y ), 77 ) def EquipAxe(): global axeSerial if not leftHand: for item in Player.Backpack.Contains: if item.ItemID in axeList: Player.EquipItem( item.Serial ) Misc.Pause( 600 ) axeSerial = Player.GetItemOnLayer( 'LeftHand' ).Serial elif Player.GetItemOnLayer( 'LeftHand' ).ItemID in axeList: axeSerial = Player.GetItemOnLayer( 'LeftHand' ).Serial else: Player.HeadMessage( 35, 'You must have an axe to chop trees!' ) Misc.Pause( 1000 ) def CutTree(): global blockCount global trees if Target.HasTarget(): Misc.SendMessage( '--> Detected block, canceling target!', 77 ) Target.Cancel() Misc.Pause( 500 ) if Player.Weight >= weightLimit: MoveToBeetle() MoveToTree() CheckEnemy() Journal.Clear() Items.UseItem( Player.GetItemOnLayer( 'LeftHand' ) ) Target.WaitForTarget( TimeoutOnWaitAction , True ) Target.TargetExecute( trees[ 0 ].x, trees[ 0 ].y, trees[ 0 ].z, trees[ 0 ].id ) Timer.Create('chopTimer', 10000) while not ( Journal.SearchByType( 'You hack at the tree for a while, but fail to produce any useable wood.', 'System' ) or Journal.SearchByType( 'You chop some', 'System' ) or Journal.SearchByType( 'There\'s not enough wood here to harvest.', 'System' ) or Timer.Check('chopTimer') == False ): Misc.Pause( 100 ) if Journal.SearchByType( 'There\'s not enough wood here to harvest.', 'System' ): Misc.SendMessage( '--> Tree change', 77 ) Timer.Create( '%i,%i' % ( trees[ 0 ].x, trees[ 0 ].y ), treeCooldown ) elif Journal.Search( 'That is too far away' ): blockCount = blockCount + 1 Journal.Clear() if blockCount > 3: blockCount = 0 Misc.SendMessage( '--> Possible block detected tree change', 77 ) Timer.Create( '%i,%i' % ( trees[ 0 ].x, trees[ 0 ].y ), treeCooldown ) else: CutTree() elif Journal.Search( 'bloodwood' ): Player.HeadMessage( 1194, 'BLOODWOOD!' ) Timer.Create('chopTimer', 10000) CutTree() elif Journal.Search( 'heartwood' ): Player.HeadMessage( 1193, 'HEARTWOOD!' ) Timer.Create('chopTimer', 10000) CutTree() elif Journal.Search( 'frostwood' ): Player.HeadMessage( 1151, 'FROSTWOOD!' ) Timer.Create('chopTimer', 10000) CutTree() elif Timer.Check('chopTimer') == False: Misc.SendMessage( '--> Tree change', 77 ) Timer.Create( '%i,%i' % ( trees[ 0 ].x, trees[ 0 ].y ), treeCooldown ) else: CutTree() def CheckEnemy(): enemy = Target.GetTargetFromList( 'enemywar' ) if enemy != None: Misc.ScriptRun( autoFightMacroName ) while enemy != None: Timer.Create('Fight', 2500) Misc.Pause( 1000 ) enemy = Mobiles.FindBySerial( enemy.Serial ) if enemy: if Player.DistanceTo( enemy ) > 1: enemyPosition = enemy.Position enemyCoords = PathFinding.Route() enemyCoords.MaxRetry = 5 enemyCoords.StopIfStuck = False enemyCoords.X = enemyPosition.X enemyCoords.Y = enemyPosition.Y - 1 PathFinding.Go( enemyCoords ) Misc.ScriptRun( autoFightMacroName ) elif Timer.Check('Fight') == False: Misc.ScriptRun( autoFightMacroName ) Timer.Create('Fight', 2500) enemy = Target.GetTargetFromList( 'enemywar' ) corpseFilter = Items.Filter() corpseFilter.Movable = False corpseFilter.RangeMax = 2 corpseFilter.Graphics = List[int]( [ 0x2006 ] ) corpses = Items.ApplyFilter( corpseFilter ) corpse = None Misc.Pause( dragDelay ) for corpse in corpses: for item in corpse.Contains: if item.ItemID == logID: Items.Move( item.Serial, Player.Backpack.Serial, 0 ) Misc.Pause( dragDelay ) PathFinding.Go( treeCoords ) def GetNumberOfBoardsInBeetle(): global beetle global boardID global dragDelay remount = False if not Mobiles.FindBySerial( beetle ): remount = True Mobiles.UseMobile( Player.Serial ) Misc.Pause( dragDelay ) numberOfBoards = 0 for item in Mobiles.FindBySerial( beetle ).Backpack.Contains: if item.ItemID == boardID: numberOfBoards += item.Amount if remount: Mobiles.UseItem( beetle ) Misc.Pause( dragDelay ) return numberOfBoards def GetNumberOfLogsInBeetle(): global beetle global logID global dragDelay remount = False if not Mobiles.FindBySerial( beetle ): remount = True Mobiles.UseMobile( Player.Serial ) Misc.Pause( dragDelay ) numberOfBoards = 0 for item in Mobiles.FindBySerial( beetle ).Backpack.Contains: if item.ItemID == boardID: numberOfBoards += item.Amount if remount: Mobiles.UseItem( beetle ) Misc.Pause( dragDelay ) return numberOfBoards def filterItem(id,range=2, movable=True): fil = Items.Filter() fil.Movable = movable fil.RangeMax = range fil.Graphics = List[int](id) list = Items.ApplyFilter(fil) return list def MoveToBeetle(): # Chop logs into boards if logsToBoards: for item in Player.Backpack.Contains: if item.ItemID == logID: Items.UseItem( Player.GetItemOnLayer( 'LeftHand' ) ) Target.WaitForTarget( 1500, False ) Target.TargetExecute( item ) Misc.Pause( dragDelay ) if Player.Mount: Mobiles.UseMobile( Player.Serial ) Misc.Pause( dragDelay ) # Move boards to beetle, if they will fit in the beetle for item in Player.Backpack.Contains: if logsToBoards and item.ItemID == boardID: numberOfBoardsInBeetle = GetNumberOfBoardsInBeetle() if numberOfBoardsInBeetle + i.Amount < 16000: Items.Move( i, beetle, 0 ) Misc.Pause( dragDelay ) elif not logsToBoards and item.ItemID == logID: numberOfBoardsInBeetle = GetNumberOfLogsInBeetle() if numberOfBoardsInBeetle + item.Amount < 16000: Items.Move( item, beetle, 0 ) Misc.Pause( dragDelay ) groundItems = filterItem([boardID,logID]) if groundItems: Player.HeadMessage(33, 'BEETLE FULL STOPPING') say('Your beetle is full, stop and unload') Stop if not Player.Mount: Mobiles.UseMobile( beetle ) Misc.Pause( dragDelay ) toonFilter = Mobiles.Filter() toonFilter.Enabled = True toonFilter.RangeMin = -1 toonFilter.RangeMax = -1 toonFilter.IsHuman = True toonFilter.Friend = False toonFilter.Notorieties = List[Byte](bytes([1,2,3,4,5,6,7])) invulFilter = Mobiles.Filter() invulFilter.Enabled = True invulFilter.RangeMin = -1 invulFilter.RangeMax = -1 invulFilter.Friend = False invulFilter.Notorieties = List[Byte](bytes([7])) def say(text): spk = SpeechSynthesizer() spk.Speak(text) def safteyNet(): if alert: toon = Mobiles.ApplyFilter(toonFilter) invul = Mobiles.ApplyFilter(invulFilter) if toon: Misc.FocusUOWindow() say("Hey, someone is here. You should tab over and take a look") toonName = Mobiles.Select(toon, 'Nearest') if toonName: Misc.SendMessage('Toon Near: ' + toonName.Name, 33) elif invul: say("Hey, something invulnerable here. You should tab over and take a look") invulName = Mobiles.Select(invul, 'Nearest') if invulName: Misc.SendMessage('Uh Oh: Invul! Who the fuck is ' + invul.Name, 33) else: Misc.NoOperation() Friend.ChangeList('lj') Misc.SendMessage('--> Start up Woods', 77) EquipAxe() while onLoop: #RecallNextSpot() ScanStatic() i = 0 while trees.Count > 0: safteyNet() MoveToTree() CutTree() trees.pop( 0 ) trees = sorted( trees, key = lambda tree: sqrt( pow( ( tree.x - Player.Position.X ), 2 ) + pow( ( tree.y - Player.Position.Y ), 2 ) ) ) trees = [] Misc.Pause( 100 ) <file_sep>These scripts have all been written for the shard Ultima Online Forever. They may work for other shards, but if they don't you now know why :) How to set up CUO + RE: 2 methods Method 1: Launch Razor Enhanced, point it to Classic UO, good to go? - Untested by me, this is a new addition to RazorEnhanced. Method 2 (what I use) with video!: https://www.youtube.com/watch?v=fSmFPxmZSOI - This assums you have downloaded the UOForver laucnher from uoforever.com and have the UO Files downloaded. How to add scripts & some basic use of Enhanced: https://www.youtube.com/watch?v=W7s7ylopA0Q Targeting Video Instructions: https://youtu.be/vqCYRl_IKME Razor Enhanced Wiki: http://razorenhanced.net/dokuwiki/doku.php ClassicUO: https://www.classicuo.eu/ www.uoforever.com <file_sep>if Misc.ShardName() == "UO Ages": delaytime = 800 else: delayTime = 600 # add (Name, PlayerSerial, MountSerial, True/False) to list # True if you want toon to DISMOUNT + ALL KILL + TARGET LAST dismountList = [ # (PlayerName, PlayerSerial, MountSerial, True/False) ("MGD" , 0x0000B71C , 0x003FAA39 , True ), ("Moltar" , 0x003C518F , 0x0007E386 , True ), ("EmGD" , 0x00255122 , 0x00215F22 , False), ("UselessGuy" , 0x0022FE20 , 0x0006EB2A , False ), ("Matsa" , 0x000470E6 , 0x0000 , False ), ("Matsa-" , 0x001DF0B7 , 0x0028E693 , False ), ("Thicc" , 0x0016218A , 0x0001E6B3 , False), ("MatsaAxa", 0x0000 , 0x00285C67 , False), ("Nalfein" , 0x000B519E , 0x00823AEA , False ), ("MatsaMilla" , 0x0002DC9C , 0x0007A37B , False ), ("useless", 0x000AE1A2 , 0x000803D8 , False), ] def dismount(mountSerial, attack): if Player.Mount: if attack: lastTarget = Mobiles.FindBySerial( Target.GetLast() ) if lastTarget: if lastTarget != Player.Serial: if Player.DistanceTo(lastTarget) < 12: Mobiles.UseMobile(Player.Serial) Misc.Pause(100) Player.ChatSay(33, 'All Kill') Target.WaitForTarget(1500) Target.TargetExecute(lastTarget) else: Mobiles.UseMobile(Player.Serial) Misc.Pause(120) mount = Mobiles.FindBySerial(mountSerial) #Misc.Pause(120) if mount: if mount.Body == 0x0317: Misc.WaitForContext(mount, 1500) Misc.Pause(150) if Player.Visible: #Misc.ContextReply(mount, 10) Misc.ContextReply(mountSerial, "Open Backpack") else: #Misc.ContextReply(mount, 0) Misc.ContextReply(mountSerial, "Open Backpack") elif mountSerial != None: mount = Mobiles.FindBySerial(mountSerial) if mount: while Player.DistanceTo(mount) > 1: if Timer.Check('MountTimer') == False: Player.ChatSay(66, mount.Name + ' Come') Timer.Create('MountTimer', 500) Misc.Pause(50) Mobiles.UseMobile(mountSerial) else: Player.HeadMessage(33,'Mount not found') for d in dismountList: if Player.Serial == d[1]: dismount(d[2], d[3]) break <file_sep>Player.ChatSay(5, "Back Left One")<file_sep># Sallos SmartPot by MatsaMilla # Drinks cure if poisoned, otherwise drinks heal def potDrink(): if Player.Poisoned: Player.ChatSay( 1 , '[drink greatercurepotion') Misc.Pause(100) if Journal.Search( 'You do not have any of those potions.'): Player.HeadMessage(33, "No Cure pots!") else: Player.ChatSay( 1 , '[drink greaterhealpotion') Misc.Pause(100) if Journal.Search( 'You do not have any of those potions.'): Player.HeadMessage(33, "No Heal pots!") def usePot(): if Player.Poisoned: orangePot = Items.FindByID(0x0F07,0,Player.Backpack.Serial,True) if orangePot: Items.UseItem(orangePot) else: Player.HeadMessage(33, "No Cure pots!") else: yellowPot = Items.FindByID(0x0F0C,0,Player.Backpack.Serial,True) if yellowPot: Items.UseItem(orangePot) else: Player.HeadMessage(33, "No Heal pots!") if Misc.ShardName() == "Ultima Forever" or Misc.ShardName() == "UOForever": potDrink() else: usePot() <file_sep># Spellbook Filler by MatsaMilla # Just open any chests containing scrolls, hit play, target a book. # script should find any scrolls and add them to book. from System.Collections.Generic import List spellBook = Target.PromptTarget('Target Spell Book to Fill') scrolls = [0x1f2d,0x1f2e,0x1f2f,0x1f30,0x1f31,0x1f32,0x1f33,0x1f34,0x1f35,0x1f36,0x1f37,0x1f38,0x1f39, 0x1f3a,0x1f3b,0x1f3c,0x1f3d,0x1f3e,0x1f3f,0x1f40,0x1f41,0x1f42,0x1f43,0x1f44,0x1f45,0x1f46,0x1f47,0x1f48, 0x1f49,0x1f4a,0x1f4b,0x1f4d,0x1f4e,0x1f4f,0x1f50,0x1f51,0x1f52,0x1f53,0x1f54,0x1f55,0x1f56,0x1f57,0x1f58, 0x1f59,0x1f5a,0x1f5b,0x1f5c,0x1f5d,0x1f5e,0x1f5f,0x1f60,0x1f61,0x1f62,0x1f63,0x1f64,0x1f65,0x1f66,0x1f67, 0x1f68,0x1f69,0x1f6a,0x1f6b,0x1f6c] if Misc.ShardName() == "UO Ages": contextResponse = 0 else: contextResponse = 1 for l in scrolls: currentScroll = Items.FindByID(l,-1,-1) if currentScroll: Misc.WaitForContext(currentScroll, 1000) Misc.ContextReply(currentScroll, contextResponse) Target.WaitForTarget(1000, False) Target.TargetExecute(spellBook) <file_sep>Player.ChatSay(5, "Forward Right One")<file_sep>''' Author: TheWarDoctor95 Other Contributors: Last Contribution By: MatsaMilla - 7/19/21 Description: Train fishing, Fishing up MIBs, nets, maps & scales Fishing pole must be in bag ''' ############# Setup Section ################ cutCorpse = True # True if you want to cut corpses #update for MAGE heal macro - use MatsaMilla Bandage_Self.py if you have healing healMacroName = 'cast_BigHeal.py' #found in MatsaMilla github # true to attack serpents - will attack by magery if no tactics attack = True ########### End Setup Section ############### from System.Collections.Generic import List from System import Byte import sys dragTime = 600 journalEntryDelay = 200 fishIDs = [ 0x09CF, 0x09CE, 0x09CC, 0x09CD ] player_bag = Items.FindBySerial(Player.Backpack.Serial) hornedFilter = Items.Filter() hornedFilter.OnGround = 1 hornedFilter.Movable = True hornedFilter.RangeMin = 0 hornedFilter.RangeMax = 2 hornedFilter.Graphics = List[int]( [ 0x1079 , 0x1081 ] ) #cut leather graphic 0x1081 hornedFilter.Hues = List[int]( [ 0x0900 ] ) fishsteakFilter = Items.Filter() fishsteakFilter.OnGround = 1 fishsteakFilter.Movable = True fishsteakFilter.RangeMin = 0 fishsteakFilter.RangeMax = 2 fishsteakFilter.Graphics = List[int]( [ 0x097A ] ) # mobile filter def find(notoriety): fil = Mobiles.Filter() fil.Enabled = True fil.RangeMax = 12 fil.IsHuman = False fil.IsGhost = False fil.Friend = False fil.Notorieties = List[Byte](bytes(notoriety)) list = Mobiles.ApplyFilter(fil) return list def Fish( fishingPole, x, y ): ''' Casts the fishing pole and returns True while the fish are biting ''' global fishIDs # eats special fish if Items.BackpackCount(0x0DD6,-1) > 0: spFish = Items.FindByID(0x0DD6,-1,Player.Backpack.Serial) Items.UseItem(spFish) Misc.Pause( dragTime ) Journal.Clear() Items.UseItemByID(0x0DBF,-1) Target.WaitForTarget( 2000, True ) statics = Statics.GetStaticsTileInfo( x, y, 0 ) if len( statics ) > 0: water = statics[ 0 ] Target.TargetExecute( x, y, water.StaticZ, water.StaticID ) else: Target.TargetExecute( x, y, -5, 0x0000 ) Misc.Pause( dragTime ) Target.Cancel() Timer.Create( 'timeout', 20000 ) while not ( Journal.SearchByType( 'You pull', 'System' ) or Journal.SearchByType( 'You fish a while, but fail to catch anything.', 'System' ) or Journal.SearchByType( 'Your fishing pole bends as you pull a big fish from the depths!', 'System' ) or Journal.SearchByType( 'Uh oh! That doesn\'t look like a fish!', 'System' )): if not Timer.Check( 'timeout' ): return False if (Journal.SearchByType( 'The fish don\'t seem to be biting here', 'System' ) or Journal.SearchByType( 'You need to be closer to the water to fish!', 'System' )): return False enemy = Mobiles.Select(find([3,4]),'Nearest') if enemy != None: FightEnemy() Misc.Pause( 50 ) if Player.Weight >= Player.MaxWeight - 20 : for fish in player_bag.Contains: # cuts fish if fish.ItemID in fishIDs: Items.UseItemByID( 0x0F52 ) Target.WaitForTarget( 2000, True ) Target.TargetExecute( fish ) Misc.Pause( dragTime ) # cuts up leather if fish.ItemID == 0x1079: Items.UseItemByID( 0x0F9F ) Target.WaitForTarget( 2000, True ) Target.TargetExecute( fish ) Misc.Pause( dragTime ) stackItem(0x097A, -1, fishsteakFilter) #stacks fish to feet stackItem(0x1081, -1, hornedFilter) #stacks cut leather to feet stackItem(0x1079, -1, hornedFilter) #stacks leather to feet if not cut return True def FightEnemy(): enemy = Mobiles.Select(find([3,4]),'Nearest') if attack == False: return if Player.GetRealSkillValue('Tactics') > 60: if enemy != None: Timer.Create('fishattack', 60000) Misc.ScriptRun( autoFightMacroName ) while enemy != None: enemy = enemy.serial Misc.Pause( 100 ) if Timer.Check('fishattack') == False: for i in range( 0, 3 ): Player.ChatSay( 0, 'back one' ) Misc.Pause( 320 ) break elif Player.GetRealSkillValue('Magery') > 70: while enemy!= None: enemy = Mobiles.FindBySerial( enemy.Serial ) if enemy == None: break while Player.Mana > 20 and enemy != None: enemy = Mobiles.FindBySerial( enemy.Serial ) if enemy == None: break Spells.CastMagery( 'Energy Bolt' ) Target.WaitForTarget( 2000, False ) Target.TargetExecute( enemy ) Misc.Pause( 1600 ) if Player.Hits < 40: Misc.ScriptRun(healMacroName) Player.UseSkill( 'Meditation' ) while Player.Mana < 34: Misc.Pause( 100 ) if Player.Hits < 40: Misc.ScriptRun(healMacroName) if enemy == None: break def scoopCorpse(): for i in range( 0, 3 ): Player.ChatSay( 0, 'back one' ) Misc.Pause( 320 ) for i in range( 0, 4 ): Player.ChatSay( 0, 'forward one' ) Misc.Pause( 320 ) for i in range( 0, 5 ): Player.ChatSay( 0, 'left one' ) Misc.Pause( 320 ) for i in range( 0, 10 ): Player.ChatSay( 0, 'right one' ) Misc.Pause( 320 ) for i in range( 0, 5 ): Player.ChatSay( 0, 'left one' ) Misc.Pause( 320 ) corpseFilter = Items.Filter() corpseFilter.Movable = False corpseFilter.RangeMax = 2 corpseFilter.Graphics = List[int]( [ 0x2006 ] ) corpseFilter.CheckIgnoreObject = True corpses = Items.ApplyFilter( corpseFilter ) corpse = None for corpse in corpses: if cutCorpse: Items.UseItemByID( 0x0F52 ) Target.WaitForTarget( 2000, True ) Target.TargetExecute( corpse.Serial ) Misc.Pause( dragTime ) Misc.IgnoreObject( corpse.Serial ) #if Items.BackpackCount( 0x1079 , -1 ) > 0: leather = Items.FindByID( 0x1079 , -1 , Player.Backpack.Serial) if leather: Items.UseItemByID( 0x0F9F ) Target.WaitForTarget( 2000, True ) Target.TargetExecute( leather ) Misc.Pause( dragTime ) stackItem(0x1081, -1, hornedFilter) #stacks cut leather to feet def UseFishing(): global moveForwardBackward fishingPole = Items.FindByID( 0x0DBF, -1 , Player.Backpack.Serial ) if fishingPole == None: Misc.SendMessage('No fishing poles!!', 33) sys.exit() while True: x = Player.Position.X - 3 y = Player.Position.Y - 3 while Fish( fishingPole, x, y ): enemy = Mobiles.Select(find([3,4]),'Nearest') if enemy != None: FightEnemy() x = Player.Position.X + 3 y = Player.Position.Y - 3 while Fish( fishingPole, x, y ): enemy = Mobiles.Select(find([3,4]),'Nearest') if enemy != None: FightEnemy() x = Player.Position.X + 3 y = Player.Position.Y + 3 while Fish( fishingPole, x, y ): enemy = Mobiles.Select(find([3,4]),'Nearest') if enemy != None: FightEnemy() x = Player.Position.X - 3 y = Player.Position.Y + 3 while Fish( fishingPole, x, y ): enemy = Mobiles.Select(find([3,4]),'Nearest') if enemy != None: FightEnemy() Misc.Pause( 320 ) scoopCorpse() for i in range( 0, 20 ): Player.ChatSay( 0, 'Forward one') Misc.Pause( 320 ) Misc.Pause( 320 ) Misc.Pause( journalEntryDelay ) if Journal.Search( 'Ar, we\'ve stopped sir.' ): Misc.Beep() Journal.Clear() def stackItem ( item , hue , filter): itemOnGround = Items.ApplyFilter( filter ) if Items.BackpackCount( item , hue ) > 0: itemInPack = Items.FindByID( item , hue , Player.Backpack.Serial ) if not itemOnGround: Items.DropItemGroundSelf( itemInPack , 0 ) else: itemStack = itemOnGround[ 0 ] Items.Move( itemInPack , itemStack , 0 ) Misc.Pause( dragTime ) def hide(): if Player.GetRealSkillValue('Hiding') > 50: if Timer.Check('hideskill' + Player.Name) == False and not Player.BuffsExist('Hiding'): if Journal.SearchByType('You can\'t seem to hide right now.' , 'System' ): Player.ChatSay( 22 , 'Forward' ) Misc.Pause(10000) Player.UseSkill('Hiding') Timer.Create('hideskill' + Player.Name,11000) # Start Fishing UseFishing() <file_sep># Dragon Armor Crafter by MatsaMilla # ToolTips must be enabled and must have a beetle # updated 5/27/22 - fixed tossing exceptional stuffs #################################################### scaleColor = 'blue' #pick color of scales, red, yellow, black, green, white, blue or blue2 fillBags = True # if true: Fill a bag with as many # bags as you want to fill with armor sets. # Make sure bag is on beetle, lot of weight. beetle = 0x00215F22 beetlePack = 0x434C292B # beetle container ID (inspect object in beetle pack for container ID ##################################################### from System.Collections.Generic import List import sys noColor = 0x0000 self_pack = Player.Backpack.Serial self = Player.Serial dragTime = 600 gmCheckDelay = 200 craftTime = 1000 gumpTimeout = 4000 dragonLegs = 0x2647 dragonTunic = 0x2641 dragonSleeves = 0x2657 dragonGloves = 0x2643 dragonHelm = 0x2645 dragonGorget = 0x2B69 dragonSuit = [(44,0x2643),(51,0x2B69),(58,0x2645),(65,0x2647),(72,0x2657),(79,0x2641)] dragonScales = 0x26B4 smithHammer = 0x13E3 if scaleColor == 'red': scaleColorGumpAction = 6 elif scaleColor == 'yellow': scaleColorGumpAction = 13 elif scaleColor == 'black': scaleColorGumpAction = 20 elif scaleColor == 'green': scaleColorGumpAction = 27 elif scaleColor == 'white': scaleColorGumpAction = 34 elif scaleColor == 'blue': scaleColorGumpAction = 41 elif scaleColor == 'blue2': scaleColorGumpAction = 48 player_bag = Items.FindBySerial(Player.Backpack.Serial) if fillBags: baseBag = Target.PromptTarget('Target bag with bags to fill') bags = [ 0xe76, 0xe75 , 0xe74 , 0xe78 , 0xe77 , 0x0E79 ] # Use neraby trashcan trashBarrelFilter = Items.Filter() trashBarrelFilter.OnGround = 1 trashBarrelFilter.Movable = False trashBarrelFilter.RangeMin = 0 trashBarrelFilter.RangeMax = 2 trashBarrelFilter.Graphics = List[int]( [ 0x0E77 ] ) trashBarrelFilter.Hues = List[int]( [ 0x03B2 ] ) trashcanhere = Items.ApplyFilter( trashBarrelFilter ) if not trashcanhere: Player.HeadMessage( 1100, 'No trashcan nearby!' ) sys.exit() else: global trashcan trashcan = trashcanhere[ 0 ] if Player.GetRealSkillValue('Tinkering') < 80: craftOwnTools = False else: craftOwnTools = True def restockScales(): if Items.BackpackCount(dragonScales,-1) < 50: if Player.Mount: Mobiles.UseMobile(Player.Serial) Misc.WaitForContext(beetle, 1500) if Player.Visible: Misc.ContextReply(beetle, 10) else: Misc.ContextReply(beetle, 0) Misc.Pause(dragTime) beetleScales = Items.FindByID( dragonScales , -1 , beetlePack, True ) if beetleScales: Items.Move( beetleScales , self_pack , 300 ) Misc.Pause(dragTime) else: Misc.SendMessage('Out of scales',33) sys.exit() def craftTools(): if craftOwnTools: currentTink = Items.FindByID(0x1EB8, -1, Player.Backpack.Serial, True ) if Items.BackpackCount(0x1BF2, noColor) < 10: Misc.SendMessage('Out of Ignots',33) sys.exit() if Items.BackpackCount(0x1EB8, noColor) < 2: Items.UseItem(currentTink.Serial) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, 8) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, 23) if Items.BackpackCount( smithHammer, noColor) < 1: Items.UseItem(currentTink.Serial) Gumps.WaitForGump(949095101,1500) Gumps.SendAction(949095101, 8) Gumps.WaitForGump(949095101,1500) Gumps.SendAction(949095101, 93) def craftDragArmor(bag): Items.UseItem(bag) Misc.Pause(dragTime) for i in dragonSuit: while True: restockScales() craftTools() hammer = Items.FindByID(smithHammer,-1,Player.Backpack.Serial,True) if Items.FindByID( i[1] , -1 , bag.Serial ): break if hammer: if Gumps.CurrentGump() != 949095101: Items.UseItem(hammer) Gumps.WaitForGump(949095101, gumpTimeout) Gumps.SendAction(949095101, 22) #Platemail Menu Gumps.WaitForGump(949095101, gumpTimeout) Gumps.SendAction(949095101, i[0]) Gumps.WaitForGump(949095101, gumpTimeout) Misc.Pause(gmCheckDelay) craftedArmor = Items.FindByID(i[1],-1,Player.Backpack.Serial) if craftedArmor: Items.WaitForProps(craftedArmor,500) if 'exceptional' in Items.GetPropStringByIndex(craftedArmor,0): moveToBag(craftedArmor,bag) break else: trashItem(craftedArmor) else: Player.HeadMessage(33,'No Smith Hammers!') sys.exit() def trashItem(item): Items.Move(item, trashcan, 0) Misc.Pause(dragTime) def moveToBag(item,container): if Player.Mount: Mobiles.UseMobile(Player.Serial) Misc.WaitForContext(beetle, 1500) if Player.Visible: Misc.ContextReply(beetle, 10) else: Misc.ContextReply(beetle, 0) Misc.Pause(dragTime) Items.Move(item, container, 0) Misc.Pause(dragTime) def setColor(): Items.UseItemByID(smithHammer,-1) Gumps.WaitForGump(949095101, gumpTimeout) Gumps.SendAction(949095101, 56) Gumps.WaitForGump(949095101, gumpTimeout) Gumps.SendAction(949095101, scaleColorGumpAction) Misc.Pause(dragTime) Journal.Clear() setColor() fillBag = Items.FindBySerial(baseBag) Items.UseItem(fillBag) Misc.Pause(dragTime) for b in fillBag.Contains: currentBag = Items.FindBySerial(b.Serial) if currentBag.IsContainer: craftDragArmor(currentBag) if not Player.Mount: Mobiles.UseMobile(beetle) Misc.SendMessage('All Done Crafting Dragon Armor') <file_sep>################## Constants ################# tongs = 0x0FBB sewingkit=0x0F9D regs = [0x0F7A, 0x0F86, 0x0F7B, 0x0F8C, 0x0F84, 0x0F85, 0x0F8D, 0x0F88] rune = [6,12,18,24,30,36,42,48,54,60,66,72,78,84,90,96] #only works with gate book = [0,1,2,3,4,5,6] deedstorag= 0x4079777D deedstosort = 0x41B89F04 deedmodel = 0x14EF deedcolor = 0x044e garbagecontainer =0x403C2A3E smithgarbotxt = 'smithgarbo' invasion = False invasion2 = False ##################Variables ################# smithbodbag = 0x41B89F04 #commpdity deed box at home to dump shit in tailorbodbag = 0x40349B3A #commodity deed box to dump shit. botname = Player.Name pname = Player.Name.lower().replace(' ', '') if pname == 'knightbot': #1 glow = False NPC = 0x00198AD9 if glow == True: tailornpc = 0x0002B253 tailorrune = 3 else: tailorrune = 6 tailornpc = 0x00008CCD book[0] = 0x434717C5 elif pname == 'fisheye': #2 book[0] = 0x423D325C glow = False NPC = 0x00198AD9 if glow == True: tailornpc = 0x0002B253 tailorrune = 3 else: tailorrune = 6 tailornpc = 0x00008CCD elif pname == 'crystalmetheny': #3 book[0] = 0x423D3CC0 glow = False NPC = 0x00198AD9 if glow == True: tailornpc = 0x0002B253 tailorrune = 3 else: tailorrune = 6 tailornpc = 0x00008CCD elif pname == 'louzar': #4 book[0] = 0x423D4195 glow = False NPC = 0x00198AD9 if glow == True: tailornpc = 0x0002B253 tailorrune = 3 else: tailorrune = 6 tailornpc = 0x00008CCD elif pname == 'wendywacko': #5 book[0] = 0x423D4783 glow = False NPC = 0x00198AD9 if glow == True: tailornpc = 0x0002B253 tailorrune = 3 else: tailorrune = 6 tailornpc = 0x00008CCD elif pname == 'terrybull': #6 book[0] = 0x423D2CF6 glow = False NPC = 0x00198AD9 if glow == True: tailornpc = 0x0002B253 tailorrune = 3 else: tailorrune = 6 tailornpc = 0x00008CCD elif pname == 'aimbotexe': #7 book[0] = 0x43466393 glow = False NPC = 0x00198AD9 if glow == True: tailornpc = 0x000610FA tailorrune = 3 else: tailorrune = 6 tailornpc = 0x00008CCD elif pname == 'ctrlaltdel': #8 book[0] = 0x423D3136 glow = False NPC = 0x00198AD9 if glow == True: tailornpc = 0x000610FA tailorrune = 3 else: tailorrune = 6 tailornpc = 0x00008CCD elif pname == 'kitkatkattle': #9 book[0] = 0x423D25EC glow = False NPC = 0x00198AD9 if glow == True: tailornpc = 0x0002B253 tailorrune = 3 else: tailorrune = 6 tailornpc = 0x00008CCD elif pname == 'bodybuilder': #10 book[0] = 0x423D2FE5 glow = False NPC = 0x00198AD9 if glow == True: tailornpc = 0x0002B253 tailorrune = 3 else: tailorrune = 6 tailornpc = 0x00008CCD elif pname == 'bodgod': #11 book[0] = 0x423D358F glow = False NPC = 0x00198AD9 if glow == True: tailornpc = 0x0002B253 tailorrune = 3 else: tailorrune = 6 tailornpc = 0x00008CCD elif pname == 'rambod': #12 book[0] = 0x423D2EE9 glow = False NPC = 0x00198AD9 if glow == True: tailornpc = 0x0002B253 tailorrune = 3 else: tailorrune = 6 tailornpc = 0x00008CCD elif pname == 'wyrmtwig': #13 book[0] = 0x423D4A9B glow = False NPC = 0x00198AD9 if glow == True: tailornpc = 0x0002B253 tailorrune = 3 else: tailorrune = 6 tailornpc = 0x00008CCD elif pname == 'saltsniffer': #14 book[0] = 0x423D40A6 glow = False NPC = 0x00198AD9 if glow == True: tailornpc = 0x0002B253 tailorrune = 3 else: tailorrune = 6 tailornpc = 0x00008CCD elif pname == 'nightbod': #15 book[0] = 0x423D3D78 glow = False NPC = 0x00198AD9 if glow == True: tailornpc = 0x0002B253 tailorrune = 3 else: tailorrune = 6 tailornpc = 0x00008CCD elif pname == 'blackfox': #16 book[0] = 0x423D3679 glow = False NPC = 0x00198AD9 if glow == True: tailornpc = 0x0002B253 tailorrune = 3 else: tailorrune = 6 tailornpc = 0x00008CCD def worldSave(): if Journal.SearchByType('The world will save in 1 minute.', 'Regular' ): Misc.SendMessage('Pausing for world save', 33) while not Journal.SearchByType('World save complete.', 'Regular'): Misc.Pause(500) Misc.Pause(2500) Misc.SendMessage('Continuing run', 33) Journal.Clear() def webhook(msg): URI = 'https://discordapp.com/api/webhooks/<KEY>' alert = msg report = "content="+ alert PARAMETERS=report from System.Net import WebRequest request = WebRequest.Create(URI) request.ContentType = "application/x-www-form-urlencoded" request.Method = "POST" from System.Text import Encoding bytes = Encoding.ASCII.GetBytes(PARAMETERS) request.ContentLength = bytes.Length reqStream = request.GetRequestStream() reqStream.Write(bytes, 0, bytes.Length) reqStream.Close() response = request.GetResponse() from System.IO import StreamReader result = StreamReader(response.GetResponseStream()).ReadToEnd().replace('\r', '\n') def recall(book, rune): mana(30) worldSave() caststr() rune = 5+6*rune currentlocation = Player.Position Misc.Pause( 750 ) Items.UseItem(book) Misc.Pause( 500 ) Gumps.WaitForGump( 1431013363, 5000 ) Misc.Pause( 500 ) Gumps.SendAction( 1431013363, rune ) Misc.Pause( 500 ) Misc.Pause(1500) def mana(mana_req): if Player.Mana < mana_req: Player.UseSkill( 'Meditation' ) while Player.Mana < ( Player.ManaMax ): Misc.Pause( 50 ) def castincog(): if Player.BuffsExist('Incognito'): Player.HeadMessage(54,'incog already on') else: Spells.CastMagery( 'Incognito' ) Misc.Pause(1500) def gohome(): if str(Player.Position) == '(6215, 3410, 35)': webhook('home already') return recall(book[0],0) Misc.Pause(500) Player.Walk("North") Player.Walk("North") Player.Walk("North") Misc.Pause(2000) if str(Player.Position) != '(6215, 3410, 35)': webhook("failed to go home") gohome() else: webhook("I am at home") def caststr(): if Player.Weight > 375 and not Player.BuffsExist( 'Strength' ): Spells.CastMagery( 'Strength' ) Target.WaitForTarget( 10000, False ) Target.Self() Misc.Pause( 1000 ) def comparetolist(bod, input): filepath = 'C:/Users/Jason/PycharmProjects/BodBot/' + input + ".txt" f = open(filepath, 'r') allinlist = f.readlines() f.close() #Player.HeadMessage(54, str(len(allinlist))) for i in range(0, len(allinlist)): #Player.HeadMessage(54, str(allinlist[i])) #Player.HeadMessage(54, str(getstringofbod(0x44D90146))) if getstringofbod(bod) == allinlist[i]: Player.HeadMessage(54, "Match found from list") return True else: Misc.Pause(5) return False def getstringofbod(bod): result= "" bodList = Items.GetPropStringList(bod) for i in range(0, len(bodList)): result = result + bodList[i] result = result.replace("[","") result = result.replace("]","") result = result.replace(" deedBlessed<BASEFONT COLOR=#585868> Hue: 1102 <BASEFONT COLOR=#FFFFFF>Weight: 1 stone","") result = result.replace("bulk orderAll items must be","") result = result.replace(".All items must be made with","") result = result.replace(".amount to make:","") result = result.replace("a bulk order","") result = result + '\n' return result def checkgarbo(bod): if comparetolist(bod, smithgarbotxt ): Player.HeadMessage(54, "Sending to garbage") Items.Move(bod, garbagecontainer, 0) return True else: return False def regcount(): webhook('Pearl: ' + str(Items.BackpackCount(0x0F7A,0)) +'/Root: ' + str(Items.BackpackCount(0x0F86,0)) + '/Moss: ' + str(Items.BackpackCount(0x0F7B,0)) + '/Sulf: ' + str(Items.BackpackCount(0x0F8C,0)) + '/Gar: ' + str(Items.BackpackCount(0x0F84,0)) + '/Gin: ' + str(Items.BackpackCount(0x0F85 ,0))+'/Silk: ' + str(Items.BackpackCount(0x0F8D,0)) + '/Shade: ' + str(Items.BackpackCount(0x0F88,0)) ) def checkregs(): #if Items.BackpackCount(0x0F7A,0) <50 or Items.BackpackCount(0x0F86,0) <50 or Items.BackpackCount(0x0F7B,0) < 50 orItems.BackpackCount(0x0F8C,0) < 50 or Items.BackpackCount(0x0F84,0) <50 or Items.BackpackCount(0x0F85,0)<50 or Items.BackpackCount(0x0F8D,0) <50 orItems.BackpackCount(0x0F88,0): for reg in regs: if Items.BackpackCount(reg,0)<50: restock() def restock(): webhook('Need Regs') recall(book[0], 1) Misc.Pause(1500) Mobiles.UseMobile(0x000E0470) Misc.Pause(1000) Gumps.WaitForGump(989312372, 10000) Gumps.SendAction(989312372, 4) Gumps.WaitForGump(989312372, 10000) Gumps.SendAction(989312372, 8) Misc.Pause(1000) regcount() Misc.Pause(1000) def smithbodready(): Journal.Clear() Misc.Pause(1000) Misc.WaitForContext(0x000BB73D, 10000) Misc.ContextReply(0x000BB73D, 1) Misc.Pause(1000) if Journal.Search("can get"): Player.HeadMessage(54, "can get an order") Misc.Pause(1000) return True else: webhook(botname + ' ended up at smith bod before its read') return False def invasionsmithbods(): Misc.Pause(1000) abortcounter = 0 webhook('Getting smith Bod') Items.UseItem(0x4083A7E1) Misc.Pause(1000) Spells.CastMagery("Recall") Target.WaitForTarget(10000, False) Misc.Pause(600) Target.TargetExecute(0x459A5682) Misc.Pause(15000) Misc.Pause(2000) Misc.Resync() Player.Walk("North") #Player.Walk("North") #Misc.Resync() #Journal.Clear() Misc.Pause(3000) Misc.WaitForContext(0x00029397, 10000) Misc.Pause(1000) Misc.ContextReply(0x00029397, 1) Misc.Pause(1000) if Journal.Search("can get"): Player.HeadMessage(54, "can get an order") Misc.Pause(1000) smithrdy = True else: webhook(botname + ' ended up at smith bod before its read') smithrdy = False if smithrdy: while not Gumps.HasGump(): abordcounter = abortcounter +1 if abortcounter > 25: gohome() if Items.FindByID(tongs, -1, Player.Backpack.Serial): Misc.WaitForContext(0x00029397, 10000) #sell Misc.ContextReply(0x00029397, 3) else: Misc.WaitForContext(0x00029397, 10000) Misc.ContextReply(0x00029397, 2) Misc.Pause(1000) while Items.FindByID(tongs, -1, Player.Backpack.Serial): Misc.WaitForContext(0x00029397, 10000) #sell Misc.ContextReply(0x00029397, 3) Gumps.WaitForGump(3188567326, 2000) Gumps.SendAction(3188567326, 1) Gumps.WaitForGump(2611865322, 2000) Gumps.SendAction(2611865322, 1) def invasionsmithbods2(): Misc.Pause(1000) abortcounter = 0 webhook('Getting smith Bod') Items.UseItem(0x4083A7E1) Misc.Pause(1000) Spells.CastMagery("Recall") Target.WaitForTarget(10000, False) Misc.Pause(600) Target.TargetExecute(0x419BD34E) Misc.Pause(15000) Misc.WaitForContext(0x000013B7, 10000) Misc.Pause(1000) Misc.ContextReply(0x000013B7, 1) Misc.Pause(1000) if Journal.Search("can get"): Player.HeadMessage(54, "can get an order") Misc.Pause(1000) smithrdy = True else: webhook(botname + ' ended up at smith bod before its read') smithrdy = False if smithrdy: while not Gumps.HasGump(): abordcounter = abortcounter +1 if abortcounter > 25: gohome() if Items.FindByID(tongs, -1, Player.Backpack.Serial): Misc.WaitForContext(0x000013B7, 10000) #sell Misc.ContextReply(0x000013B7, 3) else: Misc.WaitForContext(0x000013B7, 10000) Misc.ContextReply(0x000013B7, 2) Misc.Pause(1000) while Items.FindByID(tongs, -1, Player.Backpack.Serial): Misc.WaitForContext(0x000013B7, 10000) #sell Misc.ContextReply(0x000013B7, 3) Gumps.WaitForGump(3188567326, 2000) Gumps.SendAction(3188567326, 1) Gumps.WaitForGump(2611865322, 2000) Gumps.SendAction(2611865322, 1) def smithbods(): abortcounter = 0 webhook('Getting smith Bod') recall(book[0],2) if smithbodready(): while not Gumps.HasGump(): abordcounter = abortcounter +1 if abortcounter > 25: gohome() if Items.FindByID(tongs, -1, Player.Backpack.Serial): Misc.WaitForContext(0x000BB73D, 10000) #sell Misc.ContextReply(0x000BB73D, 3) else: Misc.WaitForContext(0x000BB73D, 10000) Misc.ContextReply(0x000BB73D, 2) Misc.Pause(1000) while Items.FindByID(tongs, -1, Player.Backpack.Serial): Misc.WaitForContext(0x000BB73D, 10000) #sell Misc.ContextReply(0x000BB73D, 3) Gumps.WaitForGump(3188567326, 2000) Gumps.SendAction(3188567326, 1) Gumps.WaitForGump(2611865322, 2000) Gumps.SendAction(2611865322, 1) def tailorbodready(): Journal.Clear() Misc.Pause(500) Misc.WaitForContext(tailornpc, 10000) Misc.ContextReply(tailornpc, 1) Misc.Pause(1000) if Journal.Search("can get"): Player.HeadMessage(54, "can get an order") Misc.Pause(1000) return True else: webhook(botname + ' ended up at tailor bod before its read') return False def tailorbods(): webhook('Getting Tailor Bod') abortcounter = 0 recall(book[0],tailorrune) if tailorbodready(): while not Gumps.HasGump(): abordcounter = abortcounter + 1 if abortcounter > 25: gohome() if Items.FindByID(sewingkit, -1, Player.Backpack.Serial): Misc.WaitForContext(tailornpc, 10000) Misc.ContextReply(tailornpc, 3) Misc.Pause(750) else: Misc.WaitForContext(tailornpc, 10000) Misc.ContextReply(tailornpc, 2) Misc.Pause(1000) while Items.FindByID(sewingkit, -1, Player.Backpack.Serial): Misc.WaitForContext(tailornpc, 10000) Misc.ContextReply(tailornpc, 3) Misc.Pause(100) Gumps.WaitForGump(3188567326, 2000) Gumps.SendAction(3188567326, 1) Gumps.WaitForGump(2611865322, 2000) Gumps.SendAction(2611865322, 1) Misc.Pause(2000) def discordbod(bod): result = '' bodList = Items.GetPropStringList(bod) for i in range(0, len(bodList)): #if i > (z -1): result = result + bodList[i] result = result.replace("bulk orderAll items must be",'') result = result.replace('.amount to make','') result = result.replace(': 0','') result = result.replace('.All items must be made with','') result = result.replace('<BASEFONT COLOR=#204018>Hue: Rusty Green (1155)<BASEFONT COLOR=#FFFFFF>Weight: 1','') result = result.replace('a bulk order deedBlessed stonelarge','') result = result.replace('a bulk order deedBlessed<BASEFONT COLOR=#606070> Hue: 1102 <BASEFONT COLOR=#FFFFFF>Weight: 1 stonesmall ','') result = result.replace('a bulk order deedBlessed<BASEFONT COLOR=#606070> Hue: 1102 <BASEFONT COLOR=#FFFFFF>Weight: 1 stonelarge','') result = result.replace('a bulk order deedBlessed stonesmall ','') webhook(result) def unload(): gohome() Misc.Pause(1000) while Items.FindByID(0x14EF, 0x0483, Player.Backpack.Serial): #tailor bods currenttarget = Items.FindByID(0x14EF, 0x0483, Player.Backpack.Serial) Items.Move(currenttarget, tailorbodbag, -1) Misc.Pause(1000) while Items.FindByID(0x14EF, 0x044E, Player.Backpack.Serial): #smith bods currenttarget = Items.FindByID(0x14EF, 0x044E, Player.Backpack.Serial) if checkgarbo(currenttarget): Player.HeadMessage(54, "garbage") Misc.Pause(500) else: Items.Move(currenttarget, smithbodbag, 0) Misc.Pause(1000) def writetime(text): f = open('C:/Users/Jason/PycharmProjects/BodBot/MastBodStatus.txt', 'w') f.write(str(text)) f.close() def readtime(file): f = open('C:/Users/Jason/PycharmProjects/BodBot/MastBodStatus.txt', 'r') x = f.read() return x restock() Misc.Pause(3000) if BuyAgent.Status( ) == False: Player.HeadMessage(54, "Starting buy agent") BuyAgent.Enable() Misc.Pause(500) if SellAgent.Status( ) == False: Player.HeadMessage(54, "Starting sell agent") SellAgent.Enable() Misc.Pause(1000) writetime('start') temp = botname + " is getting bods" webhook(temp) checkregs() if invasion: invasionsmithbods() elif invasion2: invasionsmithbods2() else: smithbods() tailorbods() Misc.Pause(2000) unload() Misc.Pause(2000) writetime('done') <file_sep> # Wep crafter by MatsaMilla; Last edit: Matsamilla 5/27/22 - fixed tossing exceptionals # # Only have 1 type of wood on you at a time, it adjusts wood type automagically # # will restock same wood type from beetle # # crafts weps for fletching and carpentry, wep list below (comment out ones not crafting) # # Moves good weps to beetle *must be exceptional, trashes all non exceptional ################## SETUP SECTION #################################### # Will automatically ID items if toon has ItemID skill useIDWands = True # true to use ID wands to ID magic items as # you craft, otherwise move all to beetle # Wands must be in backpack, not in bag in pack # update with your beetles serial to move good weps to beetle = 0x00215F22 #inspect an item in the bag of your beetle, copy root container serial here. used to restock wood beetleContainer = 0x434C292B # turn to true if client has tool tips enabled, more reliable toolTipsOn = True # Set wep choice below (comment out others) weapToCraft = 'comp' #weapToCraft = 'bow' #weapToCraft = 'xbow' #weapToCraft = 'qstaff' #weapToCraft = 'club' ################ Items to keep Setup Section ######################### # Anything in this list will be moved to beetle keepProps = ['Vanquishing','Power'] # slayer props, take out the ones you dont want to keep, if you want. Will keep all slayers in list. slayerProps = ['Silver','Elemental Ban','Undead','Dragon Slaying', 'Reptilian Death','Terathan','Exorcism','Repond','Fey', 'Orc Slaying','Ogre Trashing','Balron Damnation','Daemon Dismissal', 'Water Dissipation','Earth Shatter','Arachnid', 'Blood Drinking'] # You can move slayers you do not want to keep down here, or just delete them. # Just make sure they have a # in front so the code will ignore them. # 'Lizardman Slaughter','Scorpion\'s Bane','Vacuum','Gargoyle\'s Foe','Troll Slaughter','Flame Dousing','Summer Wind','Spider\'s Death','Elemental Health','Ophidian','Snake\'s Bane' #Any item in this list will be kept if paired with a durability or accuracy mod, does not count if on other side of # wepDmgMods = ['Vanquishing','Power', 'Force'] # 'Ruin','Might' ######################### Do not touch anything below here# ####################################### from System.Collections.Generic import List #disregaurd list below wepDurabilityMods = ['Indestructable', 'Fortified', 'Massive', 'Substantial', 'Durable'] wepAccuracyMods = ['Supremely Accurate','Exceedingly Accurate','Eminently Accurate', 'Surpassingly Accurate', 'Accurate'] #the order of these is the order of how wood will be used woodHues = [ 1193 , 1194 , 1151 , 1192 , 1191 ,2010 ] # heartwood, bloodwood, frostwood, yew, ash, oak dragTime = 600 fletchTool = 0x1022 saw = 0x1034 tink = 0x1EB8 wood = 0x1BD7 logs = 0x1BDD ignot = 0x1BF2 comp = 0x26C2 xbow = 0x0F50 bow = 0x13B2 qstaff = 0x0E89 club = 0x13B4 noColor = 0x0000 self_pack = Player.Backpack.Serial self = Player.Serial rightHand = Player.CheckLayer('RightHand') leftHand = Player.CheckLayer('LeftHand') wands = [0xdf5,0xdf3,0xdf4,0xdf2] # Will use ID Wand if skill Item ID below 75 if Player.GetRealSkillValue('Item ID') > 75: idItems = True useIDWands = False elif useIDWands: idItems = True else: idItems = False # Use neraby trashcan trashBarrelFilter = Items.Filter() trashBarrelFilter.OnGround = 1 trashBarrelFilter.Movable = False trashBarrelFilter.RangeMin = 0 trashBarrelFilter.RangeMax = 2 trashBarrelFilter.Graphics = List[int]( [ 0x0E77 ] ) trashBarrelFilter.Hues = List[int]( [ 0x03B2 ] ) trashcanhere = Items.ApplyFilter( trashBarrelFilter ) if trashcanhere: global trashcan for t in trashcanhere: trashcan = t else: Misc.SendMessage('No trashcan nearby, stopping',33) Misc.Beep() Stop # sets wep to craft if weapToCraft == 'comp': wepType = 16 craftWepID = comp carp = False fletch = True Player.HeadMessage(33, 'Crafting '+weapToCraft) elif weapToCraft == 'xbow': wepType = 9 craftWepID = xbow carp = False fletch = True Player.HeadMessage(33, 'Crafting '+weapToCraft) elif weapToCraft == 'bow': wepType = 2 craftWepID = bow carp = False fletch = True elif weapToCraft == 'qstaff': wepType = 9 craftWepID = qstaff carp = True fletch = False elif weapToCraft == 'club': wepType = 30 craftWepID = club carp = True fletch = False def setWood(): global woodHue worldSave() # check for tools if Items.BackpackCount(fletchTool, noColor) < 1: craftTools() # sets wood type packWood = FindItem(wood, Player.Backpack) packLogs = FindItem(logs, Player.Backpack) if packWood: if packWood.Hue == 0: woodGumpAction = 6 woodType = 'Regular Wood' elif packWood.Hue == 2010: woodType = 'oak' woodGumpAction = 13 elif packWood.Hue == 1191: woodType = 'ash' woodGumpAction = 20 elif packWood.Hue == 1192: woodType = 'yew' woodGumpAction = 27 elif packWood.Hue == 1193: woodType = 'heartwood' woodGumpAction = 34 elif packWood.Hue == 1194: woodType = 'bloodwood' woodGumpAction = 41 elif packWood.Hue == 1151: woodType = 'frostwood' woodGumpAction = 48 woodHue = packWood.Hue elif packLogs: if packLogs.Hue == 0: woodGumpAction = 6 woodType = 'Regular Wood' elif packLogs.Hue == 2010: woodType = 'oak' woodGumpAction = 13 elif packLogs.Hue == 1191: woodType = 'ash' woodGumpAction = 20 elif packLogs.Hue == 1192: woodType = 'yew' woodGumpAction = 27 elif packLogs.Hue == 1193: woodType = 'heartwood' woodGumpAction = 34 elif packLogs.Hue == 1194: woodType = 'bloodwood' woodGumpAction = 41 elif packLogs.Hue == 1151: woodType = 'frostwood' woodGumpAction = 48 woodHue = packLogs.Hue else: Misc.SendMessage('NO WOOD, Stopping!', 33) Misc.Beep() Stop Misc.SendMessage('Crafting with ' + woodType, 33) if fletch: currentFletch = FindItem( fletchTool , Player.Backpack ) if currentFletch: if Gumps.CurrentGump() != 949095101: Items.UseItem(currentFletch) Misc.Pause(dragTime) Gumps.WaitForGump(949095101, 2000) Gumps.SendAction(949095101, 7) Gumps.WaitForGump(949095101, 2000) Gumps.SendAction(949095101, woodGumpAction) Gumps.WaitForGump(949095101, 2000) Misc.Pause(dragTime) else: craftTools() elif carp: currentSaw = FindItem( saw , Player.Backpack ) if currentSaw: Items.UseItem(currentSaw) Misc.Pause(120) Gumps.WaitForGump(949095101, 10000) Gumps.SendAction(949095101, 7) Gumps.WaitForGump(949095101, 10000) Gumps.SendAction(949095101, woodGumpAction) Misc.Pause(dragTime) else: craftTools() def moveToBeetle(item): if Player.Mount: Mobiles.UseMobile(self) Misc.Pause(dragTime) Items.Move(item, beetle, 1) Misc.Pause(dragTime) Mobiles.UseMobile(beetle) Misc.Pause(dragTime) def restockWood( color ): global restocked if Player.Mount: Mobiles.UseMobile(self) Misc.Pause(dragTime) Mobiles.SingleClick(beetle) Misc.WaitForContext(beetle, 1500) if Player.Visible: Misc.ContextReply(beetle, 10) else: Misc.ContextReply(beetle, 0) Misc.Pause(dragTime) beetleLogs = Items.FindByID(logs, color, beetleContainer) beetleWood = Items.FindByID(wood, color, beetleContainer) if beetleLogs: Player.HeadMessage (66, 'Restocking') Items.Move(beetleLogs, self_pack, 1000) Misc.Pause(dragTime) restocked = True elif beetleWood: Player.HeadMessage (66, 'Restocking') Items.Move(beetleWood, self_pack, 1000) Misc.Pause(dragTime) restocked = True else: restocked = False if not Player.Mount: Mobiles.UseMobile(beetle) Misc.Pause(dragTime) def trashItem(item): if trashcan: Items.Move(item, trashcan.Serial, 1) Misc.Pause(dragTime) else: Misc.SendMessage('No trashcan nearby, stopping',33) Misc.Beep() Stop # Checks to see if you have enough materials, stopps if not. def checkMats(): worldSave() if fletch: # check for tools if Items.BackpackCount(fletchTool, noColor) < 1: craftTools() # check for wood if weapToCraft == 'comp': if Items.BackpackCount(wood, -1) < 12 and Items.BackpackCount(logs, -1) < 12: restockWood( woodHue ) if Items.BackpackCount(wood, -1) < 12 and Items.BackpackCount(logs, -1) < 12: Misc.SendMessage('Out of Wood',33) Gumps.CloseGump(949095101) Stop else: if Items.BackpackCount(wood, -1) < 7 and Items.BackpackCount(logs, -1) < 7: restockWood (woodHue) if Items.BackpackCount(wood, -1) < 7 and Items.BackpackCount(logs, -1) < 7: Misc.SendMessage('Out of Wood',33) Gumps.CloseGump(949095101) Stop elif carp: # check for tools if Items.BackpackCount(saw, noColor) < 1: craftTools() # check for wood if Items.BackpackCount(wood, -1) < 6 and Items.BackpackCount(logs, -1) < 7: restockWood (woodHue) if Items.BackpackCount(wood, -1) < 6 and Items.BackpackCount(logs, -1) < 7: Misc.SendMessage('Out of Wood',33) Gumps.CloseGump(949095101) Misc.Beep() Stop def craftTools(): worldSave() currentTink = FindItem( tink , Player.Backpack ) # stops script if not enough ignots to craft tools packIgnots = FindItem (ignot , Player.Backpack) if packIgnots == None or packIgnots.Amount < 10: Misc.SendMessage('Need more ignots for tools', 33) Misc.Beep() Stop # crafts tinker set if you only have 1 if Items.BackpackCount(tink, noColor) < 2: Items.UseItem(currentTink.Serial) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, 8) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, 23) Gumps.WaitForGump(949095101, 2000) Gumps.CloseGump(949095101) if fletch: # crafts fletch if Items.BackpackCount(fletchTool, noColor) < 1: Items.UseItem(currentTink.Serial) Gumps.WaitForGump(949095101,1500) Gumps.SendAction(949095101, 8) Gumps.WaitForGump(949095101,1500) Gumps.SendAction(949095101, 142) Gumps.WaitForGump(949095101, 2000) Gumps.CloseGump(949095101) Misc.Pause(2000) elif carp: # crafts saw if Items.BackpackCount(saw, noColor) < 1: Items.UseItem(currentTink.Serial) Gumps.WaitForGump(949095101,1500) Gumps.SendAction(949095101, 8) Gumps.WaitForGump(949095101,1500) Gumps.SendAction(949095101, 51) Gumps.WaitForGump(949095101, 2000) Gumps.CloseGump(949095101) Misc.Pause(2000) def craftWep(): worldSave() trashcanhere = Items.ApplyFilter( trashBarrelFilter ) if trashcanhere: global trashcan for t in trashcanhere: trashcan = t else: Misc.SendMessage('No trashcan nearby, stopping',33) Misc.Beep() Stop # makes sure you stay mounted if not Player.Mount: Mobiles.UseMobile(beetle) Misc.Pause(dragTime) if fletch: # find fletch tools in bag currentFletch = FindItem( fletchTool , Player.Backpack ) if currentFletch: checkMats() Items.UseItem(currentFletch) Gumps.WaitForGump(949095101,1500) Gumps.SendAction(949095101, 15) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, wepType) Gumps.WaitForGump(949095101, 3000) Misc.Pause(dragTime) elif carp: # find saw in bag, uses & crafts qstaff currentSaw = FindItem( saw , Player.Backpack ) if currentSaw: Items.UseItem(currentSaw) Gumps.WaitForGump(949095101,1500) Gumps.SendAction(949095101, 22) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, wepType) Misc.Pause(2000) # IDs items as you craft, if applicable # otherwise moves to beetle def idItem(item): worldSave() Journal.Clear() if idItems: idTarget() Target.WaitForTarget(1500) Target.TargetExecute(item) Items.SingleClick(item) Misc.Pause(dragTime) if Journal.Search('You are not certain'): idItem(item) if Journal.Search('Exceptional'): if any(Journal.Search(keep) for keep in keepProps): #** moves to beetle if has property in keepProps ** moveToBeetle(item) elif any(Journal.Search(keep) for keep in slayerProps): #** moves slayers to beetle ** moveToBeetle(item) elif any(Journal.Search(slash) for slash in wepDmgMods): if any(Journal.Search(sub) for sub in wepAccuracyMods): #** moves deedable weps to beetle ** moveToBeetle(item) if any(Journal.Search(sub) for sub in wepDurabilityMods): #** Good Stuff Move ** moveToBeetle(item) else: #** Trash ** trashItem(item) else: #** Trash ** trashItem(item) else: #** Trash ** trashItem(item) else: moveToBeetle(item) def idItemToolTips(item): worldSave() if idItems: idTarget() Target.WaitForTarget(1500) Target.TargetExecute(item) Misc.Pause(dragTime) if Journal.Search('You are not certain'): idItem(item) Items.WaitForProps(item, 2000) props = Items.GetPropStringList(item) if 'exceptional' in Items.GetPropStringByIndex(item,0): if any(elim in keepProps for elim in props): #if any(Journal.Search(keep) for keep in keepProps): #** moves to beetle if has property in keepProps ** moveToBeetle(item) elif any(elim in slayerProps for elim in props): #elif any(Journal.Search(keep) for keep in slayerProps): #** moves slayers to beetle ** moveToBeetle(item) elif any(elim in wepDmgMods for elim in props): #elif any(Journal.Search(slash) for slash in wepDmgMods): if any(elim in wepAccuracyMods for elim in props): #if any(Journal.Search(sub) for sub in wepAccuracyMods): #** moves deedable weps to beetle ** moveToBeetle(item) if any(elim in wepDurabilityMods for elim in props): #if any(Journal.Search(sub) for sub in wepDurabilityMods): #** Good Stuff Move ** moveToBeetle(item) else: #** Trash ** trashItem(item) else: #** Trash ** trashItem(item) else: #** Trash ** trashItem(item) else: moveToBeetle(item) # equips a wand, hopefully ID wand def equipWand(): global wandSerial if Player.CheckLayer('LeftHand') : Player.UnEquipItemByLayer('LeftHand') Misc.Pause(600) if not Player.CheckLayer('RightHand'): for i in Player.Backpack.Contains: if i.ItemID in wands: Items.WaitForProps(i, 500) if Items.GetPropValue(i, "Identification"): Player.EquipItem(i.Serial) Misc.Pause(600) wandSerial = Player.GetItemOnLayer('RightHand').Serial break else: Player.ChatSay(33, "No Wands Found, No longer IDing") Stop elif Player.GetItemOnLayer('RightHand').ItemID in wands: wandSerial = Player.GetItemOnLayer('RightHand').Serial else: Player.ChatSay(33, "No Wands Found, No longer IDing") Stop # brings up ItemID Target, with wand or skill def idTarget(): worldSave() if useIDWands: equipWand() Items.UseItem(wandSerial) Misc.Pause(200) else: Player.UseSkill('Item ID') Misc.Pause(dragTime) if not Target.HasTarget(): idTarget() # checks pack for wep you are crafting # checks journal for special item, slayer or magic # if special, ids item def wepCheck(): worldSave() craftedItem = FindItem( craftWepID , Player.Backpack ) if toolTipsOn: if Journal.SearchByType('You have successfully crafted a slayer', 'System'): idItemToolTips(craftedItem) elif Journal.SearchByType('Your material and skill have added magical properties to this weapon.', 'System'): idItemToolTips(craftedItem) else: trashItem(craftedItem) else: if Journal.SearchByType('You have successfully crafted a slayer', 'System'): idItem(craftedItem) elif Journal.SearchByType('Your material and skill have added magical properties to this weapon.', 'System'): idItem(craftedItem) else: trashItem(craftedItem) Journal.Clear() # pauses during world save def worldSave(): if Journal.SearchByType('The world is saving, please wait.', 'System' ): Misc.SendMessage('Pausing for world save', 33) while not Journal.SearchByType('World save complete.', 'System'): Misc.Pause(1000) Misc.SendMessage('Continuing', 33) Journal.Clear() def FindItem( itemID, container, color = -1, ignoreContainer = [] ): ''' Searches through the container for the item IDs specified and returns the first one found Also searches through any subcontainers, which Misc.FindByID() does not ''' ignoreColor = False if color == -1: ignoreColor = True if isinstance( itemID, int ): foundItem = next( ( item for item in container.Contains if ( item.ItemID == itemID and ( ignoreColor or item.Hue == color ) ) ), None ) elif isinstance( itemID, list ): foundItem = next( ( item for item in container.Contains if ( item.ItemID in itemID and ( ignoreColor or item.Hue == color ) ) ), None ) else: raise ValueError( 'Unknown argument type for itemID passed to FindItem().', itemID, container ) if foundItem != None: return foundItem subcontainers = [ item for item in container.Contains if ( item.IsContainer and not item.Serial in ignoreContainer ) ] for subcontainer in subcontainers: foundItem = FindItem( itemID, subcontainer, color, ignoreContainer ) if foundItem != None: return foundItem setWood() #restockWood (woodHue) while True: Journal.Clear() worldSave() checkMats() craftWep() while Items.BackpackCount(craftWepID, -1) > 0: wepCheck() <file_sep># disarm steal wep by MatsaMilla # updated 4/2/2022 # have fun Player.HeadMessage(66, "Select your Target") disarmTarget = Mobiles.FindBySerial(Target.PromptTarget()) def stealCheck(): Misc.Pause(120) if Journal.SearchByType( 'You fail to steal the item.' , 'Regular' ): Player.HeadMessage(33, 'FAILED') elif Journal.SearchByType( 'You successfully steal the item.' , 'Regular' ): Player.HeadMessage(66, 'Wep Stolen!') if disarmTarget: rightHand = disarmTarget.GetItemOnLayer('RightHand') leftHand = disarmTarget.GetItemOnLayer('LeftHand') if rightHand: stealTarget = rightHand elif leftHand: stealTarget = leftHand else: Player.HeadMessage(66, "They are unarmed") stealTarget = None if stealTarget != None: Journal.Clear() Player.WeaponDisarmSA( ) Misc.Pause(120) if Journal.SearchByType("You decide to not try to disarm anyone.",'System'): Player.WeaponDisarmSA( ) while Player.DistanceTo(disarmTarget) > 1: Misc.Pause(10) Player.Attack(disarmTarget) if not Target.HasTarget(): Player.UseSkill('Stealing') Target.WaitForTarget(1500) Target.TargetExecute(stealTarget) stealCheck() else: Player.HeadMessage(66, "You didn't target a mobile") <file_sep># Place blank scrolls in pack, have only how many you want to make (or can hold) on you. # Target a container you want to transfer them into after it makes them. # uncomment the type you would like to make deedtype = 'smith' #deedtype = 'tailor' #deedtype = 'carp' #deedtype = 'fletch' hammerID = 0x13E3 tongID = 0x0FBB scrollID = 0x0EF3 fletchID = 0x1022 sawID = 0x1034 backpack = Player.Backpack.Serial def repairDeed(type): hammer = Items.FindByID(hammerID, -1, backpack) tong = Items.FindByID(tongID, -1, backpack) scrolls = Items.FindByID(scrollID,-1, backpack) sewKit = Items.FindByID(0x0F9D,-1, backpack) fletch = Items.FindByID(fletchID,-1, backpack) saw = Items.FindByID(sawID,-1, backpack) scrolls = Items.FindByID(scrollID,-1, backpack) if type == 'smith': Misc.SendMessage('Crafting Smith Repair Deeds') if tong: tool = tong elif hammer: tool = hammer else: Misc.SendMessage('No Tools') elif type == 'tailor': Misc.SendMessage('Crafting Tailor Repair Deeds') if sewKit: tool = sewKit else: Misc.SendMessage('No Tools') elif type == 'carp': Misc.SendMessage('Crafting Carp Repair Deeds') if saw: tool = saw else: Misc.SendMessage('No Tools') elif type == 'fletch': Misc.SendMessage('Crafting Fletch Repair Deeds') if fletch: tool = fletch else: Misc.SendMessage('No Tools') while scrolls: if not Gumps.HasGump(): Items.UseItem(tool) Gumps.WaitForGump(949095101, 50) Gumps.SendAction(949095101, 42) Target.WaitForTarget(1000, False) Target.TargetExecute(scrolls) Misc.Pause(100) scrolls = Items.FindByID(scrollID,-1, backpack) def moveScrolls(): if Target.HasTarget(): Target.Cancel() repairDeeds = Items.FindByID(0x14F0, 0x01bc, backpack) if repairDeeds: Player.HeadMessage(66, 'Target Container to Move deeds to') deedContainer = Target.PromptTarget() while repairDeeds: Items.Move(repairDeeds,deedContainer,0) Misc.Pause(600) repairDeeds = Items.FindByID(0x14F0, 0x01bc, backpack) repairDeed(deedtype) moveScrolls() <file_sep>while Player.IsGhost == False: Player.UseSkill("Hiding") Misc.Pause(10000) <file_sep># This script relys on Bandage_Timer.py, if you do not have it, it will not work # Bandages any guilded pet if within 1 tile from System.Collections.Generic import List from System import Byte import sys def find(notoriety): fil = Mobiles.Filter() fil.Enabled = True fil.RangeMax = 1.5 fil.IsHuman = False fil.IsGhost = False fil.Notorieties = List[Byte](bytes([notoriety])) list = Mobiles.ApplyFilter(fil) return list # quits if you have less than 80 HP if Player.GetRealSkillValue('Veterinary') < 80: Misc.SendMessage('Not enough vet skill, stopping',33) sys.exit() healing = None broodlings = [ 0x02D9,0x0014 ] while True: petList = find(2) init = 0 plist = [] for i in petList: healPet = Mobiles.FindBySerial(i.Serial) if healPet: if healPet.Hits != int(0) and Player.InRangeMobile(healPet, int(1.5)) and healPet.Body not in broodlings: plist.append(healPet.Serial) for j in plist: if init == 0: healing = Mobiles.FindBySerial(j) init = 1 healPet = Mobiles.FindBySerial(j) if healPet: if healPet.Hits <= healing.Hits or healPet.Poisoned: healing = Mobiles.FindBySerial(healPet.Serial) if healing: pet2Heal = Mobiles.FindBySerial(healing.Serial) if pet2Heal: if (pet2Heal.Hits < int(23) or pet2Heal.Poisoned) and Player.InRangeMobile(pet2Heal, int(1.5)): if Misc.ReadSharedValue('bandageDone') == True and Player.Visible: if Target.HasTarget( ) == False: Misc.SendMessage("Healing " + pet2Heal.Name, 33) Items.UseItemByID(0x0E21, -1) Target.WaitForTarget(1500) Target.TargetExecute(pet2Heal) Misc.Pause(600) Misc.Pause(10) <file_sep>''' Author: Aga - original author of the uosteam script Other Contributors: TheWarDoctor95 - converted to Razor Enhanced script MatsaMilla - Converted to be all-in-1 script Last Contribution By: MatsaMilla - 8-28-21 Description: Tames nearby animals to train Animal Taming to GM ''' ########## Script options ############### Misc.ClearIgnore() # True to kill tame, false to not killTame = False # Change to the name that you want to rename the tamed animals to if killTame: renameTamedAnimalsTo = 'kill me' killList = [] else: renameTamedAnimalsTo = 'Thanks Matsa' # Change to the number of followers you would like to keep. # The script will auto-release the most recently tamed animal if the follower number exceeds this number # Some animals have a follower count greater than one, which may cause them to be released if this number is not set high enough numberOfFollowersToKeep = 0 # Set to the maximum number of times to attempt to tame a single animal. 0 == attempt until tamed maximumTameAttempts = 10 # Set the minimum taming difficulty to use when finding animals to tame minimumTamingDifficulty = 31 # Set this to how you would like to heal your character if they take damage # Options are: # 'Healing' = use bandages (you should just use my Bandage_Self.py instead) # 'Magery' = uses the Heal and Greater Heal ability depending on how much health is missing # 'None' = do not auto-heal healUsing = 'None' # True or False to use Peacemaking if needed enablePeacemaking = False # True or False to track the animal being tamed enableFollowAnimal = True # Change depending on the latency to your UO shard journalEntryDelayMilliseconds = 100 targetClearDelayMilliseconds = 100 ################ END SETUP SECTION ###################### import sys if not Misc.CurrentScriptDirectory() in sys.path: sys.path.append(Misc.CurrentScriptDirectory()) from System.Collections.Generic import List from System import Byte import math noAnimalsToTrainTimerMilliseconds = 10000 playerStuckTimerMilliseconds = 5000 catchUpToAnimalTimerMilliseconds = 20000 animalTamingTimerMilliseconds = 12500 peacemakingTimerMilliseconds = 5000 bandageTimerMilliseconds = 10000 if Player.GetRealSkillValue('Animal Taming') < 35: Misc.SendMessage('Buy Taming Skill Up, stopping', 33) sys.exit() from System.Collections.Generic import List class Animal: name = '' mobileID = 0 color = 0 minTamingSkill = -1 maxTamingSkill = -1 packType = None def __init__ ( self, name, mobileID, color, minTamingSkill, maxTamingSkill, packType ): self.name = name self.mobileID = mobileID self.color = color self.minTamingSkill = minTamingSkill self.maxTamingSkill = maxTamingSkill animals = { # Organized based on taming difficulty with no previous owners according to uo.com, then alphabetically by and within species # https://uo.com/wiki/ultima-online-wiki/skills/animal-taming/tameable-creatures/#mobs ### Min skill 0, Max skill 10 ### 'dog': Animal( 'dog', 0x00D9, 0x0000, 0, 10, [ 'canine' ] ), 'gorilla': Animal( 'gorilla', 0x001D, 0x0000, 0, 10, None ), 'parrot': Animal( 'parrot', 0x033F, 0x0000, 0, 10, None ), # Rabbits 'rabbit (brown)': Animal( 'rabbit', 0x00CD, 0x0000, 0, 10, None ), 'rabbit (black)': Animal( 'rabbit', 0x00CD, 0x090E, 0, 10, None ), 'jack rabbit': Animal( 'jack rabbit', 0x00CD, 0x01BB, 0, 10, None ), 'skittering hopper': Animal( 'skittering hopper', 0x012E, 0x0000, 0, 10, None ), 'squirrel': Animal( 'squirrel', 0x0116, 0x0000, 0, 10, None ), ### Min skill 0, Max skill 20 ### 'mongbat': Animal( 'mongbat', 0x0027, 0x0000, 0, 20, None ), ### Min skill 10, Max skill 20 ### # Birds # Note: the following share a color code: # 0x0835: Finch, hawk # 0x0847: Tern, Towhee # 0x0851: Nuthatch, woodpecker # 0x0901: Crow, Magpie, raven 'chickadee': Animal( 'chickadee', 0x0006, 0x0840, 10, 20, None ), 'crossbill': Animal( 'crossbill', 0x0006, 0x083A, 10, 20, None ), 'crow': Animal( 'crow', 0x0006, 0x0901, 10, 20, None ), 'finch': Animal( 'finch', 0x0006, 0x0835, 10, 20, None ), 'hawk': Animal( 'hawk', 0x0006, 0x0835, 10, 20, None ), 'kingfisher': Animal( 'kingfisher', 0x0006, 0x083F, 10, 20, None ), 'lapwing': Animal( 'lapwing', 0x0006, 0x0837, 10, 20, None ), 'magpie': Animal( 'magpie', 0x0006, 0x0901, 10, 20, None ), 'nuthatch': Animal( 'nuthatch', 0x0006, 0x0851, 10, 20, None ), 'plover': Animal( 'plover', 0x0006, 0x0847, 10, 20, None ), 'raven': Animal( 'raven', 0x0006, 0x0901, 10, 20, None ), 'skylark': Animal( 'skylark', 0x0006, 0x083C, 10, 20, None ), 'starling': Animal( 'starling', 0x083E, 0x0845, 10, 20, None ), 'swift': Animal( 'swift', 0x0006, 0x0845, 10, 20, None ), 'tern': Animal( 'tern', 0x0006, 0x0847, 10, 20, None ), 'towhee': Animal( 'towhee', 0x0006, 0x0847, 10, 20, None ), 'woodpecker': Animal( 'woodpecker', 0x0006, 0x0851, 10, 20, None ), 'wren': Animal( 'wren', 0x0006, 0x0850, 10, 20, None ), 'cat': Animal( 'cat', 0x00C9, 0x0000, 10, 20, [ 'feline' ] ), 'chicken': Animal( 'chicken', 0x00D0, 0x0000, 10, 20, None ), 'mountain goat': Animal( 'mountain goat', 0x0058, 0x0000, 10, 20, None ), 'rat': Animal( 'rat', 0x00EE, 0x0000, 10, 20, None ), 'sewer rat': Animal( 'sewer rat', 0x00EE, 0x0000, 10, 20, None ), ### Min skill 20, Max skill 30 ### 'cow (brown)': Animal( 'cow', 0x00E7, 0x0000, 20, 30, None ), 'cow (black)': Animal( 'cow', 0x00D8, 0x0000, 20, 30, None ), 'goat': Animal( 'goat', 0x00D1, 0x0000, 20, 30, None ), 'pig': Animal( 'pig', 0x00CB, 0x0000, 20, 30, None ), 'sheep': Animal( 'sheep', 0x00CF, 0x0000, 20, 30, None ), ### Min skill 20, Max skill 50 ### 'giant beetle': Animal( 'giant beetle', 0x0317, 0x0000, 20, 50, None ), 'slime': Animal( 'slime', 0x0033, 0x0000, 20, 50, None ), ### Min skill 30, Max skill 40 ### 'eagle': Animal( 'eagle', 0x0005, 0x0000, 30, 40, None ), 'bouraRuddy': None, # Not on UO Forever ### Min skill 40, Max skill 50 ### 'boar': Animal( 'boar', 0x0122, 0x0000, 40, 50, None ), 'bullfrog': Animal( 'bullfrog', 0x0051, 0x0000, 40, 50, None ), 'lowland boura': None, # Not on UO Forever 'ferret': Animal( 'ferret', 0x0117, 0x0000, 40, 50, None ), 'giant rat': Animal( 'giant rat', 0x00D7, 0x0000, 40, 50, None ), 'hind': Animal( 'hind', 0x00ED, 0x0000, 40, 50, None ), # Horses 'horse': Animal( 'horse', 0x00C8, 0x0000, 40, 50, None ), 'horse2': Animal( 'horse', 0x00E2, 0x0000, 40, 50, None ), 'horse3': Animal( 'horse', 0x00CC, 0x0000, 40, 50, None ), 'horse4': Animal( 'horse', 0x00E4, 0x0000, 40, 50, None ), 'horsePack': Animal( 'pack horse', 0x0123, 0x0000, 40, 50, None ), 'horsePalomino': None, 'horseWar': None, # Llamas 'pack llama': Animal( 'pack llama', 0x0124, 0x0000, 40, 50, None ), 'llamaRideable': None, # Ostards 'ostard': Animal( 'desert ostard', 0x00D2, 0x0000, 40, 50, [ 'ostard' ] ), 'forest ostard (green)': Animal( 'forest ostard', 0x00DB, 0x88A0, 40, 50, [ 'ostard' ] ), 'forest ostard (red)': Animal( 'forest ostard', 0x00DB, 0x889D, 40, 50, [ 'ostard' ] ), 'timber wolf': Animal( 'timber wolf', 0x00E1, 0x0000, 40, 50, [ 'canine' ] ), 'rideable wolf': Animal( 'rideable wolf', 0x0115, 0x0000, 40, 50, [ 'canine' ] ), ### Min skill 50, Max skill 60 ### 'black bear': Animal( 'black bear', 0x00D3, 0x0000, 50, 60, [ 'bear' ] ), 'polar bear': Animal( 'polar bear', 0x00D5, 0x0000, 50, 60, [ 'bear' ] ), 'deathwatch beetle': None, 'llama': Animal( 'llama', 0x00DC, 0x0000, 50, 60, None ), 'walrus': Animal( 'walrus', 0x00DD, 0x0000, 50, 60, None ), ### Min skill 60, Max skill 70 ### 'alligator': Animal( 'alligator', 0x00CA, 0x0000, 60, 70, None ), 'brown bear': Animal( 'brown bear', 0x00A7, 0x0000, 60, 70, [ 'bear' ] ), 'high plains boura': None, # Not on UO Forever 'cougar': Animal( 'cougar', 0x003F, 0x0000, 60, 70, [ 'feline' ] ), 'paralithode': None, # Not on UO Forever 'scorpion': Animal( 'scorpion', 0x0030, 0x0000, 60, 70, None ), ### Min skill 70, Max skill 80 ### 'rideable polar bear': Animal( 'rideable polar bear', 0x00D5, 0x0000, 70, 80, [ 'bear' ] ), 'grizzly bear': Animal( 'grizzly bear', 0x00D4, 0x0000, 70, 80, [ 'bear' ] ), 'young dragon': Animal( 'young dragon', 0x003C, 0x0000, 70, 80, None ), 'great hart': Animal( 'great hart', 0x00EA, 0x0000, 70, 80, None ), 'snow leopard': Animal( 'snow leopard', 0x0040, 0x0000, 70, 80, [ 'feline' ] ), 'snow leopard2': Animal( 'snow leopard', 0x0041, 0x0000, 70, 80, [ 'feline' ] ), 'panther': Animal( 'panther', 0x00D6, 0x0000, 70, 80, [ 'feline' ] ), 'snake': Animal( 'snake', 0x0034, 0x0000, 70, 80, None ), 'giant spider': Animal( 'giant spider', 0x001C, 0x0000, 70, 80, None ), 'grey wolf (light grey)': Animal( 'grey wolf', 0x0019, 0x0000, 70, 80, [ 'canine' ] ), 'grey wolf (dark grey)': Animal( 'grey wolf', 0x001B, 0x0000, 70, 80, [ 'canine' ] ), ### Min skill 80, Max skill 90 ### 'gaman': None, 'slithStone': None, 'white wolf (dark grey)': Animal( 'white wolf', 0x0022, 0x0000, 80, 90, [ 'canine' ] ), 'white wolf (light grey)': Animal( 'white wolf', 0x0025, 0x0000, 80, 90, [ 'canine' ] ), ### Min skill 90, Max skill 100 ### 'bull (solid, brown)': Animal( 'bull', 0x00E8, 0x0000, 90, 100, [ 'bull' ] ), 'bull (solid, black)': Animal( 'bull', 0x00E8, 0x0901, 90, 100, [ 'bull' ] ), 'bull (spotted, brown)': Animal( 'bull', 0x00E9, 0x0000, 90, 100, [ 'bull' ] ), 'bull (spotted, black)': Animal( 'bull', 0x00E9, 0x0901, 90, 100, [ 'bull' ] ), 'foxBlood': None, 'hellcat (small)': Animal( 'hellcat', 0x00C9, 0x0647, 90, 100, [ 'feline' ] ), 'mongbatGreater': None, 'frenzied ostard': Animal( 'frenzied ostard', 0x00DA, 0x0000, 90, 100, [ 'ostard' ] ), 'osseinRam': None, 'frost spider': Animal( 'frost spider', 0x0014, 0x0000, 90, 100, None ), 'giant toad': Animal( 'giant toad', 0x0050, 0x0000, 90, 100, None ), 'unicorn': None, 'giant ice worm': Animal( 'giant ice worm', 0x0050, 0x0000, 90, 100, None ), ### Min skill 100, Max skill 110 ### # Drakes # pathaleo drake: 0x003C 'drake (brown)': Animal( 'drake', 0x003C, 0x0000, 100, 110, None ), 'drake (red)': Animal( 'drake', 0x003D, 0x0000, 100, 110, None ), 'drakeCrimson': None, 'drakePlatinum': None, 'drakeStygian': None, 'hellcat (large)': Animal( 'hellcat', 0x007F, 0x0000, 100, 110, [ 'feline' ] ), 'hellhound': Animal( 'hellhound', 0x0062, 0x0000, 100, 110, [ 'canine' ] ), 'imp': Animal( 'imp', 0x004A, 0x0000, 100, 110, [ 'daemon' ] ), 'kitsuneBake': None, 'lava lizard': Animal( 'lava lizard', 0x00CE, 0x0000, 100, 110, None ), # ridgebacks 'ridgeback': Animal( 'ridgeback', 0x00BB, 0x0000, 100, 110, None ), 'savage ridgeback': Animal( 'savage ridgeback', 0x00BC, 0x0000, 100, 110, None ), 'slith': None, 'dire wolf': Animal( 'dire wolf', 0x0017, 0x0000, 100, 110, [ 'canine' ] ), ### Min skill 110, Max skill 120 ### 'beetleDeath': None, 'beetleFire': None, 'rune beetle': Animal( 'rune beetle', 0x00F4, 0x0000, 110, 120, None ), 'dragon': Animal( 'dragon', 0x003B, 0x0000, 110, 120, None ), 'dragonSwamp': None, 'dragonWater': None, 'dragonDeepWater': None, 'drakeCold': None, 'hiryu': None, 'hiryuLesser': None, 'lion': None, 'kiRin': None, 'nightbear': None, 'nightdragon': None, 'nightfrenzy': None, 'nightmare': None, 'nightllama': None, 'nightridge': None, 'nightwolf': None, 'skree': None, 'dread spider': Animal( 'dread spider', 0x000B, 0x0000, 110, 120, None ), 'unicorn': None, 'wolfTsuki': None, 'white wyrm': Animal( 'white wyrm', 0x00B4, 0x0000, 110, 120, None ), ### Challenging ### 'cuSidhe': None, 'dimetrosaur': None, # Not on UO Forever # Dragons 'dragonBane': None, 'dragonFrost': None, 'a greater dragon': None, #0x000C 'dragonSerpentine': None, 'gallusaurus': None, # Horses 'steedFire': None, # Pack type: Daemon, Equine 'steedSkeletal': None, # Pack type: Daemon, Equine 'horseDreadWar': None, 'miteFrost': None, 'najasaurus': None, # Not on UO Forever 'phoenix': None, 'raptor': None, # Pack type: Raptor 'reptalon': None, # Not on UO Forever 'saurosurus': None, # Not on UO Forever # Tigers 'tigerWild': None, 'tigerSabreToothed': None, 'triceratops': None, # Not on UO Forever 'turtleHatchlingDragon': None, 'wolfDragon': None, 'shadow wyrm': Animal( 'shadow wyrm', 0x006A, 0x0000, 120, 120, None ) } def GetAnimalIDsAtOrOverTamingDifficulty( minimumTamingDifficulty ): ''' Looks through the list of tameables for animals at or over the minimum taming level ''' global animals animalList = List[int]() for animal in animals: if ( not animals[ animal ] == None and not animalList.Contains( animals[ animal ].mobileID ) and animals[ animal ].minTamingSkill >= minimumTamingDifficulty ): animalList.Add( animals[ animal ].mobileID ) return animalList def FindAnimalToTame(): ''' Finds the nearest tameable animal nearby ''' global renameTamedAnimalsTo global minimumTamingDifficulty animalFilter = Mobiles.Filter() animalFilter.Enabled = True animalFilter.Bodies = GetAnimalIDsAtOrOverTamingDifficulty( minimumTamingDifficulty ) animalFilter.RangeMin = 0 animalFilter.RangeMax = 12 animalFilter.IsHuman = 0 animalFilter.IsGhost = 0 animalFilter.CheckLineOfSite = True animalFilter.Friend = False animalFilter.CheckIgnoreObject = True tameableMobiles = Mobiles.ApplyFilter( animalFilter ) # Exclude animals that have already been tamed by this player tameableMobilesTemp = tameableMobiles[:] for tameableMobile in tameableMobiles: if tameableMobile.Name == renameTamedAnimalsTo: tameableMobilesTemp.Remove( tameableMobile ) tameableMobiles = tameableMobilesTemp if len( tameableMobiles ) == 0: return None elif len( tameableMobiles ) == 1: return tameableMobiles[ 0 ] else: return Mobiles.Select( tameableMobiles, 'Nearest' ) def PlayerWalk( direction ): ''' Moves the player in the specified direction ''' playerPosition = Player.Position if Player.Direction == direction: Player.Walk( direction ) else: Player.Walk( direction ) Player.Walk( direction ) return def FollowMobile( mobile, maxDistanceToMobile = 2, startPlayerStuckTimer = False ): ''' Uses the X and Y coordinates of the animal and player to follow the animal around the map Returns True if player is not stuck, False if player is stuck ''' if not Timer.Check( 'catchUpToAnimalTimer' ): return False mobilePosition = mobile.Position playerPosition = Player.Position directions = [] if mobilePosition.X > playerPosition.X and mobilePosition.Y > playerPosition.Y: directions.append( 'Down' ) if mobilePosition.X < playerPosition.X and mobilePosition.Y > playerPosition.Y: directions.append( 'Left' ) if mobilePosition.X > playerPosition.X and mobilePosition.Y < playerPosition.Y: directions.append( 'Right' ) if mobilePosition.X < playerPosition.X and mobilePosition.Y < playerPosition.Y: directions.append( 'Up' ) if mobilePosition.X > playerPosition.X and mobilePosition.Y == playerPosition.Y: directions.append( 'East' ) if mobilePosition.X < playerPosition.X and mobilePosition.Y == playerPosition.Y: directions.append( 'West' ) if mobilePosition.X == playerPosition.X and mobilePosition.Y > playerPosition.Y: directions.append( 'South' ) if mobilePosition.X == playerPosition.X and mobilePosition.Y < playerPosition.Y: directions.append( 'North' ) if startPlayerStuckTimer: Timer.Create( 'playerStuckTimer', playerStuckTimerMilliseconds ) playerPosition = Player.Position for direction in directions: PlayerWalk( direction ) newPlayerPosition = Player.Position if playerPosition == newPlayerPosition and not Timer.Check( 'playerStuckTimer' ): # Player has been stuck in the same position for a while, try to find them a way out of the stuck position if Player.Direction == 'Up': for i in range ( 5 ): Player.Walk( 'Down' ) elif Player.Direction == 'Down': for i in range( 5 ): Player.Walk( 'Up' ) elif Player.Direction == 'Right': for i in range( 5 ): Player.Walk( 'Left' ) elif Player.Direction == 'Left': for i in range( 5 ): Player.Walk( 'Right' ) Timer.Create( 'playerStuckTimer', playerStuckTimerMilliseconds ) elif playerPosition != newPlayerPosition: Timer.Create( 'playerStuckTimer', playerStuckTimerMilliseconds ) if Player.DistanceTo( mobile ) > maxDistanceToMobile: # This pause may need further tuning # Dont want to create a ton of infinite calls if the player is stuck, but also dont want to not be able to catch up to animals Misc.Pause( 100 ) FollowMobile( mobile, maxDistanceToMobile ) #pathfindToMobile( mobile ) return True def pathfindToMobile(mobile): mobilePosition = mobile.Position mobileCoords = PathFinding.Route() mobileCoords.MaxRetry = 5 mobileCoords.StopIfStuck = True mobileCoords.UseResync = True mobileCoords.X = mobilePosition.X - 1 mobileCoords.Y = mobilePosition.Y if PathFinding.Go(mobileCoords): Misc.NoOperation() else: mobileCoords.X = mobilePosition.X + 1 if PathFinding.Go(mobileCoords): Misc.NoOperation() else: mobileCoords.X = mobilePosition.X mobileCoords.Y = mobilePosition.Y - 1 if PathFinding.Go(mobileCoords): Misc.NoOperation() else: mobileCoords.Y = mobilePosition.Y + 1 PathFinding.Go(mobileCoords) def makePeace(): enemyFilter = Mobiles.Filter() enemyFilter.Enabled = True enemyFilter.CheckIgnoreObject = False enemyFilter.Notorieties = GetEnemyNotorieties() enemyFilter.RangeMin = 0 enemyFilter.RangeMax = 12 enemyFilter.Friend = False enemies = Mobiles.ApplyFilter( enemyFilter ) enemyAtWar = False enemyToPutToPeace = None for enemy in enemies: if enemy.WarMode: enemyAtWar = True enemyToPutToPeace = enemy break while enemyAtWar: if not Timer.Check( 'skillTimer' ): try: enemyToPutToPeace = Mobiles.FindBySerial(enemyToPutToPeace.Serial) if enemyToPutToPeace == None or enemyToPutToPeace.WarMode == False : break # Clear any previously selected target and the target queue Target.ClearLastandQueue() # Wait for the target to finish clearing Misc.Pause( targetClearDelayMilliseconds ) Player.UseSkill( 'Peacemaking' ) # Wait for journal entry to come up Misc.Pause( journalEntryDelayMilliseconds ) if Journal.SearchByType( 'What instrument shall you play?', 'System' ): instrument = findInstrument() if instrument == None: Misc.SendMessage( 'No instruments to peacemake with.', 1100 ) break else: Target.WaitForTarget( 2000, False ) Target.TargetExecute( instrument.Serial ) if Journal.SearchByType( 'Whom do you wish to calm?', 'System' ): Target.WaitForTarget( 2000, False ) Target.TargetExecute( enemyToPutToPeace ) Timer.Create( 'skillTimer', peacemakingTimerMilliseconds ) enemyAtWar = False enemyToPutToPeace = None # for enemy in enemies: # if enemy.WarMode: # enemyAtWar = True # enemyToPutToPeace = enemy # break except: break # Wait a little bit so that the while loop does not consume as much CPU Misc.Pause( 50 ) if killTame == False: if Player.WarMode: Player.SetWarMode( False ) def heal(): if healUsing != 'None': if healUsing == 'Healing' and not Timer.Check( 'bandageTimer' ): # Clear any previously selected target and the target queue Target.ClearLastandQueue() # Wait for the target to finish clearing Misc.Pause( targetClearDelayMilliseconds ) bandage = Items.FindByID(0x0E21, 0, Player.Backpack.Serial) Items.UseItem( bandage ) Target.WaitForTarget(1500) Target.Self() Timer.Create( 'bandageTimer', bandageTimerMilliseconds ) elif healUsing == 'Magery': if ( Player.HitsMax - Player.Hits ) > 30: if not Target.HasTarget(): if Player.Poisoned: Spells.CastMagery('Cure') Target.WaitForTarget(1500) Target.Self() Misc.Pause(500) else: Spells.CastMagery('Greater Heal') Target.WaitForTarget(1500) Target.Self() Misc.Pause(500) elif ( Player.HitsMax - Player.Hits ) > 10: if not Target.HasTarget(): if Player.Poisoned: Spells.CastMagery('Cure') Target.WaitForTarget(1500) Target.Self() Misc.Pause(500) else: Spells.CastMagery('Heal') Target.WaitForTarget(1500) Target.Self() Misc.Pause(500) def TrainAnimalTaming(): ''' Trains Animal Taming to GM ''' # User variables global renameTamedAnimalsTo global numberOfFollowersToKeep global maximumTameAttempts global enablePeacemaking global enableFollowAnimal global journalEntryDelayMilliseconds global targetClearDelayMilliseconds # Script variables global noAnimalsToTrainTimerMilliseconds global playerStuckTimerMilliseconds global catchUpToAnimalTimerMilliseconds global animalTamingTimerMilliseconds global peacemakingTimerMilliseconds global bandageTimerMilliseconds if Player.GetRealSkillValue( 'Animal Taming' ) == Player.GetSkillCap( 'Animal Taming' ): Misc.SendMessage( 'You\'ve already maxed out Animal Taming!', 65 ) return # Initialize variables animalBeingTamed = None tameHandled = False tameOngoing = False timesTried = 0 bandageBeingApplied = False # Initialize skill timers Timer.Create( 'skillTimer', 1 ) if healUsing == 'Healing': Timer.Create( 'bandageTimer', 1 ) elif healUsing == 'Magery': Timer.Create( 'healSpellTimer', 1 ) # Initialize the journal and ignore object list Journal.Clear() # Toggle war mode to make sure the player isn not going to kill the animal being tamed if killTame == False: Player.SetWarMode( True ) Player.SetWarMode( False ) while not Player.IsGhost: if not maximumTameAttempts == 0 and timesTried > maximumTameAttempts: if killTame: Mobiles.Message( animalBeingTamed, 1100, 'Tried more than %i times to tame. Killing animal' % maximumTameAttempts ) Player.Attack( animalBeingTamed ) Misc.Pause(600) Misc.IgnoreObject( animalBeingTamed ) else: Mobiles.Message( animalBeingTamed, 1100, 'Tried more than %i times to tame. Ignoring animal' % maximumTameAttempts ) Misc.IgnoreObject( animalBeingTamed ) Misc.Pause(600) animalBeingTamed = None timesTried = 0 tameHandled = False tameOngoing = False if enablePeacemaking: makePeace() if Player.Hits != Player.HitsMax: heal() # If there is no animal being tamed, try to find an animal to tame if animalBeingTamed == None: animalBeingTamed = FindAnimalToTame() if animalBeingTamed == None: # No animals in the area. Pause for a while so that this is constantly running until something is available to tame Misc.Pause( 500 ) continue else: Mobiles.Message( animalBeingTamed, 90, 'Found animal to tame' ) # Check if animal is close enough to tame if Player.DistanceTo( animalBeingTamed ) > 12: Misc.SendMessage( 'Animal moved too far away, ignoring for now', 1100 ) animalBeingTamed = None continue elif animalBeingTamed != None and Player.DistanceTo( animalBeingTamed ) > 1: if enableFollowAnimal: Timer.Create( 'catchUpToAnimalTimer', catchUpToAnimalTimerMilliseconds ) playerStuck = not FollowMobile( animalBeingTamed, 2, True ) if playerStuck: Player.HeadMessage( 1100, 'Player stuck!' ) return elif Timer.Check('notclose') == False: while Player.DistanceTo( animalBeingTamed ) > 2: if enablePeacemaking: makePeace() if Timer.Check('notclose') == False: Mobiles.Message( animalBeingTamed, 34, 'Not close enough!' ) Timer.Create('notclose', 2000) Misc.Pause( 500 ) # If peacemaking is enabled, make sure the animal being tamed is calm if enablePeacemaking: makePeace() # Tame the animal if a tame is not currently being attempted and enough time has passed since last using Animal Taming if not tameOngoing and not Timer.Check( 'skillTimer' ): # Clear any previously selected target and the target queue Target.ClearLastandQueue() # Wait for the target to finish clearing Misc.Pause( targetClearDelayMilliseconds ) # Hey, we are finally using the Animal Taming skill! about time! Player.UseSkill( 'Animal Taming' ) Target.WaitForTarget( 2000, False ) Target.TargetExecute( animalBeingTamed ) # Check if Animal Taming was successfully triggered if Journal.Search( 'Tame which animal?' ): timesTried += 1 # Restart the timer so that it will go off when we will be able to use the skill again Timer.Create( 'skillTimer', animalTamingTimerMilliseconds ) # Set tameOngoing to true to start the journal checks that will handle the result of the taming tameOngoing = True else: continue if tameOngoing: try: animalBeingTamed = Mobiles.FindBySerial(animalBeingTamed.Serial) if animalBeingTamed == None: break except: break if ( Journal.SearchByName( 'It seems to accept you as master.', animalBeingTamed.Name ) or Journal.Search( 'That wasn\'t even challenging.' ) ): # Animal was successfully tamed if animalBeingTamed.Name != renameTamedAnimalsTo: Misc.PetRename( animalBeingTamed, renameTamedAnimalsTo ) Misc.Pause(200) if Player.Followers > numberOfFollowersToKeep: # Release recently tamed animal #Player.ChatSay(55,animalBeingTamed.Name + " release") Misc.WaitForContext( animalBeingTamed.Serial, 2000 ) Misc.ContextReply( animalBeingTamed.Serial, 'Release') Gumps.WaitForGump( 2426193729, 10000 ) Gumps.SendAction( 2426193729, 2 ) Misc.Pause(600) if killTame: Player.Attack(animalBeingTamed) Misc.Pause(600) Misc.IgnoreObject( animalBeingTamed ) animalBeingTamed = None timesTried = 0 tameHandled = True elif ( Journal.SearchByName( 'You fail to tame the creature.', animalBeingTamed.Name ) or Journal.SearchByName( 'The animal is too angry to continue taming.', animalBeingTamed.Name ) or Journal.SearchByType( 'You must wait a few moments to use another skill.', 'System' ) ): tameHandled = True Misc.SendMessage('Tame attempt ' + str(timesTried),66) elif ( Journal.SearchByType( 'That is too far away.', 'System' ) or Journal.SearchByName( 'You are too far away to continue taming.', animalBeingTamed.Name ) ): # Animal moved too far away, set to None so that another animal can be found animalBeingTamed = None timesTried = 0 Timer.Create( 'skillTimer', 1 ) #Timer.Create( 'animalTamingTimer', 1 ) tameHandled = True elif ( Journal.SearchByName( 'You have no chance of taming this creature', animalBeingTamed.Name ) or Journal.SearchByName( 'already taming', animalBeingTamed.Name ) or Journal.SearchByType( 'Target cannot be seen', 'System' ) or Journal.SearchByType( 'not have a clear path to the animal','System' ) or Journal.Search( 'This animal has had too many owners' ) or Journal.Search( 'That animal looks tame already' ) ): # Ignore the object and set to None so that another animal can be found Misc.IgnoreObject( animalBeingTamed ) animalBeingTamed = None timesTried = 0 Timer.Create( 'skillTimer', 1 ) tameHandled = True if tameHandled: Journal.Clear() tameHandled = False tameOngoing = False # Wait a little bit so that the while loop does not consume as much CPU Misc.Pause( 50 ) def findInstrument(): instruments = [0xe9e, 0x2805, 0xe9c, 0xeb3, 0xeb1, 0x0eb2, 0x0E9D ] #instrument check for i in Player.Backpack.Contains: if i.ItemID in instruments: Target.TargetExecute(i) Player.HeadMessage(msgColour, "Instrument Found") Journal.Clear() Misc.Pause(200) break class Notoriety: byte = Byte( 0 ) color = '' description = '' def __init__ ( self, byte, color, description ): self.byte = byte self.color = color self.description = description notorieties = { 'innocent': Notoriety( Byte( 1 ), 'blue', 'innocent' ), 'ally': Notoriety( Byte( 2 ), 'green', 'guilded/ally' ), 'attackable': Notoriety( Byte( 3 ), 'gray', 'attackable but not criminal' ), 'criminal': Notoriety( Byte( 4 ), 'gray', 'criminal' ), 'enemy': Notoriety( Byte( 5 ), 'orange', 'enemy' ), 'murderer': Notoriety( Byte( 6 ), 'red', 'murderer' ), 'npc': Notoriety( Byte( 7 ), '', 'npc' ) } def GetNotorietyList ( notorieties ): ''' Returns a byte list of the selected notorieties ''' notorietyList = [] for notoriety in notorieties: notorietyList.append( notoriety.byte ) return List[Byte]( notorietyList ) def GetEnemyNotorieties( minRange = 0, maxRange = 12 ): ''' Returns a list of the common enemy notorieties ''' global notorieties return GetNotorietyList( [ notorieties[ 'attackable' ], notorieties[ 'criminal' ], notorieties[ 'enemy' ], notorieties[ 'murderer' ] ] ) def GetEnemies( Mobiles, minRange = 0, maxRange = 12, notorieties = GetEnemyNotorieties(), IgnorePartyMembers = False ): ''' Returns a list of the nearby enemies with the specified notorieties ''' if Mobiles == None: raise ValueError( 'Mobiles was not passed to GetEnemies' ) enemyFilter = Mobiles.Filter() enemyFilter.Enabled = True enemyFilter.RangeMin = minRange enemyFilter.RangeMax = maxRange enemyFilter.Notorieties = notorieties enemyFilter.CheckIgnoreObject = True enemies = Mobiles.ApplyFilter( enemyFilter ) if IgnorePartyMembers: partyMembers = [ enemy for enemy in enemies if enemy.InParty ] for partyMember in partyMembers: enemies.Remove( partyMember ) return enemies # Start Animal Taming TrainAnimalTaming() <file_sep> restockchest = 0x448B879A garbagecontainer = 0x467098AD smithgarbotxt="smithgarbo" #text file containing all the smith garbage data bodstorage = 0x43A2140A fullbodz = 0x448B879A #storage for bods ready to be turned in frombook = 0x4BAB2CC4 #####COLORS###### iron=0x0000 dc=0x0415 shadow=0x0455 copper =0x045f bronze=0x06d8 gold=0x06b7 aggy=0x097e ver=0x07d2 val=0x0544 ##### CONSTANTS ##### tinktool = 0x1EB8 ingotmodel = 0x1BF2 hammermodel = 0x13E3 deedmodel = 0x14EF deedcolor = 0x044e def worldSave(): if Journal.SearchByType('The world will save in 1 minute.', 'Regular' ): Misc.SendMessage('Pausing for world save', 33) while not Journal.SearchByType('World save complete.', 'Regular'): Misc.Pause(500) Misc.Pause(2500) Misc.SendMessage('Continuing run', 33) Journal.Clear() def checktools(): if Items.BackpackCount(tinktool , -1) < 3: Misc.SendMessage('Out of Tink Tools',33) craftTink() Misc.Pause(1000) if Items.BackpackCount(hammermodel , -1) < 3: Misc.SendMessage('Out of hammers',33) craftsmithtool() def craftTink(): UseTinkTool = Items.FindByID(tinktool, -1, Player.Backpack.Serial) Items.UseItem(UseTinkTool.Serial) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, 8) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, 23) Misc.Pause(2000) def craftsmithtool(): UseTinkTool = Items.FindByID(tinktool, -1, Player.Backpack.Serial) Items.UseItem(UseTinkTool.Serial) Gumps.WaitForGump(949095101, 10000) Gumps.SendAction(949095101, 8) Gumps.WaitForGump(949095101, 10000) Gumps.SendAction(949095101, 93) Gumps.WaitForGump(949095101, 10000) Misc.Pause(2000) Gumps.SendAction(949095101, 0) def unstock(): Player.HeadMessage(54, "Unstocking") while Items.FindByID(ingotmodel,-1, Player.Backpack.Serial): moveitem = Items.FindByID(ingotmodel,-1, Player.Backpack.Serial) Items.Move(moveitem, restockchest, 0) Misc.Pause(750) stock(iron, 20) def stock(color,qtyreq): Player.HeadMessage(54, "Checking ingot stock") inbag = Items.BackpackCount(ingotmodel, color) if inbag < qtyreq: Items.UseItem(restockchest) Misc.Pause(750) instock = Items.ContainerCount(restockchest,ingotmodel,color) #how many of that ingot do we have in stock if instock >= qtyreq: qty = qtyreq-inbag moveitem = Items.FindByID(ingotmodel,color, restockchest) Items.Move(moveitem, Player.Backpack.Serial, qty) return True elif instock <= qtyreq: Player.HeadMessage(54, "Not enough of that ingot color sorry") return False def craftinglogic(bod): #Legend #bodarray = [first menue, second menue, total qty, menue for color, actual color, exeptional(t/f), full? (t/f), use special hammer) bodarray = [0,0,0,0,0,0,0,0] tempx = Items.GetPropStringList(bod) #Trim string list a bit x = "" for i in range(0, len(tempx)): x = x + tempx[i] x = x.replace("<BASEFONT COLOR=#585868> Hue: 1102 <BASEFONT COLOR=#FFFFFF>","") Player.HeadMessage(54, str(x)) ######## shields ################ if "buckler" in str(x): prop1 = 36 prop2 = 2 if "bronze shield" in str(x): prop1 = 36 prop2 = 9 if "heater shield" in str(x): prop1 = 36 prop2 = 16 if "metal shield" in str(x): prop1 = 36 prop2 = 23 if "metal kite shield" in str(x): prop1 = 36 prop2 = 30 if "tear kite shield" in str(x): prop1 = 36 prop2 = 37 ######## helmets ################ if "bascinet" in str(x): prop1 = 29 prop2 = 2 if "helmet" in str(x): if "close" in str(x): prop1 = 29 prop2 = 9 else: prop1 = 29 prop2 = 16 if "norse helm" in str(x): prop1 = 29 prop2 = 23 if "plate helm" in str(x): prop1 = 29 prop2 = 30 ######## ringmail ################ if "ringmail gloves" in str(x): prop1 = 8 prop2 = 2 if "ringmail leggings" in str(x): prop1 = 8 prop2 = 9 if "ringmail sleeves" in str(x): prop1 = 8 prop2 = 16 if "ringmail tunic" in str(x): prop1 = 8 prop2 = 23 if "ringmail tunic" in str(x): prop1 = 8 prop2 = 23 ######## chain ################ if "chainmail coif" in str(x): prop1 = 15 prop2 = 2 if "chainmail leggings" in str(x): prop1 = 15 prop2 = 9 if "chainmail tunic" in str(x): prop1 = 15 prop2 = 16 ######## plate ################ if "platemail arms" in str(x): prop1 = 22 prop2 = 2 if "platemail gloves" in str(x): prop1 = 22 prop2 = 9 if "platemail gorget" in str(x): prop1 = 22 prop2 = 16 if "platemail legs" in str(x): prop1 = 22 prop2 = 23 if "platemail tunic" in str(x): prop1 = 22 prop2 = 30 if "female plate" in str(x): prop1 = 22 prop2 = 37 ######QTY####### if "amount to make: 20" in x: prop3 = 20 if "amount to make: 15" in x: prop3 = 15 if "amount to make: 10" in x: prop3 = 10 ######color####### if "All items must be made with valorite ingots." in x: prop4 = 62 prop5 = val if "All items must be made with verite ingots." in x: prop4 = 55 prop5 = ver if "All items must be made with agapite ingots." in x: prop4 = 48 prop5 = aggy if "All items must be made with gold ingots." in x: prop4 = 41 prop5 = gold if "All items must be made with bronze ingots." in x: prop4 = 34 prop5 = bronze if "All items must be made with copper ingots." in x: prop4 = 27 prop5 = copper if "All items must be made with shadow iron ingots." in x: prop4 = 20 prop5 = shadow if "All items must be made with dull copper ingots." in x: prop4 = 13 prop5 = dc if "All items must be made with iron ingots." in x: prop4 = 6 prop5 = iron if "All items must be exceptional." in x: prop6 = True Player.HeadMessage(54, str(prop3)) if str(x).count(str(prop3)) > 1: prop7 = True #True = bod is full else: prop7 = False if "Large" in x: prop8 = True else: prop8 = False bodarray[0]= prop1 #first menue option bodarray[1] = prop2 #second menue option bodarray[2] = prop3 #Req Qty bodarray[3] = prop4 #Menue for color bodarray[4] = prop5 #color idtag bodarray[5] = prop6 #Exceptional ? T/F bodarray[6] = prop7 # Full? T/F bodarray[7] = prop8 #Lbod? T/F #prop8 = need hammer? return bodarray def bagindexing(): inventory = [] for item in Player.Backpack.Contains: inventory.append(item.Serial) Misc.Pause(15) return inventory def findnewitem(inv): #works but the string is weird if you print it. for item in Player.Backpack.Contains: if item.Serial not in inv: return item.Serial def setingotcolor(craftcolor): Misc.Pause(500) UseTool = Items.FindByID(hammermodel, -1, Player.Backpack.Serial) Items.UseItem(UseTool.Serial) Misc.Pause(500) Player.HeadMessage(54, "setting crafting ingot type") Gumps.WaitForGump(949095101, 10000) Gumps.SendAction(949095101, 7) Gumps.WaitForGump(949095101, 10000) Gumps.SendAction(949095101, craftcolor) Misc.Pause(1000) def craftitems(bod): logicarray = craftinglogic(bod) #prime Player.HeadMessage(54, "starting to craft") setingotcolor(logicarray[3]) Player.HeadMessage(54, "is it full?" + str(logicarray[6])) while logicarray[6] == False: worldSave() checktools() if stock(logicarray[4],100) is False: #stocks 100 of ingot color if it fails it stores bod sortbod(bod) return Misc.Pause(1000) inventory = bagindexing() Misc.Pause(1000) UseTool = Items.FindByID(hammermodel, -1, Player.Backpack.Serial) Items.UseItem(UseTool.Serial) Misc.Pause(250) Gumps.WaitForGump(949095101, 10000) Gumps.SendAction(949095101, logicarray[0]) Gumps.WaitForGump(949095101, 10000) Gumps.SendAction(949095101, logicarray[1]) Misc.Pause(2000) item = findnewitem(inventory) if item != None: Journal.Clear() Items.SingleClick(item) Misc.Pause(800) if Journal.Search("Exceptional"): Player.HeadMessage(54, "Exceptional") Items.UseItem(bod) Misc.Pause(750) Gumps.SendAction(1526454082, 2) Misc.Pause(750) Target.TargetExecute(item) Misc.Pause(750) else: Player.HeadMessage(54, "Shitty craft bro") Misc.Pause(500) UseTool = Items.FindByID(hammermodel, -1, Player.Backpack.Serial) Items.UseItem(UseTool.Serial) Misc.Pause(500) Gumps.WaitForGump(949095101, 10000) Gumps.SendAction(949095101, 14) Misc.Pause(750) Target.TargetExecute(item) Misc.Pause(1000) logicarray = craftinglogic(bod) #craft loop finished ############################################################################ ####################################### SORTING ############################ def comparetolist(bod, input): filepath = 'C:/Users/Jason/PycharmProjects/BodBot/' + input + ".txt" f = open(filepath, 'r') allinlist = f.readlines() f.close() #Player.HeadMessage(54, str(len(allinlist))) for i in range(0, len(allinlist)): #Player.HeadMessage(54, str(allinlist[i])) #Player.HeadMessage(54, str(getstringofbod(0x44D90146))) if getstringofbod(bod) == allinlist[i]: Player.HeadMessage(54, "Match found from list") return True else: Misc.Pause(5) return False def getstringofbod(bod): result= "" bodList = Items.GetPropStringList(bod) for i in range(0, len(bodList)): result = result + bodList[i] result = result.replace("[","") result = result.replace("]","") result = result.replace(" deedBlessed<BASEFONT COLOR=#585868> Hue: 1102 <BASEFONT COLOR=#FFFFFF>Weight: 1 stone","") result = result.replace("bulk orderAll items must be","") result = result.replace(".All items must be made with","") result = result.replace(".amount to make:","") result = result.replace("a bulk order","") result = result + '\n' return result def stringtest(x): f = open('C:/Users/Jason/PycharmProjects/BodBot/test.txt', 'a') f.write(str(x)) f.close() def checkgarbo(bod): if comparetolist(bod, smithgarbotxt ): Player.HeadMessage(54, "Sending to garbage") Items.Move(bod, garbagecontainer, 0) return True else: return False def sortbod(bod): #soem sort of logic to sort bods, this is called if we run out of ingots for a bod logicarray = craftinglogic(bod) if logicarray[6] is True: #ie bod is full Items.Move(bod, fullbodz, 0) Player.HeadMessage(54, "Congrats Bod is ready to be turned in") else: Items.Move(bod, bodstorage, 0) def grabbod(): Items.UseItem(frombook) Misc.Pause(1000) Gumps.SendAction(1425364447, 5) Misc.Pause(1000) x = Items.FindByID(deedmodel, deedcolor, Player.Backpack.Serial) return x ####################################### SORTING ############################ ############################################################################ def main(): Journal.Clear() logicarray = [0,0,0,0,0] #initializing #bod = grabbod() while Items.FindByID(deedmodel,deedcolor, Player.Backpack.Serial): bod=Items.FindByID(deedmodel,deedcolor, Player.Backpack.Serial) Player.HeadMessage(54, "mark1") if checkgarbo(bod) is True: return else: #bod = 0x47079787 #bod = 0x43F14045 #half full bod #stringtest(logicarray) #stringtest(Items.GetPropStringList(bod)) #Player.HeadMessage(54, str(logicarray)) craftitems(bod) Misc.Pause(1000) unstock() sortbod(bod) #Player.HeadMessage(54, str(craftinglogic(0x4050F4EF)) ) while True: #unstock() main() Misc.Pause(1000)<file_sep>if Player.GetItemOnLayer("RightHand"): item = Player.GetItemOnLayer("RightHand") elif Player.GetItemOnLayer("LeftHand"): item = Player.GetItemOnLayer("LeftHand") else: Misc.SendMessage("No Weapon in Hand",48) Items.WaitForProps(item,2000) charges = Items.GetPropValue(item,"Charges") if charges > 0: Player.HeadMessage(78,"{} poison charges".format(int(charges))) if charges < 1: Player.HeadMessage(48,"Repoisoning, {} potions left".format(int(Items.BackpackCount(0x0F0A)))) pot = Items.FindByID(0x0F0A,-1,Player.Backpack.Serial) if pot: Player.UseSkill("Poisoning") Target.WaitForTarget(2000) Target.TargetExecute(pot) Target.WaitForTarget(2000) Target.TargetExecute(item) Player.HeadMessage(48,"{} potions left".format(int(Items.BackpackCount(0x0F0A)))) else: Misc.SendMessage("No Poison Pots",48) <file_sep>Player.ChatSay(5, "Forward")<file_sep>Player.ChatSay(5, "Left One")<file_sep># ItemID script by MatsaMilla v2 # Item ID from System.Collections.Generic import List import sys import winsound #********************************************************** # turn to true if client has tool tips enabled toolTipsOn = True # True if you want to keep scrolls sortScrolls = False #if you mark sortScrolls true and this false all lvl8 scrolls go in scroll chest keeplvl8Scrolls = False # True to place all junk in trash barrel, else leaves in chest tossJunk = False # path to sound when overweight sound = "D:\\Program Files\\CUO Launcher\\ClassicUO\\Data\\Plugins\\Razor-Enhanced\\Sounds\\pssst.wav" # Servers drag delay dragTime = 650 #********************************************************** # constant chests regChest = 0x43510513 netChest = 0x4012EC5A goldChest = 0x463A35DB gemChest = 0x4208D8F2 lvl8bag = 0x424A881A #where to put lvl 8 scrolls scrollChest = 0x41FF4A29 #chest for all other scrolls # bags inside scrollChest, from 1-8 for lvls scrollBags = [ 0x424A8818,0x424A881B,0x424A8817,0x424A8816,0x424A8819,0x424A8815,0x424A8814,0x424A881A] #********************************************************** containerToOrganize = Target.PromptTarget('Select container to ID stuff in') sellBag = Target.PromptTarget('Select Sell to NPC Bag') goodChest = Target.PromptTarget('Select KEEPER container (GOOD SHIT)') # Will use ID Wand if skill Item ID below 80 if Player.GetRealSkillValue('Item ID') < 80: idWand = True else: idWand = False ############################################################## # Use neraby trashcan ############################################################## trashBarrelFilter = Items.Filter() trashBarrelFilter.OnGround = 1 trashBarrelFilter.Movable = False trashBarrelFilter.RangeMin = 0 trashBarrelFilter.RangeMax = 2 trashBarrelFilter.Graphics = List[int]( [ 0x0E77 ] ) trashBarrelFilter.Hues = List[int]( [ 0x03B2 ] ) trashcanhere = Items.ApplyFilter( trashBarrelFilter ) if not trashcanhere: Player.HeadMessage( 1100, 'No trashcan nearby!' ) sys.exit() else: global trashCan trashCan = trashcanhere[ 0 ] msgColor = 45 stopWeight = 380 rightHand = Player.CheckLayer('RightHand') leftHand = Player.CheckLayer('LeftHand') # I do not know what this is loot = [0x2260,0x2831] #0x2831 = Recipe Scroll perk = [0x2dd5,0x1f18,0x2da3,0x166e,0x26BB,0x139B] gold = [0xeed] gems = [0xf16,0xf15,0xf19,0xf25,0xf21,0xf10,0xf26,0xf2d,0xf13,0x1F4C] #0x1F4C recall wands = [0xdf5,0xdf3,0xdf4,0xdf2] regs= [0xf7a,0xf7b,0xf86,0xf84,0xf85,0xf88,0xf8d,0xf8c] net = [0x0DCA] boneArmor = [0x1450,0x1f0b,0x1452,0x144f,0x1451,0x144e] weps = [0xf62,0x1403,0xe87,0x1405,0x1401,0xf52,0x13b0,0xdf0,0x1439,0x1407,0xe89,0x143d,0x13b4,0xe81,0x13f8, 0xf5c,0x143b,0x13b9,0xf61,0x1441,0x13b6,0xec4,0x13f6,0xf5e,0x13ff,0xec3,0xf43,0xf45,0xf4d,0xf4b,0x143e, 0x13fb,0x1443,0xf47,0xf49,0xe85,0xe86,0x13fd,0xf50,0x13b2,] armor = [0x1b72,0x1b73,0x1b7b,0x1b74,0x1b79,0x1b7a,0x1b76,0x1408,0x1410,0x1411,0x1412,0x1413,0x1414,0x1415, 0x140a,0x140c,0x140e,0x13bb,0x13be,0x13bf,0x13ee,0x13eb,0x13ec,0x13f0,0x13da,0x13db,0x13d5,0x13d6,0x13dc, 0x13c6,0x13cd,0x13cc,0x13cb,0x13c7,0x1db9,0x1c04,0x1c0c,0x1c02,0x1c00,0x1c08,0x1c06,0x1c0a,] # useless items no matter how good they are, aka bad shields & ringmail sellItems = [ 0x1B72,0x13DB,0x13D5,0x13DA,0x1B7B,0x1DB9,0x13BB,0x1B79,0x13EB,0x1B7A,0x13F0,0x1C02,0x1C0C, 0x13EC,0x1B73,0x13DC,0x13BE,0x13EE,0x13D6,0x13BF ] trash = [0x171c,0x1717,0x1718,0x1544,0x1540,0x1713,0x1715,0x1714,0x1716,0x1717,0x1718,0x1719,0x171a,0x171b, 0x171c,0x2306,0x13f6,0xec4,0x1716,0x171c,0xe81,0xe86,] keepArmorMods = ['Invulnerability','Exceptional'] #'Fortification', 'Hardening', 'Guarding', 'Defence' keepArmorHPMods = ['Indestructible','Fortified','Massive'] # 'Substantial' , 'Durable' keepWepDmgMods = ['Power'] # 'Force', 'Might', 'Ruin' keepWepAccuracyMods = ['Supremely Accurate','Exceedingly Accurate'] # 'Eminently Accurate', 'Surpassingly Accurate', 'Accurate' keepProps = ['Vanquishing'] slayerProps = ['Silver','Undead','Snake','Lizardman','Dragon','Reptile','Terathan', 'Orc Slaying','Ogre','Water','Earth','Elemental','Repond','Fey','Daemon','Exorcism','Poison','Arachnid'] # 'Scorpion','Flame','Vacuum','Gargoyle','Spider' lvl1Scrolls = [ 0x1f2e,# Clumsy 0x1f2f,# Create Food 0x1f30,# Feeblemind 0x1f31,# Heal 0x1f32,# Magic Arrow 0x1f33,# Night Sight 0x1f2d,# Reactive Armor 0x1f34,# Weaken ] lvl2Scrolls = [ 0x1f35,# Agility 0x1f36,# Cunning 0x1f37,# Cure 0x1f38,# Harm 0x1f39,# Magic Trap 0x1f3a,# Magic Untrap 0x1f3b,# Protection 0x1f3c,# Strength ] lvl3Scrolls = [ 0x1f3d,# Bless 0x1f3e,# Fireball 0x1f3f,# Magic Lock 0x1f40,# Poison 0x1f41,# Telekinesis 0x1f42,# Teleport 0x1f43,# Unlock 0x1f44,# Wall of Stone ] lvl4Scrolls = [ 0x1f45,# Arch Cure 0x1f46,# Arch Protection 0x1f47,# Curse 0x1f48,# Fire Field 0x1f49,# Greater Heal 0x1f4a,# Lightning 0x1f4b,# Mana Drain 0x1f4c,# Recall ] lvl5Scrolls = [ 0x1f4d,# Blade Spirit 0x1f4e,# Dispel Field 0x1f4f,# Incognito 0x1f50,# Magic Reflection 0x1f51,# Mind Blast 0x1f52,# Paralyze 0x1f53,# Poison Field 0x1f54,# Summon Creature ] lvl6Scrolls = [ 0x1f55,# Dispel 0x1f56,# Energy Bolt 0x1f57,# Explosion 0x1f58,# Invisibility 0x1f59,# Mark 0x1f5a,# Mass# Curse 0x1f5b,# Paralyze Field 0x1f5c,# Reveal ] lvl7Scrolls = [ 0x1f5d,# Chain Lightning 0x1f5e,# Energy Field 0x1f5f,# Flamestrike 0x1f60,# Gate Travel 0x1f61,# Mana Vampire 0x1f62,# Mass Dispel 0x1f63,# Meteor Swarm 0x1f64,# Polymorph ] lvl8Scrolls = [ 0x1f65,# Earthquake 0x1f66,# Energy Vortex 0x1f67,# Ressurrection 0x1f68,# Summon Air Elemental 0x1f69,# Summon Daemon 0x1f6a,# Summon Earth Elemental 0x1f6b,# Summon Fire Elemental 0x1f6c,# Summon Water Elemental ] if sortScrolls or keeplvl8Scrolls: Items.UseItem(scrollChest) Misc.Pause(dragTime) def equipWand(): global wandSerial player_bag = Items.FindBySerial(Player.Backpack.Serial) if leftHand: Player.UnEquipItemByLayer('LeftHand') Misc.Pause(dragTime) if not rightHand: for i in player_bag.Contains: if i.ItemID in wands: Player.EquipItem(i.Serial) Misc.Pause(dragTime) wandSerial = Player.GetItemOnLayer('RightHand').Serial elif Player.GetItemOnLayer('RightHand').ItemID in wands: wandSerial = Player.GetItemOnLayer('RightHand').Serial else: Player.ChatSay(33, "No Wands Found, Stopping Script") sys.exit() Misc.Pause(dragTime) def idTarget(): worldSave() if idWand: equipWand() Items.UseItem(wandSerial) Misc.Pause(100) else: Player.UseSkill('Item ID') Misc.Pause(100) if not Target.HasTarget(): Misc.Pause(1000) idTarget() def checkWeight(): if Player.Weight >= stopWeight: Player.HeadMessage(msgColor, 'Go Sell this shit') winsound.PlaySound(sound, winsound.SND_ALIAS) sys.exit() def idStuff(container, type): idContainer = Items.FindBySerial(container) if type == 'weps': idItems = weps tier1 = keepWepDmgMods tier2 = keepWepAccuracyMods worthlessBag = sellBag elif type == 'armor': idItems = armor tier1 = keepArmorMods tier2 = keepArmorHPMods worthlessBag = sellBag elif type == 'bone': idItems = boneArmor tier1 = keepArmorMods tier2 = ['Indestructible'] worthlessBag = trashCan for i in idContainer.Contains: worldSave() if i.ItemID in idItems: checkWeight() Journal.Clear() idTarget() Target.WaitForTarget(1500) Target.TargetExecute(i.Serial) Misc.Pause(dragTime) Items.SingleClick(i) if any(Journal.Search(keep) for keep in keepProps): #** Good Stuff Move ** Items.Move(i, goodChest, 0) Misc.Pause(dragTime) elif any(Journal.Search(slash) for slash in tier1): #moves items if in sell ids if i.ItemID in sellItems: #** Sell Stuff Move ** Items.Move(i, worthlessBag, 0) Misc.Pause(dragTime) elif any(Journal.Search(sub) for sub in tier2): #** Good Stuff Move ** Items.Move(i, goodChest, 0) Misc.Pause(dragTime) else: #** Sell Stuff Move ** Items.Move(i, worthlessBag, 0) Misc.Pause(dragTime) else: #** Sell Stuff Move ** Items.Move(i, worthlessBag, 0) Misc.Pause(dragTime) def idStuffToolTips(container, type): idContainer = Items.FindBySerial(container) if type == 'weps': idItems = weps tier1 = keepWepDmgMods tier2 = keepWepAccuracyMods worthlessBag = sellBag elif type == 'armor': idItems = armor tier1 = keepArmorMods tier2 = keepArmorHPMods worthlessBag = sellBag elif type == 'bone': idItems = boneArmor tier1 = keepArmorMods tier2 = ['Indestructible'] worthlessBag = trashCan for i in idContainer.Contains: worldSave() if i.ItemID in idItems: checkWeight() Journal.Clear() idTarget() Target.WaitForTarget(1500) Target.TargetExecute(i.Serial) Misc.Pause(dragTime) Items.WaitForProps(i,2000) props = Items.GetPropStringList(i) if any(elem in keepProps for elem in props): #** Good Stuff Move ** Items.Move(i, goodChest, 0) Misc.Pause(dragTime) elif any(elem in tier1 for elem in props): #moves items if in sell ids if i.ItemID in sellItems: #** Sell Stuff Move ** Items.Move(i, worthlessBag, 0) Misc.Pause(dragTime) elif any(elem in tier2 for elem in props): #** Good Stuff Move ** Items.Move(i, goodChest, 0) Misc.Pause(dragTime) else: #** Sell Stuff Move ** Items.Move(i, worthlessBag, 0) Misc.Pause(dragTime) else: #** Sell Stuff Move ** Items.Move(i, worthlessBag, 0) Misc.Pause(dragTime) def organizeItems(container): idContainer = Items.FindBySerial(container) for i in idContainer.Contains: worldSave() if i.ItemID in loot: Items.Move(i, Player.Backpack.Serial, 0) Misc.Pause(dragTime) elif i.ItemID in perk: Items.Move(i, Player.Backpack.Serial, 0) Misc.Pause(dragTime) elif i.ItemID in gold: Items.Move(i, goldChest, 0) Misc.Pause(dragTime) elif i.ItemID in regs: Items.Move(i, regChest, 0) Misc.Pause(dragTime) elif i.ItemID in gems: Items.Move(i, gemChest, 0) Misc.Pause(dragTime) elif i.ItemID in net: Items.Move(i, netChest, 0) Misc.Pause(dragTime) elif i.ItemID in lvl8Scrolls: if keeplvl8Scrolls and sortScrolls == False: Items.Move(i, scrollBags[7], 0) Misc.Pause(dragTime) for i in idContainer.Contains: if i.ItemID in lvl1Scrolls: scrollSorter(i, scrollBags[0]) elif i.ItemID in lvl2Scrolls: scrollSorter(i, scrollBags[1]) elif i.ItemID in lvl3Scrolls: scrollSorter(i, scrollBags[2]) elif i.ItemID in lvl4Scrolls: scrollSorter(i, scrollBags[3]) elif i.ItemID in lvl5Scrolls: scrollSorter(i, scrollBags[4]) elif i.ItemID in lvl6Scrolls: scrollSorter(i, scrollBags[5]) elif i.ItemID in lvl7Scrolls: scrollSorter(i, scrollBags[6]) elif i.ItemID in lvl8Scrolls: scrollSorter(i, scrollBags[7]) elif i.ItemID in trash: if tossJunk: Items.Move(i, trashCan, 0) Misc.Pause(dragTime) def scrollSorter(item, destination): if sortScrolls: Items.Move(item, destination, 0) Misc.Pause(dragTime) else: if tossJunk: Items.Move(item, trashCan, 0) Misc.Pause(dragTime) def worldSave(): if Journal.SearchByType('The world is saving, please wait.', 'Regular' ): Misc.SendMessage('Pausing for world save', 33) while not Journal.SearchByType('World save complete.', 'Regular'): Misc.Pause(1000) Misc.SendMessage('Continuing', 33) Journal.Clear() def findChest(): # Filters chest = Items.Filter() chest.Enabled = True chest.OnGround = True chest.Movable = True chest.RangeMax = 1 chest.Graphics = List[int]( [ 0x0E40,0x0E43,0x0E41,0x0E43,0x09AB,0x0E42 ] ) chest.CheckIgnoreObject = True chest = Items.ApplyFilter(chest) sortChest = Items.Select(chest, 'Nearest') if sortChest: Items.UseItem(sortChest) Misc.Pause(dragTime) if Journal.Search("locked")== True: lockpickchest(sortChest) Misc.Pause(3000) Items.UseItem( sortChest ) while Player.Hits < Player.HitsMax: Spells.CastMagery('Greater Heal') Target.WaitForTarget(1500) Target.Self() Misc.Pause(2500) Items.UseItem( sortChest ) Misc.Pause(dragTime) organizeItems(sortChest.Serial) if toolTipsOn: idStuffToolTips(sortChest.Serial, 'weps') idStuffToolTips(sortChest.Serial, 'armor') idStuffToolTips(sortChest.Serial, 'bone') else: idStuff(sortChest.Serial, 'weps') idStuff(sortChest.Serial, 'armor') idStuff(sortChest.Serial, 'bone') Player.HeadMessage(msgColor, 'Chest Cleared') # Items.Move(sortChest.Serial, trashCan, 0) # Misc.Pause(dragTime) # Misc.IgnoreObject(sortChest.Serial) def lockpickchest(chest): lockpicks = Items.FindByID(0x14FC, -1, Player.Backpack.Serial) if lockpicks == None: Player.HeadMessage( 33, 'You don\'t have any lockpicks!' ) return Items.UseItem(lockpicks) lockedChest = Items.FindBySerial( chest.Serial ) Player.HeadMessage( 44, 'Starting chest unlock!' ) Journal.Clear() while not ( Journal.SearchByName( 'The lock quickly yields to your skill.', '' ) or Journal.SearchByType( 'This does not appear to be locked.', 'Regular' ) ): Items.UseItem( lockpicks ) Target.WaitForTarget( 2000, True ) Target.TargetExecute( lockedChest ) Misc.Pause( 4000 ) Misc.Pause( 120 ) lockpicks = Items.FindByID(0x14FC, -1, Player.Backpack.Serial) if lockpicks == None: Player.HeadMessage( 33, 'Ran out of lockpicks!' ) return else: return False Items.UseItem(containerToOrganize) Misc.Pause(dragTime) Items.UseItem(sellBag) Misc.Pause(dragTime) Journal.Clear() organizeItems(containerToOrganize) if toolTipsOn: idStuffToolTips(containerToOrganize, 'weps') idStuffToolTips(containerToOrganize, 'armor') idStuffToolTips(containerToOrganize, 'bone') else: idStuff(containerToOrganize, 'weps') idStuff(containerToOrganize, 'armor') idStuff(containerToOrganize, 'bone') Player.HeadMessage(msgColor, 'Chest Cleared') Items.Move(containerToOrganize, trashCan, 0) <file_sep># Slayer Spellbook Crafter by MatsaMilla # Last edit: Matsamilla 3/16/22 # # Restocks blank scrolls from beetle (1k at a time) # Moves slayers to beetle # Must have tooltips enabled from System.Collections.Generic import List #***************SETUP SECTION********************************** keepAll = False # true to keep all slayers, false keeps only ones in keepSlayerProps keepSlayerProps = ['Silver','Reptilian Death','Elemental Ban','Repond','Exorcism','Arachnid Doom','Fey Slayer', 'Balron Damnation','Daemon Dismissal','Orc Slaying','Dragon Slaying'] #************************************************************** dragTime = 600 pen = 0xfbf scrolls = 0x0EF3 spellbook = 0x0EFA noColor = 0x0000 self_pack = Player.Backpack.Serial self = Player.Serial rightHand = Player.CheckLayer('RightHand') fullSpellbook = Items.FindByID(0x0EFA,0x0000,Player.Backpack.Serial) if fullSpellbook: Items.WaitForProps(fullSpellbook, 500) if "64 Spells" in str(fullSpellbook.Properties): if not Player.CheckLayer("RightHand"): Player.HeadMessage(66,'Equiping full spellbook to not trash') Player.EquipItem(fullSpellbook) Misc.Pause(dragTime) else: Player.HeadMessage(33,'You have a full spellbook in your pack and cant equip to save it. Stopping.') Player.HeadMessage(66,'Target Pack Animal') beetle = Target.PromptTarget() Player.HeadMessage(66,'Target an Item in Pack Animals Backpack') beetleContainer = Items.FindBySerial(Target.PromptTarget()) beetleContainer = beetleContainer.RootContainer isitabeetle = Mobiles.FindBySerial(beetle) if isitabeetle.Body == 0x0317: itsAbeetle = True else: itsAbeetle = False if not keepAll: Player.HeadMessage(66, 'Keeping:') for i in keepSlayerProps: Player.HeadMessage(66, i) Misc.Pause(200) else: Player.HeadMessage(66, 'Keeping All Slayers') slayers = ['Silver','Reptilian Death','Elemental Ban','Repond','Exorcism','Arachnid Doom','Fey Slayer', 'Balron Damnation','Daemon Dismissal','Orc Slaying', 'Blood Drinking', 'Troll Slaughter', 'Ogre Thrashing','Dragon Slaying','Earth Shatter','Elemental Health','Flame Dousing', 'Summer Wind','Vacuum','Water Dissipation','Gargoyles Foe','Scorpions Bane','Spiders Death', 'Terathan','Lizardman Slaughter','Ophidian','Snakes Bane'] slayersLower = [] keepSlayerPropsLower = [] for i in range(len(keepSlayerProps)): slayersLower.append(keepSlayerProps[i].lower()) for k in range(len(slayers)): keepSlayerPropsLower.append(slayers[k].lower()) # Use neraby trashcan trashBarrelFilter = Items.Filter() trashBarrelFilter.OnGround = 1 trashBarrelFilter.Movable = False trashBarrelFilter.RangeMin = 0 trashBarrelFilter.RangeMax = 2 trashBarrelFilter.Graphics = List[int]( [ 0x0E77 ] ) trashBarrelFilter.Hues = List[int]( [ 0x03B2 ] ) trashcanhere = Items.ApplyFilter( trashBarrelFilter ) if not trashcanhere: Player.HeadMessage( 1100, 'No trashcan nearby!' ) Misc.ScriptStop( 'craft_SlayerSpellbook.py' ) Misc.Pause(5000) Stop else: global trashcan trashcan = trashcanhere[ 0 ] def moveSlayerBookToBeetle(): if Player.Mount and itsAbeetle: Mobiles.UseMobile(self) Misc.Pause(dragTime) Items.Move(craftedBook, beetle, 1) Misc.Pause(dragTime) Mobiles.UseMobile(beetle) Misc.Pause(dragTime) def trashSpellbook(): if craftedBook: Items.Move(craftedBook, trashcan, 1) Misc.Pause(dragTime) def hide(): if not Player.BuffsExist('Hiding') and Timer.Check('hideskill') == False: Player.UseSkill('Hiding') Timer.Create('hideskill',11000) def checkMats(): if Items.BackpackCount(scrolls, -1) < 16: restockScrolls() Misc.Pause(dragTime) if Items.BackpackCount(scrolls, -1) < 16: Misc.SendMessage('Out of Scrolls',33) if not Player.Mount and itsAbeetle: Mobiles.UseMobile(beetle) Misc.Pause(dragTime) Stop def restockScrolls(): if Player.Mount and itsAbeetle: Mobiles.UseMobile(self) Misc.Pause(dragTime) Mobiles.SingleClick(beetle) Misc.WaitForContext(beetle, 1500) if Player.Visible: Misc.ContextReply(beetle, "Open Backpack") #10 else: Misc.ContextReply(beetle, "Open Backpack") #0 Misc.Pause(dragTime) beetleScrolls = Items.FindByID(scrolls, noColor, beetleContainer) if beetleScrolls: Player.HeadMessage (66, 'Restocking') Items.Move(beetleScrolls, self_pack, 500) Misc.Pause(dragTime) if not Player.Mount and itsAbeetle: Mobiles.UseMobile(beetle) Misc.Pause(dragTime) def FindItem( itemID, container, color = -1, ignoreContainer = [] ): ''' Searches through the container for the item IDs specified and returns the first one found Also searches through any subcontainers, which Misc.FindByID() does not ''' ignoreColor = False if color == -1: ignoreColor = True if isinstance( itemID, int ): foundItem = next( ( item for item in container.Contains if ( item.ItemID == itemID and ( ignoreColor or item.Hue == color ) ) ), None ) elif isinstance( itemID, list ): foundItem = next( ( item for item in container.Contains if ( item.ItemID in itemID and ( ignoreColor or item.Hue == color ) ) ), None ) else: raise ValueError( 'Unknown argument type for itemID passed to FindItem().', itemID, container ) if foundItem != None: return foundItem subcontainers = [ item for item in container.Contains if ( item.IsContainer and not item.Serial in ignoreContainer ) ] for subcontainer in subcontainers: foundItem = FindItem( itemID, subcontainer, color, ignoreContainer ) if foundItem != None: return foundItem def craftBook(): currentPen = FindItem(pen, Player.Backpack) #Items.FindByID(pen, -1, -1,True) if currentPen: if Gumps.CurrentGump() != 0x38920abd: Items.UseItem(currentPen.Serial) Gumps.WaitForGump(0x38920abd,1500) Gumps.SendAction(0x38920abd, 57) Gumps.WaitForGump(0x38920abd,1500) Gumps.SendAction(0x38920abd, 16) Misc.Pause(2000) else: Misc.SendMessage('Out of Pens',33) Misc.Beep() if not Player.Mount and itsAbeetle: Mobiles.UseMobile(beetle) Misc.Pause(dragTime) Stop def slayerCheck(): global craftedBook craftedBook = Items.FindByID(spellbook, -1, self_pack) while craftedBook: if keepAll: Items.WaitForProps(craftedBook, 1500) props = Items.GetPropStringList(craftedBook) if any(elem in slayers for elem in props) or any(elem in slayersLower for elem in props): Player.HeadMessage (66, props[3]) # moveSlayerBookToBeetle() else: trashSpellbook() else: Items.WaitForProps(craftedBook, 1500) props = Items.GetPropStringList(craftedBook) if any(elem in keepSlayerProps for elem in props) or any(elem in keepSlayerPropsLower for elem in props): Player.HeadMessage (66, props[3]) # moveSlayerBookToBeetle() else: trashSpellbook() craftedBook = Items.FindByID(spellbook, -1, self_pack) while True: Journal.Clear() if Player.GetRealSkillValue('Hiding') > 30: hide() checkMats() craftBook() while Items.BackpackCount(spellbook, -1) > 0: slayerCheck() if not Player.Mount and itsAbeetle: Mobiles.UseMobile(beetle) Misc.Pause(dragTime) <file_sep># Sallos . recall and . gate commands # By MatsaMilla, Version 2.0 - UOAges Compatible Misc.Pause(5000) runebookDelay = 600 if Misc.ShardName() == "UO Ages": runebookID = 0x0EFA runebookDelay = 800 else: runebookID = 0x22C5 if Player.GetRealSkillValue('Magery') > 35: mageRecall = True else: mageRecall = False Misc.SendMessage('Recalling by Charges') def makeRunebookList( ): sortedRuneList = [] for i in Player.Backpack.Contains: if i.ItemID == runebookID: # opens runebook Items.UseItem( i ) Misc.Pause(120) Gumps.WaitForGump( 1431013363, 500 ) if Journal.Search('You must wait'): Misc.SendMessage('trying runebook again') Items.UseItem( i ) Gumps.WaitForGump( 1431013363, 500 ) Journal.Clear() bookSerial = i.Serial runeNames = [] lineList = Gumps.LastGumpGetLineList() # Remove the default 3 lines from the top of the list lineList = lineList[ 3 : ] # Remove the items before the names of the runes endIndexOfDropAndDefault = 0 for i in range( 0, len( lineList ) ): if lineList[ i ] == 'Set default' or lineList[ i ] == 'Drop rune': endIndexOfDropAndDefault += 1 else: break # Add two for the charge count and max charge numbers endIndexOfDropAndDefault += 2 runeNames = lineList[ endIndexOfDropAndDefault : ( endIndexOfDropAndDefault + 16 ) ] runeNames = [ name for name in runeNames if name != 'Empty' ] mageRecall = 5 chargeRecall = 2 gate = 6 for x in runeNames: sortedRuneList.append( (bookSerial, x.lower(), mageRecall , chargeRecall , gate) ) mageRecall = mageRecall + 6 chargeRecall = chargeRecall + 6 gate = gate + 6 Gumps.CloseGump(1431013363) Misc.Pause(runebookDelay) Misc.SendMessage('Runebooks Updated', 66) return sortedRuneList def recall( str ): for f in runeNames: if str == f[1]: Items.UseItem(f[0]) Gumps.WaitForGump(1431013363, 1000) Gumps.SendAction(1431013363, f[2]) Player.HeadMessage(66, '- ' + str + ' -') def chargeRecall( str ): for f in runeNames: if str == f[1]: Items.UseItem(f[0]) Misc.Pause(50) Gumps.WaitForGump(1431013363, 1000) Gumps.SendAction(1431013363, f[3]) Player.HeadMessage(66, '- ' + str + ' -') # Items.WaitForProps(f[0],500) # charges = Items.GetPropValue(f[0],'Charges') # Player.HeadMessage(66, str(int(charges)) + ' charges left' ) def gate( str ): for f in runeNames: if str == f[1]: Items.UseItem(f[0]) Gumps.WaitForGump(1431013363, 1000) Gumps.SendAction(1431013363, f[4]) Player.HeadMessage(66, '- ' + str + ' -') #Misc.SendMessage('Gating ' + str,11) def FindItem( itemID, container, color = -1, ignoreContainer = [] ): ''' Searches through the container for the item IDs specified and returns the first one found Also searches through any subcontainers, which Misc.FindByID() does not ''' ignoreColor = False if color == -1: ignoreColor = True if isinstance( itemID, int ): foundItem = next( ( item for item in container.Contains if ( item.ItemID == itemID and ( ignoreColor or item.Hue == color ) ) ), None ) elif isinstance( itemID, list ): foundItem = next( ( item for item in container.Contains if ( item.ItemID in itemID and ( ignoreColor or item.Hue == color ) ) ), None ) else: raise ValueError( 'Unknown argument type for itemID passed to FindItem().', itemID, container ) if foundItem != None: return foundItem subcontainers = [ item for item in container.Contains if ( item.IsContainer and not item.Serial in ignoreContainer ) ] for subcontainer in subcontainers: foundItem = FindItem( itemID, subcontainer, color, ignoreContainer ) if foundItem != None: return foundItem def checkRegs(): if (FindItem(0x0F7A , Player.Backpack) and FindItem(0x0F86 , Player.Backpack) and FindItem(0x0F7B , Player.Backpack) ): return True else: return False def parseJournal (str): # Fetch the Journal entries (oldest to newest) regularText = Journal.GetTextBySerial(Player.Serial) # Reverse the Journal entries so that we read from newest to oldest regularText.Reverse() # Read back until the item ID was started to see if it succeeded try: for line in regularText[ 0 : len( regularText ) ]: #if line == str: if str in line: line = line.split(str + ' ', 1)[1] Journal.Clear() return line except: Player.HeadMessage(33,'Not Found') playerSerialCheck = Misc.ReadSharedValue('playerSerial') runeNames = Misc.ReadSharedValue('runeNames'+str(Player.Serial)) if runeNames == 0: Misc.SendMessage('Reading Runebooks, please wait', 33) runeNames = makeRunebookList() Misc.Pause(500) Misc.SetSharedValue('runeNames'+str(Player.Serial), runeNames) else: Misc.SendMessage('Runes Still In Memory', 66) Journal.Clear() while Player.IsGhost: Misc.Pause(5000) while True: if Journal.SearchByName(". recall", Player.Name): if mageRecall and checkRegs(): recallLocation = parseJournal('. recall') if recallLocation != None: recall(recallLocation.lower()) Misc.NoOperation() else: recallLocation = parseJournal('. recall') if recallLocation != None: chargeRecall(recallLocation.lower()) Misc.NoOperation() Journal.Clear() elif Journal.SearchByName(". gate", Player.Name): gateLocation = parseJournal('. gate') if gateLocation != None: gate(gateLocation.lower()) Journal.Clear() Misc.Pause(50) <file_sep># Poison trainer by MatsaMilla # NEED: Bag of poison kegs # Empty bag for emtpy kegs to go into # Food to poison backpack = Player.Backpack.Serial dragTime = 600 msgColor = 33 pKeg = None import sys def GetBag ( sharedValue, promptString ): if Misc.CheckSharedValue( sharedValue ): bag = Misc.ReadSharedValue( sharedValue ) if not Items.FindBySerial( bag ): bag = Target.PromptTarget( promptString ) Misc.SetSharedValue( sharedValue, bag ) else: bag = Target.PromptTarget( promptString ) Misc.SetSharedValue( sharedValue, bag ) return bag kegBag = Target.PromptTarget( 'Select Bag with Poison Kegs' )# GetBag( 'KegBag', 'Select Bag with Poison Kegs' ) emptyKegBag = Target.PromptTarget( 'Select Bag for empty Kegs' ) #GetBag( 'eKegBag', 'Select Bag for empty Kegs' ) toPoison = Target.PromptTarget( 'Target what you want to poison' ) #GetBag( 'toPoisonn', 'Target what you want to poison') Items.UseItem(kegBag) Misc.Pause(dragTime) def restockKeg(): emptyKeg = Items.FindByID( 0x1940 , -1 , backpack ) if emptyKeg != None: Items.Move( emptyKeg , emptyKegBag , 0 ) Misc.Pause(dragTime) Items.UseItem(kegBag) Misc.Pause(dragTime) pKeg = Items.FindByID( 0x1940 , -1 , kegBag ) if pKeg != None: Items.Move( pKeg , backpack , 0 ) Misc.Pause(dragTime) elif pkeg == None: Misc.SendMessage('Out of kegs', msgColor) Misc.Beep() sys.exit() def trainPoison(): pkeg = Items.FindByID( 0x1940 , -1 , backpack ) if not Items.BackpackCount(0xf0a, -1): Items.UseItem(pkeg) Misc.Pause(dragTime) ppot = Items.FindByID( 0xf0a , -1 , backpack ) if ppot and Timer.Check('poisonTimer') == False: Player.UseSkill('Poisoning') Target.WaitForTarget(1500) Target.TargetExecute(ppot) Target.WaitForTarget(1500) Target.TargetExecute(toPoison) Timer.Create('poisonTimer', 11000) elif pkeg == None: restockKeg() Journal.Clear() if Journal.Search('The keg is empty.'): restockKeg() Journal.Clear() def boxRefresh(): if Timer.Check('boxrefresh') == False: Items.DropItemGroundSelf(kegBag, 0) Timer.Create('boxrefresh', 180000) #300000 = 5 mins Journal.Clear() while True: if Player.GetRealSkillValue('Poisoning') > 30 and Player.GetRealSkillValue('Poisoning') < 100: trainPoison() boxRefresh() Misc.Pause(100) while Player.Hits < 50: Misc.Pause(50) <file_sep>Player.ChatSay(5, "Forward One")<file_sep>Player.ChatSay(5, "Fire Left")<file_sep>''' Author: TheWarDoctor95 Other Contributors: Last Contribution By: MatsaMilla - March 28, 2020 Description: Uses the instruments from the player backpack and the selected target to train Provocation to GM Provokes mobs onto yourself Targets nearest mob until 75, then tries to target a rotting corpse if one is around. ''' from System.Collections.Generic import List from System import Byte import sys # provo skill cooldown provocationTimerMilliseconds = 10200 instruments = [0xe9e, 0x2805, 0xe9c, 0xeb3, 0xeb1, 0x0eb2 , 0x0E9D] enemyFilter = Mobiles.Filter() enemyFilter.Enabled = True enemyFilter.RangeMax = 12 enemyFilter.Notorieties = List[Byte](bytes( [ 3 , 4 ] ) ) rottingFilter = Mobiles.Filter() rottingFilter.Enabled = True rottingFilter.RangeMax = 12 rottingFilter.Bodies = List[int] ( [ 0x009B ] ) def TrainProvocation(): ''' Trains Musicianship by using the instruments in the player bag Transitions to a new instrument if the one being used runs out of uses ''' global provocationTimerMilliseconds global provocationTarget Timer.Create( 'provocationTimer', 1 ) while Player.GetSkillValue( 'Provocation' ) < 100: rottingMob = Mobiles.ApplyFilter(rottingFilter) rotting = Mobiles.Select(rottingMob, "Nearest") enemyMob = Mobiles.ApplyFilter(enemyFilter) enemy = Mobiles.Select(enemyMob, "Farthest") if Timer.Check( 'provocationTimer' ) == False: Journal.Clear() Player.UseSkill( 'Provocation' ) Misc.Pause(120) # selects an instrument if on is needed. if Journal.Search("What instrument shall you play?"): for i in Player.Backpack.Contains: if i.ItemID in instruments: Target.TargetExecute(i) Player.HeadMessage(33, "Instrument Found") Journal.Clear() Misc.Pause(200) break Misc.SendMessage('No Instruments found',33) sys.exit() Target.WaitForTarget( 2000, True ) # targets a mob if Player.GetSkillValue( 'Provocation' ) < 75: Target.TargetExecute( enemy ) elif Player.GetSkillValue( 'Provocation' ) > 75: if rotting: Target.TargetExecute( rotting ) else: Target.TargetExecute( enemy ) else: Target.TargetExecute( enemy ) Target.WaitForTarget( 2000, True ) Target.Self() Timer.Create( 'provocationTimer', provocationTimerMilliseconds ) # Wait a little bit so that the while loop does not consume as much CPU Misc.Pause( 50 ) Player.HeadMessage(66, 'Wahoo! GM Provo!') # Start Training TrainProvocation() <file_sep>Download both files. Edit ButlerProfiles with as many profiles as you would like. It works by pulling the toon name (no spaces or caps) and going from there. Follow / replace / copy the examples there to get it to work. This will replace current profile(s) on butler, so if you use multiple clients / helpers you may not want to use these scripts. <file_sep>Journal.Clear() Player.WeaponStunSA( ) Misc.Pause(120) if Journal.Search("You get yourself ready to stun your opponent."): Player.HeadMessage(33, "Stun: ON") if Journal.Search("You decide to not try to stun anyone."): Player.HeadMessage(33, "Stun: OFF") if Journal.Search("You are not skilled enough to stun your opponent."): Player.HeadMessage(33, "NO STUN")<file_sep>''' Author: TheWarDoctor95 Other Contributors: Last Contribution By: Matsamilla - 12/7/21 Description: Selects enemies to use the Provocation skill on. • Automatically selects an instrument if one is needed • Maintains a list of enemies that have been successfully been provoked together and will ignore enemies that have been provoked together • If one of the enemies that has already been provokd dies, the script will detect the death and free up the enemy that is still alive to be provoked again • Priority: 1. PKs 2. Paragons 3. Enemies in War Mode 4. Any other enemy ''' ## Script options ## # Change depending on whether or not you want a more verbose output on what is being provoked or ignored by the script showTargets = True import re from System.Collections.Generic import List from System import Byte journalEntryDelayMilliseconds = 200 targetClearDelayMilliseconds = 200 dragDelayMilliseconds = 600 enemiesProvodSharedValue = 'enemiesProvod' pkFilter = Mobiles.Filter() pkFilter.Enabled = True pkFilter.RangeMax = 12 pkFilter.IsHuman = True pkFilter.IsGhost = False pkFilter.Friend = False pkFilter.Notorieties = List[Byte](bytes([ 6 ])) def GetEmptyMobileList( Mobiles ): ''' Creates a filter that returns an empty list, and then returns the empty list ''' emptyFilter = Mobiles.Filter() emptyFilter.Enabled = True emptyFilter.Name = 'there_is_no_way this_is someones_name_since_its_way_too_long' return Mobiles.ApplyFilter( emptyFilter ) class Notoriety: byte = Byte( 0 ) color = '' description = '' def __init__ ( self, byte, color, description ): self.byte = byte self.color = color self.description = description notorieties = { 'innocent': Notoriety( Byte( 1 ), 'blue', 'innocent' ), 'ally': Notoriety( Byte( 2 ), 'green', 'guilded/ally' ), 'attackable': Notoriety( Byte( 3 ), 'gray', 'attackable but not criminal' ), 'criminal': Notoriety( Byte( 4 ), 'gray', 'criminal' ), 'enemy': Notoriety( Byte( 5 ), 'orange', 'enemy' ), 'murderer': Notoriety( Byte( 6 ), 'red', 'murderer' ), 'npc': Notoriety( Byte( 7 ), '', 'npc' ) } def GetNotorietyList ( notorieties ): ''' Returns a byte list of the selected notorieties ''' notorietyList = [] for notoriety in notorieties: notorietyList.append( notoriety.byte ) return List[Byte]( notorietyList ) def GetEnemyNotorieties( minRange = 0, maxRange = 12 ): ''' Returns a list of the common enemy notorieties ''' global notorieties return GetNotorietyList( [ notorieties[ 'attackable' ], notorieties[ 'criminal' ], notorieties[ 'enemy' ], notorieties[ 'murderer' ] ] ) def GetEnemies( Mobiles, minRange = 0, maxRange = 12, notorieties = GetEnemyNotorieties(), IgnorePartyMembers = True ): ''' Returns a list of the nearby enemies with the specified notorieties ''' if Mobiles == None: raise ValueError( 'Mobiles was not passed to GetEnemies' ) enemyFilter = Mobiles.Filter() enemyFilter.Enabled = True enemyFilter.RangeMin = minRange enemyFilter.RangeMax = maxRange enemyFilter.Notorieties = notorieties enemyFilter.CheckIgnoreObject = True enemyFilter.Friend = False enemies = Mobiles.ApplyFilter( enemyFilter ) if IgnorePartyMembers: partyMembers = [ enemy for enemy in enemies if enemy.InParty ] for partyMember in partyMembers: enemies.Remove( partyMember ) return enemies class myItem: name = None itemID = None color = None category = None weight = None def __init__ ( self, name, itemID, color, category, weight ): self.name = name self.itemID = itemID self.color = color self.category = category self.weight = weight def FindItem( itemID, container, color = -1, ignoreContainer = [] ): ''' Searches through the container for the item IDs specified and returns the first one found Also searches through any subcontainers, which Misc.FindByID() does not ''' ignoreColor = False if color == -1: ignoreColor = True if isinstance( itemID, int ): foundItem = next( ( item for item in container.Contains if ( item.ItemID == itemID and ( ignoreColor or item.Hue == color ) ) ), None ) elif isinstance( itemID, list ): foundItem = next( ( item for item in container.Contains if ( item.ItemID in itemID and ( ignoreColor or item.Hue == color ) ) ), None ) else: raise ValueError( 'Unknown argument type for itemID passed to FindItem().', itemID, container ) if foundItem != None: return foundItem subcontainers = [ item for item in container.Contains if ( item.IsContainer and not item.Serial in ignoreContainer ) ] for subcontainer in subcontainers: foundItem = FindItem( itemID, subcontainer, color, ignoreContainer ) if foundItem != None: return foundItem colors = { 'green': 65, 'cyan': 90, 'orange': 43, 'red': 1100, 'yellow': 52 } instruments = { 'drum': myItem( 'drum', 0x0E9C, 0x0000, 'instrument', None ), 'flute': myItem( 'flute', 0x2805, 0x0000, 'instrument', None ), 'lute': myItem( 'lute', 0x0EB3, 0x0000, 'instrument', None ), # Harps 'lap harp': myItem( 'lap harp', 0x0EB2, 0x0000, 'instrument', None ), 'standing harp': myItem( 'standing harp', 0x0EB1, 0x0000, 'instrument', None ), # Tambourines 'tambourine': myItem( 'tambourine', 0x0E9E, 0x0000, 'instrument', None ), 'tambourine (tassle)': myItem( 'tambourine', 0x0E9D, 0x0000, 'instrument', None ) } def FindInstrument( container ): ''' Uses FindItem to look through the players backpack for an instrument ''' global instruments instrumentIDs = [ instruments[ instrument ].itemID for instrument in instruments ] return FindItem( instrumentIDs, container ) def CheckPlayerInDungeon( Player ): ''' Uses the Players X and Y coordinates to determine if they are in a dungeon ''' if Player.Position.X < 5120: # Player is west of the dungeon cutoff return False if Player.Position.Y < 2305: # Player is east of the dungeon cutoff and to the north of the Lost Lands return True if Player.Position.X > 6140: # Player is east of the Lost Lands return True # Player is in the Lost Lands return False def SelectEnemyToProvo( enemies ): ''' Selects the nearest enemy who is not provoked to use Provocation on ''' enemiesAlreadyProvod = None enemiesAlreadyProvodCheck = Misc.CheckSharedValue( enemiesProvodSharedValue ) if enemiesAlreadyProvodCheck: enemiesAlreadyProvod = Misc.ReadSharedValue( enemiesProvodSharedValue ) # Make sure the enemies we provoked previously are still around verifiedEnemiesAlreadyProvod = None enemySets = enemiesAlreadyProvod.split( ',' ) for enemySet in enemySets: enemySerials = enemySet.split( '`' ) bothEnemiesStillExist = True for enemySerial in enemySerials: enemyMobile = Mobiles.FindBySerial( int( enemySerial ) ) if enemyMobile == None: bothEnemiesStillExist = False if bothEnemiesStillExist and verifiedEnemiesAlreadyProvod == None: verifiedEnemiesAlreadyProvod = enemySet elif bothEnemiesStillExist: verifiedEnemiesAlreadyProvod += ',' + enemySet # Update the stored values enemiesAlreadyProvod = verifiedEnemiesAlreadyProvod if verifiedEnemiesAlreadyProvod == None: Misc.RemoveSharedValue( enemiesProvodSharedValue ) else: Misc.SetSharedValue( enemiesProvodSharedValue, verifiedEnemiesAlreadyProvod ) enemiesNotYetProvod = enemies if enemiesAlreadyProvod != None: # Remove the enemies we have already provoked from the list of potential enemies to provo enemiesAlreadyProvodSerials = [] enemySets = enemiesAlreadyProvod.split( ',' ) for enemySet in enemySets: enemySerials = enemySet.split( '`' ) for enemy in enemySerials: enemiesAlreadyProvodSerials.append( int( enemy ) ) enemiesNotYetProvodPythonList = list( filter( lambda enemy: enemy.Color == 1157 or not ( enemy.Serial in enemiesAlreadyProvodSerials ), enemies ) ) # We have the Python formatted list, but we need a C# list to pass to Mobiles.Select() enemiesNotYetProvodCSharpList = GetEmptyMobileList( Mobiles ) for enemy in enemiesNotYetProvodPythonList: enemiesNotYetProvodCSharpList.Add( enemy ) enemiesNotYetProvod = enemiesNotYetProvodCSharpList # Make sure there are still enemies yet to be provod, if not, use all of the enemies given enemiesToProvo = enemiesNotYetProvod if len( enemiesToProvo ) == 0: enemiesToProvo = enemies # Select the enemy to provo paragons = [ enemy for enemy in enemiesToProvo if enemy.Color == 1157 ] if len( paragons ) > 0: paragonMobiles = GetEmptyMobileList( Mobiles ) for paragon in paragons: paragonMobiles.Add( paragon ) return Mobiles.Select( paragonMobiles, 'Nearest' ) if not CheckPlayerInDungeon( Player ): # Make sure we are pulling enemies attacking and not birds or rabbits enemiesInWarMode = [ enemy for enemy in enemiesToProvo if enemy.WarMode ] if len( enemiesInWarMode ) > 0: warModeMobiles = GetEmptyMobileList( Mobiles ) for enemyInWarMode in enemiesInWarMode: warModeMobiles.Add( enemyInWarMode ) return Mobiles.Select( warModeMobiles, 'Nearest' ) return Mobiles.Select( enemiesToProvo, 'Nearest' ) def ProvoEnemies(): ''' Identifies enemies that need to be provoked and uses the Provocation skill on them Having this encapsulated in a function makes it possible to use the 'return' keyword ''' global showTargets Misc.ClearIgnore() provoAttemptCompleted = False while not provoAttemptCompleted: enemies = GetEnemies( Mobiles, 0, 12, GetEnemyNotorieties(), IgnorePartyMembers = True ) #murderer = GetEnemies( Mobiles, 0, 12, 'murderer' , IgnorePartyMembers = True ) if enemies == None or len( enemies ) < 2: Misc.SendMessage( 'Not enough enemies to provo!', colors[ 'red' ] ) return else: # Clear any previously selected target and the target queue Target.ClearLastandQueue() # Wait for the target to finish clearing Misc.Pause( targetClearDelayMilliseconds ) Player.UseSkill( 'Provocation' ) # Wait for the journal entry to appear Misc.Pause( journalEntryDelayMilliseconds ) if Journal.SearchByType( 'You must wait a few moments to use another skill.', 'System' ): # Something is on cooldown, nothing we can do Player.HeadMessage( 55, 'Skill Timer, try again') Journal.Clear() return elif Journal.SearchByType( 'What instrument shall you play?', 'System' ): instrument = FindInstrument( Player.Backpack ) if instrument == None: Misc.SendMessage( 'No instrument to provo with!', colors[ 'red' ] ) return Target.WaitForTarget( 2000, True ) Target.TargetExecute( instrument ) Target.WaitForTarget( 2000, True ) enemyToProvo1 = SelectEnemyToProvo( enemies ) Target.TargetExecute( enemyToProvo1 ) # Wait for the journal entry to appear Misc.Pause( journalEntryDelayMilliseconds ) if Journal.SearchByType( 'Target cannot be seen', 'System' ): if showTargets: Mobiles.Message( enemyToProvo1, colors[ 'red' ], 'Target 1 cannot be seen' ) Misc.IgnoreObject( enemyToProvo1 ) Journal.Clear() provoAttemptCompleted = False Misc.Pause( 1000 ) continue # Remove the selected enemy to ensure we don not provo an enemy onto themselves enemies.Remove( enemyToProvo1 ) pkscan = Mobiles.ApplyFilter( pkFilter ) pk = Mobiles.Select( pkscan , 'Nearest' ) Target.WaitForTarget( 2000, True ) if pk: Target.TargetExecute(pk) Player.HeadMessage( 33 , 'Provo on ' + pk.Name) Target.SetLast(pk) else: enemyToProvo2 = SelectEnemyToProvo( enemies ) Target.TargetExecute( enemyToProvo2 ) # Wait for the journal entry to appear Misc.Pause( journalEntryDelayMilliseconds ) if Journal.SearchByType( 'Target cannot be seen', 'System' ): if showTargets: Mobiles.Message( enemyToProvo2, colors[ 'red' ], 'Target 2 cannot be seen' ) Misc.IgnoreObject( enemyToProvo2 ) Journal.Clear() provoAttemptCompleted = False Misc.Pause( 1000 ) continue if showTargets: Mobiles.Message( enemyToProvo1, colors[ 'cyan' ], 'Provo Target 1' ) Mobiles.Message( enemyToProvo2, colors[ 'cyan' ], 'Provo Target 2' ) # Wait for the journal entry to appear Misc.Pause( journalEntryDelayMilliseconds ) if Journal.SearchByType( 'Your music succeeds, as you start a fight.', 'System' ): Journal.Clear() newEntry = '%i`%i' % ( enemyToProvo1.Serial, enemyToProvo2.Serial ) enemiesAlreadyProvodCheck = Misc.CheckSharedValue( enemiesProvodSharedValue ) if enemiesAlreadyProvodCheck: enemiesAlreadyProvod = Misc.ReadSharedValue( enemiesProvodSharedValue ) Misc.SetSharedValue( enemiesProvodSharedValue, enemiesAlreadyProvod + ',' + newEntry ) else: Misc.SetSharedValue( enemiesProvodSharedValue, newEntry ) provoAttemptCompleted = True # Run ProvoEnemies while Target.HasTarget(): Misc.Pause(10) ProvoEnemies() <file_sep># Bandage Timer by Wardoc # Contributions by Matsamilla # I have this always running, start at login. # version 2.0 - If running RazorEnhanced 7.7.23 or greater use this now, or change line 13 to match # True for overhead Bandage Available message, false for in system messages overheadMessage = True msgcolor = 88 Misc.SetSharedValue('bandageDone', True) def BandagesApplying(): # Fetch the Journal entries (oldest to newest) regularText = Journal.GetTextByType( 'System' ) # Reverse the Journal entries so that we read from newest to oldest regularText.Reverse() # Read back until the bandages were started to see if they have finished applying for line in regularText[ 0 : len( regularText ) ]: if (line == 'You begin applying the bandages.' or line == 'Your hands are still busy applying other bandages.'): break if ( line == 'You finish applying the bandages.' or line == 'You heal what little damage your patient had.' or line == 'You apply the bandages, but they barely help.' or line == 'That being is not damaged!' or line == 'You have cured the target of all poisons!' or line == 'You are unable to resurrect your patient.' or line == 'You are able to resurrect your patient' or line == 'You are able to resurrect the creature.' or line == 'You fail to resurrect the creature.' or line == 'You did not stay close enough to heal your patient!'): return False return True def WaitForBandagesToApply(): Misc.SetSharedValue('bandageDone', False) #bandageDone = False secondsCounter = 0 while BandagesApplying(): worldSave() Misc.Pause( 1000 ) secondsCounter += 1 if overheadMessage: Player.HeadMessage( msgcolor, 'Bandage: %is' % ( secondsCounter ) ) else: Player.HeadMessage ( msgcolor, 'Bandage: %is' % ( secondsCounter ) ) if secondsCounter > 18: break if overheadMessage: Player.HeadMessage(msgcolor, 'Bandage Available') else: Misc.SendMessage( 'Bandage Available', msgcolor ) Misc.SetSharedValue('bandageDone', True) return def worldSave(): if Journal.SearchByType('The world is saving, please wait.', 'System' ): Misc.SendMessage('Pausing for world save', 33) while not Journal.SearchByType('World save complete.', 'System'): Misc.Pause(1000) Misc.SendMessage('Continuing', 33) Journal.Clear() Journal.Clear() while True: if Player.IsGhost: # Player died, wait until Player is resurrected while Player.IsGhost: Misc.Pause( 100 ) if Journal.Search('You begin applying the bandages.'): WaitForBandagesToApply() Journal.Clear() Misc.Pause( 50 ) <file_sep># in dress agent create one that is your player name # without spaces and a 2 at the end. # Example: "Player Name" needs to be playername2 msgcolor = 62 wep2 = Player.Name.lower().replace(' ', '') + '2' Player.HeadMessage(msgcolor, "Weapon 2") Dress.ChangeList(wep2) Dress.DressFStart() <file_sep>Player.ChatSay(5, "Back Left")<file_sep># use this to dye all items inside a container (I use to dye armor) dyeTub = Target.PromptTarget( 'Target dye tub' ) container = Items.FindBySerial( Target.PromptTarget( 'Target Container with armor' ) ) for i in container.Contains: Items.UseItem(dyeTub) Target.WaitForTarget(1500) Target.TargetExecute(i) Misc.Pause(550)<file_sep># Automatic Potion Butler Filler by MatsaMilla # - Version 4, updated 4/3/22 (Includes DP now) # Must have TOOLTIPSON ([toggletooltips in game to turn off/on) # NEED: Restock Chest (containing regs / empty pots), # Mortars in backpack or in restock chest (can be in a bag in restock chest, has to be open). # Empty keg in toons backpack. # Makes Make sure restock chest & motar restock bags are open #mark false to NOT fill DP fillDeadlyPoison = False #*******************************************************************# Player.HeadMessage(66,'Target Butler') butler = Target.PromptTarget('Target Butler') Player.HeadMessage(66,'Target Restock Chest') restockChest = Items.FindBySerial( Target.PromptTarget('Target Restock Chest') ) #Player.HeadMessage(66,'Mortar Restock Bag (optional)') #mortarBag = Items.FindBySerial( Target.PromptTarget('Mortar Restock Bag (optional)') ) import sys keg = Items.FindByID( 0x1940 , -1 , Player.Backpack.Serial ) if keg: Misc.SendMessage('Using keg in pack', 66) else: Player.HeadMessage(66,'Target keg to fill') kegTarget = Target.PromptTarget('Target keg to fill') Misc.SendMessage('Using targeted Keg', 66) keg = Items.FindBySerial(kegTarget) fillStopNumber = 5000 dragTime = 800 butlerGump = 989312372 def setValues( regValue , potValue , gump1 , gump2 ): global regID global potID global gumpAction1 global gumpAction2 regID = regValue potID = potValue gumpAction1 = gump1 gumpAction2 = gump2 def FindItem( itemID, container, color = -1, ignoreContainer = [] ): ''' Searches through the container for the item IDs specified and returns the first one found Also searches through any subcontainers, which Misc.FindByID() does not ''' ignoreColor = False if color == -1: ignoreColor = True if isinstance( itemID, int ): foundItem = next( ( item for item in container.Contains if ( item.ItemID == itemID and ( ignoreColor or item.Hue == color ) ) ), None ) elif isinstance( itemID, list ): foundItem = next( ( item for item in container.Contains if ( item.ItemID in itemID and ( ignoreColor or item.Hue == color ) ) ), None ) else: raise ValueError( 'Unknown argument type for itemID passed to FindItem().', itemID, container ) if foundItem != None: return foundItem subcontainers = [ item for item in container.Contains if ( item.IsContainer and not item.Serial in ignoreContainer ) ] for subcontainer in subcontainers: foundItem = FindItem( itemID, subcontainer, color, ignoreContainer ) if foundItem != None: return foundItem def craftPot (potType): # set values for pot items if potType == 'cure': setValues( 0x0F84 , 0x0F07 , 43 , 16 ) elif potType == 'heal': setValues( 0x0F85, 0x0F0C , 22 , 16 ) elif potType == 'refresh': setValues ( 0x0F7A , 0x0F0B , 1 , 9 ) elif potType == 'explode': setValues ( 0x0F8C, 0x0F0D , 50 , 16 ) elif potType == 'strength': setValues ( 0x0F86 , 0x0F09 , 29 , 9 ) elif potType == 'agility': setValues ( 0x0F7B, 0x0F08 , 8 , 9 ) elif potType == 'DP': setValues ( 0x0F88 , 0x0F0A , 36 , 23 ) else: Misc.SendMessage('potType not defined, stopping', 33) sys.exit() while not Items.GetPropValue(keg,'The Keg Is Completely Full.'): #while not Journal.SearchByType('The keg will not hold any more!', 'System'): # non-tool tips change worldSave() # find mortar, even if nested in backpack mortar = FindItem( 0x0E9B , Player.Backpack ) if not mortar: mortarFound = FindItem( 0x0E9B , restockChest )#Items.FindByID(0x0E9B , -1 , mortarBag) if mortarFound: Items.Move(mortarFound, Player.Backpack.Serial, 0) Misc.Pause(dragTime) else: Misc.SendMessage('Out of Mortars!', 33) Misc.Pause(5000) sys.exit() # count / restock reg type packRegs = FindItem(regID, Player.Backpack) if not packRegs or packRegs.Amount < 10: #if Items.BackpackCount(regID) < 10: Misc.Pause(100) regFound = FindItem(regID, restockChest) #Items.FindByID( regID, -1, restockChest) if regFound: Items.WaitForProps( regFound.Serial , dragTime) Items.Move( regFound, Player.Backpack , 250 ) Misc.Pause(800) packRegs = FindItem(regID, Player.Backpack) if not packRegs or packRegs.Amount < 10: #if Items.BackpackCount(regID) < 10: Misc.NoOperation() #Misc.SendMessage('Out of regs for this pot type, moving to next pot - 1', 33) break else: Misc.SendMessage('Out of regs for this pot type, moving to next pot', 33) return False # move pot to keg pot = FindItem( potID , Player.Backpack) while pot: Items.Move(pot, keg, 0) Misc.Pause(dragTime) pot = FindItem( potID , Player.Backpack) if Journal.SearchByType('The keg will not hold any more!', 'System'): break # make sure you have empty bottle if Items.BackpackCount(0x0F0E) < 1: emptyPot = FindItem(0x0F0E,restockChest) #Items.FindByID( 0x0F0E, -1, restockChest) if emptyPot: Items.Move(emptyPot, Player.Backpack.Serial, 2) Misc.Pause(dragTime) else: Player.HeadMessage(33,'Need empty pot(s) in restock container or in backpack.') sys.exit() # empty keg of other potion if Journal.Search('You decide that it would be a bad idea to mix different types of potions.'): Misc.SendMessage('Oops') Items.Move( keg , butler , 0 ) Misc.Pause(dragTime) Journal.Clear() #craft pot Items.UseItem(mortar) Gumps.WaitForGump(949095101, dragTime) Gumps.SendAction(949095101, gumpAction1) Gumps.WaitForGump(949095101, dragTime) Gumps.SendAction(949095101, gumpAction2) Gumps.WaitForGump(949095101, dragTime) Misc.Pause(120) #check keg level Items.WaitForProps(keg, dragTime) # move keg to butler Items.Move( keg , butler , 0 ) Misc.Pause(dragTime) Journal.Clear() def worldSave(): if Journal.SearchByType('The world is saving, please wait.', 'Regular' ): # if Journal.SearchByType('The world will save in 1 minute.', 'Regular' ): Misc.SendMessage('Pausing for world save', 33) while not Journal.SearchByType('World save complete.', 'Regular'): Misc.Pause(1000) Misc.SendMessage('Continuing', 33) Journal.Clear() Journal.Clear() Misc.Pause(1000) Mobiles.UseMobile(butler) Misc.Pause(1000) if Gumps.LastGumpTextExist( 'Remove Leather Tub?' ): Misc.SendMessage('Leather Tub Detected') fillList = [('cure',37),('agility',38),('strength',39),('DP',40),('refresh',41),('heal',42),('explode',43)] else: fillList = [('cure',35),('agility',36),('strength',37),('DP',38),('refresh',39),('heal',40),('explode',41)] while True: # verify its butler gump if Gumps.CurrentGump() == butlerGump: # iterate through fillList for i in fillList: # read gump line fillNumber = fillStopNumber - int(float(Gumps.LastGumpGetLine(i[1]))) while fillNumber > 100: #int(float(Gumps.LastGumpGetLine(i[1]))) < fillStopNumber: if str(i[0]) == 'DP' and fillDeadlyPoison == False: break Gumps.CloseGump(butlerGump) Misc.SendMessage('Filling ' + str(i[0])+ ', ' + str(fillNumber) + ' left', 66) Misc.Pause(dragTime) craftPot (i[0]) Mobiles.UseMobile(butler) Misc.Pause(dragTime) fillNumber = fillStopNumber - int(float(Gumps.LastGumpGetLine(i[1]))) Misc.SendMessage('Butler is as full as we can get it!', 66) Gumps.CloseGump(butlerGump) sys.exit() else: Mobiles.UseMobile(butler) Misc.Pause(dragTime) <file_sep># ButlerProfiles.py by MatsaMilla - 2 part script, part 1 is ButlerHelper.py # updated 4/2/22 - new field: Misc.SetSharedValue('deadlypoison', 0) # You need to set up a "profile" for each toon based on name # see examples below # Note - armor (0 = no, 1 = yes) (all but cap) # cap (0 = no, 1 = yes) (cap only) # If upgrading, add this line to your profiles to take a cap: Misc.SetSharedValue('cap', 1) #makes player name lowercase with no spaces.... if name of toon is <NAME>, makes it matsamilla name = Player.Name.lower().replace(' ', '') if name == 'matsamilla': #Replace matsamilla with toon name, no caps or spaces Misc.SendMessage('Loading: ' + name) Misc.SetSharedValue('moss', 75) Misc.SetSharedValue('ash', 75) Misc.SetSharedValue('root', 75) Misc.SetSharedValue('pearl', 75) Misc.SetSharedValue('shade', 75) Misc.SetSharedValue('ginseng', 75) Misc.SetSharedValue('garlic', 75) Misc.SetSharedValue('silk', 75) Misc.SetSharedValue('bandies', 50) Misc.SetSharedValue('exp', 10) Misc.SetSharedValue('str', 10) Misc.SetSharedValue('refresh', 20) Misc.SetSharedValue('agil', 10) Misc.SetSharedValue('heal', 15) Misc.SetSharedValue('cure', 10) Misc.SetSharedValue('arrows', 0) Misc.SetSharedValue('bolts', 0) Misc.SetSharedValue('armor', 1) Misc.SetSharedValue('cap', 1) Misc.SetSharedValue('deadlypoison', 0) #****************** # copy, paste and edit as many as this next section as you need for toons elif name == 'playername': #Replace playername with toon name, no caps or spaces Misc.SendMessage('Loading: ' + name) Misc.SetSharedValue('moss', 0) Misc.SetSharedValue('ash', 0) Misc.SetSharedValue('root', 0) Misc.SetSharedValue('pearl', 0) Misc.SetSharedValue('shade', 0) Misc.SetSharedValue('ginseng', 0) Misc.SetSharedValue('garlic', 0) Misc.SetSharedValue('silk', 0) Misc.SetSharedValue('bandies', 100) Misc.SetSharedValue('exp', 0) Misc.SetSharedValue('str', 10) Misc.SetSharedValue('refresh', 20) Misc.SetSharedValue('agil', 10) Misc.SetSharedValue('heal', 10) Misc.SetSharedValue('cure', 10) Misc.SetSharedValue('arrows', 0) Misc.SetSharedValue('bolts', 0) Misc.SetSharedValue('armor', 0) Misc.SetSharedValue('cap', 0) Misc.SetSharedValue('deadlypoison', 0) #****************** Misc.ScriptRun('ButlerHelper.py') <file_sep>Player.ChatSay(5, "Back One")<file_sep>Player.ChatSay(5, "Back Right")<file_sep># Toggle alternate wep by MatsaMilla # Updated 7/16/21 leftHand = Player.GetItemOnLayer('LeftHand') rightHand = Player.GetItemOnLayer('RightHand') shields = [ 0x1B76,0x1B74,0x1B7B,0x1B73,0x1B72,0x1B79,0x1B7A ] if Misc.CheckSharedValue(Player.Name + 'wep2'): tempwep = Items.FindBySerial(Misc.ReadSharedValue(Player.Name + 'wep2')) if tempwep: wep = tempwep else: Player.HeadMessage(66,'Target New Wep') wep = Items.FindBySerial( Target.PromptTarget() ) Misc.SetSharedValue(Player.Name + 'wep2', wep.Serial) Player.HeadMessage(66, 'Wep Set') else: Player.HeadMessage(66,'Target Wep') wep = Items.FindBySerial( Target.PromptTarget() ) Misc.SetSharedValue(Player.Name + 'wep2', wep.Serial) Player.HeadMessage(66, 'Wep Set') def toggleWep(): if wep.IsTwoHanded: Misc.SendMessage('Two Handed') if rightHand: Items.Move(rightHand.Serial,Player.Backpack.Serial,0) Misc.Pause(600) if leftHand: if leftHand.Serial == wep.Serial: Items.Move(wep,Player.Backpack.Serial,0) Misc.Pause(600) else: Items.Move(leftHand.Serial,Player.Backpack.Serial,0) Misc.Pause(600) Player.EquipItem(wep) else: Player.EquipItem(wep) elif wep.ItemID in shields: Misc.SendMessage('Shield') if leftHand: if leftHand.Serial == wep.Serial: Items.Move(wep,Player.Backpack.Serial,0) else: Items.Move(leftHand.Serial,Player.Backpack.Serial,0) Misc.Pause(600) Player.EquipItem(wep) else: Player.EquipItem(wep) else: if rightHand: if rightHand.Serial == wep.Serial: Items.Move(wep,Player.Backpack.Serial,0) else: Items.Move(rightHand,Player.Backpack.Serial,0) Misc.Pause(600) Player.EquipItem(wep) if leftHand: if leftHand.Serial == wep.Serial: Items.Move(wep,Player.Backpack.Serial,0) elif leftHand.ItemID in shields: Player.EquipItem(wep) else: Items.Move(leftHand,Player.Backpack.Serial,0) Misc.Pause(600) Player.EquipItem(wep) else: Player.EquipItem(wep) toggleWep() <file_sep>Player.ChatSay(5, "Forward Right")<file_sep>Player.ChatSay(5, "Drop Anchor") Misc.Pause(400) Player.ChatSay(5, "Disembark")<file_sep># Weapon Swapper by Matsamilla # Swaps between weps you target, last targeted is first equipted # if only one weapon targeted, acts as a wep toggle. # Version 3.1, updated 7/16/21 leftHand = Player.GetItemOnLayer('LeftHand') rightHand = Player.GetItemOnLayer('RightHand') shields = [ 0x1B76,0x1B74,0x1B7B,0x1B73,0x1B72,0x1B79,0x1B7A ] def setWeps(text, multiple=True): Player.HeadMessage(76,text) list = [] if multiple: while multiple: chosenid = Target.PromptTarget() if chosenid > -1: chosen = Items.FindBySerial(chosenid) Misc.Pause(500) list.append(chosen.Serial) else: multiple = False if len(list) == 1: return chosen else: return list else: chosenid = Target.PromptTarget() if chosenid > -1: chosen = Items.FindBySerial(chosenid) Misc.Pause(500) Misc.SendMessage("Chose {}".format(chosen.Name)) return chosenid def swampWeps(): for i in mainWeplist: if Items.FindBySerial(i) == None: Player.HeadMessage(33, 'Set New Weps') Misc.RemoveSharedValue(Player.Name + 'weplist') Misc.RemoveSharedValue(Player.Name + 'mainWeplist') checkList() break # set weps to temp list if Misc.CheckSharedValue(Player.Name + 'weplist'): weplist = Misc.ReadSharedValue(Player.Name + 'weplist') else: weplist =[] for i in mainWeplist: weplist.append(i) Misc.SetSharedValue(Player.Name + 'weplist', weplist) # get last list position lastPos = len(weplist) -1 # equip next wep in list #currentWep = Items.FindBySerial(currentWep) wep = Items.FindBySerial(weplist[lastPos]) if wep.IsTwoHanded: Misc.SendMessage('Two Handed') if rightHand: Items.Move(rightHand.Serial,Player.Backpack.Serial,0) Misc.Pause(600) if leftHand: Items.Move(leftHand.Serial,Player.Backpack.Serial,0) Misc.Pause(600) Player.EquipItem(wep) else: Player.EquipItem(wep) elif wep.ItemID in shields: Misc.SendMessage('Shield') if leftHand: if leftHand.Serial == wep.Serial: Items.Move(wep,Player.Backpack.Serial,0) else: Items.Move(leftHand.Serial,Player.Backpack.Serial,0) Misc.Pause(600) Player.EquipItem(wep) else: Player.EquipItem(wep) else: if rightHand: Misc.SendMessage('disarming right') Items.Move(rightHand,Player.Backpack.Serial,0) Misc.Pause(600) Player.EquipItem(wep) # delete last equipt wep from temp list weplist.pop() if not weplist: Misc.RemoveSharedValue(Player.Name + 'weplist') else: weplist = Misc.ReadSharedValue(Player.Name + 'weplist') return if leftHand: Misc.SendMessage('disarming left') if leftHand.ItemID in shields: Player.EquipItem(wep) else: Items.Move(leftHand,Player.Backpack.Serial,0) Misc.Pause(600) Player.EquipItem(wep) else: Player.EquipItem(wep) # delete last equipt wep from temp list weplist.pop() if not weplist: Misc.RemoveSharedValue(Player.Name + 'weplist') else: weplist = Misc.ReadSharedValue(Player.Name + 'weplist') def toggleWep(): if wep.IsTwoHanded: Misc.SendMessage('Two Handed') if rightHand: Items.Move(rightHand.Serial,Player.Backpack.Serial,0) Misc.Pause(600) if leftHand: if leftHand.Serial == wep.Serial: Items.Move(wep,Player.Backpack.Serial,0) Misc.Pause(600) else: Items.Move(leftHand.Serial,Player.Backpack.Serial,0) Misc.Pause(600) Player.EquipItem(wep) else: Player.EquipItem(wep) elif wep.ItemID in shields: Misc.SendMessage('Shield') if leftHand: if leftHand.Serial == wep.Serial: Items.Move(wep,Player.Backpack.Serial,0) else: Items.Move(leftHand.Serial,Player.Backpack.Serial,0) Misc.Pause(600) Player.EquipItem(wep) else: Player.EquipItem(wep) else: if rightHand: if rightHand.Serial == wep.Serial: Items.Move(wep,Player.Backpack.Serial,0) return if leftHand: if leftHand.Serial == wep.Serial: Items.Move(wep,Player.Backpack.Serial,0) return elif leftHand.ItemID in shields: Player.EquipItem(wep) else: Player.EquipItem(wep) # check to see if weps are saved def checkList(): global mainWeplist global wep if Misc.CheckSharedValue(Player.Name + 'singlewep'): tempwep = Items.FindBySerial(Misc.ReadSharedValue(Player.Name + 'singlewep')) if tempwep: wep = tempwep else: Misc.RemoveSharedValue(Player.Name + 'singlewep') checkList() elif Misc.CheckSharedValue(Player.Name + 'mainWeplist') == False: mainWeplist = setWeps("Target Wep(s), then cancel target.") if isinstance(mainWeplist, list): Misc.SetSharedValue(Player.Name + 'mainWeplist', mainWeplist) else: Misc.SetSharedValue(Player.Name + 'singlewep', mainWeplist.Serial) wep = mainWeplist Misc.Pause(600) else: mainWeplist = Misc.ReadSharedValue(Player.Name + 'mainWeplist') try: checkList() if isinstance(mainWeplist, list): Misc.SendMessage('Swap Wep', 33) swampWeps() else: Misc.SendMessage('Toggle Wep', 33) toggleWep() except: Misc.RemoveSharedValue(Player.Name + 'mainWeplist') Misc.RemoveSharedValue(Player.Name + 'singlewep') Misc.RemoveSharedValue(Player.Name + 'weplist') Player.HeadMessage(33, 'Something went wrong, reset weps') <file_sep># Explode pot 1 key executer. # hit once to arm # hit again to toss at last target # true to cancel target after arming cancelTarget = False msgcolor = 53 fakeTarget = 0x00000 lastTarget = Target.GetLast() import sys def potArmOrThrow(): # tosses pot if has been charging if Timer.Check( 'ex' + Player.Name ) == True: Player.HeadMessage( msgcolor, 'Tossing' ) usePot() Target.WaitForTarget(1500) Target.TargetExecute(lastTarget) Timer.Create( 'ex' + Player.Name , 1) # starts charging pot else: usePot() Timer.Create( 'ex' + Player.Name , 4500) if cancelTarget: Target.Cancel() def usePot(): if Misc.ShardName() == "Ultima Forever": drinkPot() else: usePotType() def drinkPot(): Player.ChatSay(msgcolor, '[drink GreaterExplosionPotion') Misc.Pause(120) if Journal.Search( 'You do not have any of those potions.'): Player.HeadMessage(msgcolor, 'Out of Exp Pots') sys.exit() elif Journal.Search('You must wait a moment before using another explosion potion'): Misc.NoOperation() def usePotType(): pot = Items.FindByID(0x0F0D,0,Player.Backpack.Serial,True) if pot: Items.UseItem(pot) else: Player.HeadMessage(33, "No Explode pots!") Journal.Clear() potArmOrThrow() <file_sep>Player.ChatSay(5, "Backwards")<file_sep>leftHand = Player.GetItemOnLayer('LeftHand') chugtime = 650 msgColor = 66 noBow = True bows = [ 0x13B2,0x26C2,0x0F50,0x13FD,0x0A12,0x0F6B] # 0x0A12,0x0F6B = torch if not leftHand: noBow = True elif leftHand.ItemID in bows: noBow = False elif leftHand: noBow = True def potDrink(): if leftHand and noBow: Player.UnEquipItemByLayer('LeftHand') Misc.Pause(650) Player.ChatSay( 1 , '[drink greaterStrengthPotion') Misc.Pause(100) if Journal.Search( 'You do not have any of those potions.'): Player.HeadMessage(msgColor, "No Strength pots!") Misc.Pause(chugtime) Player.EquipItem(leftHand) Misc.Pause(50) else: Player.ChatSay( 1 , '[drink greaterStrengthPotion') Misc.Pause(100) if Journal.Search( 'You do not have any of those potions.'): Player.HeadMessage(msgColor, "No Strength pots!") else: Misc.NoOperation() def usePot(): pot = Items.FindByID(0x0F09,0,Player.Backpack.Serial,True) if pot: if leftHand and noBow: Player.UnEquipItemByLayer('LeftHand') Misc.Pause(chugtime) Items.UseItem(pot) Misc.Pause(chugtime) Player.EquipItem(leftHand) Misc.Pause(50) else: Items.UseItem(pot) else: Player.HeadMessage(msgColor, "No Strength pots!") if Misc.ShardName() == "Ultima Forever" or Misc.ShardName() == "UOForever": potDrink() else: usePot() <file_sep>#frombook = 0x43909128 frombook =0x43909128 #dehued normal book in bag lbodstorage = 0x4083CF0E lbodstorage2 = 0x45E3CA15 fullbod = [ 0x41660840 , 0x43908F54 ] #chest first, book second nomatchstorage = 0x41113188 bonestorage = 0x43E08982 #leatherstorage= 0x4391DCB4 #leather keeper 1 leatherstorage= 0x43647AB7 garbagebox = 0x4009C22A #temporary deed = 0x14EF tinktool = 0x1EB8 sewtool = 0x0F9D restockchest = 0x405183AA cloth = 0x1766 leather = 0x1081 #no color so it randomly pics a quality ingot = 0x1BF2 trash = 0x403C2A3E bone = 0x0F7E barbedcolor= 0x059d spinecolor= 0x05e4 hornedcolor= 0x0900 leathercolor = 0x0000 def worldSave(): if Journal.SearchByType('The world will save in 1 minute.', 'Regular' ): Misc.SendMessage('Pausing for world save', 33) while not Journal.SearchByType('World save complete.', 'Regular'): Misc.Pause(500) Misc.Pause(2500) Misc.SendMessage('Continuing run', 33) Journal.Clear() def checktools(): if Items.BackpackCount(tinktool , -1) < 3: Misc.SendMessage('Out of Tink Tools',33) craftTink() Misc.Pause(1000) if Items.BackpackCount(sewtool , -1) < 3: Misc.SendMessage('Out of sewtool',33) craftsewtool() def craftTink(): UseTinkTool = Items.FindByID(tinktool, -1, Player.Backpack.Serial) Items.UseItem(UseTinkTool.Serial) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, 8) Gumps.WaitForGump(949095101, 1500) Gumps.SendAction(949095101, 23) Misc.Pause(2000) def craftsewtool(): UseTinkTool = Items.FindByID(tinktool, -1, Player.Backpack.Serial) Items.UseItem(UseTinkTool.Serial) Gumps.WaitForGump(949095101, 10000) Gumps.SendAction(949095101, 8) Gumps.WaitForGump(949095101, 10000) Gumps.SendAction(949095101, 44) Gumps.WaitForGump(949095101, 10000) Misc.Pause(2000) Gumps.SendAction(949095101, 0) def setsemat(material): if material == barbedcolor: UseTool = Items.FindByID(sewtool, -1, Player.Backpack.Serial) Items.UseItem(UseTool.Serial) Misc.Pause(500) Gumps.SendAction(949095101, 7) Misc.Pause(500) Gumps.SendAction(949095101, 27) if material == hornedcolor: UseTool = Items.FindByID(sewtool, -1, Player.Backpack.Serial) Items.UseItem(UseTool.Serial) Misc.Pause(500) Gumps.SendAction(949095101, 7) Misc.Pause(500) Gumps.SendAction(949095101, 20) if material == spinecolor: UseTool = Items.FindByID(sewtool, -1, Player.Backpack.Serial) Items.UseItem(UseTool.Serial) Misc.Pause(500) Gumps.SendAction(949095101, 7) Misc.Pause(500) Gumps.SendAction(949095101, 13) if material == "-1": UseTool = Items.FindByID(sewtool, -1, Player.Backpack.Serial) Items.UseItem(UseTool.Serial) Misc.Pause(500) Gumps.SendAction(949095101, 7) Misc.Pause(500) Gumps.SendAction(949095101, 6) if material == -1: UseTool = Items.FindByID(sewtool, -1, Player.Backpack.Serial) Items.UseItem(UseTool.Serial) Misc.Pause(500) Gumps.SendAction(949095101, 7) Misc.Pause(500) Gumps.SendAction(949095101, 6) def unstock(): while Items.FindByID(bone,-1, Player.Backpack.Serial): moveitem = Items.FindByID(bone,-1, Player.Backpack.Serial) Items.Move(moveitem, restockchest, 0) Misc.Pause(750) while Items.FindByID(leather,-1, Player.Backpack.Serial): moveitem = Items.FindByID(leather,-1, Player.Backpack.Serial) Items.Move(moveitem, restockchest, 0) Misc.Pause(750) while Items.FindByID(cloth,-1, Player.Backpack.Serial): moveitem = Items.FindByID(cloth,-1, Player.Backpack.Serial) Items.Move(moveitem, restockchest, 0) Misc.Pause(750) def checkrestock(materialtype, color): #loads crafting stuff if materialtype == "cloth": material = cloth elif color == barbedcolor: material = leather elif color == hornedcolor: material = leather elif color == spinecolor: material = leather elif color == -1: material = leather color = leathercolor Player.HeadMessage(54, str(materialtype)) Player.HeadMessage(54, str(color)) x = Items.BackpackCount(material, color) Player.HeadMessage(54, "Material Count" + str(x)) if materialtype == "bone": if Items.BackpackCount(bone, -1) < 15: Items.UseItem(restockchest) Misc.Pause(500) if Items.FindByID(bone, -1, restockchest): targetitem = Items.FindByID(bone, -1, restockchest) Items.Move(targetitem, Player.Backpack.Serial , 30) Misc.Pause(1000) if Items.BackpackCount(leather, color) < 20: if Items.FindByID(leather, color, restockchest): targetitem = Items.FindByID(leather, color, restockchest) Items.Move(targetitem, Player.Backpack.Serial , 75) Misc.Pause(1000) if Items.BackpackCount(material, color) < 25: Items.UseItem(restockchest) Misc.Pause(1000) if Items.FindByID(material, color, restockchest): targetitem = Items.FindByID(material, color, restockchest) Items.Move(targetitem, Player.Backpack.Serial , 100) Misc.Pause(1000) if Items.BackpackCount(ingot, -1) < 10: Items.UseItem(restockchest) Misc.Pause(1000) if Items.FindByID(ingot, -1, restockchest): targetitem = Items.FindByID(ingot, -1, restockchest) Items.Move(targetitem, Player.Backpack.Serial , 50) Misc.Pause(1000) def catagorylogic(bod): #working #Hats is first gump 1 #shirts is first gump 8 #pants is gump 15 #misc is gump 22 #footware is 29 x = Items.GetPropStringList(bod) ######## HATS ################ if "doublet: 0" in x: return [8,2,"cloth"]; if "shirt: 0" in x: return [8,9,"cloth"]; if "fancy shirt: 0" in x: return [8,16,"cloth"]; if "tunic: 0" in x: return [8,23,"cloth"]; if "surcoat: 0" in x: return [8,30,"cloth"]; if "plain dress: 0" in x: return [8,37,"cloth"]; if "fancy dress: 0" in x: return [8,44,"cloth"]; if "cloak: 0" in x: return [8,51,"cloth"]; if "robe: 0" in x: return [8,58,"cloth"]; if "jester suit: 0" in x: return [8,65,"cloth"]; ######## shirts ################ if "skullcap: 0" in x: return [1,2,"cloth"]; if "bandana: 0" in x: return [1,9,"cloth"]; if "floppy hat: 0" in x: return [1,16,"cloth"]; if "cap: 0" in x: return [1,23,"cloth"]; if "wide-brim hat: 0" in x: return [1,30,"cloth"]; if "straw hat: 0" in x: return [1,37,"cloth"]; if "tall straw hat: 0" in x: return [1,44,"cloth"]; if "wizard's hat: 0" in x: return [1,51,"cloth"]; if "bonnet: 0" in x: return [1,58,"cloth"]; if "feathered hat: 0" in x: return [1,65,"cloth"]; if "tricorne hat: 0" in x: return [1,72,"cloth"]; if "jester hat: 0" in x: return [1,79,"cloth"]; ######## pants ################ if "short pants: 0" in x: return [15,2,"cloth"]; if "long pants: 0" in x: return [15,9,"cloth"]; if "kilt: 0" in x: return [15,16,"cloth"]; if "skirt: 0" in x: return [15,23,"cloth"]; ######## Misc ################ if "body sash: 0" in x: return [22,2,"cloth"]; if "half apron: 0" in x: return [22,9,"cloth"]; if "full apron: 0" in x: return [22,16,"cloth"]; if "oil cloth: 0" in x: return [22,23,"cloth"]; ######## FOOTWARE ################ if "sandals: 0" in x: return [29,2,"leather"]; if "shoes: 0" in x: return [29,9,"leather"]; if "boots: 0" in x: return [29,16,"leather"]; if "thigh boots: 0" in x: return [29,23,"leather"]; ######## Leather ################ if "leather gorget: 0" in x: return [36,2,"leather"]; if "leather cap: 0" in x: return [36,9,"leather"]; if "leather gloves: 0" in x: return [36,16,"leather"]; if "leather sleeves: 0" in x: return [36,23,"leather"]; if "leather leggings: 0" in x: return [36,30,"leather"]; if "leather tunic: 0" in x: return [36,37,"leather"]; ######## Studded Leather ################ if "studded gorget: 0" in x: return [43,2,"leather"]; if "studded cap: 0" in x: return [43,9,"leather"]; if "studded gloves: 0" in x: return [43,16,"leather"]; if "studded sleeves: 0" in x: return [43,23,"leather"]; if "studded leggings: 0" in x: return [43,30,"leather"]; if "studded tunic: 0" in x: return [43,37,"leather"]; ######## Female Leather ################ if "leather shorts: 0" in x: return [50,2,"leather"]; if "leather skirt: 0" in x: return [50,9,"leather"]; if "leather bustier: 0" in x: return [50,16,"leather"]; if "studded bustier: 0" in x: return [50,23,"leather"]; if "female leather armor: 0" in x: return [50,30,"leather"]; if "studded armor: 0" in x: return [50,37,"leather"]; ######## Bone Leather ################ if "bone helmet: 0" in x: return [57,2,"bone"]; if "bone gloves: 0" in x: return [57,9,"bone"]; if "bone arms: 0" in x: return [57,16,"bone"]; if "bone leggings: 0" in x: return [57,23,"bone"]; if "bone armor: 0" in x: return [57,30,"bone"]; if "orc helm: 0" in x: return [57,37,"bone"]; def bagindexing(): inventory = [] for item in Player.Backpack.Contains: inventory.append(item.Serial) Misc.Pause(5) return inventory def findnewitem(inv): #works but the string is weird if you print it. for item in Player.Backpack.Contains: if item.Serial not in inv: return item.Serial def craftitems(bod): count = 0 bodarray = [0,0,0,0,0] checkbod = analsbod(bod) #grabs array of bod info bodarray[0] = bod temp = catagorylogic(bodarray[0]) while checkbod[3] == False: #checkbod[3] is true if full and false if not full bodarray [1] = temp[0] bodarray [2] = temp[1] bodarray [3] = temp[2] bodarray [4] = checkbod[1] worldSave() checktools() Player.HeadMessage(54, "Crafting Items") if str(bodarray[4]) == "barbed": material = barbedcolor elif str(bodarray[4]) == "spined": material = spinecolor elif str(bodarray[4]) == "horned": material = hornedcolor else: material = -1 setsemat(material) checkrestock(bodarray[3],material) inventory = bagindexing() UseSewTool = Items.FindByID(sewtool, -1, Player.Backpack.Serial) Items.UseItem(UseSewTool.Serial) Misc.Pause(250) Gumps.WaitForGump(949095101, 10000) Gumps.SendAction(949095101, bodarray[1]) Gumps.WaitForGump(949095101, 10000) Gumps.SendAction(949095101, bodarray[2]) Misc.Pause(2000) item = findnewitem(inventory) if item != None: Journal.Clear() Items.SingleClick(item) Misc.Pause(800) if Journal.Search("Exceptional"): Player.HeadMessage(54, "good") Items.UseItem(bodarray[0]) Misc.Pause(750) Gumps.SendAction(1526454082, 2) Misc.Pause(750) Target.TargetExecute(item) Misc.Pause(750) count = count + 1 else: Player.HeadMessage(54, "bad") scissors = Items.FindByID(0x0F9F, -1, Player.Backpack.Serial) Items.UseItem(scissors.Serial) Misc.Pause(500) Target.TargetExecute(item) Misc.Pause(1000) if Journal.Search("Scissors cannot be used"): Items.Move(item, trash, 0) Misc.Pause(500) checkbod = analsbod(bod) unstock() ######################################################################################## ######################################################################################## ######################################################################################## def grabbod(): Items.UseItem(frombook) Misc.Pause(1000) Gumps.SendAction(1425364447, 5) Misc.Pause(1000) x = Items.FindByID(0x14EF, 0x0483, Player.Backpack.Serial) return x def sortnonmatch(bod): #sorts a bod that doesnt match an Lbod sbod = catagorylogic(bod) if sbod[2] == "cloth": craftitems(bod) Misc.Pause(500) while Items.FindByID(deed, -1, Player.Backpack.Serial): Items.UseItem(fullbod[0]) #open Chest Misc.Pause(600) Items.Move(fullbod[1],Player.Backpack.Serial, 0) Misc.Pause(600) Items.Move(bod, fullbod[1], 0) #store full bod in chest. Misc.Pause(600) Items.Move(fullbod[1],fullbod[0], 0) Misc.Pause(600) elif sbod[2] == "bone": while Items.FindByID(deed, -1, Player.Backpack.Serial): Items.UseItem(nomatchstorage) #open Chest Misc.Pause(600) Items.Move(bonestorage,Player.Backpack.Serial, 0) Misc.Pause(600) Items.Move(bod, bonestorage, 0) #store full bod in chest. Misc.Pause(600) Items.Move(bonestorage,nomatchstorage, 0) Misc.Pause(600) elif sbod[2] == "leather": while Items.FindByID(deed, -1, Player.Backpack.Serial): Items.UseItem(nomatchstorage) #open Chest Misc.Pause(600) Items.Move(leatherstorage,Player.Backpack.Serial, 0) Misc.Pause(600) Items.Move(bod, leatherstorage, 0) #store full bod in chest. Misc.Pause(600) Items.Move(leatherstorage,nomatchstorage, 0) Misc.Pause(600) else: Items.Move(bod, nomatchstorage, 0) Player.HeadMessage(54, "No lbod match moving to storage") def comparebods(bod): Items.UseItem(lbodstorage) Misc.Pause(600) Items.UseItem(lbodstorage2) Misc.Pause(600) sbod = analsbod(bod) lbodstoragecontainer = Items.FindBySerial(lbodstorage) lbodstoragecontainer2 = Items.FindBySerial(lbodstorage2) Player.HeadMessage(54, "checking 1st container") for item in lbodstoragecontainer.Contains: lbod = anallbod(item.Serial) if sbod[2] == lbod[2]: #qty if sbod[1] == lbod[1] or lbod[1] == "cloth": #material for i in range(0, len(lbod)): if str(sbod[4]) == str(lbod[i]): Player.HeadMessage(54, "Mark 4") craftitems(bod) #fills sbod Misc.Pause(600) #adds it to lbod Items.Move(item, Player.Backpack.Serial, 0) Misc.Pause(600) Items.UseItem(item) Misc.Pause(600) Gumps.SendAction(2703603018, 2) Misc.Pause(600) Target.TargetExecute(bod) Misc.Pause(600) if lbod[1] == "spined" or lbod[1] == "barbed" or lbod[1] == "horned": lbodqty=4 else: lbodqty = 3 if len(lbod) == lbodqty: Player.HeadMessage(54, "Lbod Full store in complete") while Items.FindByID(deed, -1, Player.Backpack.Serial): Items.UseItem(fullbod[0]) #open Chest Misc.Pause(600) Items.Move(fullbod[1],Player.Backpack.Serial, 0) #moves book to inventory Misc.Pause(600) Items.Move(item, fullbod[1], 0) #puts bod in book Misc.Pause(600) Items.Move(fullbod[1],fullbod[0], 0)#store full bod in chest. Misc.Pause(600) return else: #checks 2nd box Misc.Pause(1000) Items.Move(item, lbodstorage, 0) Misc.Pause(600) return Player.HeadMessage(54, "checking 2nd container") for item in lbodstoragecontainer2.Contains: lbod = anallbod(item.Serial) if sbod[2] == lbod[2]: #qty if sbod[1] == lbod[1] or lbod[1] == "cloth": #material for i in range(0, len(lbod)): if str(sbod[4]) == str(lbod[i]): Player.HeadMessage(54, "Mark 4") craftitems(bod) #fills sbod Misc.Pause(600) #adds it to lbod Items.Move(item, Player.Backpack.Serial, 0) Misc.Pause(600) Items.UseItem(item) Misc.Pause(600) Gumps.SendAction(2703603018, 2) Misc.Pause(600) Target.TargetExecute(bod) Misc.Pause(600) if lbod[1] == "spined" or lbod[1] == "barbed" or lbod[1] == "horned": lbodqty=4 else: lbodqty = 3 if len(lbod) == lbodqty: Player.HeadMessage(54, "Lbod Full store in complete") while Items.FindByID(deed, -1, Player.Backpack.Serial): Items.UseItem(fullbod[0]) #open Chest Misc.Pause(600) Items.Move(fullbod[1],Player.Backpack.Serial, 0) #moves book to inventory Misc.Pause(600) Items.Move(item, fullbod[1], 0) #puts bod in book Misc.Pause(600) Items.Move(fullbod[1],fullbod[0], 0)#store full bod in chest. Misc.Pause(600) return else: #checks 2nd box Misc.Pause(1000) Items.Move(item, lbodstorage2, 0) Misc.Pause(600) return def anallbod(bod): #returns an array of info including only empty sbod info result = [0,0,0] bodList = Items.GetPropStringList(bod) bodsize = len(bodList) qtyarraynum = 6 #quantity in array slot 6 unless its spined/.barbed then we change to 7 #Player.HeadMessage(54, bodsize) brints msg if bodList[4] == "small bulk order": result[0] = "small" else: result[0] = "large" if bodList[6].find("barbed") == -1: if bodList[6].find("spined") == -1: if bodList[6].find("horned") == -1: result[1] = "cloth" else: result[1] = "horned" qtyarraynum = 7 else: result[1] = "spined" qtyarraynum = 7 else: result[1] = "barbed" qtyarraynum = 7 if bodList[qtyarraynum].find("20") == -1: if bodList[qtyarraynum].find("15") == -1: result[2] = 10 else: result[2] = 15 else: result[2] = 20 if result[1] == "spined" or result[1] == "barbed" or result[1] == "horned": start = 8 else: start = 7 for i in range(start, bodsize): temp = bodList[i] #Player.HeadMessage(54, temp) #Player.HeadMessage(54, str(i)) if temp.find(' 0') == -1: Misc.Pause(10) else: temp = temp.replace(":","") temp = temp.replace("20","") temp = temp.replace("15","") temp = temp.replace("10","") temp = temp.replace("0","") result.append(temp) return result def analsbod(bod): result = [0,0,0,0, 0,0,0] #added two zeros to deal with spined leather? bodList = Items.GetPropStringList(bod) qtyarraynum = 6 if bodList[4] == "small bulk order": result[0] = "small" else: result[0] = "large" if bodList[6].find("barbed") == -1: if bodList[6].find("spined") == -1: if bodList[6].find("horned") == -1: result[1] = "cloth" fullcheck = 7 else: result[1] = "horned" qtyarraynum = 7 fullcheck = 8 else: result[1] = "spined" qtyarraynum = 7 fullcheck = 8 else: result[1] = "barbed" qtyarraynum = 7 fullcheck = 8 if bodList[qtyarraynum].find("20") == -1: if bodList[qtyarraynum].find("15") == -1: result[2] = 10 else: result[2] = 15 else: result[2] = 20 if bodList[fullcheck].find(str(result[2])) == -1: result[3] = False else: result[3] = True if result[1] == "spined" or result[1] == "barbed" or result[1] == "horned": start = 8 else: start = 7 Misc.Pause(500) temp = bodList[start] temp = temp.replace(":","") temp = temp.replace("20","") temp = temp.replace("15","") temp = temp.replace("10","") temp = temp.replace("0","") result[4] = temp return result def testingsmalloutput(bod): x = analsbod(bod) Player.HeadMessage(54, str(x)) Player.HeadMessage(54, 'we are making ' + str(x[0])) Player.HeadMessage(54, 'it is ' + x[1] ) Player.HeadMessage(54, 'we need to make ' + str(x[2]) ) Player.HeadMessage(54, 'is it full '+ str(x[3]) ) Player.HeadMessage(54, 'we making '+ str(x[4]) ) def testlbodoutput(bod): zz = anallbod(bod) Player.HeadMessage(54, '<NAME>') Player.HeadMessage(54, str(len(zz))) for i in range(0, len(zz)): Player.HeadMessage(54, str(zz[i])) def getstringofbod(bod): result= "" bodList = Items.GetPropStringList(bod) for i in range(0, len(bodList)): result = result + bodList[i] result = result.replace("[","") result = result.replace("]","") result = result.replace("deedBlessed<BASEFONT COLOR=#204018>","") result = result.replace("(1155)<BASEFONT COLOR=#FFFFFF>","") result = result.replace("Hue: Rusty Green Weight: 1 stone","") result = result.replace("a bulk order","") result = result + '\n' return result def comparetolist(bod, input): filepath = 'C:/Users/Jason/PycharmProjects/BodBot/' + input + ".txt" f = open(filepath, 'r') allinlist = f.readlines() f.close() #Player.HeadMessage(54, str(len(allinlist))) for i in range(0, len(allinlist)): #Player.HeadMessage(54, str(allinlist[i])) #Player.HeadMessage(54, str(getstringofbod(0x44D90146))) if getstringofbod(bod) == allinlist[i]: Player.HeadMessage(54, "Match found from list") return True else: Misc.Pause(5) return False def main(): #initializing isautofill = False isgarbage = False x = Items.GetPropValue(frombook, "Deeds In Book:") for z in range(x): #runs all the items in the book Misc.Pause(500) #STEP 1: grab bod out of book Misc.Pause(1000) bod = grabbod() Misc.Pause(2500) #STEP 2: analyze for garbage garbbodList = Items.GetPropStringList(bod) checkbod = analsbod(bod) #grabs array of bod info specifically for loop if its full sbod if comparetolist(bod, "garbo"): Player.HeadMessage(54, "Found garbage - dumping") Items.Move(bod, garbagebox, 0) Misc.Pause(1000) isgarbage = True elif str(garbbodList[5]) != "All items must be exceptional.": Player.HeadMessage(54, "Normal") Items.Move(bod, garbagebox, 0) Misc.Pause(1000) isgarbage = True #STEP 3: analyze for autocraft elif checkbod[3] == True: Player.HeadMessage(54, "BODZ FULL LOOKING FOR LBOD") comparebods(bod) while Items.FindByID(deed, -1, Player.Backpack.Serial): Items.UseItem(fullbod[0]) #open Chest Misc.Pause(800) Items.Move(fullbod[1],Player.Backpack.Serial, 0) Misc.Pause(800) Items.Move(bod, fullbod[1], 0) #store full bod in chest. Misc.Pause(800) Items.Move(fullbod[1],fullbod[0], 0) Misc.Pause(800) elif comparetolist(bod, "autofill"): Player.HeadMessage(54, "Found autofill - filling") craftitems(bod) Misc.Pause(500) while Items.FindByID(deed, -1, Player.Backpack.Serial): Items.UseItem(fullbod[0]) #open Chest Misc.Pause(600) Items.Move(fullbod[1],Player.Backpack.Serial, 0) Misc.Pause(600) Items.Move(bod, fullbod[1], 0) #store full bod in chest. Misc.Pause(600) Items.Move(fullbod[1],fullbod[0], 0) Misc.Pause(600) isautofill = True #STEP 3: is it small or large else: x = analsbod(bod) if str(x[0]) == "small": comparebods(bod) else: Player.HeadMessage(54, 'found large') Items.Move(bod, lbodstorage, 0) Misc.Pause(600) #Step 4: What do we do if no match? Misc.Pause(1000) if Items.FindByID(deed, -1, Player.Backpack.Serial): sortnonmatch(bod) checktools() main() #testlbodoutput(0x450C4341) #testlbodoutput(0x44FBDC4C) #testingsmalloutput(0x45044849)
b2eb342428b617561e2033484e58d9b6b595a863
[ "Python", "Text" ]
98
Python
matsamilla/Razor-Enhanced
f414b9ec67d67e74d7f0b9692a011e7270519ede
695138ea867751e8425d3d4c3bcc4d34f32d7f1c
refs/heads/master
<file_sep>package org.crazyit.activityjump; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { private Button button; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.button = (Button) this.findViewById(R.id.button); this.button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(MainActivity.this, NextActivity.class); // intent.addFlags(intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(intent); } }); Log.v("onCreate1", "onCreate1 is called"); processExtraData(); } protected void onNewIntent(Intent intent) { super.onNewIntent(intent); Log.v("onNewIntent1", "onNewIntent1 is called"); setIntent(intent);//must store the new intent unless getIntent() will return the old one processExtraData(); } private void processExtraData(){ Intent intent=new Intent(); //use the data received here } } <file_sep>package org.crazyit.activityjump; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; public class NextActivity extends Activity { private Button button; @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); // intent.addFlags(intent.FLAG_ACTIVITY_SINGLE_TOP); Log.v("onNewIntent2", "onNewIntent2 is called"); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.next_activity); Log.v("onCreate2", "onCreate2 is called"); this.button = (Button) this.findViewById(R.id.button); this.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(NextActivity.this, NextNextActivity.class); startActivity(intent); } }); } }
c43b25fccfb4097bdfbc286afa4c9cda88e28c33
[ "Java" ]
2
Java
czl514/test
49184b0c29ee4a30d2eac854d51222506f72be48
c7d948c9db8c1d600d7a734defd90d2362c1ead5
refs/heads/master
<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Data; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Text; using System.Diagnostics; using System.Diagnostics; namespace GradeDiagramTest { public partial class GradeDiagramPlot : System.Web.UI.Page { // Student Scroe and Question from Database public string []FirstColDefault = {"學生","總分"}; // List<ScoreAnalysisM> ScoreAnalysisList = new List<ScoreAnalysisM>(); private int table_rows; private int table_cols; private List<int[]> QuestionAvg=new List<int[]>(); private List<string> correctXML = new List<string>(); private int MemberQuestionNum; private int studentNum; private int currentQuestion=0; private List<string> AddRowsName = new List<string>(); private List<string> AddColsName = new List<string>(); public string[] QuestionName; public List<string[]> MemberQuestionAnswer=new List<string[]>(); private Hashtable[] correctAnswerHT ; protected void Page_Load(object sender, EventArgs e) { //下方3個變數的值之後會由DB取得 //get all the data from IPCExamHWCorrectAnswer table string cActivityID_Selector = Request.QueryString["cActivityID"]; DataTable dt = CsDBOp.GetAllTBData("IPCExamHWCorrectAnswer", cActivityID_Selector); //Exception for empty table data if (dt.Rows.Count==0) Response.End(); //Test for cActivityID with input for IPCExamHWCorrectAnswer QuestionName=dt.Rows[0].Field<string>("QuestionBodyPart").Split(','); string TempCA=dt.Rows[0].Field<string>("correctAnswer"); foreach (string TempCA_fullstr in TempCA.Remove(TempCA.Length - 1).Split(':')) { MemberQuestionAnswer.Add(TempCA_fullstr.Split(',')); } string temp_str= dt.Rows[0].Field<string>("correctAnswerOrdering"); string[] tempCAOstr = temp_str.Remove(temp_str.Length-1).Split(':'); correctAnswerHT = new Hashtable[tempCAOstr.Length]; int index = 0; foreach (string tempCAOstr_split in tempCAOstr) { string[] tempCAOstr_in_split = tempCAOstr_split.Split(','); correctXML.Add(tempCAOstr_in_split[0]); correctAnswerHT[index] = new Hashtable(); for (int i = 1; i < tempCAOstr_in_split.Length; i++) { correctAnswerHT[index].Add(tempCAOstr_in_split[i], MemberQuestionAnswer[index][i]); } index++; } dt = CsDBOp.GetAllTBData("StuCouHWDe_IPC", cActivityID_Selector); //Get the retrieved data from each row of the retrieved data table. foreach (DataRow dr in dt.Rows) { string StudentIDTemp = dr.Field<string>("StuCouHWDe_ID"); string Gradetemp = dr.Field<string>("Grade"); if (Gradetemp != null) { ScoreAnalysisM log_temp = new ScoreAnalysisM(StudentIDTemp, Gradetemp); ScoreAnalysisList.Add(log_temp); continue; } string AnsewerTemp = dr.Field<string>("StudentAnswer"); string QuesOrdering = dr.Field<string>("QuesOrdering"); if (AnsewerTemp == null) continue; ScoreAnalysisM log = new ScoreAnalysisM(StudentIDTemp, AnsewerTemp, QuesOrdering,correctXML,correctAnswerHT); ScoreAnalysisList.Add(log); //比對學生作答內容中的XML檔名 if (log.XMLerror) { Response.Write("alert('Student answer XML file name does not match Correct answer XML file name')"); Response.End(); } } //// Add a row named Avg AddRow("Avg"); //// calculate average MemberQueAvgCal(); // Add table html for front-end dynamically AddDynamicTableHtml(QuestionName.Length, QuestionName); /// plot the chart tab_content_chart_control.InnerHtml = AddChartTabPaneHtml(); } private string AddChartTabPaneHtml() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < QuestionName.Length; i++) { if (i == 0) sb.Append("<div class='tab-pane fade in active " + QuestionName[i] + "Table " + QuestionName[i] + "Chart'></div>"); else sb.Append("<div class='tab-pane fade " + QuestionName[i] + "Table " + QuestionName[i] + "Chart'></div>"); } return sb.ToString(); } private void AddDynamicTableHtml(int tab_num, string[] question_name) { Table[] temp_table; temp_table = new Table[question_name.Length]; Panel temp_div; StringBuilder sb=new StringBuilder(); for (int i = 0; i < tab_num; i++) { temp_table[i] = new Table(); temp_div = new Panel(); tab_content_control.Controls.Add(temp_div); temp_div.ID = question_name[i] + "Table"; temp_div.Controls.Add(temp_table[i]); MemberVariableSet(i); GenerateTable(table_cols, table_rows, temp_table[i]); if (i == 0) { temp_div.Attributes.Add("class", "tab-pane fade in active "+question_name[i]+"Table"); // nav_control innerHtml add string sb.Append("<li class='Question active " + question_name[i] + "'><a data-toggle='tab' href='." + question_name[i] + "Table" + "'>" + question_name[i] + "</a></li>"); } else { temp_div.Attributes.Add("class", "tab-pane fade "+ question_name[i] + "Table"); // nav_control innerHtml add string sb.Append("<li class='Question " + question_name[i] + "'><a data-toggle='tab' href='." + question_name[i] + "Table" + "'>" + question_name[i] + "</a></li>"); } } nav_control.InnerHtml = sb.ToString(); } private void MemberQueAvgCal() { int Question_start=ScoreAnalysisList[0].QueIndex_start; int QuestionNum= ScoreAnalysisList[0].QuestionNum; int[] QuestionAvgTemp; for (int QueIndex = 0; QueIndex < QuestionNum; QueIndex++) { int MemberQuestionNum = ScoreAnalysisList[0].MemberQuestionNum[QueIndex]; QuestionAvgTemp = new int[MemberQuestionNum]; for (int index = 0; index < MemberQuestionNum; index++) { int sum = 0; for (int student = 0; student < ScoreAnalysisList.Count; student++) sum = Convert.ToInt16(ScoreAnalysisList[student].Grade[QueIndex][Question_start+index]) + sum; sum = sum / ScoreAnalysisList.Count; QuestionAvgTemp[index] = sum; } QuestionAvg.Add(QuestionAvgTemp); } } private void MemberVariableSet(int Question_num) { currentQuestion = Question_num; table_cols = ScoreAnalysisList[0].Grade[currentQuestion].Length+1;// +1 mean student column studentNum = ScoreAnalysisList.Count; table_rows = studentNum+AddRowsName.Count; MemberQuestionNum = ScoreAnalysisList[0].MemberQuestionNum[currentQuestion]; } protected void DownLoadToExl_Click(object sender, EventArgs e) { Debug.WriteLine(currentQuestion); DownLoadFile(); } private void DownLoadFile() // Convert Table to excel file { Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename= " + DateTime.Now.ToString("yyyyMMdd") + "成績清單.xls"); Response.ContentType = "application/excel"; Response.Write('\uFEFF'); // Add this, then the saved file will include BOM. StringWriter tw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(tw); tab_content_control.RenderControl(hw); this.EnableViewState = false; Response.Write(tw.ToString()); Response.End(); } private void InsertTableStr(int row, int col, string str_insert) { TableCell tc_temp; tc_temp = (TableCell)FindControl("TextBoxRow_"+row+"Col_" + col+"_"+currentQuestion); tc_temp.Text = str_insert; } private void InsertTableStr(int row, int col, string str_insert,string Classname_Insert) { TableCell tc_temp; tc_temp = (TableCell)FindControl("TextBoxRow_" + row + "Col_" + col + "_" + currentQuestion); tc_temp.Attributes.Add("class", Classname_Insert); tc_temp.Text = str_insert; } private string GetTableStr(int row, int col) { TableCell tc_temp; tc_temp = (TableCell)FindControl("TextBoxRow_" + row + "Col_" + col + "_" + currentQuestion); return tc_temp.Text; } private void AddRow(string RowName) { AddRowsName.Add(RowName); } private void AddCol(string ColName) { AddColsName.Add(ColName); } private void GenerateTable(int colsCount, int rowsCount,Table table_select) { //Creat the Table and Add it to the Page table_select.Attributes.Add("border", "1"); table_select.Attributes.Add("cellpadding", "1"); table_select.Attributes.Add("cellspacing", "1"); table_select.Style.Add("width", "100%"); // Now iterate through the table and add your controls for (int i = 0; i <= rowsCount; i++) { TableRow row = new TableRow(); for (int j = 0; j < colsCount; j++) { TableCell cell = new TableCell(); cell.ID = "TextBoxRow_" + i + "Col_" + j + "_" + currentQuestion; row.Controls.Add(cell); row.Cells.Add(cell); } table_select.Rows.Add(row); } for (int i = 1; i <= studentNum; i++) { for (int j = 0; j <ScoreAnalysisList[i - 1].Grade[currentQuestion].Length; j++) InsertTableStr(i, j+1, ScoreAnalysisList[i - 1].Grade[currentQuestion][j]); } // Row 0 set for (int i = 0; i < FirstColDefault.Length; i++) InsertTableStr(0, i, FirstColDefault[i]); for (int i = 1; i <=MemberQuestionNum; i++) InsertTableStr(0, i+FirstColDefault.Length-1, MemberQuestionAnswer[currentQuestion][i],"MQ"+QuestionName[currentQuestion]); // Column 0 set for (int i = 1; i <= studentNum; i++) InsertTableStr(i, 0, ScoreAnalysisList[i - 1].StuCouHWDe_ID); for (int i = studentNum + 1; i <= rowsCount; i++) InsertTableStr(i, 0, AddRowsName[i - rowsCount]); //Average Calculage for (int index = 0; index <MemberQuestionNum; index++) { string sum = QuestionAvg[currentQuestion][index].ToString(); InsertTableStr(rowsCount, index + FirstColDefault.Length,sum,"Average"+QuestionName[currentQuestion]); } int avg_total=0; for (int i = 0; i < studentNum; i++) avg_total += Convert.ToInt16(ScoreAnalysisList[i].Grade[currentQuestion][0]); avg_total /= studentNum; InsertTableStr(rowsCount, 1, avg_total.ToString()); } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for ScoreAnalysisM /// </summary> public class ScoreAnalysisM { public string StuCouHWDe_ID; public List<string[]> Grade=new List<string[]>(); public int QuestionNum; public int[] MemberQuestionNum; public int QueIndex_start=1; public bool XMLerror = false; public ScoreAnalysisM(string id, string AnswerStr,string QuesOdrStr,List<string> xmlFile ,Hashtable[] correctAnswerHT) { //string[] temp_str_ar; StuCouHWDe_ID = id; string[] AnswerStr_Question= AnswerStr.Remove(AnswerStr.Length - 1).Split(':'); string[] QuesOdrStr_Question = QuesOdrStr.Remove(QuesOdrStr.Length - 1).Split(':'); MemberQuestionNum = new int[AnswerStr_Question.Length]; QuestionNum = AnswerStr_Question.Length; for (int i = 0; i < AnswerStr_Question.Length; i++) { string[] AnswerStr_MemQuestion = AnswerStr_Question[i].Split(','); string[] QuesOdrStr_MemQuestion = QuesOdrStr_Question[i].Split(','); if (xmlFile[i] != AnswerStr_MemQuestion[0]) XMLerror = true; MemberQuestionNum[i] = QuesOdrStr_MemQuestion.Length-QueIndex_start; Grade.Add(new string[QuesOdrStr_MemQuestion.Length]); int grade_perQuestion = 100 / QuesOdrStr_MemQuestion.Length; int correct_num = 0; for (int index = 1; index < QuesOdrStr_MemQuestion.Length; index++) { string compare_valstr=correctAnswerHT[i][QuesOdrStr_MemQuestion[index]].ToString(); if (compare_valstr == AnswerStr_MemQuestion[index]) { Grade[i][index] = grade_perQuestion.ToString(); correct_num++; } else Grade[i][index] = 0.ToString(); } Grade[i][0] = (correct_num * grade_perQuestion).ToString(); } } }<file_sep> using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for ScoreAnalysisM /// </summary> public class ScoreAnalysisM { public string StuCouHWDe_ID; public List<string[]> Grade=new List<string[]>(); public int QuestionNum; public int[] MemberQuestionNum; public int QueIndex_start=3; public ScoreAnalysisM(string id,string grade_str) { string[] temp_str_arr = MemberQueSpilt(grade_str); StuCouHWDe_ID = id; for (int i = 0; i < QuestionNum; i++) { MemberQueGradeSpilt(temp_str_arr[i], i); } } private string[] MemberQueSpilt(string grade_str) { string[] temp_str_arr = grade_str.Remove(grade_str.Length-1).Split(':'); QuestionNum = temp_str_arr.Length; MemberQuestionNum = new int[QuestionNum]; return temp_str_arr; } private string[] MemberQueGradeSpilt(string grade_member_str,int questionNum) { string[] temp_str_arr = grade_member_str.Split(','); MemberQuestionNum[questionNum] = temp_str_arr.Length - QueIndex_start; Grade.Add(temp_str_arr); return temp_str_arr; } }<file_sep> GradeDiagramPlot Webform Document 目的 : 結合前後端的script來達成動態產生表格,以及運算平均值、繪圖。 Step 1 前端配置以便後端使用id動態修改內部Html <!--在前端aspx擋裡的head標籤裡套用d3與c3等javascript、css script讓 後端傳入的javascript能使用 --> <head runat="server"> <script src="./d3-3.5.0/d3.min.js" charset="utf-8"></script> <script src="./c3-0.4.15/c3.min.js"></script> <link href="./c3-0.4.15/c3.css" rel="stylesheet"/> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <!--在body標籤裡form1這個form底下加上一個id為chart並讓他runat server能用 後端C# script來進行內部html的控制--> <form id="form1" runat="server"> <div> </div> </form> <div id="chart" runat="server"> Step 2 後端C# script GradeDiagramPlot.aspx.cs Doc 功用: 作為後端Script,最主要的作用是透過Page_Load這個複寫函式,當一進前端頁面就會執行這個function。而在這個class寫的private member 與private function都是Page_Load用來動態生成Table用的。 public member variable : // 此字串矩陣裡為Table的預設欄位,不受動態配置的欄位 public string []FirstColDefault = {"總分"}; // 此List<ScoreAnalysisM> 用來存把DB的資料以學生為單位存入這條List裡 // 以便之後用來製作動態Table或跟外面做連接 public List<ScoreAnalysisM> StuScoreStore=new List<ScoreAnalysisM>(); private member variable : // Table 總行數與總列數 private int table_rows; private int table_cols; // QuestionAvg 這個Array是用來存每題運算後的平均值 private int []QuestionAvg; // 總題數,目前以每個題數一樣為準 private int QuestionNum; // 在首行與首列額外增加的行列名稱(Ex.Total行、Avg列 etc.) private List<string> AddRows = new List<string>(); private List<string> AddCols = new List<string>(); // 用來做TableCell暫存以便存取Table Date的資料 private TableCell tc_temp; // 使用priave因為這個script裡用的function都只限於這個script所以都封裝在此,並讓之後複寫的Page_Load function使用 private member function : // 用來增加首行額外的欄位(Ex.Total),Input為要輸入的欄位名稱 private void AddRow(string RowName); // 用來增加首列額外的欄位(Ex.Avg),Input為要輸入的欄位名稱 private void AddCol(string ColName); // 用來動態產生Table的function,Input為Table的行術與列數 private void GenerateTable(int colsCount, int rowsCount); // 新增以RowName命名的列 private void AddRow(string RowName); // 新增以ColName命名的列 private void AddCol(string ColName); // 取得Table row列col行的字串 private string GetTableStr(int row, int col); // 修改 Table row列col行的字串 private void InsertTableStr(int row, int col, string str_insert); 之後複寫class裡 void Page_Load(object sender, EventArgs e) 讓後端在Load Page時會受到這個function的控制。 // Code 裡分為四個部分Initalize the ScoreAnalysisM List、Initalize the Page member variable、 Generate Table Function 、後端控制Chart Div。 protected void Page_Load(object sender, EventArgs e) { //Get all the data from ScoreDetailTB table DataTable dt = CsDBOp.GetAllTBData(); //Get the retrieved data from each row of the retrieved data table foreach (DataRow dr in dt.Rows) { ScoreAnalysisM log = new ScoreAnalysisM(); log.StuCouHWDe_ID = dr.Field<string>("StuCouHWDe_ID"); log.Grade = dr.Field<string>("Grade"); log.QuestionNum = log.Grade.Split(',')[1]; ScoreAnalysisList.Add(log); } //Initalize the Page QuestionNum = ScoreAnalysisList[0].Grade.Split(',').Length-FirstColDefault.Length; table_cols = FirstColDefault.Length+QuestionNum; table_rows = ScoreAnalysisList.Count; studentNum = table_rows; // Add a row named Avg AddRow("Avg"); // Generate Table Function GenerateTable(table_cols, table_rows); // 後端控制Chart Div裡的Html String 加入JavaScript的Script String string tempcolstr =""; for (int i = 0; i < QuestionNum;i++ ) { string temp2; temp2 = "['第" + (i+1) + "題'," + QuestionAvg[i] + "],"; tempcolstr = tempcolstr + temp2; } // 此段Script採用C3.js,其Reference;http://c3js.org/reference.html chart.InnerHtml="<script>var chart = c3.generate({bindto: '#chart',data: {columns: ["+tempcolstr+"],type : 'pie'}});</script>"; } P.S 想之後把Page_Load和GenerateTable裡的function拆得更細會不會可以做的更多可變性,但想說這個Script裡function或是variable都只可能在這個C#裡使用,之後想改的話只要改Script裡的東西,想問問看學長的意見。 P.S 以後可能會出問題的點可能是題數的問題,目前我以一個private string來存一個大家都一樣的題數,但我在ScoreAnalysis這個Class裡加了一個public string QuestionNum用來存各自的題數,以便之後要對動態表格格式做修改。 P.S 之後會再寫每個人題數不一樣的Table,這種table因為不是方正的Table,所以Table產生得流程會不一樣,以及平均值的算法是以哪題為準。這修都會照程Document與Flow得改寫。
3e93161b5696dbc993d22b3a585ae5fc331da25f
[ "Markdown", "C#" ]
4
C#
t5i0m7/DiagramPlot
816f844b3771e856bf56112e533cd77b9014ced4
f1a14e6a9a6c0900fc623cf66cc7829f1e4f0a8e
refs/heads/master
<repo_name>callme119/thinkphp-guide<file_sep>/Application/Wjy/Controller/SampleController.class.php <?php namespace Wjy\Controller; use Think\Controller; use Wjy\Model\UserModel; Class SampleController extends Controller { public function indexAction() { $UserM = new UserModel(); $users = $UserM->getLists(); dump($users); $this->display(); } } <file_sep>/Application/User/Model/Index/addModel.class.php <?php namespace User\Model\Index; class addModel { protected $id = 0; protected $userName = ""; protected $password = ""; protected $user = array(); public function setUser($user) { $this->user = $user; } public function getId() { return $this->user['id']; } public function getUserName() { return $this->user['username']; } public function getPassword() { return $this->user['password']; } } <file_sep>/Application/User/Logic/UserLogic.class.php <?php namespace User\Logic; use User\Model\UserModel; class UserLogic extends UserModel { protected $pageShow = 0; protected $errors = array(); public function getErrors() { return $this->errors; } public function getListByName($name) { //判断是否是字符串 if (is_string($name)!==true) { $this->errors[] = "传入变量类型非string"; return false; } //去空格 $name=trim((string)$name, " "); $map['name'] = $name; $status=$this->create($map,4); //判断状态 if (!$status) { $this->errors[]=$this->getError(); return false; } $data = $this->where($map)->find(); return $data; } public function getListById($id) { $map['id'] = $id; $data = $this->where($map)->find(); return $data; } public function getPageShow(){ return $this->pageShow; } public function deleteInfo($id) { $map['id'] = $id; $datas=$this->where($map)->delete(); return $datas; } public function addList($list) { try{ if($this->create($list)) { $id=$this->add(); return $id; } else { $this->errors[]=$this->getError(); return false; } } catch(\Think\Exception $e) { $this->errors[]=$e->getMessage(); return false; } } public function saveList($list){ try{ if($this->create($list)) { $id=$this->save(); return $id; } else { $this->errors[]=$this->getError(); return false; } } catch(\Think\Exception $e) { $this->errors[]=$e->getMessage(); return false; } } }<file_sep>/Application/Login/Controller/IndexController.class.php <?php namespace Login\Controller; use Think\Controller; use User\Logic\UserLogic; //用户表 class IndexController extends Controller { public function indexAction(){ $this->display(); } public function loginAction() { //取用户名 $userName = I('post.name'); //抓取用户名 $UserL = new UserLogic(); $user = $UserL->getListByName($userName); //判断用户名是否合法 if($user===false){ $errors = $UserL->getErrors(); $this->error("操作错误".'<br/>'.implode('<br/>', $errors)); //数组变字符串 implode() } //判断是否有此用户 if($user == null) { echo "the username is not "; exit(); } //取用户传入密码 $userPassword = I('<PASSWORD>'); //判断密码正确性 if($userPassword != $user['password']) { echo "wrong password"; exit(); } //seesion userId session('userId',$user['id']); //跳转至首页 $this->success("操作成功" , U('Home/Index/index')); } public function logoutAction() { session('userId',null); // 删除name $this->success("注销成功",U('Login/Index/index')); } }<file_sep>/Application/User/Controller/SampleController.class.php <?php namespace User\Controller; use Think\Controller; use Wjy\Model\UserModel; use User\Logic\UserLogic; //用户表 use User\Model\Index\indexModel; Class SampleController extends Controller { public function indexAction() { //获取列表 $UserM = new UserModel(); $users = $UserM->getLists(); echo $UserM->getLastSql(); dump($users); $IndexModel = new indexModel(); $IndexModel->setUsers($users); //传入列表 $this->assign('M',$IndexModel); $this->display(); } } <file_sep>/Application/Home/Controller/IndexController.class.php <?php namespace Home\Controller; use Think\Controller; use User\Logic\UserLogic; // class IndexController extends Controller { public function indexAction() { //判断用户是否登陆 $userId = I('session.userId'); if($userId == '') { $this->success("请登录",U('Login/Index/index')); exit(); } //取用户信息 $UserL = new UserLogic(); $user = $UserL->getListById($userId); //传值 $this->assign("user",$user); $this->display(); } }<file_sep>/Application/Deng/Logic/wechatMenuapiLogic.class.php <?php namespace Admin\Logic; use Admin\Controller\IndexController; class wechatMenuapiLogic extends IndexController { private $access_token; public function setAccessToken($access_token){ $this->access_token = $access_token; } public function createMenu(){ $jsonmenu = '{ "button":[ { "type":"click", "name":"我要住店", "key":"hotel" }, { "type":"click", "name":"我要旅游", "key":"tour" }, { "name":"看这里", "sub_button":[ { "type":"click", "name":"客房环境", "key" : "environment" }, { "type":"click", "name":"酒店介绍", "key" : "description" }, { "type":"view", "name":"一键导航", "url":"https://www.baidu.com" }, { "type":"view", "name":"全景360", "url":"https://www.baidu.com" }] }] }'; $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->access_token; echo "hello"; $result = $this->https_request($url, $jsonmenu); var_dump($result); } private function https_request($url,$data = null){ $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); if(!empty($data)){ curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return $output; } }<file_sep>/Application/Wjy/Model/UserModel.class.php <?php namespace Wjy\Model; use Wjy\Model\YunzhiModel; class UserModel extends YunzhiModel { }<file_sep>/Application/User/Model/Index/indexModel.class.php <?php namespace User\Model\Index; use User\Model\UserModel; use UserPost\Model\UserPostModel; use Post\Model\PostModel; use UserPost\Model\UserPostViewModel; class indexModel { protected $pageShow = ""; //xxxxx protected $users = array();//xxxxxx public function setPageShow($pageShow) { $this->pageShow = (string)$pageShow; } public function getPageShow() { $pageShow = "<a href=" . U('?p=2'); } public function setUsers($users) { $this->users = $users; } public function getUsers() { return $this->users; } public function getPostsByUserId($userId) { $userId = (int)$userId; $UserPostViewM = new UserPostViewModel(); $lists = $UserPostViewM->where("user_id = $userId")->select(); // echo $UserPostM->getLastSql(); return $lists; } public function getNameByPostId($postId) { $postId = (int)$postId; $PostM = new PostModel(); $list = $PostM->where("id = $postId")->find(); return $list['name']; } }<file_sep>/Application/Deng/Controller/IndexController.class.php <?php namespace Deng\Controller; use Think\Controller; use Deng\Logic\wechatInterfaceapiLogic; use Deng\Logic\wechatMenuapiLogic; use Deng\Logic\CustomMenuLogic; use Deng\Model\CustomMenuModel; class IndexController extends Controller { public function createMenu(){ //调用微信接口获取access_token等基本信息 $appid = C("APPID"); $appsecret = C("APPSECRET"); $wechatInterface = new wechatInterfaceapiLogic(); $access_token = $wechatInterface->getAccessToken($appid,$appsecret); //创建菜单 $wechatMenu = new wechatMenuapiLogic(); $wechatMenu->setAccessToken($access_token); $wechatMenu->createMenu(); } //自定义菜单查询 public function indexAction(){ $MenuL = new CustomMenuLogic(); //获取列表 $menu = $MenuL->getLists(); $MenuM = new CustomMenuModel(); $MenuM->setMenus($menu); //传入列表 $this->assign('M',$MenuM); //调用V层 $this->display(); } //自定义菜单修改 public function editAction(){ //获取菜单ID $menuId = I('get.id'); //取菜单信息,并且将pid换位上级菜单名称 $MenuL = new CustomMenuLogic(); $menu = $MenuL->getListById($menuId); $menu['pid'] = $MenuL->getListById($menu['pid'])['title']; $MenuM = new CustomMenuModel(); $MenuM->setMenu($menu); //传入列表 $this->assign('M',$MenuM); //显示 display('add') $this->display('add'); } //自定义菜单更新 public function updateAction(){ //取用户信息 $data = I('post.'); //传给M层 $MenuL = new CustomMenuLogic(); $MenuL->saveList($data); //判断异常 if(count($errors=$MenuL->getErrors())!==0) { //数组变字符串 $error =implode('<br/>', $errors); //显示错误 $this->error("添加失败,原因:".$error,U('User/Index/index')); return false; } $this->success("操作成功" , U('User/Index/index')); } //自定义菜单添加 public function addAction(){ $MenuL = new CustomMenuLogic(); $titles = $MenuL->getTitles(); //传入列表 $MenuM = new CustomMenuModel(); $MenuM->setTitles($titles); $this->assign('M',$MenuM); //显示 display $this->display(); } //自定义菜单保存 public function saveAction(){ //取用户信息 $menu = I('post.'); //添加 add() $MenuL = new CustomMenuLogic(); $MenuL->addList($menu); //判断异常 if(count($errors=$MenuL->getErrors())!==0) { //数组变字符串 $error =implode('<br/>', $errors); //显示错误 $this->error("添加失败,原因:".$error,U('User/Index/index')); } $this->success("操作成功" , U('index')); } //自定义菜单删除 public function deleteAction(){ $menuId = I('get.id'); $MenuL = new CustomMenuLogic(); $status = $MenuL->deleteInfo($menuId); if($status!==false){ $this->success("删除成功", U('index')); } else{ $this->error("删除失败" , U('index')); } } }<file_sep>/Application/UserPost/Model/UserPostViewModel.class.php <?php namespace UserPost\Model; use Think\Model\ViewModel; class UserPostViewModel extends ViewModel { public $viewFields = array( 'UserPost'=>array('id', 'user_id', 'post_id'), 'User'=>array('name'=>"user_name", '_on'=>'UserPost.user_id=User.id'), 'Post'=>array('name'=>"post_name", '_on'=>'UserPost.post_id=Post.id'), ); }<file_sep>/Application/UserPost/Model/UserPostModel.class.php <?php namespace UserPost\Model; use Think\Model; class UserPostModel extends Model{ }<file_sep>/Application/Deng/Logic/CustomMenuLogic.class.php <?php namespace Deng\Logic; use Deng\Model\CustomMenuModel; class CustomMenuLogic extends CustomMenuModel { public function getErrors() { return $this->errors; } public function getListById($id) { $map['id'] = $id; $data = $this->where($map)->find(); return $data; } public function getListByName($name) { //判断是否是字符串 if (is_string($name)!==true) { $this->errors[] = "传入变量类型非string"; return false; } //去空格 $name=trim((string)$name, " "); $map['title'] = $name; $data = $this->where($map)->find(); return $data; } public function getLists($status=0) { try { $lists=$this->select(); return $lists; } catch(\Think\Exception $e) { $this->errors[]=$e->getMessage(); return false; } } public function deleteInfo($id) { $map['id'] = $id; $datas = $this->where($map)->delete(); return $datas; } public function addList($list) { try{ //将ptitle转换为pid $ptitle = $list['pid']; $list['pid'] = $this->getListByName($ptitle)['id']; if($this->create($list)) { $data = $this->add(); return $data; } else { $this->errors[]=$this->getError(); return false; } } catch(\Think\Exception $e) { $this->errors[]=$e->getMessage(); return false; } } public function saveList($list){ try{ if($this->create($list)) { $id=$this->save(); return $id; } else { $this->errors[]=$this->getError(); return false; } } catch(\Think\Exception $e) { $this->errors[]=$e->getMessage(); return false; } } public function getTitles(){ try { $titles = array(); $data = $this->getLists(); foreach ($data as $key => $value) { $titles[] = $value['title']; } return $titles; } catch(\Think\Exception $e) { $this->errors[]=$e->getMessage(); return false; } } }<file_sep>/Application/User/Controller/IndexController.class.php <?php namespace User\Controller; use Think\Controller; use User\Logic\UserLogic; //用户表 use User\Model\Index\indexModel; // class IndexController extends Controller { public function indexAction(){ //获取列表 $UserL = new UserLogic(); $users = $UserL->getLists(); //获取分页信息 $page = $UserL->__construct(); //判断异常 if(count($errors=$UserL->getErrors())!==0) { //数组变字符串 $error = implode('<br/>', $errors); //显示错误 $this->error("查找失败,原因:".$error,U('Home/Index/index')); return false; } $IndexModel = new indexModel(); $IndexModel->setPageShow($page); $IndexModel->setUsers($users); //传入列表 $this->assign('M',$IndexModel); //调用V层 $this->display(); } // public function detailAction(){ // //取用户ID // $userId = I('get.id'); // //抓取用户信息 // $UserL = new UserLogic(); // $user = $UserL->getListById($userId); // //传值 // $this->assign('user',$user); // $this->display(); // } // public function addAction(){ // //显示 display // $this->display(); // } // public function saveAction(){ // //取用户信息 // $user = I('post.'); // //添加 add() // $UserL = new UserLogic(); // $UserL->addList($user); // //判断异常 // if(count($errors=$UserL->getErrors())!==0) // { // //数组变字符串 // $error =implode('<br/>', $errors); // //显示错误 // $this->error("添加失败,原因:".$error,U('User/Index/index?p='.I('get.p'))); // } // $this->success("操作成功" , U('User/Index/index?p='.I('get.p'))); // } // public function editAction(){ // //获取用户ID // $userId = I('get.id'); // //取用户信息 getListById() // $UserL = new UserLogic(); // $user = $UserL->getListById($userId); // //传给前台 // $this->assign('user',$user); // //显示 display('add') // $this->display('add'); // } // public function updateAction(){ // //取用户信息 // $data = I('post.'); // //传给M层 // $UserL = new UserLogic(); // $UserL->saveList($data); // //判断异常 // if(count($errors=$UserL->getErrors())!==0) // { // //数组变字符串 // $error =implode('<br/>', $errors); // //显示错误 // $this->error("添加失败,原因:".$error,U('User/Index/index?p='.I('get.p'))); // return false; // } // $this->success("操作成功" , U('User/Index/index?id=', I('get.'))); // } // public function deleteAction(){ // $userId = I('get.id'); // $UserL = new UserLogic(); // $status = $UserL->deleteInfo($userId); // if($status!==false){ // $this->success("删除成功", U('User/Index/index?p='.I('get.p'))); // } // else{ // $this->error("删除失败" , U('User/Index/index?p='.I('get.p'))); // } // } }<file_sep>/Application/Post/Model/PostModel.class.php <?php namespace Post\Model; use Think\Model; class PostModel extends Model{ }
d26f5272b176053574bb2164b32fddf3dd540f54
[ "PHP" ]
15
PHP
callme119/thinkphp-guide
0215f0836117ef60ff7342cb00014b638aea47a1
652789fd75f65555ecee88c92980c69517342cf3
refs/heads/master
<repo_name>rnowotniak/mydoom-client2004<file_sep>/mydoom-client.c /* * klient MyDoom.c (Shimg) * * <NAME> <<EMAIL>> * nie 01 lut 2004 21:27:20 CET * *********************************************************************** ************* Program _WYŁĄCZNIE_ do celów edukacyjnych *************** *********************************************************************** * * * Koń trojanski Shimg (instalowany przez MyDoom.A i mutacje) * standardowo nasłuchuje na porcie 3127 w oczekiwaniu na jedno * z dwu żądań: uruchomienie przesłanego pliku wykonywalnego * lub ustanowienie tunelowanego połączenia z trzecim hostem. * * * Format pakietów jest następujący: * *********************************************************************** * * 0000000: 0401 0fc8 c0a8 4201 00 474554202f2048 ......B..GET / H * ^^1^ ^^2^ ^^^^3^^^^ ^4 ^^^^^^^^5^^^^^ * 0000010: 5454 502f 312e 310a 486f 7374 3a20 7777 TTP/1.1.Host: ww * 0000020: 772e 6d69 6372 6f73 6f66 742e 636f 6d0a w.microsoft.com. * sent 0, rcvd 49 * * 1 -- 2 bajty, żądanie ustanowienia tunelu [\x04\x01] * 2 -- 2 bajty, docelowy port w porządku sieciowym * 3 -- 4 bajty, docelowy adres IP w porządku sieciowym * 4 -- 1 bajt, separator żądania od tunelowanych danych [\x00] * 5 -- dane do przesłania ustanowionym tunelem * *********************************************************************** * * 0000000: 85 133c9ea2 4d5a900003000000040000 ..<..MZ......... * ^1 ^^^^2^^^ ^^^^^^^^^^^3^^^^^^^^^^ * 0000010: 00ff ff00 00b8 0000 0000 0000 0040 0000 .............@.. * [...] * 0000050: 4ccd 2154 6869 7320 7072 6f67 7261 6d20 L.!This program * 0000060: 6361 6e6e 6f74 2062 6520 7275 6e20 696e cannot be run in * 0000070: 2044 4f53 206d 6f64 652e 0d0d 0a24 0000 DOS mode....$.. * * 1 -- 1 bajt, żądanie wykonania przesłanego programu [\x85] * 2 -- 4 bajty, liczba potwierdzająca [\x13\x3C\x9E\xA2] * 3 -- dane zawierające program do uruchomienia * *********************************************************************** * * */ #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <unistd.h> #include <time.h> #include <signal.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/stat.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <locale.h> #define DEFAULT_SHIMG_PORT 3127 #define DEFAULT_PROXY_PORT 6060 #define DEFAULT_LISTEN_PORT 2731 #define DEFAULT_FORWARD_PORT 80 #define HOST_MAXLEN 70 #define TIMEOUT 15 /* Takie dane będą wysłane w celu rozpoznania Shimg */ #define TOUCH_CONTENT {'\001'} /* Takie dane oznaczają wykrycie Shimg */ #define MYDOOM_FGRPRNT {'\x04','\x5B','\x00','\x00','\x00','\x00','\x00','\x00'} /* Żądanie uruchomienia programu */ #define RUN_CONTENT {'\x85','\x13','\x3C','\x9E','\xA2'} /* Żądanie zestawienia tunelu */ #define FORW_CONTENT {'\x04','\x01','\x00','\x00','\x00','\x00','\x00','\x00','\000'} #define PROXY_RESP "HTTP/1.0 200 Connection established" #ifndef BUFLEN #define BUFLEN 200 #endif #ifndef HAVE_SIN_LEN /* Na GNU/Linux to ma być 0, na Uniksie to ma być 1 */ #define HAVE_SIN_LEN 0 #endif const char *ARGV0; struct sockaddr_in VICTIM_ADDR; struct sockaddr_in PROXY_ADDR; void usage(void); void baner(void); void Blad(const char *str); int Polacz(const struct sockaddr_in *cel); void Do_Touch(void); void Do_Forward(const char *dst, int input); void Do_Run(const char *nazwa); void Nasluchuj(const char *listen_loc, const char *dst); void Ustal_Adres(struct sockaddr_in *dst, const char *src, uint16_t def_port); int main(int argc, char * const *argv) { int ch; int touch = 0; char *forward = NULL, *run = NULL; char *listen = NULL, *proxy = NULL; setlocale(LC_ALL, ""); signal(SIGPIPE, SIG_IGN); if( NULL == (ARGV0 = argv[0]) ) exit(EXIT_FAILURE); if( argc < 2 ) usage(); while( (ch=getopt(argc, argv, "f:r:thl:p:")) != -1 ) { switch(ch) { case 'f': forward = optarg; break; case 'r': run = optarg; break; case 't': touch = 1; break; case 'l': listen = optarg; break; case 'p': proxy = optarg; break; case '?': case 'h': default: usage(); } } argc -= optind; argv += optind; if( argc != 1 ) usage(); if( ! touch && ! forward && ! run ) touch = 1; baner(); Ustal_Adres(&VICTIM_ADDR, *argv, DEFAULT_SHIMG_PORT); if( proxy ) Ustal_Adres(&PROXY_ADDR, proxy, DEFAULT_PROXY_PORT); if( touch ) Do_Touch(); if( run ) Do_Run(run); if( listen && forward ) Nasluchuj(listen, forward); else if( forward ) Do_Forward(forward, 0); exit(EXIT_SUCCESS); } /*--------------------------------------------------------- --- Definicje funkcji {{{ --------------------------------- ---------------------------------------------------------*/ /* * Przyjmuje wskaźnik src na łańcuch znaków (ip lub nazwa hosta) * i wypełnia strukturę sockaddr_in, wskazywaną przez dst. */ void Ustal_Adres(struct sockaddr_in *dst, const char *src, uint16_t def_port) { char *port; char Adres[HOST_MAXLEN]; struct hostent *he1; if( ! src || ! dst ) return; strncpy(Adres, src, sizeof(Adres)); Adres[sizeof(Adres)-1] = '\0'; memset((void*)dst, '\0', sizeof(*dst)); #if defined(HAVE_SIN_LEN) && HAVE_SIN_LEN != 0 dst->sin_len = sizeof(struct in_addr); #endif dst->sin_family = AF_INET; if( (port=index(Adres, ':')) && *(port+1) ) { *port = '\0'; dst->sin_port = htons(atoi(port+1)); } else dst->sin_port = htons(def_port); if( (dst->sin_addr.s_addr=inet_addr(Adres)) == INADDR_NONE ) { he1 = gethostbyname2(Adres, AF_INET); if( ! he1 || ! he1->h_addr_list[0] ) { fprintf(stderr, "Błąd: Nie udało się rozpoznać podanego adresu (%s).\n", src); exit(EXIT_FAILURE); } dst->sin_addr.s_addr = *(in_addr_t*)(he1->h_addr_list[0]); printf("[i] Nazwa %s wskazuje na adres %s\n", Adres, inet_ntoa(dst->sin_addr)); endhostent(); } } /* * Wyświetla komunikat o błędze na podstawie wartości errno */ void Blad(const char *str) { char *buf; if( ! str ) return; if( NULL == (buf = malloc(strlen(str)+4+1)) ) exit(EXIT_FAILURE); sprintf(buf, "[B] %s", str); perror(buf); exit(EXIT_FAILURE); } /* * Tworzy gniazdo internetowe i ustanawia połączenie z celem */ int Polacz(const struct sockaddr_in *cel) { int fd; int ver, status, err; FILE *proxy; char buf[80]; struct timeval tv1 = { TIMEOUT, 0 }; if( ! cel ) return -1; if( PROXY_ADDR.sin_addr.s_addr == (in_addr_t)0 || ( PROXY_ADDR.sin_port == cel->sin_port && PROXY_ADDR.sin_addr.s_addr == cel->sin_addr.s_addr ) ) { /* Łączenie bezpośrednie */ if( (fd=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0 ) Blad("socket()"); if( connect(fd, (struct sockaddr *)cel, sizeof(*cel)) < 0 ) Blad("connect()"); } else { /* Próba łączenia przez proxy */ fprintf(stderr, "[i] Łączenie z proxy...\n"); fd = Polacz(&PROXY_ADDR); if( setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv1, sizeof(tv1)) < 0 ) Blad("setsockopt()"); if( NULL == (proxy=fdopen(fd, "r+")) ) Blad("fdopen()"); fprintf(proxy, "CONNECT %s:%d HTTP/1.1\r\n\r\n", inet_ntoa(cel->sin_addr), ntohs(cel->sin_port)); if( (err=fscanf(proxy, "HTTP/1.%d %d ", &ver, &status)) != 2 || NULL == fgets(buf, sizeof(buf), proxy) || NULL == fgets(buf, sizeof(buf), proxy) ) { if( err != -1 && err != 2 ) { fprintf(stderr, "[B] Niezrozumiała odpowiedź od serwera proxy.\n"); exit(EXIT_FAILURE); } else if( errno == EWOULDBLOCK ) { fprintf(stderr, "[B] Brak odpowiedzi od proxy w ciągu %ds\n", TIMEOUT); exit(EXIT_FAILURE); } else Blad("fgets()"); } if( ver != 0 && ver != 1 ) { fprintf(stderr, "[B] Błędna odpowiedź od proxy.\n"); exit(EXIT_FAILURE); } if( status != 200 ) { fprintf(stderr, "[B] Proxy nie udało się nawiązać połączenia.\n"); fprintf(stderr, "[B] Status odpowiedzi od serwera: %d\n", status); exit(EXIT_FAILURE); } printf("[i] Serwer proxy ustanowił połączenie.\n"); } return fd; } /* * Otwiera port na adresie listen_loc i serwuje łączącym się klientom * tunelowane połączenie z dst. */ void Nasluchuj(const char *listen_loc, const char *dst) { int listen_fd, client_fd; struct sockaddr_in listen_addr, client_addr; socklen_t addr_len = sizeof(struct sockaddr_in); if( ! listen_loc || ! *listen_loc ) return; Ustal_Adres(&listen_addr, listen_loc, DEFAULT_LISTEN_PORT); if( (listen_fd=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0 ) Blad("socket()"); if( bind(listen_fd, (struct sockaddr*)&listen_addr, sizeof(listen_addr)) < 0 ) Blad("bind()"); if( listen(listen_fd, 3) < 0 ) Blad("listen()"); fprintf(stderr, "[*] Oczekiwanie na połączenie klienta...\n"); if( (client_fd=accept(listen_fd, (struct sockaddr *) &client_addr, &addr_len)) < 0 ) Blad("accept()"); fprintf(stderr, "[i] Nadeszło połączenie z %s:%d...\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); Do_Forward(dst, client_fd); } /* * Sprawdzenie, czy na serwerze działa Shimg */ void Do_Touch(void) { int fd, n, len; char zapyt[] = TOUCH_CONTENT; char oczek[] = MYDOOM_FGRPRNT; char odpow[sizeof(oczek)]; struct timeval tv1 = { TIMEOUT, 0 }; printf("[*] Sprawdzanie dostępności portu %d na serwerze %s...\n", ntohs(VICTIM_ADDR.sin_port), inet_ntoa(VICTIM_ADDR.sin_addr)); fd = Polacz(&VICTIM_ADDR); if( send(fd, (void*)zapyt, sizeof(zapyt), 0) != sizeof(zapyt) ) Blad("send()"); if( setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv1, sizeof(tv1)) < 0 ) Blad("setsockopt()"); if( (len=recv(fd, (void*)odpow, sizeof(odpow), 0)) < 0 ) { if( errno == EWOULDBLOCK ) { fprintf(stderr, "[B] Port otwarty, ale brak odpowiedzi w ciągu %ds\n", TIMEOUT); exit(EXIT_FAILURE); } else Blad("recv()"); } printf("[i] Odpowiedź od serwera:\n[i] "); if( len ) for( n=0; n<len; ++n ) printf("0x%X ", odpow[n]); else printf("(brak)"); printf("\n"); if( len != sizeof(oczek) || memcmp(odpow, oczek, sizeof(oczek) ) ) printf("[!] Port otwarty, ale odpowiedź nie przypomina trojana MyDoom.\n"); else printf("[!] W podanym położeniu działa trojan MyDoom (shimg).\n"); if( close(fd) < 0 ) Blad("close()"); } /* * Zestawienie tunelu do dst, wykorzystując komputer z Shimg jako proxy * input to deskryptor, z którego przychodzą dane do przesyłania. */ void Do_Forward(const char *dst, int input) { int victim_fd; int wczytane, zapisane; struct sockaddr_in cel; char HEADER[] = FORW_CONTENT; char RESP[sizeof(HEADER) - 1]; char bufor; int max; fd_set orig_rdfds, rdfds; if( ! dst || ! *dst ) return; Ustal_Adres(&cel, dst, DEFAULT_FORWARD_PORT); *(uint16_t*)&(HEADER[2]) = cel.sin_port; *(uint32_t*)&(HEADER[4]) = cel.sin_addr.s_addr; printf("[*] Ustanawianie połączenia z %s:%d ", inet_ntoa(cel.sin_addr), ntohs(cel.sin_port)); printf("poprzez %s:%d...\n", inet_ntoa(VICTIM_ADDR.sin_addr), ntohs(VICTIM_ADDR.sin_port)); victim_fd = Polacz(&VICTIM_ADDR); if( write(victim_fd, (void*)HEADER, sizeof(HEADER)) != sizeof(HEADER) ) Blad("write()"); if( read(victim_fd, (void*)RESP, sizeof(RESP)) < 0 ) Blad("read()"); HEADER[1] = 0x5A; if( memcmp( HEADER, RESP, sizeof(RESP) ) ) { printf("[B] <NAME> odpowiedział, że nie może się połączyć.\n"); exit(EXIT_FAILURE); } printf("[!] <NAME> odpowiedział, że nawiązał połączenie.\n"); if( fcntl(victim_fd, F_SETFL, O_NONBLOCK) < 0 ) Blad("fcntl()"); if( fcntl(input, F_SETFL, O_NONBLOCK) < 0 ) Blad("fcntl()"); max = ( (victim_fd>input)?victim_fd:input ) + 1; FD_ZERO(&orig_rdfds); FD_SET(victim_fd, &orig_rdfds); FD_SET(input, &orig_rdfds); for(;;) { rdfds = orig_rdfds; if( select( max, &rdfds, NULL, NULL, NULL ) < 0 ) Blad("select()"); if( FD_ISSET(input, &rdfds) ) { wczytane = read(input, &bufor, 1); if( wczytane == 0 ) break; else if( wczytane < 0 ) Blad("read()"); do zapisane = write(victim_fd, &bufor, 1); while( zapisane < 0 && errno == EWOULDBLOCK ); if( zapisane < 0 ) Blad("write()"); } if( FD_ISSET(victim_fd, &rdfds) ) { wczytane = read(victim_fd, &bufor, 1); if( wczytane == 0 ) break; else if( wczytane < 0 ) Blad("read()"); do zapisane = write(input, &bufor, 1); while( zapisane < 0 && errno == EWOULDBLOCK ); if( zapisane < 0 ) Blad("write()"); } } if( close(victim_fd) < 0 ) Blad("close()"); printf("\n[*] Połączenie zostało zamknięte.\n"); } /* * Wysłanie programu do trojana i żądania uruchomienia */ void Do_Run(const char *nazwa) { int serw, plik; int wczytane; char RUN[] = RUN_CONTENT; char bufor[BUFLEN]; if( ! nazwa || ! *nazwa ) return; printf("[*] Wysyłanie pliku (%s) do uruchomienia przez trojana...\n", nazwa); if( (plik = open(nazwa, O_RDONLY)) < 0 ) Blad("open()"); serw = Polacz(&VICTIM_ADDR); if( send(serw, (void*)RUN, sizeof(RUN), 0) != sizeof(RUN) ) Blad("send()"); do { wczytane = read(plik, (void*)bufor, sizeof(bufor)); if( wczytane < 0 ) Blad("read()"); if( write(serw, (void*)bufor, wczytane) != wczytane ) Blad("write()"); } while( wczytane ); if( close(plik) < 0 ) Blad("close()"); if( close(serw) < 0 ) Blad("close()"); printf("[!] OK. Plik został przesłany na podany adres.\n"); } void baner(void) { printf("--------------------------------------------------\n"); printf("**** klient MyDoom.c (shimg) *****\n"); printf("**** nie 01 lut 2004 21:27:20 CET *****\n"); printf("**** <NAME> <<EMAIL>> *****\n"); printf("--------------------------------------------------\n"); printf("*** Program _WYŁĄCZNIE_ do celów edukacyjnych. ***\n"); printf("--------------------------------------------------\n"); printf("\n"); } void usage(void) { fprintf(stderr, "\n"); fprintf(stderr, " Użycie:\n"); fprintf(stderr, "%s [-t] [[-l <adres[:port]>] -f <Adres_Docelowy[:port]>]\n" "\t[-p <Proxy[:port]>] [-r <Plik.exe>] <Cel_Ataku[:port]>\n", ARGV0); fprintf(stderr, "\n"); fprintf(stderr, " -t Sprawdzenie, czy w podanej lokalizacji działa trojan MyDoom (shimg)\n"); fprintf(stderr, " -f Zestawienie tunelowanego połączenia z Adresem_Docelowym (forwarding)\n"); fprintf(stderr, " -r Uruchomienie podanego <Pliku.exe> na atakowanym komputerze\n"); fprintf(stderr, " -p Wykonywanie wszyskich działań przez proxy (metoda CONNECT)\n"); fprintf(stderr, " -l Nasłuchiwanie na porcie w celu tunelowania\n"); fprintf(stderr, "\n"); exit(EXIT_FAILURE); } /*--------------------------------------------------------- ------------------------------------ }}} ------------------ ---------------------------------------------------------*/ /* vim: set ts=3 sw=3 fdm=marker: */
0e76c8b74e41f7577b186943ff35045dfb3ad1ae
[ "C" ]
1
C
rnowotniak/mydoom-client2004
0227474f458e5cc92b5114d61a552bdfeaac3024
aaf6395483355f2aa63cc91ff404150ff4254d69
refs/heads/main
<repo_name>drsubathra/first<file_sep>/fibronacci sequence.py new_num=1 old_num=0 sum=0 print(old_num) while sum<50: sum = old_num+new_num if sum>50: break print(sum) old_num=new_num new_num=sum
2ec1d944e9376cf188f08a4cb2e7369543fdf054
[ "Python" ]
1
Python
drsubathra/first
aae8919a66bd3942caab51a407c3a96d0b43be04
2e382204b62010137978ba089e40b587d1cde0da
refs/heads/master
<repo_name>cuarti/zenox-config<file_sep>/test/specs/util/loadDirectory.ts import {join} from 'path'; import {loadDirectory} from '../../../src/util'; test('loadDirectory', () => { const path = join('test', 'config'); expect(loadDirectory(path)).toEqual({ db: {domain: 'localhost', port: 1418}, http: {port: 3000, domain: 'domain.com'} }); expect(loadDirectory(join(path, 'development'))).toEqual({ http: {port: 3001, subdomains: ['blog', 'admin']}, log: {apiKey: '<KEY>'} }); expect(loadDirectory(join(path, 'production'))).toEqual({ http: {port: 3002} }); expect(loadDirectory('config')).toEqual({}); }); <file_sep>/test/specs/util/listFiles.ts import {join} from 'path'; import {listFiles} from '../../../src/util'; test('listFiles', () => { const path = join('test', 'config'); expect(listFiles(path)).toEqual(['db.yml', 'http.yml']); expect(listFiles(join(path, 'development'))).toEqual(['http.yml', 'log.yml']); expect(listFiles(join(path, 'production'))).toEqual(['http.yml']); expect(listFiles('config')).toEqual([]); }); <file_sep>/src/util/index.ts export * from './listFiles'; export * from './loadDirectory'; export * from './merge'; <file_sep>/src/util/listFiles.ts import {readdirSync} from 'fs'; /** * List YAML files of directory * * @param path Directory path * @return YAML files */ export function listFiles(path: string): string[] { try { return readdirSync(path).filter(f => f.endsWith('.yml')); } catch(err) { return []; } } <file_sep>/test/specs/ConfigService.ts import {join} from 'path'; import {ConfigService} from '../..'; const config = new ConfigService({ http: {port: 3000, domain: 'domain.com', plugins: {session: true}}, db: {port: 1418, domain: 'localhost'} }); describe('ConfigService', () => { test('#get', () => { expect(config.get('http')).toEqual({port: 3000, domain: 'domain.com', plugins: {session: true}}); expect(config.get('log')).not.toBeDefined(); expect(config.get('log', true)).toBe(true); expect(config.get('http.port')).toBe(3000); expect(config.get('http.port', 80)).toBe(3000); expect(config.get('http.sessionId')).not.toBeDefined(); expect(config.get('http.sessionId', 'secret')).toBe('secret'); expect(config.get('http.plugins')).toEqual({session: true}); expect(config.get('http.plugins', {})).toEqual({session: true}); expect(config.get('http.plugins.session')).toBe(true); expect(config.get('http.plugins.session', false)).toBe(true); }); test('#getAll()', () => { expect(config.getAll()).toEqual({ http: {port: 3000, domain: 'domain.com', plugins: {session: true}}, db: {port: 1418, domain: 'localhost'} }); }); test('fromYaml', () => { const path = join('test', 'config'); expect(ConfigService.fromYaml(path).getAll()).toEqual({ db: {domain: 'localhost', port: 1418}, http: {port: 3000, domain: 'domain.com'} }); expect(ConfigService.fromYaml(path, 'development').getAll()).toEqual({ db: {domain: 'localhost', port: 1418}, http: {port: 3001, domain: 'domain.com', subdomains: ['blog', 'admin']}, log: {apiKey: '<KEY>'} }); expect(ConfigService.fromYaml(path, 'production').getAll()).toEqual({ db: {domain: 'localhost', port: 1418}, http: {port: 3002, domain: 'domain.com'} }); expect(ConfigService.fromYaml('config').getAll()).toEqual({}); }); }); <file_sep>/src/Config.ts import {join} from 'path'; import {ConfigService} from './ConfigService'; export interface Config { /** * Get config from namespace if exists * * @param namespace Namespace config * @return Config value */ get<T>(namespace: string): T | undefined; /** * Get config from namespace if exists or default value otherwise * * @param namespace Namespace config * @param defaultValue Default value for config * @return Config value */ get<T>(namespace: string, defaultValue: T): T; /** * Get all configurations * * @return All configuration */ getAll<T extends object = object>(): T; } const {ZENOX_PROJECT_DIR, ZENOX_CONFIG_DIR, NODE_ENV} = process.env; const path = ZENOX_CONFIG_DIR || join(ZENOX_PROJECT_DIR || process.cwd(), 'config'); const env = NODE_ENV || 'development'; export const Config: Config = ConfigService.fromYaml(path, env); <file_sep>/src/ConfigService.ts import {join} from 'path'; import {Config} from './Config'; import {loadDirectory, merge} from './util'; /** * Config basic implementation */ export class ConfigService implements Config { /** * Config data */ private readonly data: object; /** * Constructor method * * @param data Config data */ public constructor(data: object) { this.data = data; } public get<T>(namespace: string, defaultValue?: T): T | undefined { let value = namespace.split('.').reduce((r, k) => r && r[k], this.data); return value || defaultValue; } public getAll<T extends object = object>(): T { return this.data as T; } /** * Create config from YAML config directory and environment * * @param path Config directory * @param env Environment * @return Config */ public static fromYaml(path: string, env?: string): Config { let data = loadDirectory(path); if(env) { data = merge(data, loadDirectory(join(path, env))); } return new ConfigService(data); } } <file_sep>/src/util/merge.ts /** * Merge two objects * * @param a First object to merge * @param b Second object to merge * @return Merged object */ export function merge(a: object = {}, b: object = {}): object { let keys = Object.keys(a).concat(Object.keys(b)) .filter((k, i, arr) => arr.indexOf(k, i + 1) < 0); return keys.reduce((r, k) => { if(!b.hasOwnProperty(k)) { r[k] = a[k]; } else if(typeof b[k] === 'object' && !(b[k] instanceof Array)) { r[k] = merge(a[k], b[k]); } else { r[k] = b[k]; } return r; }, {}); } <file_sep>/README.md # zenox-config Library to load configuration data from YAML files depending of NODE_ENV value. ### Default config from YAML files Default config service that loads config from YAML files with path of one of next options: - ZENOX_CONFIG_DIR env variable. - ZENOX_PROJECT_DIR env variable plus "config" child. - Current working directory plus "config" child. ###### Usage ```typescript import {Config} from '@zenox/config'; let port = Config.get('http.port'); ``` ### Custom config from object literal Custom config service that loads config from object literal. ###### Usage ```typescript import {ConfigService} from '@zenox/config'; let config = new ConfigService({http: {port: 3000}}); let port = config.get('http.port'); ``` ### Custom config from YAML files Custom config service that loads config from path of directory with YAML files. ###### Usage ```typescript import {ConfigService} from '@zenox/config'; let path = '<relative path to config dir>'; let config = ConfigService.fromYaml(path); let port = config.get('http.port'); ``` <file_sep>/src/util/loadDirectory.ts import {readFileSync} from 'fs'; import {join} from 'path'; import {load} from 'js-yaml'; import {listFiles} from './listFiles'; /** * Load YAML configuration files from directory * * @param path Directory path * @return Config */ export function loadDirectory(path: string): object { return listFiles(path).reduce((r, file) => { let name = file.substring(0, file.length - 4); r[name] = load(readFileSync(join(path, file), 'utf8')); return r; }, {}); } <file_sep>/src/index.ts export * from './Config'; export * from './ConfigService'; <file_sep>/test/specs/util/merge.ts import {merge} from '../../../src/util'; test('merge', () => { expect(merge({name: 'joe'}, {age: 12})).toEqual({name: 'joe', age: 12}); expect(merge({name: 'joe', age: 12}, {name: 'jake'})).toEqual({name: 'jake', age: 12}); });
c02447cb5ad2d9814e2132ffcf5137130d639d5f
[ "Markdown", "TypeScript" ]
12
TypeScript
cuarti/zenox-config
57309886ad5880d5911216f8fbb6cc66cb6f8d55
c50b027e766d91768a31b7bf72d527e4dc3dbf3b
refs/heads/master
<repo_name>Kimserey/knockoutexample<file_sep>/README.md knockoutexample =============== Form example using knockoutjs. The viewmodel takes a url_map as input. It is supposed to contain the url for the loading of the profile, the saving and the uploading of profile pic. Issue faced ============== Jquery post can't send images. Had to use XMLHttpRequest and instantiate a formData to pass the file. <file_sep>/public/lib/profile.js /* * profile.js */ /*jslint browser : true, continue : true, devel : true, indent : 2, maxerr : 50, newcap : true, nomen : true, plusplus : true, regexp : true, sloppy : true, vars : false, white : true */ /*global $, ko */ // represent the profile information function Profile() { var self = this; self.name = ko.observable(''); self.about = ko.observable(''); self.sports = ko.observableArray([]); self.friends = ko.observableArray([]); self.imageurl = ko.observable(''); } // represent the current state of the edit form function Profileform() { var self = this; self.previousimageurl = ko.observable(); self.name = ko.observable(); self.about = ko.observable(); self.image = ko.observable(); self.chosenSports = ko.observableArray([]); } // represent the profile viewmodel // Arguments : // * url_map { loadUrl, getAllSports, saveUrl } // Exposes : // * allSports[] - { id:int, name:string } // * resetForm - reset all value from the form // * load - load the current data and set the profile // * submit - submit the profile form // function ProfileVM( url_map ) { var self = this; self.profile = new Profile(); self.profileForm = new Profileform(); self.allSports = ko.observableArray([]); self.uploadProfilePicture = function ( file ) { self.profileForm.image = file; //Creating an XMLHttpRequest and sending var xhr = new XMLHttpRequest(), formData = new FormData(); formData.append(file.name, file); xhr.open('POST', url_map.uploadProfilePicture); xhr.send(formData); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { alert(xhr.responseText); } //if (data.err) { alert('Failed'); } //self.profileForm.previousimageurl( data.imageurl ); }; }; self.resetForm = function () { self.profileForm.name(''); self.profileForm.about(''); self.profileForm.image(''); self.profileForm.chosenSports.removeAll(); }; // Begin Load of me profile self.load = function () { // Begin load of view model values $.getJSON(url_map.getAllSports, {}, function (data) { var all_sports; all_sports = data.map(function (sport) { return { imageurl: sport.imageurl, name: sport.name }; }); self.allSports(all_sports); }); // End load of view model values // Begin load of profile values $.getJSON(url_map.loadUrl, {}, function (data) { var sports, friends; sports = data.Sports.map(function (sport) { return { id: sport.Id, imageurl: sport.ImageUrl, name: sport.Name }; }); friends = data.Friends.map(function (friend) { return { id: friend.Id, imageurl: friend.ImageUrl, name: friend.Name }; }); self.profile.name( data.Name ); self.profile.about( data.About ); self.profile.sports( sports ); self.profile.friends( friends ); self.profile.imageurl(data.ImageUrl); }); // End load of profile form values }; // End Load of me profile self.submit = function () { var profileForm_json = ko.toJSON(self.profileForm); $.post(url_map.saveUrl, profileForm_json, function ( data ) { self.profile.name( self.profileForm.name() ); self.profile.about( self.profileForm.about() ); self.profile.sports( self.profileForm.chosenSports() ); self.profile.imageurl( self.profileForm.previousimageurl() ); self.resetForm(); }); }; }
c47a4a44504fab5c19868143525e7f0bbe07ea67
[ "Markdown", "JavaScript" ]
2
Markdown
Kimserey/knockoutexample
fc1a9854b0cf9f7a70997c7fd57bc34f8767f19b
d64d70ff95d48781a043d93fce21fd946fc74339
refs/heads/master
<file_sep>#include <opencv2/opencv.hpp> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <setjmp.h> #include "hpdf.h" using namespace cv; jmp_buf env; void error_handler(HPDF_STATUS error_no, HPDF_STATUS detail_no, void* user_data) { printf ("ERROR: error_no=%04X, detail_no=%u\n", (HPDF_UINT)error_no, (HPDF_UINT)detail_no); longjmp(env, 1); } void draw_image (HPDF_Doc pdf, const char* filename, float x, float y) { HPDF_Page page = HPDF_GetCurrentPage (pdf); HPDF_Image image; image = HPDF_LoadPngImageFromFile (pdf, filename); /* Draw image to the canvas. */ HPDF_Page_DrawImage (page, image, 0, 0, x, y); } int main (int argc, char **argv) { HPDF_Doc pdf; HPDF_Font font; HPDF_Page page; char fname[256] = "chessboard"; int length_size; int width_size; float grid_size; HPDF_Destination dst; grid_size = atof(argv[1]); length_size = atoi(argv[2]); width_size = atoi(argv[3]); std::cout << "grid size: " << grid_size << "mm" << std::endl; std::cout << "size num of length: " << length_size << std::endl; std::cout << "size num of width: " << width_size << std::endl; strcat (fname, ".pdf"); int blockSize=600; int imageSize_length=blockSize*length_size; int imageSize_width=blockSize*width_size; Mat chessBoard(imageSize_width,imageSize_length,CV_8UC3,Scalar::all(0)); unsigned char color1=0; unsigned char color2=0; for(int i=0;i<imageSize_length;i=i+blockSize){ color1=~color1; color2 = color1; for(int j=0;j<imageSize_width;j=j+blockSize){ Mat ROI=chessBoard(Rect(i,j,blockSize,blockSize)); ROI.setTo(Scalar::all(color2)); color2=~color2; } } copyMakeBorder(chessBoard, chessBoard, blockSize/2, blockSize/2, blockSize/2, blockSize/2, BORDER_CONSTANT, Scalar(255, 255, 255)); imwrite("chessboard.png", chessBoard); pdf = HPDF_New (error_handler, NULL); if (!pdf) { printf ("error: cannot create PdfDoc object\n"); return 1; } /* error-handler */ if (setjmp(env)) { HPDF_Free (pdf); return 1; } HPDF_SetCompressionMode (pdf, HPDF_COMP_ALL); /* create default-font */ font = HPDF_GetFont (pdf, "Helvetica", NULL); /* add a new page object. */ page = HPDF_AddPage (pdf); HPDF_Page_SetWidth (page, length_size * grid_size * 0.03937 * 72); HPDF_Page_SetHeight (page, width_size* grid_size * 0.03937 * 72); dst = HPDF_Page_CreateDestination (page); HPDF_Destination_SetXYZ (dst, 0, HPDF_Page_GetHeight (page), 1); HPDF_SetOpenAction(pdf, dst); HPDF_Page_SetFontAndSize (page, font, 12); draw_image (pdf, "chessboard.png", length_size * grid_size * 0.03937 * 72, width_size* grid_size * 0.03937 * 72); /* save the document to a file */ HPDF_SaveToFile (pdf, fname); /* clean up */ HPDF_Free (pdf); std::cout << "chessboard: " << length_size * grid_size/10.0 << "cm x " << width_size* grid_size/10.0 << "cm \n"; return 0; } <file_sep>cmake_minimum_required(VERSION 2.8.3) project(chessboard) find_package( OpenCV REQUIRED ) link_directories(/usr/local/lib) add_executable(chessboard src/main.cpp) target_link_libraries( chessboard ${OpenCV_LIBS} hpdf ) <file_sep># chessboard Chessboard (checkerboard) generator for camera calibration ### Install libharu ``` https://github.com/libharu/libharu ``` ### Install OPENCV ``` https://opencv.org/ ``` ### Usage ``` ./chesssboard [grid_size(mm)] [length_grid_num] [width_grid_num] ```
1927998d66408ff50fbb049787350203bc349d84
[ "Markdown", "CMake", "C++" ]
3
C++
Osborn28/chessboard
4699b2808e5a7b337d8e6b00e4570247de706315
6518f3f89e0a53addbd59470c2c0acdce9f575cc
refs/heads/master
<file_sep>package CopyFileText; import java.io.*; import java.util.ArrayList; import java.util.List; public class CopyFileText { public List<String> readFile(String path) { List<String> strings = new ArrayList<>(); try { FileReader fileReader = new FileReader(path); BufferedReader bufferedReader = new BufferedReader(fileReader); String line = ""; while ((line = bufferedReader.readLine()) != null) { strings.add(line + "\n"); } bufferedReader.close(); } catch (IOException e) { System.out.println("Tệp nguồn không tồn tại hoặc bị lỗi."); } return strings; } public void writeFile(String path, List<String> strings) { try { FileWriter fileWriter = new FileWriter(path); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); for (String string: strings) { bufferedWriter.write(string); } bufferedWriter.close(); } catch (IOException e) { System.out.println("Tệp nguồn không tồn tại hoặc bị lỗi."); } } public static void main(String[] args) { CopyFileText copyTextFile = new CopyFileText(); List<String> strings = copyTextFile.readFile("folder.txt"); copyTextFile.writeFile("foldercoppy.txt", strings); } }
c650a72fc4135ca2c827e32a317afb5bfbefac72
[ "Java" ]
1
Java
dominthao91/MD2-TextFile
fb64aab5c446aa0b9bfa24aedc4fe3640a3a1437
c0fc45bea98ac509970d0b6e23450500eeab9352
refs/heads/master
<file_sep>package Leetcode; /** * Created by qy on 2016/5/23. * task: * Given n non-negative integers a1,a2,...,an, where each represents a point at coordinate(i,ai). * n vertical lines are drawn such that the two endpoints of line i is at(i,ai) and (i,0). * Find two lines, which together with x-axis forms a container, such that the container contains the most water * note: You may not slant the container. */ public class ContainerWithMostWater { /** * created by qy * the last cast'time limit exceeded. * * understand the meaning of this question wrong... * really fool.. * WTF!! * * */ public int maxArea(int[] height){ int count = 0; int left,right; int temp = 0; for (int i = 0; i < height.length;i++){ left = i; right = i; while (height[left] >= height[i] || height[right] >= height[i]){ temp = height[i] * (right - left); if (count < temp){ count = temp; } if (left ==0 && right== height.length -1 ){ break; } if (left != 0 && right != height.length -1 && height[right+1] < height[i] && height[left-1] < height[i]){ break; } if (left == 0 && right < height.length -1 && height[right+1] < height[i]) { break; } if (right == height.length-1 && left >0 && height[left-1] < height[i]){ break; } if (left != 0 && height[left-1] >= height[i] ){ left--; } if (right != height.length - 1 && height[right+1] >= height[i]){ right ++; } } } return count; } /** * really fast. * 2ms,99.86% * To find the biggest number, we don't neet to find it from the smallest,wo can begin with calculating from the result which wo can get easily. */ public int maxArea1(int[] height) { int left=0; int right = height.length-1; int max=0,area; while(left<right) { int l = height[left]; int r = height[right]; if( l > r){ area = (right-left) * r; while (height[--right] <= r); }else{ area = (right-left) * l; while (height[++left] < l); } if (area > max) max = area; } return max; } /** * 4ms,78.29% */ public int maxArea2(int[] height) { int max = 0, i = 0, j = height.length - 1; while(i < j) max = Math.max(max, (j - i) * (height[i] < height[j] ? height[i++] : height[j--])); return max; } public static void main(String[] args) { int[] arr = {1,2,3,4,2,1}; int c = new ContainerWithMostWater().maxArea(arr); System.out.println(c); } } <file_sep>package Test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Created by Yiy on 2016/7/6. */ public class internQuestionTest { public static void main(String[] args) { System.out.print("请输入1-9之间的任一数字"); BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); try { System.out.println(r.readLine()); } catch (IOException e) { e.printStackTrace(); } System.out.print(1 + " "); System.out.print("\n"); System.out.println("3"); } } <file_sep>package JDBC.com.qy; import java.sql.*; /** * Created by Yiy on 2016/4/12. */ public class DBTest { private static final String URL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=GB2312"; private static final String USER = "root"; private static final String PASSWORD = "<PASSWORD>"; private static Connection conn = null; static { try { //加载驱动 Class.forName("com.mysql.jdbc.Driver"); //获得连接 conn = DriverManager.getConnection( URL , USER, PASSWORD); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public static Connection getConn(){ return conn; } public static void main(String[] args) { try { //加载驱动 Class.forName("com.mysql.jdbc.Driver"); //获得连接 Connection conn = DriverManager.getConnection( URL , USER, PASSWORD); //通过数据库的连接操作数据库 Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from admin;"); while (rs.next()){ System.out.println(rs.getString("adminname")+ "," + rs.getString("password") ); } } catch (Exception e) { e.printStackTrace(); } } } <file_sep>package Test; /** * Created by Yiy on 2016/3/7. */ public class quickSort{ static int[] a = {2, 7,4,6,9,0,8,5,3,1}; public quickSort(){ // a = this.a; } public static void sort(int[] a, int left ,int right){ // int[] a = b; if (left < right){ int temp = a[left]; int i = left; int j = right; while (i != j) { while ( a[right] > temp && i <j){ j--; } while ( a[left] < temp && i < j ) { i++; } if (i < j) { int t = a[j]; a[j] = a[i]; a[i] = t; } a[left] = a[i]; a[i] = temp; if (left != i-1) { sort(a, left, i-1); } if (right != i+1) { sort(a, i+1, right); } } } } public static void main(String[] args) { // for (int i = 0; i < N; i++) { // a[i] = Integer.valueOf(args[i]); // } int N = a.length; quickSort.sort(a,0, N-1); for (int i = 0; i < N;i++ ) { System.out.print(a[i]); System.out.print(" "); } } } <file_sep>package JavaNet; /** * Created by Yiy on 2016/3/22. */ public class Net_exp2 { public static void main(String[] args) { try { // InputStream in = (new URL("http://www.baidu.com/img/baidu_sylogol.gif")).openStream(); // FileOutputStream fo = new FileOutputStream("D://桌面/logo.gif"); // BufferedOutputStream bo = new BufferedOutputStream(fo); // DataOutputStream dao = new DataOutputStream(bo); // int ch; // while ((ch = in.read()) != -1){ // dao.write(ch); // } // bo.flush(); // bo.close(); // fo.close(); // in.close(); System.out.println(System.getProperty("file.encoding")); } catch (Exception e){ e.printStackTrace(); } } } <file_sep>package ThinkingInJava; import java.io.File; /** * Created by Yiy on 2016/3/12. */ public class IOtest { public static void main(String[] args) { File file = new File("D:/桌面/test.txt"); File file1 = new File("D:/桌面/ceshi"); try{ // file1.mkdirs(); // file.createNewFile(); // file1.createNewFile(); // file1.mkdirs(); // file1.delete(); // System.out.println("该磁盘总容量为" + // file.getTotalSpace()/(1024*1024*1024) + "G"); // file.mkdirs(); // System.out.println("文件名" + file.getName()); // System.out.println("fulujing:" + file1.getParent()); } catch (Exception e){ e.printStackTrace(); } } } <file_sep>package ThinkingInJava; import java.io.*; /** * Created by Yiy on 2016/3/13. */ class student implements Serializable{ private String name; private int age; public student(String name, int age){ super(); this.name = name; this.age = age; } public String toString(){ return "Student:[ name = " + name + "][ age = " + age + " ]"; } } public class objectstreaam { public static void main(String[] args) { ObjectOutputStream output = null; ObjectInputStream input = null; try { output = new ObjectOutputStream(new FileOutputStream("D:/桌面/student.txt")); output.writeObject(new student("qinyi", 18)); output.writeObject(new student("qinhi", 12)); output.writeObject(new student("dddd", 232)); input = new ObjectInputStream(new FileInputStream("D:/桌面/student.txt")); for (int i = 0; i < 3; i++){ System.out.println(input.readObject()); } } catch (IOException | ClassNotFoundException e){ e.printStackTrace(); } finally { try { output.close(); input.close(); } catch (Exception e){ e.printStackTrace(); } } } } <file_sep>package JavaNet; import java.io.*; /** * Created by Yiy on 2016/3/19. */ public class outTest { public static void main(String[] args) throws IOException{ File file = new File("D:/桌面/a1.txt"); file.createNewFile(); BufferedOutputStream buffOut = new BufferedOutputStream(new FileOutputStream(file)); buffOut.write("java写文件测试".getBytes()); buffOut.flush(); buffOut.close(); BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[1024]; int in; while ( (in = buffIn.read(buffer)) != -1){ String str = new String(buffer, 0 ,in); System.out.println(str); } if (buffIn != null){ buffIn.close(); } File file1 = new File("D:/桌面/a2.txt"); file1.createNewFile(); FileOutputStream fileOutputStream = new FileOutputStream(file1); fileOutputStream.write("java文件测完2".getBytes()); fileOutputStream.close(); FileInputStream fileInputStream = new FileInputStream(file1); byte[] bufferIn = new byte[1024]; int in1; while ((in1 = fileInputStream.read(bufferIn)) != -1){ String str1 = new String(bufferIn, 0 ,in1); System.out.println(str1); } fileInputStream.close(); File file3 = new File("D:/桌面/a3.txt"); FileWriter fw = new FileWriter(file3); fw.write("java文件测试3"); fw.close(); FileReader fr = new FileReader(file3); char[] ch = new char[100]; int in2; while ((in2 = fr.read(ch)) != -1){ String str2 = new String(ch, 0 ,in2); System.out.println(str2); } fr.close(); File file2 = new File("D:/桌面/a2.txt"); file2.createNewFile(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file2)); outputStreamWriter.write("java文件测试1"); outputStreamWriter.close(); InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file2)); char[] ch1 = new char[100]; int in3; while ((in3 = inputStreamReader.read(ch1)) != -1){ String str3 = new String(ch1, 0 ,in3); System.out.println(str3); } File file4 = new File("D:/桌面/a4.txt"); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file4))); bw.write("java文件测试4"); bw.close(); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file4))); char[] ch3 = new char[100]; int in4; while ((in4 = br.read(ch3)) != -1){ String str3 = new String(ch3, 0, in4); System.out.println(str3); } } } <file_sep>package JDBC.com.qy.dao; import JDBC.com.qy.DBTest; import JDBC.com.qy.model.Goddess; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Created by Yiy on 2016/4/12. */ public class GoddessDao { public void addGoddess(Goddess g){ try { Connection conn = DBTest.getConn(); String sql = "" + "insert into goddess" + "(user_name,sex,age,birthday,email,mobile," + "create_user,create_date,update_user,update_date,isdel)" + "values(" + "?,?,?,?,?,?,?,current_date(),?,current_date(),?);"; PreparedStatement ptmt = conn.prepareStatement(sql); ptmt.setString(1, g.getUser_name() ); ptmt.setInt(2, g.getSex()); ptmt.setInt(3, g.getAge()); ptmt.setDate(4, new Date(g.getBirthday().getTime())); ptmt.setString(5, g.getEmail()); ptmt.setString(6, g.getMobile()); ptmt.setString(7,g.getCreate_user()); ptmt.setString(8, g.getUpdate_user()); ptmt.setInt(9, g.getIdel()); ptmt.execute(); System.out.println("新增女神成功"); } catch (SQLException e) { e.printStackTrace(); System.out.println("新增女神失败"); } } public void updateGoddess(Goddess g){ try { Connection conn = DBTest.getConn(); String sql = "" + " update goddess " + " set user_name = ?,sex = ?,age = ?,birthday = ?,email = ?,mobile = ?," + " update_user = ?,update_date = current_date(),isdel = ?" + " where id = ?;"; PreparedStatement ptmt = conn.prepareStatement(sql); ptmt.setString(1, g.getUser_name() ); ptmt.setInt(2, g.getSex()); ptmt.setInt(3, g.getAge()); ptmt.setDate(4, new Date(g.getBirthday().getTime())); ptmt.setString(5, g.getEmail()); ptmt.setString(6, g.getMobile()); ptmt.setString(7, g.getUpdate_user()); ptmt.setInt(8, g.getIdel()); ptmt.setInt(9,g.getId()); ptmt.execute(); } catch (SQLException e) { e.printStackTrace(); } } public void delGoddess(Integer id){ try { Connection conn = DBTest.getConn(); String sql = " delete from goddess " + " where id = ?;"; PreparedStatement ptmt = conn.prepareStatement(sql); ptmt.setInt(1,id); ptmt.execute(); } catch (SQLException e) { e.printStackTrace(); } } public List<Goddess> query(){ List<Goddess> gs = new ArrayList<>(); Goddess g = null; try { Connection conn = DBTest.getConn(); StringBuilder sb = new StringBuilder(); sb.append("select * from goddess; "); PreparedStatement ptmt = conn.prepareStatement(sb.toString()); ResultSet rs = ptmt.executeQuery(); while (rs.next()){ g = new Goddess(); g.setId(rs.getInt("id")); g.setUser_name(rs.getString("user_name")); g.setAge(rs.getInt("age")); g.setSex(rs.getInt("sex")); g.setBirthday(rs.getDate("birthday")); g.setEmail(rs.getString("email")); g.setMobile(rs.getString("mobile")); g.setCreate_user(rs.getString("create_user")); g.setCreate_date(rs.getDate("create_date")); g.setUpdate_user(rs.getString("update_user")); g.setUpdate_date(rs.getDate("update_date")); g.setIdel(rs.getInt("isdel")); gs.add(g); // System.out.println(rs.getString("user_name") + "," + rs.getInt("age")); } } catch (SQLException e) { e.printStackTrace(); } return gs; } public List<Goddess> query(String name){ List<Goddess> gs = new ArrayList<>(); Goddess g = null; try { Connection conn = DBTest.getConn(); StringBuilder sb = new StringBuilder(); sb.append("select * from goddess "); sb.append(" where user_name like ?; "); PreparedStatement ptmt = conn.prepareStatement(sb.toString()); ptmt.setString(1, "%" +name+"%"); ResultSet rs = ptmt.executeQuery(); while (rs.next()) { g = new Goddess(); g.setId(rs.getInt("id")); g.setAge(rs.getInt("age")); g.setSex(rs.getInt("sex")); g.setBirthday(rs.getDate("birthday")); g.setEmail(rs.getString("email")); g.setMobile(rs.getString("mobile")); g.setCreate_user(rs.getString("create_user")); g.setCreate_date(rs.getDate("create_date")); g.setUpdate_user(rs.getString("update_user")); g.setUpdate_date(rs.getDate("update_date")); g.setIdel(rs.getInt("isdel")); gs.add(g); } } catch (SQLException e) { e.printStackTrace(); } return gs; } public List<Goddess> query(List<Map<String,Object>> params){ List<Goddess> gs = new ArrayList<>(); Goddess g = null; try { Connection conn = DBTest.getConn(); StringBuilder sb = new StringBuilder(); sb.append("select * from goddess where 1=1 "); if (params != null && params.size() >0){ for (int i = 0; i < params.size(); i++){ Map<String,Object> map = params.get(i); sb.append(" and " + map.get("name") + " " + map.get("rela") + " " + map.get("value")); } sb.append(";"); } System.out.println(sb.toString()); PreparedStatement ptmt = conn.prepareStatement(sb.toString()); ResultSet rs = ptmt.executeQuery(); while (rs.next()) { g = new Goddess(); g.setId(rs.getInt("id")); g.setUser_name(rs.getString("user_name")); g.setAge(rs.getInt("age")); g.setSex(rs.getInt("sex")); g.setBirthday(rs.getDate("birthday")); g.setEmail(rs.getString("email")); g.setMobile(rs.getString("mobile")); g.setCreate_user(rs.getString("create_user")); g.setCreate_date(rs.getDate("create_date")); g.setUpdate_user(rs.getString("update_user")); g.setUpdate_date(rs.getDate("update_date")); g.setIdel(rs.getInt("isdel")); gs.add(g); } } catch (SQLException e) { e.printStackTrace(); } return gs; } public Goddess get(Integer id){ Goddess g = null; try { Connection conn = DBTest.getConn(); String sql = ""+ " select * from goddess" + " where id = ?;"; PreparedStatement ptmt = conn.prepareStatement(sql); ptmt.setInt(1,id); ResultSet rs = ptmt.executeQuery(); while (rs.next()){ g = new Goddess(); g.setId(rs.getInt("id")); g.setAge(rs.getInt("age")); g.setSex(rs.getInt("sex")); g.setBirthday(rs.getDate("birthday")); g.setEmail(rs.getString("email")); g.setMobile(rs.getString("mobile")); g.setCreate_user(rs.getString("create_user")); g.setCreate_date(rs.getDate("create_date")); g.setUpdate_user(rs.getString("update_user")); g.setUpdate_date(rs.getDate("update_date")); g.setIdel(rs.getInt("isdel")); } } catch (SQLException e) { e.printStackTrace(); } return g; } } <file_sep>package Leetcode; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; /** * Created by Yiy on 2016/8/18. */ public class CombinationSum2 { /** * created by qy * 参考CombinationSum, 利用深度优先进行递归,直至找到所有符合条件的list,将list存入list<list>内饰判断是否list已经存在 * 但又较大重复,故浪费一定的时间 * 如果按照第二中方法进行修改,则将重复消除,时间变快 */ public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); List<List<Integer>> result = new ArrayList<>(); addElement(candidates,result,new ArrayList<Integer>(),target,0); return result; } public void addElement(int[] candidates, List<List<Integer>> result, List<Integer> list, int target,int start){ if (target > 0 ){ for (int i = start; i < candidates.length && target>=candidates[i]; i++){ if (i > start && candidates[i] == candidates[i-1]){ continue; } list.add(candidates[i]); addElement(candidates,result,list,target-candidates[i],i+1); list.remove(list.size() - 1); } } else if (target == 0){ // List<Integer> newList = new ArrayList<>(list); // if (!result.contains(newList)){ // result.add(newList); // } result.add(new ArrayList<Integer>(list)); } } // 78.84%,5ms public List<List<Integer>> combinationSum22(int[] candidates, int target) { List<List<Integer>> ans = new ArrayList<>(); List<Integer> comb = new ArrayList<>(); Arrays.sort(candidates); // need sort to make this work. combination(candidates, target, 0, comb, ans); return ans; } private void combination(int[] candi, int target, int start, List<Integer> comb, List<List<Integer>> ans) { for (int i = start; i < candi.length; i++) { if (i > start && candi[i] == candi[i - 1]) //remove duplicates. continue; if (candi[i] == target) { //recursion exit. List<Integer> newComb = new ArrayList<>(comb); newComb.add(candi[i]); ans.add(newComb); } else if (candi[i] < target) { //continue to look for the rest. List<Integer> newComb = new ArrayList<>(comb); newComb.add(candi[i]); combination(candi, target - candi[i], i + 1, newComb, ans); } else break; //invalid path, return nothing. } } public static void main(String[] args) { int[] can = {10,1,2,7,6,1,5}; List<List<Integer>> result = new CombinationSum2().combinationSum2(can,8); Iterator it = result.iterator(); while (it.hasNext()){ Iterator it1 = ((List<Integer>)it.next()).iterator(); while (it1.hasNext()){ System.out.print(it1.next() + ","); } System.out.println(); } } }
e2d84d0d704f381582f5479b7632e9e27161dce0
[ "Java" ]
10
Java
QxYy/java
81864d30db2627e95d8f588b5403d39744295ac4
1f7c271a2eb3163b0863082f2ecc20393bcf0970
refs/heads/master
<file_sep>################################################################################ # Utils functions for the package # ################################################################################ #' Convert \code{funData} objects into right format for this package #' #' @param data An object of the class \code{funData::funData} #' @param norm Boolean, if TRUE, the sampling are normalized on \eqn{[0, 1]} #' #' @return A list, where each element represents a curve. Each curve is defined #' as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points #' } #' @export funData2list <- function(data, norm = TRUE){ t <- funData::argvals(data)[[1]] x <- funData::X(data) data_list <- list() for(i in 1:funData::nObs(data)){ if(norm) t <- (t - min(t)) / (max(t) - min(t)) data_list[[i]] <- list(t = t, x = x[i,]) } data_list } #' Convert comprehensive lists into \code{funData::funData} objects. #' #' We assume that we \strong{know} that the curves are on the same interval. #' #' @importFrom magrittr %>% #' #' @param data_list A list, where each element represents a curve. Each curve is #' defined as list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points #' } #' #' @return An object of the class \code{funData::funData} #' @export list2funData <- function(data_list){ argvals <- data_list[[1]]$t obs <- data_list %>% purrr::map_dfc("x") %>% as.matrix() %>% t() funData::funData(argvals = argvals, X = obs) } #' Convert \code{irregFunData} objects into right format for this package #' #' @param data An object of the class \code{funData::irregFunData} #' @param norm Boolean, if TRUE, the sampling are normalized on \eqn{[0, 1]} #' #' @return A list, where each element represents a curve. Each curve is defined #' as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points #' } #' @export irregFunData2list <- function(data, norm = TRUE){ t <- data@argvals x <- data@X data_list <- list() if(norm) { data_list <- purrr::map2(t, x, ~ list(t = (.x - min(.x)) / (max(.x) - min(.x)), x = .y)) } else { data_list <- purrr::map2(t, x, ~ list(t = .x, x = .y)) } data_list } #' Convert comprehensive lists into \code{funData::irregFunData} objects. #' #' @importFrom magrittr %>% #' #' @param data_list A list, where each element represents a curve. Each curve is #' defined as list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points #' } #' #' @return An object of the class \code{funData::irregFunData} #' @export list2irregFunData <- function(data_list){ argvalsList <- data_list %>% purrr::map("t") obsList <- data_list %>% purrr::map("x") funData::irregFunData(argvals = argvalsList, X = obsList) } #' Convert \code{multiFunData} objects into right format for this package #' #' @param data An object of the class \code{funData::multiFunData} #' @param norm Boolean, if TRUE, the sampling are normalized on \eqn{[0, 1]} #' #' @return A list, where each element represents a curve. Each curve is defined #' as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points #' } #' @export multiFunData2list <- function(data, norm = TRUE){ data_list <- list() cpt <- 1 for(fun_data in data){ if(inherits(fun_data, 'funData')) { data_list[[cpt]] <- funData2list(fun_data, norm) } else if(inherits(fun_data, 'irregFunData')) { data_list[[cpt]] <- irregFunData2list(fun_data, norm) } else if(inherits(fun_data, 'multiFunData')){ data_list[[cpt]] <- multiFunData2list(fun_data, norm) } else{ stop('Something went wrong with one of the functional data object!') } cpt <- cpt + 1 } data_list } #' Check the input data and return a list in the right list format #' #' @param data An object from the package \code{funData} #' #' @return A list, where each element represents a curve. Each curve is defined #' as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points #' } #' @export checkData <- function(data){ if (inherits(data, 'funData')){ data_ <- funData2list(data) } else if (inherits(data, 'irregFunData')) { data_ <- irregFunData2list(data) } else { stop('Wrong data type!') } data_ }<file_sep>################################################################################ # Functions for bandwith parameter estimation using regularity # ################################################################################ #' Perform an estimation of the bandwith #' #' This function performs an estimation of the bandwidth for a univariate kernel #' regression estimator defined over continuous data using the method of #' \cite{add ref}. An estimation of \eqn{H_0}, \eqn{L_0} and \eqn{\sigma} have #' to be provided to estimate the bandwidth. #' #' @importFrom magrittr %>% #' #' @family estimate bandwidth #' #' @param data A list, where each element represents a curve. Each curve have to #' be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param H0 Numeric, an estimation of \eqn{H_0}. #' @param L0 Numeric, an estimation of \eqn{L_0}. #' @param sigma Numeric, an estimation of \eqn{\sigma}. #' @param K Character string, the kernel used for the estimation: #' \itemize{ #' \item epanechnikov (default) #' \item beta #' \item uniform #' } #' #' @return Numeric, an estimation of the bandwidth. estimate_b <- function(data, H0 = 0.5, L0 = 1, sigma = 0, K = "epanechnikov") { if(!inherits(data, 'list')){ data <- checkData(data) } # Set kernel constants if (K == "epanechnikov") { K_norm2 <- 0.6 K_phi <- 3 / ((H0 + 1) * (H0 + 3)) } else if (K == "beta") { K_norm2_f <- function(x, alpha = 1, beta = 1) { x**(2 * (alpha - 1)) * (1 - x)**(2 * (beta - 1)) / beta(alpha, beta)**2 } phi <- function(x, H0, alpha = 1, beta = 1) { abs(x**(alpha - 1) * (1 - x)**(beta - 1)) * x**H0 / abs(beta(alpha, beta)) } K_norm2 <- stats::integrate(K_norm2_f, lower = 0, upper = 1)$value K_phi <- stats::integrate(phi, lower = 0, upper = 1, H0 = H0)$value } else { K_norm2 <- 1 K_phi <- 1 / (H0 + 1) } # Estimate mu M_n <- data %>% purrr::map_int(~ length(.x$t)) # Estimate b nume <- sigma**2 * K_norm2 * factorial(floor(H0)) deno <- H0 * L0 * K_phi frac <- nume / deno (frac / M_n)**(1 / (2 * H0 + 1)) } #' Perform an estimation of the bandwidth given a list of \eqn{H_0} and \eqn{L_0} #' #' This function performs an estimation of the bandwidth for a univariate kernel #' regression estimator defined over continuous data using the method of #' \cite{add ref}. An estimation of \eqn{H_0}, \eqn{L_0} and \eqn{\sigma} have #' to be provided to estimate the bandwidth. #' #' @importFrom magrittr %>% #' #' @family estimate bandwidth #' #' @param data A list, where each element represents a curve. Each curve have to #' be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param H0_list A vector of numerics, estimations of \eqn{H_0}. #' @param L0_list A vector of numerics, estimations of \eqn{L_0}. #' @param sigma Numeric, an estimation of \eqn{\sigma}. #' @param K Character string, the kernel used for the estimation: #' \itemize{ #' \item epanechnikov (default) #' \item beta #' \item uniform #' } #' #' @return A vector of numerices, estimations of the bandwidth. #' @export #' @examples #' df <- denoisr::generate_fractional_brownian(N = 1000, M = 300, #' H = 0.5, sigma = 0.05) #' b <- estimate_b_list(df, H0_list = 0.5, L0_list = 1, sigma = 0.05) #' #' df_piece <- generate_piecewise_fractional_brownian(N = 1000, M = 300, #' H = c(0.2, 0.5, 0.8), #' sigma = 0.05) #' b <- estimate_b_list(df_piece, #' H0_list = c(0.2, 0.5, 0.8), #' L0_list = c(1, 1, 1), #' sigma = 0.1, #' K = 'epanechnikov') estimate_b_list <- function(data, H0_list, L0_list, sigma = 0, K = "epanechnikov") { if(!inherits(data, 'list')){ data <- checkData(data) } if (length(H0_list) != length(L0_list)) { stop("H0_list and L0_list must have the same length.") } H0_list %>% purrr::map2_dfc(L0_list, ~ estimate_b(data, H0 = .x, L0 = .y, sigma = sigma, K = K )) } #' Perform an estimation of the bandwidth #' #' This function performs an estimation of the bandwidth to be used in the Nadaraya-Watson #' estimator. The bandwidth is estimated using the method from \cite{add ref}. #' #' @importFrom magrittr %>% #' #' @param data A list, where each element represents a curve. Each curve have to #' be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param t0_list A vector of numerics, the sampling points at which we estimate #' \eqn{H0}. We will consider the \eqn{8k0 - 7} nearest points of \eqn{t_0} for #' the estimation of \eqn{H_0} when \eqn{\sigma} is unknown. #' @param k0_list A vector of numerics, the number of neighbors of \eqn{t_0} to #' consider. Should be set as \deqn{k0 = (M / log(M) + 7) / 8}. We can set a #' different \eqn{k_0}, but in order to use the same for each \eqn{t_0}, just #' put a unique numeric. #' @param K Character string, the kernel used for the estimation: #' \itemize{ #' \item epanechnikov (default) #' \item uniform #' \item beta #' } #' #' @return A list, with elements: #' \itemize{ #' \item \strong{sigma} An estimation of the standard deviation of the noise #' \item \strong{H0} An estimation of \eqn{H_0} #' \item \strong{L0} An estimation of \eqn{L_0} #' \item \strong{b} An estimation of the bandwidth #' } #' @export #' @examples #' df <- denoisr::generate_fractional_brownian(N = 1000, M = 300, #' H = 0.5, sigma = 0.05) #' b <- estimate_bandwidth(df) #' #' df_piece <- generate_piecewise_fractional_brownian(N = 1000, M = 300, #' H = c(0.2, 0.5, 0.8), #' sigma = 0.05) #' b <- estimate_bandwidth(df_piece, t0_list = c(0.15, 0.5, 0.85), k0_list = 6) estimate_bandwidth <- function(data, t0_list = 0.5, k0_list = 2, K = "epanechnikov") { if(!inherits(data, 'list')){ data <- checkData(data) } # Estimation of the noise sigma_estim <- estimate_sigma(data) # Estimation of H0 H0_estim <- estimate_H0_list(data, t0_list = t0_list, k0_list = k0_list, sigma = NULL) # Estimation of L0 L0_estim <- estimate_L0_list(data, t0_list = t0_list, H0_list = H0_estim, k0 = k0_list[1], sigma = NULL, density = FALSE ) # Estimation of the bandwidth b_estim <- estimate_b_list(data, H0_list = H0_estim, L0_list = L0_estim, sigma = sigma_estim, K = K) list( "sigma" = sigma_estim, "H0" = H0_estim, "L0" = L0_estim, "b" = b_estim ) } #' Perform an estimation of the bandwidth using least-squares cross validation #' #' The function performs an estimation of the bandwidth for a univariate kernel #' regression estimator defined over continuous data using least-square cross #' validation for each curve and return the average bandwidth among them. #' #' @importFrom magrittr %>% #' @importFrom foreach foreach #' @importFrom foreach %dopar% #' #' @family estimate bandwidth #' @seealso \code{\link[np]{npregbw}} #' #' @param data A list, where each element represents a curve. Each curve have to #' be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' #' @return Numeric, an estimation of the bandwidth. #' @export #' @examples #' df <- denoisr::generate_fractional_brownian(N = 5, M = 300, #' H = 0.5, sigma = 0.05) #' b <- estimate_b_cv(df) estimate_b_cv <- function(data) { if(!inherits(data, 'list')){ data <- checkData(data) } # Create clusters for parallel computation cl <- parallel::detectCores() %>% -1 %>% parallel::makeCluster() doParallel::registerDoParallel(cl) j <- 1:length(data) bw_list <- foreach(j = iterators::iter(j)) %dopar% { sqrt(5) * np::npregbw(x ~ t, data = data[[j]], bwmethod = "cv.ls", # Least Square Cross Validation ckertype = "epanechnikov", # Kernel used regtype = "lc" # Local Constant Regression )$bw } parallel::stopCluster(cl) bw_list } <file_sep>################################################################################ # Generate fractional Brownian motion # ################################################################################ #' Generate fractional Brownian motion with a random noise #' #' This function generates a realization of a fractional Brownian motion with #' random noise. The increments of a fractional Brownian motion are not #' independent. A fractional Brownian motion is characterized by a parameter #' \eqn{H}, named Hurst coefficient. We define it on \eqn{[0, 1]}. #' #' @importFrom stats rnorm #' @importFrom stats rpois #' #' @param M An integer, expected number of points in the trajectory. #' The number of points follows a Poisson distribution with mean \eqn{M}. #' @param H Numeric, Hurst coefficient. \eqn{0 < H < 1} #' @param sigma A vector of numerics, standard deviation of the noise to add to #' the fractional Brownian motion. #' @param pdf Function, probability density function for the sampling points. #' @param L Numeric, multiplicative constant. #' #' @return A tibble containing the following elements: #' \itemize{ #' \item \strong{...1} The sampling points #' \item \strong{...2} The true trajectory #' \item \strong{...3} The trajectory contaminated by noise with standard #' deviation \eqn{\sigma} #' } fractional_brownian_trajectory <- function(M, H, sigma, pdf = NULL, L = 1) { M_n <- rpois(1, M) if (!inherits(pdf, "function")) { t <- seq(0, 1, length.out = M_n + 1) } else { t <- pdf(M_n + 1) t <- t[order(t)] } x <- L * as.vector(somebm::fbm(hurst = H, n = M_n)) # Start to fill the data simu <- matrix(rep(0, (M_n + 1) * (length(sigma) + 2)), nrow = M_n + 1) simu[, 1] <- t simu[, 2] <- x e <- rnorm(M_n + 1, mean = 0, sd = 1) # Add columns with homoscedastic noise. j <- 3 for (i in sigma) { simu[, j] <- x + i * e j <- j + 1 } dplyr::as_tibble(simu, .name_repair = "unique") } #' Generate a list of fractional Brownian trajectory. #' #' This function generates a list of realizations of a fractional Brownian #' motion with random noise. The increments of a fractional Brownian motion #' are not independent. A fractional Brownian motion is characterized by a #' parameter \eqn{H}, named Hurst coefficient. We define it on \eqn{[0, 1]}. #' #' @param N An integer, number of curves to simulate. #' @param M An integer, expected number of points in the trajectory. #' The number of points follows a Poisson distribution with mean \eqn{M}. #' @param H Numeric, Hurst coefficient. \eqn{0 < H < 1} #' @param sigma A vector of numerics, standard deviation of the noise to add to #' the fractional Brownian motion. #' @param pdf Function, probability density function for the sampling points. #' @param L Numeric, multiplicative constant. #' #' @return A tibble containing the following elements: #' \itemize{ #' \item \strong{...1} The sampling points #' \item \strong{...2} The true trajectory #' \item \strong{...3} The trajectory contaminated by noise with standard #' deviation \eqn{\sigma} #' } #' #' @export #' #' @examples #' generate_fractional_brownian(100, 50, 0.7, 0.1) #' generate_fractional_brownian(100, 50, 0.5, 0.05, pdf = rnorm) generate_fractional_brownian <- function(N = 100, M = 10, H = 0.5, sigma = 0.05, pdf = NULL, L = 1){ simulation_ <- purrr::rerun(N, fractional_brownian_trajectory(M, H, sigma, pdf, L)) purrr::map(simulation_, ~ list(t = .x$...1, x = .x$...3, x_true = .x$...2)) } ################################################################################ # Generate piecewise fractional Brownian motion # ################################################################################ #' Generate piecewise fractional Brownian motion with a random noise #' #' This function generates a realization of a piecewise fractional Brownian motion #' wih random noise. A piecewise fractional Brownian motion is defined by a non #' constant Hurst parameter along the sampling points. We observe the process at #' regularly spaced time \eqn{t_i = \frac{i}{M_n}}, where \eqn{i = 0, \dots, M_n}. #' We define a segmentation \eqn{\tau = (\tau_k)_{k=0, \dots, K+1}}, with #' \eqn{0 = \tau_0 < \tau_1 < \dots < \tau_{K} < \tau_{K+1} = 1}. So, on the #' interval \eqn{[\tau_k, \tau_{k+1}]}, for \eqn{k = 0, \dots, K}, the process #' is a fractional Brownian motion with Hurst parameter \eqn{H_k}. #' #' @param M An integer, expected number of points in the trajectory. #' THe number of points follows a Poisson distribution with mean \eqn{M}. #' @param H A vector of numeric, Hurst coefficients. \eqn{0 < H_k < 1} #' @param sigma A vector of numerics, standard deviation of the noise to add to #' the piecewise fractional Brownian motion. Should have the length of H. It #' adds heteroscedastic noise to the data. #' @param pdf A function for the generation of the sampling points. #' #' @return A tibble containing the following elements: #' \itemize{ #' \item \strong{...1}: The sampling points #' \item \strong{...2} The true trajectory #' \item \strong{...3} The trajectory contaminated by noise with standard #' deviation \eqn{\sigma} #' } piecewise_fractional_brownian_trajectory <- function(M, H, sigma, pdf = NULL){ M_n <- rpois(1, M) M_nn <- vector(length = length(H)) for(i in 1:(length(H) - 1)){ M_nn[i] <- round(M_n / length(H)) } M_nn[length(H)] <- M_n - sum(M_nn) if (!inherits(pdf, "function")) { t <- c() for(i in 1:length(H)){ t <- c(t, seq((i - 1) / length(H), i / length(H), length.out = M_nn[i])) } } else { t <- pdf(M_n) t <- t[order(t)] } x <- list() for(i in seq_along(H)){ x[i] <- list(as.vector(somebm::fbm(hurst = H[i], n = M_nn[i] - 1))) } # Some continuity in the change point y <- c(x[[1]]) for(i in 2:length(x)){ y <- c(y, x[[i]] + y[length(y)]) } # Start to fill the data simu <- matrix(rep(0, length(y) * 3), nrow = length(y)) simu[, 1] <- t simu[, 2] <- y e <- rnorm(length(y), mean = 0, sd = 1) if (length(sigma) > 1){ sigma <- rep(sigma, M_nn) } # Add columns with homoscedastic noise. simu[, 3] <- y + sigma * e dplyr::as_tibble(simu, .name_repair = 'unique') } #' Generate a list of piecewise fractional Brownian trajectory. #' #' This function generates a list of realizations of a piecewise fractional Brownian #' motion with random noise. A piecewise fractional Brownian motion is defined by a #' non constant Hurst parameter along the sampling points. We observe the process at #' regularly spaced time \eqn{t_i = \frac{i}{M_n}}, where \eqn{i = 0, \dots, M_n}. #' We define a segmentation \eqn{\tau = (\tau_k)_{k=0, \dots, K+1}}, with #' \eqn{0 = \tau_0 < \tau_1 < \dots < \tau_{K} < \tau_{K+1} = 1}. So, on the #' interval \eqn{[\tau_k, \tau_{k+1}]}, for \eqn{k = 0, \dots, K}, the process #' is a fractional Brownian motion with Hurst parameter \eqn{H_k}. #' #' @param N An integer, number of curves to simulate. #' @param M An integer, expected number of points in the trajectory. #' THe number of points follows a Poisson distribution with mean \eqn{M}. #' @param H A vector of numeric, Hurst coefficients. \eqn{0 < H_k < 1} #' @param sigma A vector of numerics, standard deviation of the noise to add to #' the piecewise fractional Brownian motion. Should have the length of H. It #' adds heteroscedastic noise to the data. #' @param pdf A function for the generation of the sampling points. #' #' @return A tibble containing the following elements: #' \itemize{ #' \item \strong{...1}: The sampling points #' \item \strong{...2} The true trajectory #' \item \strong{...3} The trajectory contaminated by noise with standard #' deviation \eqn{\sigma} #' } #' #' @export #' @examples #' generate_piecewise_fractional_brownian(100, 50, c(0.2, 0.5, 0.8), 0.1) generate_piecewise_fractional_brownian <- function(N = 100, M = 100, H = c(0.2, 0.5, 0.8), sigma = 0.05, pdf = NULL){ simulation_ <- purrr::rerun(N, piecewise_fractional_brownian_trajectory(M, H, sigma, pdf)) purrr::map(simulation_, ~ list(t = .x$...1, x = .x$...3, x_true = .x$...2)) } ################################################################################ # Generate integrate fractional Brownian motion # ################################################################################ #' Generate integrate fractional Brownian motion with a random noise #' #' This function generates a realization of an integrate fractional Brownian #' motion with random noise. The increments of a integrate fractional Brownian #' motion are not independent. An integrate fractional Brownian motion is #' characterized by a parameter \eqn{H}, named Hurst coefficient. #' We define it on \eqn{[0, 1]}. #' #' @importFrom stats rnorm #' @importFrom stats rpois #' #' @param M An integer, expected number of points in the trajectory. #' The number of points follows a Poisson distribution with mean \eqn{M}. #' @param H Numeric, Hurst coefficient. \eqn{0 < H < 1}. As we return its #' integrated version, the true Hurst will be 1 + H. #' @param sigma A vector of numerics, standard deviation of the noise to add to #' the fractional Brownian motion. #' @param L Numeric, multiplicative constant. #' #' @return A tibble containing the following elements: #' \itemize{ #' \item \strong{...1} The sampling points #' \item \strong{...2} The true trajectory #' \item \strong{...3} The trajectory contaminated by noise with standard #' deviation \eqn{\sigma} #' } integrate_fractional_brownian_trajectory <- function(M, H, sigma, L = 1) { M_n <- rpois(1, M) t <- seq(0, 1, length.out = M_n + 1) x <- L * as.vector(somebm::fbm(hurst = H, n = M_n)) # Start to fill the data simu <- matrix(rep(0, (M_n + 1) * (length(sigma) + 2)), nrow = M_n + 1) simu[, 1] <- t simu[, 2] <- cumsum(x) / (M_n + 1) e <- rnorm(M_n + 1, mean = 0, sd = 1) # Add columns with homoscedastic noise. j <- 3 for (i in sigma) { simu[, j] <- cumsum(x) / (M_n + 1) + i * e j <- j + 1 } dplyr::as_tibble(simu, .name_repair = "unique") } #' Generate a list of integrate fractional Brownian trajectory. #' #' This function generates a list of realizations of a integrate fractional #' Brownian motion with random noise. The increments of a integrate fractional #' Brownian motion are not independent. An integrate fractional Brownian motion #' is characterized by a parameter \eqn{H}, named Hurst coefficient. #' We define it on \eqn{[0, 1]}. #' #' @param N An integer, number of curves to simulate. #' @param M An integer, expected number of points in the trajectory. #' The number of points follows a Poisson distribution with mean \eqn{M}. #' @param H Numeric, Hurst coefficient. \eqn{0 < H < 1}. As we return its #' integrated version, the true Hurst will be 1 + H. #' @param sigma A vector of numerics, standard deviation of the noise to add to #' the fractional Brownian motion. #' @param L Numeric, multiplicative constant. #' #' @return A tibble containing the following elements: #' \itemize{ #' \item \strong{...1} The sampling points #' \item \strong{...2} The true trajectory #' \item \strong{...3} The trajectory contaminated by noise with standard #' deviation \eqn{\sigma} #' } #' #' @export #' @examples #' generate_integrate_fractional_brownian(100, 50, 0.7, 0.1) #' generate_integrate_fractional_brownian(100, 50, 0.5, 0.05, 2) generate_integrate_fractional_brownian <- function(N = 100, M = 10, H = 0.5, sigma = 0.05, L = 1){ simulation_ <- purrr::rerun(N, integrate_fractional_brownian_trajectory(M, H, sigma, L)) purrr::map(simulation_, ~ list(t = .x$...1, x = .x$...3, x_true = .x$...2)) } <file_sep>################################################################################ # Functions that performs kernel smoothing over a set of curves # ################################################################################ #' Perform a non-parametric smoothing of a set of curves #' #' This function performs a non-parametric smoothing of a set of curves using the #' Nadaraya-Watson estimator. The bandwidth is estimated using the method from #' \cite{add ref}. #' #' @importFrom magrittr %>% #' #' @param data A list, where each element represents a curve. Each curve have to #' be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param U A vector of numerics, sampling points at which estimate the curves. #' If NULL, the sampling points for the estimation are the same than the #' observed ones. #' @param t0_list A vector of numerics, the sampling points at which we estimate #' \eqn{H0}. We will consider the \eqn{8k0 - 7} nearest points of \eqn{t_0} for #' the estimation of \eqn{H_0} when \eqn{\sigma} is unknown. #' @param k0_list A vector of numerics, the number of neighbors of \eqn{t_0} to #' consider. Should be set as \deqn{k0 = M* exp(-log(log(M))^2)}. We can set a #' different \eqn{k_0}, but in order to use the same for each \eqn{t_0}, just #' put a unique numeric. #' @param K Character string, the kernel used for the estimation: #' \itemize{ #' \item epanechnikov (default) #' \item uniform #' \item beta #' } #' #' @return A list, which contains two elements. The first one is a list which #' contains the estimated parameters: #' \itemize{ #' \item \strong{sigma} An estimation of the standard deviation of the noise #' \item \strong{H0} An estimation of \eqn{H_0} #' \item \strong{L0} An estimation of \eqn{L_0} #' \item \strong{b} An estimation of the bandwidth #' } #' The second one is another list which contains the estimation of the curves: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The estimated points. #' } #' @export #' @examples #' df <- generate_fractional_brownian(N = 1000, M = 300, H = 0.5, sigma = 0.05) #' df_smooth <- smooth_curves(df) #' #' df_piece <- generate_piecewise_fractional_brownian(N = 1000, M = 300, #' H = c(0.2, 0.5, 0.8), #' sigma = 0.05) #' df_piece_smooth <- smooth_curves(df_piece, t0_list = c(0.15, 0.5, 0.85), #' k0_list = 6) smooth_curves <- function(data, U = NULL, t0_list = 0.5, k0_list = 2, K = "epanechnikov") { if(!inherits(data, 'list')){ data <- checkData(data) } # Estimation of the noise sigma_estim <- estimate_sigma(data) # Estimation of H0 H0_estim <- estimate_H0_list(data, t0_list = t0_list, k0_list = k0_list, sigma = NULL) # Estimation of L0 L0_estim <- estimate_L0_list(data, t0_list = t0_list, H0_list = H0_estim, k0 = k0_list[1], sigma = NULL, density = FALSE ) # Estimation of the bandwidth b_estim <- estimate_b_list(data, H0_list = H0_estim, L0_list = L0_estim, sigma = sigma_estim, K = K ) %>% purrr::transpose() %>% purrr::map(~ unname(unlist(.x))) # Estimation of the curves if (is.null(U)) { curves <- data %>% purrr::map2(b_estim, ~ estimate_curve(.x, U = .x$t, b = .y, t0_list = t0_list, kernel = K )) } else { curves <- data %>% purrr::map2(b_estim, ~ estimate_curve(.x, U = U, b = .y, t0_list = t0_list, kernel = K )) } list( "parameter" = list( "sigma" = sigma_estim, "H0" = H0_estim, "L0" = L0_estim, "b" = b_estim ), "smooth" = curves ) } #' Perform a non-parametric smoothing of a set of curves when the regularity is #' larger than 1 #' #' This function performs a non-parametric smoothing of a set of curves using the #' Nadaraya-Watson estimator when the regularity of the underlying curves is #' larger than 1. The bandwidth is estimated using the method from #' \cite{add ref}. In the case of a regularly larger than 1, we currently #' assume that the regularly is the same all over the curve. #' #' @importFrom magrittr %>% #' #' @param data A list, where each element represents a curve. Each curve have to #' be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param U A vector of numerics, sampling points at which estimate the curves. #' If NULL, the sampling points for the estimation are the same than the #' observed ones. #' @param t0 Numeric, the sampling point at which we estimate \eqn{H0}. We will #' consider the \eqn{8k0 - 7} nearest points of \eqn{t_0} for the estimation of #' \eqn{H_0} when \eqn{\sigma} is unknown. #' @param k0 Numeric, the number of neighbors of \eqn{t_0} to consider. Should #' be set as \eqn{k0 = M * exp(-log(log(M))^2)}. #' @param K Character string, the kernel used for the estimation: #' \itemize{ #' \item epanechnikov (default) #' \item uniform #' \item beta #' } #' @param eps Numeric, precision parameter. It is used to control how much larger #' than 1, we have to be in order to consider to have a regularity larger than 1 #' (default to 0.1). #' #' @return A list, which contains two elements. The first one is a list which #' contains the estimated parameters: #' \itemize{ #' \item \strong{sigma} An estimation of the standard deviation of the noise #' \item \strong{H0} An estimation of \eqn{H_0} #' \item \strong{L0} An estimation of \eqn{L_0} #' \item \strong{b} An estimation of the bandwidth #' } #' The second one is another list which contains the estimation of the curves: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The estimated points. #' } #' @export #' @examples #' df <- generate_integrate_fractional_brownian(N = 1000, M = 300, #' H = 0.5, sigma = 0.01) #' df_smooth <- smooth_curves_regularity(df, U = seq(0, 1, length.out = 101), #' t0 = 0.5, k0 = 14) smooth_curves_regularity <- function(data, U = NULL, t0 = 0.5, k0 = 2, K = "epanechnikov", eps = 0.1) { if(!inherits(data, 'list')){ data <- checkData(data) } # Estimation of the noise sigma_estim <- estimate_sigma(data) # Estimation of H0 H0_estim <- estimate_H0(data, t0 = t0, k0 = k0, sigma = NULL) # H > 1 cpt <- 0 while (H0_estim > 1 + eps) { L0 <- estimate_L0(data, t0 = t0, H0 = cpt + H0_estim, k0 = k0) b <- estimate_b(data, sigma = sigma_estim, H0 = H0_estim + cpt, L0 = L0) smooth <- data %>% purrr::map2(b, ~ list( t = .x$t, x = KernSmooth::locpoly(.x$t, .x$x, drv = 1 + cpt, bandwidth = .y, gridsize = length(.x$t) )$y )) H0_estim <- estimate_H0(smooth, t0 = t0, k0 = k0, sigma = NULL) cpt <- cpt + 1 } # Estimation of L0 L0_estim <- estimate_L0(data, t0 = t0, H0 = cpt + H0_estim, k0 = k0) # Estimation of the bandwidth b_estim <- estimate_b(data, sigma = sigma_estim, H0 = H0_estim + cpt, L0 = L0_estim) # Estimation of the curves if (is.null(U)) { curves <- data %>% purrr::map2(b_estim, ~ estimate_curve(.x, U = .x$t, b = .y, t0_list = t0, kernel = K )) } else { curves <- data %>% purrr::map2(b_estim, ~ estimate_curve(.x, U = U, b = .y, t0_list = t0, kernel = K )) } list( "parameter" = list( "sigma" = sigma_estim, "H0" = H0_estim + cpt, "L0" = L0_estim, "b" = b_estim ), "smooth" = curves ) } <file_sep>################################################################################ # Document the data # ################################################################################ #' Canadian average annual temperature #' #' Daily temperature at 35 different locations in Canada averaged over 1960 to #' 1994. #' #' @format A list with 35 elements. Each element corresponds to a particular #' Canadian station. Each station is a list with 2 elements which are: #' \itemize{ #' \item \strong{t} The day of the year the temperature is taken (normalized on \eqn{[0, 1]}) #' \item \strong{x} The average temperature for each day of the year #' } #' #' @references Ramsay, <NAME>., and Silverman, <NAME>. (2006), Functional Data Analysis, 2nd ed., Springer, New York. #' @references Ramsay, <NAME>., and Silverman, <NAME>. (2002), Applied Functional Data Analysis, Springer, New York #' #' @seealso \code{\link[fda]{CanadianWeather}} "canadian_temperature_daily"<file_sep>// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- // estimate_curve.cpp #include <RcppArmadillo.h> using namespace Rcpp; // [[Rcpp::export]] arma::vec epaKernelSmoothingCurve( const arma::vec & U, // Estimation points in U const arma::vec & T, // Sampling points const arma::vec & Y, // Curves points const arma::vec & b // Smoothing bandwiths ){ // Get parameters arma::uword M = T.n_elem; // Number of sampling points arma::uword L = U.n_elem; // Number of estimation points // Define output arma::vec Y_hat(L); Y_hat.fill(0); // Loop over the points to estimate for(arma::uword i=0; i<L; i++){ double cpt = 0; // Loop over the known points for (arma::uword k=0; k<M; k++){ if (std::abs(T(k) - U(i)) <= b(i)){ //if (std::abs(T(k) - U(i)) != 0){ Y_hat(i) += (Y(k) * (1 - std::pow((T(k) - U(i))/b(i), 2))); cpt += (1 - std::pow((T(k) - U(i))/b(i), 2)); //} } } if(cpt == 0){ Y_hat(i) = 0; } else{ Y_hat(i) /= cpt; } } return Y_hat; } // [[Rcpp::export]] arma::vec uniKernelSmoothingCurve( const arma::vec & U, // Estimation points in U const arma::vec & T, // Sampling points const arma::vec & Y, // Curves points const arma::vec & b // Smoothing bandwiths ){ // Get parameters arma::uword M = T.n_elem; // Number of sampling points arma::uword L = U.n_elem; // Number of estimation points // Define output arma::vec Y_hat(L); Y_hat.fill(0); // Loop over the points to estimate for(arma::uword i=0; i<L; i++){ double cpt = 0; // Loop over the known points for (arma::uword k=0; k<M; k++){ if (std::abs(T(k) - U(i)) <= b(i)){ Y_hat(i) += Y(k); cpt += 1; } } if(cpt == 0){ Y_hat(i) = 0; } else{ Y_hat(i) /= cpt; } } return Y_hat; } // [[Rcpp::export]] arma::vec betaKernelSmoothingCurve( const arma::vec & U, // Estimation points const arma::vec & T, // Sampling points const arma::vec & Y, // Curves points const arma::vec & b // Smoothing bandwiths ){ // Get parameters arma::uword M = T.n_elem; // Number of sampling points arma::uword L = U.n_elem; // Number of estimation points // Define output arma::vec Y_hat(L); Y_hat.fill(0); // Create the S vector arma::vec S(M); S.fill(0); S(M-1) = 1; for(arma::uword m=1; m<(M-1); m++){ S(m) = (T(m) + T(m+1)) / 2; } // Loop over the points to estimate for(arma::uword i=0; i<L; i++){ double B = R::beta(U(i)/b(i) + 1, (1 - U(i))/b(i) + 1); // Loop over the known points for(arma::uword k=1; k<M; k++){ arma::vec S_k = arma::linspace<arma::vec>(S(k-1), S(k), 100); arma::vec K = arma::pow(S_k, U(i)/b(i)) % arma::pow((1 - S_k), (1 - U(i))/b(i)); arma::mat intK = arma::trapz(S_k, K); Y_hat(i) += (Y(k) * intK(0, 0)) / B; } } return Y_hat; } // [[Rcpp::export]] arma::vec modifiedBetaKernelSmoothingCurve( const arma::vec & U, // Estimation points const arma::vec & T, // Sampling points const arma::vec & Y, // Curves points const arma::vec & b // Smoothing bandwiths ){ // Get parameters arma::uword M = T.n_elem; // Number of sampling points arma::uword L = U.n_elem; // Number of estimation points // Define output arma::vec Y_hat(L); Y_hat.fill(0); // Create the S vector arma::vec S(M); S.fill(0); S(M-1) = 1; for(arma::uword m=1; m<(M-1); m++){ S(m) = (T(m) + T(m+1)) / 2; } // Loop over the points to estimate for(arma::uword i=0; i<L; i++){ if(U(i) < 2*b(i)){ double rho = 2 * std::pow(b(i), 2) + 2.5 - std::pow(4 * std::pow(b(i), 4) + 6 * std::pow(b(i), 2) + 2.25 - std::pow(U(i), 2) - U(i) / b(i), 0.5); double B = R::beta(rho, (1 - U(i))/b(i)); // Loop over the known points for(arma::uword k=1; k<M; k++){ arma::vec S_k = arma::linspace<arma::vec>(S(k-1), S(k), 10); arma::vec K = arma::pow(S_k, rho - 1) % arma::pow((1 - S_k), (1 - U(i))/b(i) - 1); arma::mat intK = arma::trapz(S_k, K); Y_hat(i) += (Y(k) * intK(0, 0)) / B; } } else if(U(i) > 1 - 2*b(i)){ double rho = 2 * std::pow(b(i), 2) + 2.5 - std::pow(4 * std::pow(b(i), 4) + 6 * std::pow(b(i), 2) + 2.25 - std::pow((1 - U(i)), 2) - (1 - U(i)) / b(i), 0.5); double B = R::beta(U(i)/b(i), rho); // Loop over the known points for(arma::uword k=1; k<M; k++){ arma::vec S_k = arma::linspace<arma::vec>(S(k-1), S(k), 10); arma::vec K = arma::pow(S_k, U(i)/b(i) - 1) % arma::pow((1 - S_k), rho - 1); arma::mat intK = arma::trapz(S_k, K); Y_hat(i) += (Y(k) * intK(0, 0)) / B; } } else{ // 2*b < U(i) < 1 - 2*b double B = R::beta(U(i)/b(i), (1 - U(i))/b(i)); // Loop over the known points for(arma::uword k=1; k<M; k++){ arma::vec S_k = arma::linspace<arma::vec>(S(k-1), S(k), 10); arma::vec K = arma::pow(S_k, U(i)/b(i) - 1) % arma::pow((1 - S_k), (1 - U(i))/b(i) - 1); arma::mat intK = arma::trapz(S_k, K); Y_hat(i) += (Y(k) * intK(0, 0)) / B; } } } return Y_hat; } <file_sep>// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- // estimate_sigma.cpp // [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadillo.h> using namespace Rcpp; // [[Rcpp::export]] double estimateSigma( const List & curves // Curves list ($x and $t) ){ // Get the number of curves arma::uword N = curves.length(); List mycurve = curves[0]; double sigma = 0; for(arma::uword n=0; n<N; n++){ mycurve = curves[n]; arma::vec x = mycurve["x"]; arma::uword M_n = x.n_elem; double squared_diff = 0; for(arma::uword l=1; l<M_n; l++){ squared_diff += std::pow(x(l) - x(l-1), 2); } sigma += (squared_diff / (2 * (M_n - 1))); } return std::pow((sigma / N), 0.5); } // [[Rcpp::export]] double estimateSigmaMSE( const List & curves, // Curves list ($x and $t) const List & curves_estim // Estimated curve ($x and $t) ){ // Get the number of curves arma::uword N = curves.length(); List mycurve = curves[0]; List mycurve_estim = curves_estim[0]; double sigma = 0; for(arma::uword n=0; n<N; n++){ mycurve = curves[n]; mycurve_estim = curves_estim[n]; arma::vec x = mycurve["x"]; arma::vec x_estim = mycurve_estim["x"]; arma::uword M_n = x.n_elem; double squared_diff = 0; for(arma::uword l=0; l<M_n; l++){ squared_diff += std::pow(x(l) - x_estim(l), 2); } sigma += (squared_diff / M_n); } return std::pow((sigma / N), 0.5); } <file_sep> <!-- README.md is generated from README.Rmd/ Please edit that file --> # denoisr <!-- badges: start --> [![Build Status](https://travis-ci.org/StevenGolovkine/denoisr.svg?branch=master)](https://travis-ci.org/StevenGolovkine/denoisr) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/d5b2b6c6083c4d269ace4a8a1b8103b3)](https://www.codacy.com/manual/StevenGolovkine/denoisr?utm_source=github.com&utm_medium=referral&utm_content=StevenGolovkine/denoisr&utm_campaign=Badge_Grade) [![DOI](https://zenodo.org/badge/215247523.svg)](https://zenodo.org/badge/latestdoi/215247523) <!-- badges: end --> ## Overview `denoisr` is a non-parametric smoother for noisy curve data, providing different functions to estimate various parameters: - `estimate_H0_list()` and `estimate_H0_deriv_list()` estimate the smoothness of the curves. - `estimate_b_list()` and `estimate_bandwidth()` estimate the bandwidth used in the Nadaraya-Watson estimator. - `estimate_curve()` estimates one curve, given bandwidths. - `smooth_curves()` and `smooth_curves_regularity()` estimate the curves. - `estimate_mean()` and `estimate_covariance()` estimate the leave-one-out smoothing mean and covariance. You can learn more about thm in `vignette('denoisr')`. ## Installation The package is not yet on CRAN. But, you can install from source with ``` r devtools::install_url("https://github.com/StevenGolovkine/denoisr/raw/master/denoisr_1.0.2.tar.gz") ``` ## Development version You can install the last released version of `denoisr` from [Github](https://github.com/StevenGolovkine/denoisr) with: ``` r devtools::install_github("StevenGolovkine/denoisr") ``` ## Usage ``` r # Load packages library(denoisr) library(dplyr) library(funData) library(ggplot2) library(reshape2) ``` ``` r # Load data data("canadian_temperature_daily") ``` ``` r # Convert list to funData object data_fd <- list2funData(canadian_temperature_daily) ``` ``` r # Plot of the data autoplot(data_fd) + labs(title = 'Daily Temperature Data', x = 'Normalized Day of Year', y = 'Temperature in °C') + theme_minimal() ``` <img src="man/figures/README-plot_data-1.svg" width="100%" style="display: block; margin: auto;" /> ``` r # Smooth the data smooth_data <- smooth_curves(canadian_temperature_daily, t0_list = 0.5, k0_list = 5) ``` ``` r # Plot of the smoothed data smooth_data_fd <- list2funData(smooth_data$smooth) autoplot(smooth_data_fd) + labs(title = 'Smooth Daily Temperature Data', x = 'Normalized Day of Year', y = 'Temperature in °C') + theme_minimal() ``` <img src="man/figures/README-plot_data2-1.svg" width="100%" style="display: block; margin: auto;" /> ``` r # Plot one realisation of the smoothed data montreal <- tibble(t = canadian_temperature_daily$Montreal$t, Data = canadian_temperature_daily$Montreal$x, Smooth = smooth_data$smooth$Montreal$x) %>% reshape2::melt(id = 't') ggplot(montreal, aes(x = t, y = value, color = variable)) + geom_line() + labs(title = 'Example of Montreal', x = 'Normalized Day of Year', y = 'Temperature in °C', color = '') + theme_minimal() ``` <img src="man/figures/README-plot_data3-1.svg" width="100%" style="display: block; margin: auto;" /> ``` r # Compute the mean curve mean_curve <- estimate_mean(canadian_temperature_daily, U = seq(0, 1, length.out = 501), b = smooth_data$parameter$b) ``` ``` r mean_curve_plot <- tibble(t = seq(0, 1, length.out = 501), x = mean_curve) autoplot(data_fd) + geom_line(data = mean_curve_plot, mapping = aes(x = t, y = x, group = NULL), col = 'red', size = 2) + labs(title = 'Daily Temperature Data', x = 'Normalized Day of Year', y = 'Temperature in °C') + theme_minimal() ``` <img src="man/figures/README-plot_mean-1.svg" width="100%" style="display: block; margin: auto;" /> ``` r # Compute the covariance surface U <- seq(0, 1, length.out = 101) cov_surface <- estimate_covariance(canadian_temperature_daily, U = U, b = smooth_data$parameter$b, h = 0.05) ``` ``` r cov_surface_plot <- tibble(expand.grid(U, U), C = as.vector(cov_surface)) ggplot(cov_surface_plot) + geom_contour_filled(aes(x = Var1, y = Var2, z = C)) + labs(title = 'Covariance surface of daily temperature data', x = '', y = '', fill = 'Level') + theme_minimal() ``` <img src="man/figures/README-plot_covariance-1.svg" width="100%" style="display: block; margin: auto;" /> <file_sep>################################################################################ # Functions for sigma parameter estimation using regularity # ################################################################################ #' Perform an estimation of the standard deviation of the noise #' #' This function performs an estimation of the standard deviation of the noise #' in the curves. Based on \cite{add ref}, the following formula is used: #' \deqn{\hat{\sigma^2} = \frac{1}{N}\sum_{n = 1}^{N} #' \frac{1}{2(M_n - 1)}\sum_{l = 2}^{M_n}(Y_{n, (l)} - Y_{n, (l-1)})^2} #' #' @param data A list, where each element represents a curve. Each curve have to #' be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' #' @return Numeric, an estimation of the standard deviation of the noise. #' @export #' @examples #' df <- generate_fractional_brownian(N = 1000, M = 300, H = 0.5, sigma = 0.05) #' estimate_sigma(df) estimate_sigma <- function(data) { if(!inherits(data, 'list')){ data <- checkData(data) } estimateSigma(data) } <file_sep>library(testthat) library(denoisr) test_check("denoisr") <file_sep>.onUnload <- function(libpath){ library.dynam.unload("denoisr", libpath) }<file_sep>################################################################################ # Functions for k0 parameter estimation using regularity # ################################################################################ #' Perform the estimation of the recommanded \eqn{k_0} #' #' This function performs the estimation of the recommanded \eqn{k_0} as used in #' \cite{add ref}. #' #' @family estimate \eqn{k_0} #' #' @param M Numeric, mean number of sampling points per curve #' #' @return Numeric, the recommanded \eqn{k_0} #' @export #' @examples #' estimate_k0(200) estimate_k0 <- function(M) { trunc(M * exp(-log(log(M))**2)) } #' Perform the estimation of the pilot \eqn{k_0} #' #' This function performs the estimation of the pilot \eqn{k_0} as used in #' \cite{add ref}. #' #' @family estimate \eqn{k_0} #' #' @param M Numeric, mean number of sampling points per curve #' #' @return Numeric, the pilot \eqn{k_0} #' @export #' @examples #' estimate_k0_pilot(200) estimate_k0_pilot <- function(M) { trunc((M + 1) * exp(-sqrt(log(M + 1)))) + 1 } #' Perform the estimation of the oracle \eqn{k_0} #' #' This function performs the estimation of the oracle \eqn{k_0} as used in #' \cite{add ref}. #' #' @family estimate \eqn{k_0} #' #' @param M Numeric, mean number of sampling points per curve #' @param H Numeric, estimation of \eqn{H_0} #' #' @return Numeric, the oracle \eqn{k_0} #' @export #' @examples #' estimate_k0_oracle(200, 0.5) estimate_k0_oracle <- function(M, H) { trunc((M + 1)**(H / (2 + H))) + 1 } <file_sep>// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- // estimate_mean.cpp // [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadillo.h> #include "estimate_curve.h" using namespace Rcpp; // [[Rcpp::export]] arma::vec LOOmean( const List & curves, // Curves list ($x and $t) const arma::vec & U, // Estimation points const List & b, // Smoothing bandwidths const arma::uword & n // Curve to remove from the estimation ){ // Get parameters arma::uword N = curves.length(); // Number of curves arma::uword L = U.n_elem; // Number of sampling points List mycurve = curves[0]; // Define output arma::mat res(L, N - 1); res.fill(0); arma::uword cpt = 0; for(arma::uword m=0; m<N; m++){ if(m != n){ mycurve = curves[m]; arma::vec X = mycurve["x"]; arma::vec T = mycurve["t"]; arma::vec bandwidth = b[m]; res.col(cpt) = epaKernelSmoothingCurve(U, T, X, bandwidth); cpt++; } } return mean(res, 1); } // [[Rcpp::export]] arma::vec mean_cpp( const List & curves, // Curves list ($x and $t) const arma::vec & U, //Estimation points const List & b // Smoothing badnwidths ){ // Get parameters arma::uword N = curves.length(); // Number of curves arma::uword L = U.n_elem; // Number of sampling points List mycurve = curves[0]; arma::mat res(L, N); for(arma::uword n=0; n<N; n++){ mycurve = curves[n]; arma::vec T = mycurve["t"]; arma::vec X = mycurve["x"]; res.col(n) = LOOmean(curves, U, b, n); } return mean(res, 1); } // [[Rcpp::export]] arma::mat covariance_cpp( const List & curves, // Curves list ($x and $t) const List & meanLOO_curves, // Mean LOO curves list const arma::vec & sampling_points, // Estimation points const List & b, // Smoothing bandwidth const List & h // Smoothing bandwidth ){ // Get parameters arma::uword N = curves.length(); // Number of curves arma::vec U = sampling_points; List mycurve = curves[0]; // Define output arma::mat res(U.n_elem, U.n_elem); arma::mat smooths_U(U.n_elem, N); arma::mat smooths_V(U.n_elem, N); for(arma::uword n=0; n<N; n++){ mycurve = curves[n]; arma::vec T = mycurve["t"]; arma::vec X = mycurve["x"]; arma::vec mean_curve = meanLOO_curves[n]; arma::vec smooth_curve = epaKernelSmoothingCurve(T, T, X, b[n]); arma::vec smooth_curve_unmean = smooth_curve - mean_curve; smooths_U.col(n) = epaKernelSmoothingCurve(U, T, smooth_curve_unmean, h[n]); smooths_V.col(n) = epaKernelSmoothingCurve(U, T, smooth_curve_unmean, h[n]); } res = cov(smooths_U.t(), smooths_V.t(), 1); // Normalisation using N return res; } <file_sep>// estimtate_risk.h #ifndef ESTIMATE_RISK_H #define ESTIMATE_RISK_H #include <RcppArmadillo.h> List estimateRisk( const List & curves, // Curves list ($x and $t) const List & curves_estim, // Estimated curves list ($x and $t) const double & t0 // In which point estimate the risk. ); double estimateRiskCurve( const List & curve, // Curve ($x and $t) const List & curve_estim // Estimated curve ($x and $t) ); List estimateRiskCurves( const List & curves, // Curves list ($x and $t) const List & curves_estim // Estimated curves list ($x and $t) ); #endif<file_sep>#' denoisr: A package for the smoothing of a set of curves. #' #' The package provides functions in order to smooth a set of curves. The idea is #' to perform non-parametric kernel regression of each of curves using the #' Nadaraya-Watson estimator. In order to use this estimator, we need to select #' a bandwidth. A common way to select this bandwidth is to used cross-validation. #' However, we are going to use the large number of curves to estimate it more #' efficiently. The idea is to estimate the underlying regularity of the curves #' (assuming they have the same). Then, the estimation of the bandwidth follows. #' #' @docType package #' @name denoisr NULL<file_sep># Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: <PASSWORD> epaKernelSmoothingCurve <- function(U, T, Y, b) { .Call('_denoisr_epaKernelSmoothingCurve', PACKAGE = 'denoisr', U, T, Y, b) } uniKernelSmoothingCurve <- function(U, T, Y, b) { .Call('_denoisr_uniKernelSmoothingCurve', PACKAGE = 'denoisr', U, T, Y, b) } betaKernelSmoothingCurve <- function(U, T, Y, b) { .Call('_denoisr_betaKernelSmoothingCurve', PACKAGE = 'denoisr', U, T, Y, b) } modifiedBetaKernelSmoothingCurve <- function(U, T, Y, b) { .Call('_denoisr_modifiedBetaKernelSmoothingCurve', PACKAGE = 'denoisr', U, T, Y, b) } LOOmean <- function(curves, U, b, n) { .Call('_denoisr_LOOmean', PACKAGE = 'denoisr', curves, U, b, n) } mean_cpp <- function(curves, U, b) { .Call('_denoisr_mean_cpp', PACKAGE = 'denoisr', curves, U, b) } covariance_cpp <- function(curves, meanLOO_curves, sampling_points, b, h) { .Call('_denoisr_covariance_cpp', PACKAGE = 'denoisr', curves, meanLOO_curves, sampling_points, b, h) } estimateRisk <- function(curves, curves_estim, t0) { .Call('_denoisr_estimateRisk', PACKAGE = 'denoisr', curves, curves_estim, t0) } estimateRiskCurve <- function(curve, curve_estim) { .Call('_denoisr_estimateRiskCurve', PACKAGE = 'denoisr', curve, curve_estim) } estimateRiskCurves <- function(curves, curves_estim) { .Call('_denoisr_estimateRiskCurves', PACKAGE = 'denoisr', curves, curves_estim) } estimateSigma <- function(curves) { .Call('_denoisr_estimateSigma', PACKAGE = 'denoisr', curves) } estimateSigmaMSE <- function(curves, curves_estim) { .Call('_denoisr_estimateSigmaMSE', PACKAGE = 'denoisr', curves, curves_estim) } <file_sep>################################################################################ # Functions that performs kernel smoothing # ################################################################################ #' Perform the smoothing of individual curve. #' #' This function performs the smoothing of a curve using the Nadaraya-Watson #' estimator given a particular kernel. #' #' @importFrom magrittr %>% #' @importFrom Rcpp evalCpp #' #' @param curve A list, with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param U A vector of numerics, sampling points at which estimate the curve. #' @param b Numeric or vector of numerics, estimation of the bandwidth. If one #' is provided, we use a unique bandwidth for the curve. However, if a vector #' is given, the bandwidth changes depending on the sampling points. #' @param t0_list A vector of numerics, times at which the bandwidths have been #' estimated. Only used if the parameter \code{b} is a vector. #' @param kernel Character string, the kernel used for the estimation: #' \itemize{ #' \item epanechnikov (default) #' \item uniform #' \item beta #' \item mBeta #' } #' @useDynLib denoisr #' #' @return A list, with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The estimated points. #' } #' @export #' @examples #' df_piece <- generate_piecewise_fractional_brownian(N = 1, M = 300, #' H = c(0.2, 0.5, 0.8), #' sigma = 0.05) #' estimate_curve(df_piece[[1]], #' U = seq(0, 1, length.out = 200), #' b = c(0.2, 0.5, 0.8), #' t0_list = c(0.16, 0.5, 0.83)) estimate_curve <- function(curve, U, b, t0_list = NULL, kernel = "epanechnikov") { if (length(b) == 1) { bandwidth <- rep(b, length(U)) } else if ((length(b) != length(U)) & !is.null(t0_list)) { idx <- U %>% purrr::map_dbl(~ order(abs(.x - t0_list))[1]) bandwidth <- b[idx] } else if (length(b) == length(U)) { bandwidth <- b } else { stop("Issues with the bandwidth parameter.") } if (kernel == "epanechnikov") { x_hat <- epaKernelSmoothingCurve(U, curve$t, curve$x, bandwidth) } else if (kernel == "uniform") { x_hat <- uniKernelSmoothingCurve(U, curve$t, curve$x, bandwidth) } else if (kernel == "beta") { x_hat <- betaKernelSmoothingCurve(U, curve$t, curve$x, bandwidth) } else if (kernel == "mBeta") { x_hat <- modifiedBetaKernelSmoothingCurve(U, curve$t, curve$x, bandwidth) } else { print("Wrong kernel name") x_hat <- rep(0, length(U)) } list(t = U, x = as.vector(x_hat)) } <file_sep>############################################################################### # Functions for L0 parameter estimation using regularity # ############################################################################### #' Perform an estimation of \eqn{L_0} #' #' This function performs an estimation of \eqn{H_0} used for the estimation of #' the bandwidth for a univariate kernel regression estimator defined over #' continuous domains data using the method of \cite{add ref}. #' #' @importFrom magrittr %>% #' #' @family estimate \eqn{L_0} #' #' @param data A list, where each element represents a curve. Each curve have to #' be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param t0 Numeric, the sampling point at which we estimate \eqn{H0}. We will #' consider the \eqn{8k0 - 7} nearest points of \eqn{t_0} for the estimation of #' \eqn{H_0} when \eqn{\sigma} is unknown. #' @param H0 Numeric, an estimation of \eqn{H_0} #' @param k0 Numeric, the number of neighbors of \eqn{t_0} to consider. Should #' be set as \eqn{k0 = M * exp(-log(log(M))^2)}. #' @param sigma Numeric, true value of sigma. Can be NULL. #' @param density Logical, do the sampling points have a uniform distribution? #' (default is FALSE) #' #' @return Numeric, an estimation of L0. estimate_L0 <- function(data, t0 = 0, H0 = 0, k0 = 2, sigma = NULL, density = FALSE) { # Estimate mu mu_hat <- data %>% purrr::map_int(~ length(.x$t)) %>% mean() # Estimate L0 theta <- function(v, k, idx) (v[idx + 2 * k - 1] - v[idx + k])**2 eta <- function(v, k, idx, H) (v[idx + 2 * k - 1] - v[idx + k])**(2 * H) nume <- 1 deno <- 1 if (!density) { # Case where the density is not known if (is.null(sigma)) { # Subcase where sigma is not known idxs <- data %>% purrr::map_dbl(~ min(order(abs(.x$t - t0))[seq_len(4 * k0 - 2)])) a <- data %>% purrr::map2_dbl(idxs, ~ theta(.x$x, k = 2 * k0 - 1, idx = .y)) %>% mean() b <- data %>% purrr::map2_dbl(idxs, ~ theta(.x$x, k = k0, idx = .y)) %>% mean() c <- data %>% purrr::map2_dbl(idxs, ~ eta(.x$t, k = 2 * k0 - 1, idx = .y, H = H0)) %>% mean() d <- data %>% purrr::map2_dbl(idxs, ~ eta(.x$t, k = k0, idx = .y, H = H0)) %>% mean() if ((a - b > 0) & (c - d > 0)) { nume <- a - b deno <- c - d } } else { # Subcase where sigma is known idxs <- data %>% purrr::map_dbl(~ min(order(abs(.x$t - t0))[seq_len(2 * k0)])) a <- data %>% purrr::map2_dbl(idxs, ~ theta(.x$x, k = k0, idx = .y)) %>% mean() b <- data %>% purrr::map2_dbl(idxs, ~ eta(.x$t, k = k0, idx = .y, H = H0)) %>% mean() if ((a - 2 * sigma**2 > 0) & b > 0) { nume <- a - 2 * sigma**2 deno <- b } } } else { # Case where the density is known (only the uniform case) if (is.null(sigma)) { # Subcase where sigma is not known idxs <- data %>% purrr::map_dbl(~ min(order(abs(.x$t - t0))[seq_len(4 * k0 - 2)])) a <- data %>% purrr::map2_dbl(idxs, ~ theta(.x$x, k = 2 * k0 - 1, idx = .y)) %>% mean() b <- data %>% purrr::map2_dbl(idxs, ~ theta(.x$x, k = k0, idx = .y)) %>% mean() if (a - b > 0) nume <- a - b deno <- (2**(2 * H0) - 1) * ((k0 - 1) / (mu_hat + 1))**(2 * H0) } else { # Subcase where sigma is known idxs <- data %>% purrr::map_dbl(~ min(order(abs(.x$t - t0))[seq_len(2 * k0)])) a <- data %>% purrr::map2_dbl(idxs, ~ theta(.x$x, k = k0, idx = .y)) %>% mean() if (a - 2 * sigma**2 > 0) nume <- a - 2 * sigma**2 deno <- ((k0 - 1) / (mu_hat + 1))**(2 * H0) } } (nume / deno)**0.5 } #' Perform the estimation of \eqn{L_0} given a list of \eqn{t_0} #' #' This function performs an estimation of \eqn{H_0} used for the estimation of #' the bandwidth for a univariate kernel regression estimator defined over #' continuous domains data using the method of \cite{add ref}. #' #' @importFrom magrittr %>% #' #' @family estimate \eqn{L_0} #' #' @param data A list, where each element represents a curve. Each curve have to #' be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param t0_list A vetor of numerics, the sampling points at which we estimate #' \eqn{H0}. We will consider the \eqn{8k0 - 7} nearest points of \eqn{t_0} for #' the estimation of \eqn{H_0} when \eqn{\sigma} is unknown. #' @param H0_list A vector of numerics, an estimation of \eqn{H_0} at every #' \eqn{t_0} given in \code{t0_list}. #' @param k0 Numeric, the number of neighbors of \eqn{t_0} to consider. Should #' be set as \eqn{k0 = M * exp(-log(log(M))^2)}. #' @param sigma Numeric, true value of sigma. Can be NULL. #' @param density Logical, do the sampling points have a uniform distribution? #' (default is FALSE) #' #' @return A vector of numerics, an estimation of \eqn{L_0} at each \eqn{t_0}. #' @export #' @examples #' df <- generate_fractional_brownian(N = 1000, M = 300, H = 0.5, sigma = 0.05) #' L0 <- estimate_L0_list(df, t0_list = 0.5, H0_list = 0.5) #' #' df_piece <- generate_piecewise_fractional_brownian(N = 1000, M = 300, #' H = c(0.2, 0.5, 0.8), #' sigma = 0.05) #' L0 <- estimate_L0_list(df_piece, t0_list = c(0.15, 0.5, 0.85), #' H0_list = c(0.2, 0.5, 0.8), k0 = 6) estimate_L0_list <- function(data, t0_list, H0_list, k0 = 2, sigma = NULL, density = FALSE) { if(!inherits(data, 'list')){ data <- checkData(data) } if (length(t0_list) != length(H0_list)) { stop("t0_list and H0_list must have the same length") } t0_list %>% purrr::map2_dbl(H0_list, ~ estimate_L0(data, t0 = .x, H0 = .y, k0 = k0, sigma = sigma, density = density )) } <file_sep>################################################################################ # Functions for risk estimation using regularity # ################################################################################ #' Perform an estimation of the risk on a set of curves at a particular point. #' #' This function performs the estimation of the risk on a set of curves at a #' particular sampling points \eqn{t_0}. Both the real and estimated curves have #' to be sampled on the same grid. #' #' Actually, two risks are computed. They are defined as: #' \deqn{MeanRSE(t_0) = \frac{1}{N}\sum_{n = 1}^{N}(X_n(t_0) - \hat{X}_n(t_0))^2} #' and #' \deqn{MeanRSE(t_0) = \max_{1 \leq n \leq N} (X_n(t_0) - \hat{X}_n(t_0))^2} #' #' @importFrom magrittr %>% #' #' @param curves A list, where each element represents a real curve. Each curve #' have to be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param curves_estim A list, where each element represents an estimated curve. #' Each curve have to be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The estimated points. #' } #' @param t0_list A vector of numerics, sampling points where the risk will be #' computed. Can have a single value. #' #' @return A list, with the mean and max residual squared error in \eqn{t_0}. #' @export #' @examples #' df <- generate_fractional_brownian(N = 1000, M = 300, H = 0.5, sigma = 0.05) #' curves_smoothed <- smooth_curves(df)$smooth #' estimate_risk(df, curves_smoothed, t0_list = 0.5) estimate_risk <- function(curves, curves_estim, t0_list = 0.5) { risk_df <- dplyr::tibble(t0 = numeric(), MeanRSE = numeric(), MaxRSE = numeric()) for(t0 in t0_list) { risk <- estimateRisk(curves, curves_estim, t0) risk_df <- risk_df %>% dplyr::add_row(t0 = t0, MeanRSE = risk[[1]], MaxRSE = risk[[2]]) } risk_df } #' Perform an estimation of the risk on a set of curves along the sampling points. #' #' This function performs the estimation of the risk on a set of curves along #' the sampling points. Both the real and estimated curves have to be sampled on #' the same grid. #' #' Actually, two risks are computed. They are defined as: #' \deqn{MeanIntRSE = \frac{1}{N}\sum_{n = 1}^{N}\int(X_n(t) - \hat{X}_n(t))^2dt} #' and #' \deqn{MeanIntRSE = \max_{1 \leq n \leq N} \int(X_n(t) - \hat{X}_n(t))^2dt} #' #' @param curves A list, where each element represents a real curve. Each curve #' have to be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param curves_estim A list, where each element represents an estimated curve. #' Each curve have to be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The estimated points. #' } #' #' @return A list, with the mean and max integrated residual squared error #' in \eqn{t_0}. #' @export #' @examples #' df <- generate_fractional_brownian(N = 1000, M = 300, H = 0.5, sigma = 0.05) #' curves_smoothed <- smooth_curves(df)$smooth #' estimate_risks(df, curves_smoothed) estimate_risks <- function(curves, curves_estim) { risk <- estimateRiskCurves(curves, curves_estim) c("MeanIntRSE" = risk[1], "MaxIntRSE" = risk[2]) } #' Perform an estimation of the risk on one curve along the sampling points. #' #' This function performs the estimation of the risk on one curve along #' the sampling points. Both the real and estimated curve have to be sampled on #' the same grid. #' #' Actually, one risk is computed. They are defined as: #' \deqn{IntRSE = \int(X_n(t) - \hat{X}_n(t))^2dt} #' #' @param curves A list, where each element represents a real curve. Each curve #' have to be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param curves_estim A list, where each element represents an estimated curve. #' Each curve have to be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The estimated points. #' } #' #' @return Numeric, the integrated mean squarred eror #' @export #' @examples #' df <- generate_fractional_brownian(N = 1000, M = 300, H = 0.5, sigma = 0.05) #' curves_smoothed <- smooth_curves(df)$smooth #' estimate_int_risk(df[[1]], curves_smoothed[[1]]) estimate_int_risk <- function(curves, curves_estim) { estimateRiskCurve(curves, curves_estim) } <file_sep>// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 1<PASSWORD> #include <RcppArmadillo.h> #include <Rcpp.h> using namespace Rcpp; // epaKernelSmoothingCurve arma::vec epaKernelSmoothingCurve(const arma::vec& U, const arma::vec& T, const arma::vec& Y, const arma::vec& b); RcppExport SEXP _denoisr_epaKernelSmoothingCurve(SEXP USEXP, SEXP TSEXP, SEXP YSEXP, SEXP bSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const arma::vec& >::type U(USEXP); Rcpp::traits::input_parameter< const arma::vec& >::type T(TSEXP); Rcpp::traits::input_parameter< const arma::vec& >::type Y(YSEXP); Rcpp::traits::input_parameter< const arma::vec& >::type b(bSEXP); rcpp_result_gen = Rcpp::wrap(epaKernelSmoothingCurve(U, T, Y, b)); return rcpp_result_gen; END_RCPP } // uniKernelSmoothingCurve arma::vec uniKernelSmoothingCurve(const arma::vec& U, const arma::vec& T, const arma::vec& Y, const arma::vec& b); RcppExport SEXP _denoisr_uniKernelSmoothingCurve(SEXP USEXP, SEXP TSEXP, SEXP YSEXP, SEXP bSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const arma::vec& >::type U(USEXP); Rcpp::traits::input_parameter< const arma::vec& >::type T(TSEXP); Rcpp::traits::input_parameter< const arma::vec& >::type Y(YSEXP); Rcpp::traits::input_parameter< const arma::vec& >::type b(bSEXP); rcpp_result_gen = Rcpp::wrap(uniKernelSmoothingCurve(U, T, Y, b)); return rcpp_result_gen; END_RCPP } // betaKernelSmoothingCurve arma::vec betaKernelSmoothingCurve(const arma::vec& U, const arma::vec& T, const arma::vec& Y, const arma::vec& b); RcppExport SEXP _denoisr_betaKernelSmoothingCurve(SEXP USEXP, SEXP TSEXP, SEXP YSEXP, SEXP bSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const arma::vec& >::type U(USEXP); Rcpp::traits::input_parameter< const arma::vec& >::type T(TSEXP); Rcpp::traits::input_parameter< const arma::vec& >::type Y(YSEXP); Rcpp::traits::input_parameter< const arma::vec& >::type b(bSEXP); rcpp_result_gen = Rcpp::wrap(betaKernelSmoothingCurve(U, T, Y, b)); return rcpp_result_gen; END_RCPP } // modifiedBetaKernelSmoothingCurve arma::vec modifiedBetaKernelSmoothingCurve(const arma::vec& U, const arma::vec& T, const arma::vec& Y, const arma::vec& b); RcppExport SEXP _denoisr_modifiedBetaKernelSmoothingCurve(SEXP USEXP, SEXP TSEXP, SEXP YSEXP, SEXP bSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const arma::vec& >::type U(USEXP); Rcpp::traits::input_parameter< const arma::vec& >::type T(TSEXP); Rcpp::traits::input_parameter< const arma::vec& >::type Y(YSEXP); Rcpp::traits::input_parameter< const arma::vec& >::type b(bSEXP); rcpp_result_gen = Rcpp::wrap(modifiedBetaKernelSmoothingCurve(U, T, Y, b)); return rcpp_result_gen; END_RCPP } // LOOmean arma::vec LOOmean(const List& curves, const arma::vec& U, const List& b, const arma::uword& n); RcppExport SEXP _denoisr_LOOmean(SEXP curvesSEXP, SEXP USEXP, SEXP bSEXP, SEXP nSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const List& >::type curves(curvesSEXP); Rcpp::traits::input_parameter< const arma::vec& >::type U(USEXP); Rcpp::traits::input_parameter< const List& >::type b(bSEXP); Rcpp::traits::input_parameter< const arma::uword& >::type n(nSEXP); rcpp_result_gen = Rcpp::wrap(LOOmean(curves, U, b, n)); return rcpp_result_gen; END_RCPP } // mean_cpp arma::vec mean_cpp(const List& curves, const arma::vec& U, const List& b); RcppExport SEXP _denoisr_mean_cpp(SEXP curvesSEXP, SEXP USEXP, SEXP bSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const List& >::type curves(curvesSEXP); Rcpp::traits::input_parameter< const arma::vec& >::type U(USEXP); Rcpp::traits::input_parameter< const List& >::type b(bSEXP); rcpp_result_gen = Rcpp::wrap(mean_cpp(curves, U, b)); return rcpp_result_gen; END_RCPP } // covariance_cpp arma::mat covariance_cpp(const List& curves, const List& meanLOO_curves, const arma::vec& sampling_points, const List& b, const List& h); RcppExport SEXP _denoisr_covariance_cpp(SEXP curvesSEXP, SEXP meanLOO_curvesSEXP, SEXP sampling_pointsSEXP, SEXP bSEXP, SEXP hSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const List& >::type curves(curvesSEXP); Rcpp::traits::input_parameter< const List& >::type meanLOO_curves(meanLOO_curvesSEXP); Rcpp::traits::input_parameter< const arma::vec& >::type sampling_points(sampling_pointsSEXP); Rcpp::traits::input_parameter< const List& >::type b(bSEXP); Rcpp::traits::input_parameter< const List& >::type h(hSEXP); rcpp_result_gen = Rcpp::wrap(covariance_cpp(curves, meanLOO_curves, sampling_points, b, h)); return rcpp_result_gen; END_RCPP } // estimateRisk Rcpp::List estimateRisk(const List& curves, const List& curves_estim, const double& t0); RcppExport SEXP _denoisr_estimateRisk(SEXP curvesSEXP, SEXP curves_estimSEXP, SEXP t0SEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const List& >::type curves(curvesSEXP); Rcpp::traits::input_parameter< const List& >::type curves_estim(curves_estimSEXP); Rcpp::traits::input_parameter< const double& >::type t0(t0SEXP); rcpp_result_gen = Rcpp::wrap(estimateRisk(curves, curves_estim, t0)); return rcpp_result_gen; END_RCPP } // estimateRiskCurve double estimateRiskCurve(const List& curve, const List& curve_estim); RcppExport SEXP _denoisr_estimateRiskCurve(SEXP curveSEXP, SEXP curve_estimSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const List& >::type curve(curveSEXP); Rcpp::traits::input_parameter< const List& >::type curve_estim(curve_estimSEXP); rcpp_result_gen = Rcpp::wrap(estimateRiskCurve(curve, curve_estim)); return rcpp_result_gen; END_RCPP } // estimateRiskCurves List estimateRiskCurves(const List& curves, const List& curves_estim); RcppExport SEXP _denoisr_estimateRiskCurves(SEXP curvesSEXP, SEXP curves_estimSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const List& >::type curves(curvesSEXP); Rcpp::traits::input_parameter< const List& >::type curves_estim(curves_estimSEXP); rcpp_result_gen = Rcpp::wrap(estimateRiskCurves(curves, curves_estim)); return rcpp_result_gen; END_RCPP } // estimateSigma double estimateSigma(const List& curves); RcppExport SEXP _denoisr_estimateSigma(SEXP curvesSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const List& >::type curves(curvesSEXP); rcpp_result_gen = Rcpp::wrap(estimateSigma(curves)); return rcpp_result_gen; END_RCPP } // estimateSigmaMSE double estimateSigmaMSE(const List& curves, const List& curves_estim); RcppExport SEXP _denoisr_estimateSigmaMSE(SEXP curvesSEXP, SEXP curves_estimSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const List& >::type curves(curvesSEXP); Rcpp::traits::input_parameter< const List& >::type curves_estim(curves_estimSEXP); rcpp_result_gen = Rcpp::wrap(estimateSigmaMSE(curves, curves_estim)); return rcpp_result_gen; END_RCPP } static const R_CallMethodDef CallEntries[] = { {"_denoisr_epaKernelSmoothingCurve", (DL_FUNC) &_denoisr_epaKernelSmoothingCurve, 4}, {"_denoisr_uniKernelSmoothingCurve", (DL_FUNC) &_denoisr_uniKernelSmoothingCurve, 4}, {"_denoisr_betaKernelSmoothingCurve", (DL_FUNC) &_denoisr_betaKernelSmoothingCurve, 4}, {"_denoisr_modifiedBetaKernelSmoothingCurve", (DL_FUNC) &_denoisr_modifiedBetaKernelSmoothingCurve, 4}, {"_denoisr_LOOmean", (DL_FUNC) &_denoisr_LOOmean, 4}, {"_denoisr_mean_cpp", (DL_FUNC) &_denoisr_mean_cpp, 3}, {"_denoisr_covariance_cpp", (DL_FUNC) &_denoisr_covariance_cpp, 5}, {"_denoisr_estimateRisk", (DL_FUNC) &_denoisr_estimateRisk, 3}, {"_denoisr_estimateRiskCurve", (DL_FUNC) &_denoisr_estimateRiskCurve, 2}, {"_denoisr_estimateRiskCurves", (DL_FUNC) &_denoisr_estimateRiskCurves, 2}, {"_denoisr_estimateSigma", (DL_FUNC) &_denoisr_estimateSigma, 1}, {"_denoisr_estimateSigmaMSE", (DL_FUNC) &_denoisr_estimateSigmaMSE, 2}, {NULL, NULL, 0} }; RcppExport void R_init_denoisr(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); } <file_sep>################################################################################ # Tests of the file estimate_k0.R # ################################################################################ library(denoisr) test_that("estimate_k0_pilot is double", { expect_equal(estimate_k0_pilot(200), 21) expect_type(estimate_k0_pilot(200), "double") }) test_that("estimate_k0_oracle is double", { expect_equal(estimate_k0_oracle(200, 0.5), 3) expect_type(estimate_k0_oracle(200, 0.5), "double") }) <file_sep>// estimate_moment.h #ifndef ESTIMATE_MOMENT_H #define ESTIMATE_MOMENT_H #include <RcppArmadillo.h> arma::vec LOOmean( const List & curves, // Curves list ($x and $t) const arma::vec & U, // Estimation points const List & b, // Smoothing bandwidths const arma::uword & n // Curve to remove from the estimation ); arma::vec mean_cpp( const List & curves, // Curves list ($x and $t) const arma::vec & U, //Estimation points const List & b // Smoothing badnwidths ); arma::mat covariance_cpp( const List & curves, // Curves list ($x and $t) const arma::vec & sampling_points, // Estimation points const List & b, // Smoothing bandwidth const List & h // Smoothing bandwidth ); #endif<file_sep>// estimate_sigma.h #ifndef ESTIMATE_SIGMA_H #define ESTIMATE_SIGMA_H #include <RcppArmadillo.h> double estimateSigma( const List & curves // Curves list ($x and $t) ); #endif<file_sep>// estimate_curve.h #ifndef ESTIMATE_CURVE_H #define ESTIMATE_CURVE_H #include <RcppArmadillo.h> arma::vec epaKernelSmoothingCurve( const arma::vec & U, // Estimation points in U const arma::vec & T, // Sampling points const arma::vec & Y, // Curves points const arma::vec & b // Smoothing bandwiths ); arma::vec uniKernelSmoothingCurve( const arma::vec & U, // Estimation points in U const arma::vec & T, // Sampling points const arma::vec & Y, // Curves points const arma::vec & b // Smoothing bandwiths ); arma::vec betaKernelSmoothingCurve( const arma::vec & U, // Estimation points const arma::vec & T, // Sampling points const arma::vec & Y, // Curves points const arma::vec & b // Smoothing bandwiths ); arma::vec modifiedBetaKernelSmoothingCurve( const arma::vec & U, // Estimation points const arma::vec & T, // Sampling points const arma::vec & Y, // Curves points const arma::vec & b // Smoothing bandwiths ); #endif<file_sep>// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- // estimate_risk.cpp // [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadillo.h> using namespace Rcpp; // [[Rcpp::export]] Rcpp::List estimateRisk( const List & curves, // Curves list ($x and $t) const List & curves_estim, // Estimated curves list ($x and $t) const double & t0 // In which point estimate the risk. ){ // Define risk list List risk(2); // Get the number of curves arma::uword N = curves.length(); List mycurve = curves[0]; List mycurve_estim = curves_estim[0]; arma::uvec idx; arma::vec squared_diff(N); for(arma::uword n=0; n<N; n++){ mycurve = curves[n]; arma::vec x = mycurve["x"]; arma::vec t = mycurve["t"]; mycurve_estim = curves_estim[n]; arma::vec x_estim = mycurve_estim["x"]; arma::vec t_estim = mycurve_estim["t"]; double idx = arma::max(find(t <= t0)); double real = x(idx); double pred = x_estim(idx); squared_diff(n) = std::pow(pred - real, 2); } risk(0) = arma::mean(squared_diff); risk(1) = arma::max(squared_diff); return (risk); } // [[Rcpp::export]] double estimateRiskCurve( const List & curve, // Curve ($x and $t) const List & curve_estim // Estimated curve ($x and $t) ){ arma::mat risk; arma::vec x = curve["x"]; arma::vec t = curve["t"]; arma::vec x_estim = curve_estim["x"]; arma::vec squared_diff = pow(x - x_estim, 2); risk = arma::trapz(t, squared_diff); // Numerical integration return (risk(0, 0)); } // [[Rcpp::export]] List estimateRiskCurves( const List & curves, // Curves list ($x and $t) const List & curves_estim // Estimated curves list ($x and $t) ){ List risk(2); // Get the number of curves arma::uword N = curves.length(); List mycurve = curves[0]; List mycurve_estim = curves_estim[0]; arma::vec risk_int(N); for(arma::uword n=0; n < N; n++){ mycurve = curves[n]; mycurve_estim = curves_estim[n]; risk_int(n) = estimateRiskCurve(mycurve, mycurve_estim); } risk(0) = arma::mean(risk_int); risk(1) = arma::max(risk_int); return (risk); } <file_sep>################################################################################ # Functions for H0 parameter estimation using regularity # ################################################################################ #' Perform an estimation of \eqn{H_0} #' #' This function performs an estimation of \eqn{H_0} used for the estimation of #' the bandwidth for a univariate kernel regression estimator defined over #' continuous domains data using the method of \cite{add ref}. #' #' @importFrom magrittr %>% #' #' @family estimate \eqn{H_0} #' #' @param data A list, where each element represents a curve. Each curve have to #' be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param t0 Numeric, the sampling point at which we estimate \eqn{H0}. We will #' consider the \eqn{8k0 - 7} nearest points of \eqn{t_0} for the estimation of #' \eqn{H_0} when \eqn{\sigma} is unknown. #' @param k0 Numeric, the number of neighbors of \eqn{t_0} to consider. Should #' be set as \eqn{k0 = M * exp(-log(log(M))^2)}. #' @param sigma Numeric, true value of sigma. Can be NULL if true value #' is unknown. #' #' @return Numeric, an estimation of H0. estimate_H0 <- function(data, t0 = 0, k0 = 2, sigma = NULL) { theta <- function(v, k, idx) (v[idx + 2 * k - 1] - v[idx + k])**2 first_part <- 0 second_part <- 0 two_log_two <- 2 * log(2) if (is.null(sigma)) { # Case where sigma is unknown idxs <- data %>% purrr::map_dbl(~ min(order(abs(.x$t - t0))[seq_len(8 * k0 - 6)])) a <- data %>% purrr::map2_dbl(idxs, ~ theta(.x$x, k = 4 * k0 - 3, idx = .y)) %>% mean() b <- data %>% purrr::map2_dbl(idxs, ~ theta(.x$x, k = 2 * k0 - 1, idx = .y)) %>% mean() c <- data %>% purrr::map2_dbl(idxs, ~ theta(.x$x, k = k0, idx = .y)) %>% mean() if ((a - b > 0) & (b - c > 0) & (a - 2 * b + c > 0)) { first_part <- log(a - b) second_part <- log(b - c) } } else { # Case where sigma is known idxs <- data %>% purrr::map_dbl(~ min(order(abs(.x$t - t0))[seq_len(4 * k0 - 2)])) a <- data %>% purrr::map2_dbl(idxs, ~ theta(.x$x, k = 2 * k0 - 1, idx = .y)) %>% mean() b <- data %>% purrr::map2_dbl(idxs, ~ theta(.x$x, k = k0, idx = .y)) %>% mean() if ((a - 2 * sigma**2 > 0) & (b - 2 * sigma**2 > 0) & (a - b > 0)) { first_part <- log(a - 2 * sigma**2) second_part <- log(b - 2 * sigma**2) } } (first_part - second_part) / two_log_two } #' Perform an estimation of \eqn{H_0} given a list of \eqn{t_0} #' #' This function performs an estimation of \eqn{H_0} used for the estimation of #' the bandwidth for a univariate kernel regression estimator defined over #' continuous domains data using the method of \cite{add ref}. #' #' @importFrom magrittr %>% #' #' @family estimate \eqn{H_0} #' #' @param data A list, where each element represents a curve. Each curve have to #' be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param t0_list A vector of numerics, the sampling points at which we estimate #' \eqn{H0}. We will consider the \eqn{8k0 - 7} nearest points of \eqn{t_0} for #' the estimation of \eqn{H_0} when \eqn{\sigma} is unknown. #' @param k0_list A vector of numerics, the number of neighbors of \eqn{t_0} to #' consider. Should be set as \deqn{k0 = (M / log(M) + 7) / 8}. We can set a #' different \eqn{k_0}, but in order to use the same for each \eqn{t_0}, just #' put a unique numeric. #' @param sigma Numeric, true value of sigma. Can be NULL. #' #' @return A vector of numeric, an estimation of \eqn{H_0} at each \eqn{t_0}. #' @export #' @examples #' df <- generate_fractional_brownian(N = 1000, M = 300, H = 0.5, sigma = 0.05) #' H0 <- estimate_H0_list(df, t0_list = 0.5, k0_list = 6) #' #' df_piece <- generate_piecewise_fractional_brownian(N = 1000, M = 300, #' H = c(0.2, 0.5, 0.8), #' sigma = 0.05) #' H0 <- estimate_H0_list(df_piece, t0_list = c(0.15, 0.5, 0.85), #' k0_list = c(2, 4, 6)) #' H0 <- estimate_H0_list(df_piece, t0_list = c(0.15, 0.5, 0.85), k0_list = 6) estimate_H0_list <- function(data, t0_list, k0_list = 2, sigma = NULL) { if(!inherits(data, 'list')){ data <- checkData(data) } t0_list %>% purrr::map2_dbl(k0_list, ~ estimate_H0(data, t0 = .x, k0 = .y, sigma = sigma)) } #' Perform an estimation of \eqn{H_0} when the curves are derivables #' #' This function performs an estimation of \eqn{H_0} used for the estimation of #' the bandwidth for a univariate kernel regression estimator defined over #' continuous domains data in the case the curves are derivables. #' #' @importFrom magrittr %>% #' @importFrom KernSmooth locpoly #' #' @family estimate \eqn{H_0} #' #' @param data A lis, where each element represents a curve. Each curve have to #' be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param t0 Numeric, the sampling points at which we estimate \eqn{H_0}. We will #' consider the \eqn{8k0 - 7} nearest points of \eqn{t_0} for the estimation of #' \eqn{H_0} when \eqn{\sigma} is unknown. #' @param eps Numeric, precision parameter. It is used to control how much larger #' than 1, we have to be in order to consider to have a regularity larger than 1 #' (default to 0.01). #' @param k0 Numeric, the number of neighbors of \eqn{t_0} to consider. #' @param sigma Numeric, true value of sigma. Can be NULL. #' #' @return Numeric, an estimation of \eqn{H_0}. estimate_H0_deriv <- function(data, t0 = 0, eps = 0.01, k0 = 2, sigma = NULL){ sigma_estim <- estimate_sigma(data) H0_estim <- estimate_H0(data, t0 = t0, k0 = k0, sigma = sigma) cpt <- 0 while (H0_estim > 1 + eps){ L0 <- estimate_L0(data, t0 = t0, H0 = cpt + H0_estim, k0 = k0) b <- estimate_b(data, sigma = sigma_estim, H0 = cpt + H0_estim, L0 = L0) smooth <- data %>% purrr::map2(b, ~ list( t = .x$t, x = KernSmooth::locpoly(.x$t, .x$x, drv = 1 + cpt, bandwidth = .y, gridsize = length(.x$t) )$y )) H0_estim <- estimate_H0(smooth, t0 = t0, k0 = k0, sigma = sigma) cpt <- cpt + 1 } cpt + H0_estim } #' Perform an estimation of \eqn{H_0} given a list of \eqn{t_0} when the curves #' are derivables #' #' This function performs an estimation of \eqn{H_0} used for the estimation of #' the bandwidth for a univariate kernel regression estimator defined over #' continuous domains data using the method of \cite{add ref} in the case the #' curves are derivables. #' #' @importFrom magrittr %>% #' #' @family estimate \eqn{H_0} #' #' @param data A list, where each element represents a curve. Each curve have to #' be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param t0_list A vector of numerics, the sampling points at which we estimate #' \eqn{H0}. We will consider the \eqn{8k0 - 7} nearest points of \eqn{t_0} for #' the estimation of \eqn{H_0} when \eqn{\sigma} is unknown. #' @param eps Numeric, precision parameter. It is used to control how much larger #' than 1, we have to be in order to consider to have a regularity larger than 1 #' (default to 0.1). #' @param k0_list A vector of numerics, the number of neighbors of \eqn{t_0} to #' consider. Should be set as \deqn{k0 = M * exp(-log(log(M))^2)}. We can set a #' different \eqn{k_0}, but in order to use the same for each \eqn{t_0}, just #' put a unique numeric. #' @param sigma Numeric, true value of sigma. Can be NULL. #' #' @return A vector of numeric, an estimation of \eqn{H_0} at each \eqn{t_0}. #' @export #' @examples #' df <- generate_integrate_fractional_brownian(N = 1000, M = 300, #' H = 0.5, sigma = 0.01) #' H0 <- estimate_H0_deriv_list(df, t0_list = 0.5, eps = 0.01, k0_list = 14) estimate_H0_deriv_list <- function(data, t0_list, eps = 0.01, k0_list = 2, sigma = NULL) { if(!inherits(data, 'list')){ data <- checkData(data) } t0_list %>% purrr::map2_dbl(k0_list, ~ estimate_H0_deriv(data, t0 = .x, k0 = .y, sigma = sigma)) } <file_sep>--- output: github_document --- <!-- README.md is generated from README.Rmd/ Please edit that file --> ```{r setup, include=FALSE} knitr::opts_chunk$set( collapse=TRUE, comment = "#>", fig.path = "man/figures/README-", dev = 'svg', out.width = "100%") options(tibble.print_min = 5, tibble.print_max = 5) ``` # denoisr <!-- badges: start --> [![Build Status](https://travis-ci.org/StevenGolovkine/denoisr.svg?branch=master)](https://travis-ci.org/StevenGolovkine/denoisr) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/d5b2b6c6083c4d269ace4a8a1b8103b3)](https://www.codacy.com/manual/StevenGolovkine/denoisr?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=StevenGolovkine/denoisr&amp;utm_campaign=Badge_Grade) [![DOI](https://zenodo.org/badge/215247523.svg)](https://zenodo.org/badge/latestdoi/215247523) <!-- badges: end --> ## Overview `denoisr` is a non-parametric smoother for noisy curve data, providing different functions to estimate various parameters: * `estimate_H0_list()` and `estimate_H0_deriv_list()` estimate the smoothness of the curves. * `estimate_b_list()` and `estimate_bandwidth()` estimate the bandwidth used in the Nadaraya-Watson estimator. * `estimate_curve()` estimates one curve, given bandwidths. * `smooth_curves()` and `smooth_curves_regularity()` estimate the curves. * `estimate_mean()` and `estimate_covariance()` estimate the leave-one-out smoothing mean and covariance. You can learn more about them in `vignette('denoisr')`. ## Installation The package is not yet on CRAN. But, you can install from source with ```{r, eval=FALSE} devtools::install_url("https://github.com/StevenGolovkine/denoisr/raw/master/denoisr_1.0.2.tar.gz") ``` ## Development version You can install the last released version of `denoisr` from [Github](https://github.com/StevenGolovkine/denoisr) with: ```{r, eval=FALSE} devtools::install_github("StevenGolovkine/denoisr") ``` ## Usage ```{r load_package, warning=FALSE, message=FALSE} # Load packages library(denoisr) library(dplyr) library(funData) library(ggplot2) library(reshape2) ``` ```{r load_data} # Load data data("canadian_temperature_daily") ``` ```{r convert_funData} # Convert list to funData object data_fd <- list2funData(canadian_temperature_daily) ``` ```{r plot_data, fig.height=4.35, fig.width=7, fig.align='center'} # Plot of the data autoplot(data_fd) + labs(title = 'Daily Temperature Data', x = 'Normalized Day of Year', y = 'Temperature in °C') + theme_minimal() ``` ```{r smooth_data} # Smooth the data smooth_data <- smooth_curves(canadian_temperature_daily, t0_list = 0.5, k0_list = 5) ``` ```{r plot_data2, fig.height=4.35, fig.width=7, fig.align='center'} # Plot of the smoothed data smooth_data_fd <- list2funData(smooth_data$smooth) autoplot(smooth_data_fd) + labs(title = 'Smooth Daily Temperature Data', x = 'Normalized Day of Year', y = 'Temperature in °C') + theme_minimal() ``` ```{r plot_data3, fig.height=4.35, fig.width=7, fig.align='center'} # Plot one realisation of the smoothed data montreal <- tibble(t = canadian_temperature_daily$Montreal$t, Data = canadian_temperature_daily$Montreal$x, Smooth = smooth_data$smooth$Montreal$x) %>% reshape2::melt(id = 't') ggplot(montreal, aes(x = t, y = value, color = variable)) + geom_line() + labs(title = 'Example of Montreal', x = 'Normalized Day of Year', y = 'Temperature in °C', color = '') + theme_minimal() ``` ```{r compute_mean} # Compute the mean curve mean_curve <- estimate_mean(canadian_temperature_daily, U = seq(0, 1, length.out = 501), b = smooth_data$parameter$b) ``` ```{r plot_mean, fig.height=4.35, fig.width=7, fig.align='center'} mean_curve_plot <- tibble(t = seq(0, 1, length.out = 501), x = mean_curve) autoplot(data_fd) + geom_line(data = mean_curve_plot, mapping = aes(x = t, y = x, group = NULL), col = 'red', size = 2) + labs(title = 'Daily Temperature Data', x = 'Normalized Day of Year', y = 'Temperature in °C') + theme_minimal() ``` ```{r compute_covariance} # Compute the covariance surface U <- seq(0, 1, length.out = 101) cov_surface <- estimate_covariance(canadian_temperature_daily, U = U, b = smooth_data$parameter$b, h = 0.05) ``` ```{r plot_covariance, fig.height=5, fig.width=5, fig.align='center'} cov_surface_plot <- tibble(expand.grid(U, U), C = as.vector(cov_surface)) ggplot(cov_surface_plot) + geom_contour_filled(aes(x = Var1, y = Var2, z = C)) + labs(title = 'Covariance surface of daily temperature data', x = '', y = '', fill = 'Level') + theme_minimal() ```<file_sep>--- title: "Introduction to denoisr" author: "<NAME>" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction to denoisr} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` *References:* * <NAME>, <NAME> and <NAME> (2020). fda: Functional Data Analysis. R package version 5.1.4. https://CRAN.R-project.org/package=fda * <NAME> (2020). “Object-Oriented Software for Functional Data.” _Journal of Statistical Software_, *93*(5), 1-38. doi: 10.18637/jss.v093.i05 (URL: https://doi.org/10.18637/jss.v093.i05). ## Introduction `denoisr` is a **R** package which permits to smooth (remove the noise from) functional data by, first, estimate the Hurst coefficient of the underlying generating process. Functional data to smooth should be defined on a univariate compact, but can be irregularly sampled. `denoisr` can also be used only for Hurst parameter estimation. And finally, there is also some functions to compute the mean curve and the corariance surface. `denoisr` have a support for the package [`funData`](https://cran.r-project.org/web/packages/funData/index.html). ## Model Let $I$ be a compact interval of $\mathbb{R}$. We assume $X^{(1)}, \dots, X^{(N)}$ to be an independent sample of a random process $X = \left(X_t : t \in I\right)$ with continuous trajectories. For each $1 \leq n \leq N$, and given a positive integer $M_n$, let $T_m^{(n)}, 1 \leq m \leq M_n$ be the random observation times for the curve $X^{(n)}$. These times are obtained as independent copies of a variable $T$ taking values in $I$. The integers $M_1, \dots, M_N$ represent an independent sample of an integer-valued random variable $M$ with expectation $\mu$. We assume that the realizations $X$, $M$ and $T$ are mutually independent. The observations consist of the pairs $\left(Y_m^{(n)}, T_m^{(n)}\right) \in \mathbb{R} \times I$ where $Y_m^{(n)}$ is defined as $$Y_m^{(n)} = X^{(n)}(T_m^{(n)}) + \varepsilon_m^{(n)}, \quad 1 \leq n \leq N,~ 1 \leq m \leq M_n,$$ and $\varepsilon_m^{(n)}$ are independent copies of a centered error variable $\varepsilon$. Let $t_0 \in I$ an arbitrarily fixed piont. The aim is to estimate $X^{(1)}(t_0), \dots, X^{(N)}(t_0)$. ```{r setup, warning=FALSE, message=FALSE} # Load packages library(denoisr) library(dplyr) library(funData) library(ggplot2) library(reshape2) ``` ## Example on temperature data The Canadian temperature data correspond to the daily temperature at $35$ different locations in Canada averaged over 1960 to 1994. This dataset is included in the package [`fda`](https://CRAN.R-project.org/package=fda). This section performs the smoothing of the Canadian temperature Weather data. ```{r load_data} # Load data data("canadian_temperature_daily") ``` This package manipulates lists to define functional data. So, functions are provided to convert it as functional data object defined in the package *funData*. ```{r convert_funData} # Convert list to funData object data_fd <- list2funData(canadian_temperature_daily) ``` So, we can use all the available function for `funData` object. As an example, we can plot the data with the `ggplot2` style. ```{r plot_data, fig.height=4.35, fig.width=7} # Plot of the data autoplot(data_fd) + labs(title = 'Daily Temperature Data', x = 'Normalized Day of Year', y = 'Temperature in °C') + theme_minimal() ``` The smoothing of the curves can be performed using the function `smooth_curves`. It accepts the parameter `t0_list` which correspond to the times where we want to estimate the bandwidth and the parameter `k0_list` which is the considered neighborhood. ```{r smooth_data} # Smooth the data smooth_data <- smooth_curves(canadian_temperature_daily, t0_list = 0.5, k0_list = 5) ``` Then, we can plot the smoothed data. ```{r plot_data2, fig.height=4.35, fig.width=7} # Plot of the smoothed data smooth_data_fd <- list2funData(smooth_data$smooth) autoplot(smooth_data_fd) + labs(title = 'Smooth Daily Temperature Data', x = 'Normalized Day of Year', y = 'Temperature in °C') + theme_minimal() ``` Finally, we show on particular curve along its smoothed version to look at the impact of smoothing. ```{r plot_data3, fig.height=4.35, fig.width=7} # Plot one realisation of the smoothed data montreal <- tibble(t = canadian_temperature_daily$Montreal$t, Data = canadian_temperature_daily$Montreal$x, Smooth = smooth_data$smooth$Montreal$x) %>% reshape2::melt(id = 't') ggplot(montreal, aes(x = t, y = value, color = variable)) + geom_line() + labs(title = 'Example of Montreal', x = 'Normalized Day of Year', y = 'Temperature in °C', color = '') + theme_minimal() ``` ### Mean and Covariance First, we compute the mean curve. The mean curve is defined as the mean of the Leave-One-Out mean curves that are computed after removing one curve sequentially. ```{r compute_mean} # Compute the mean curve mean_curve <- estimate_mean(canadian_temperature_daily, U = seq(0, 1, length.out = 501), b = smooth_data$parameter$b) ``` Show the mean function along the complete set of curves. ```{r plot_mean, fig.height=4.35, fig.width=7} mean_curve_plot <- tibble(t = seq(0, 1, length.out = 501), x = mean_curve) autoplot(data_fd) + geom_line(data = mean_curve_plot, mapping = aes(x = t, y = x, group = NULL), col = 'red', size = 2) + labs(title = 'Daily Temperature Data', x = 'Normalized Day of Year', y = 'Temperature in °C') + theme_minimal() ``` Next, we compute the covariance surface. The covariance surface is defined as a 2-dimensional Nadaraya-Watson estimator of the smoothed version of the noisy curves. ```{r compute_covariance} # Compute the covariance surface U <- seq(0, 1, length.out = 101) cov_surface <- estimate_covariance(canadian_temperature_daily, U = U, b = smooth_data$parameter$b, h = 0.05) ``` Show the covariance surface. ```{r plot_covariance, fig.height=5, fig.width=5, fig.align='center'} cov_surface_plot <- tibble(expand.grid(U, U), C = as.vector(cov_surface)) ggplot(cov_surface_plot) + geom_contour_filled(aes(x = Var1, y = Var2, z = C)) + labs(title = 'Covariance surface of daily temperature data', x = '', y = '', fill = 'Level') + theme_minimal() ``` ## Example on simulated data We will do the same analysis on some simulated datasets. ### On fractional brownian motion First, we will do the analysis on a dataset of fractional brownian motion. A fractional brownian motion is a continuous-time Gaussian process $B_H(t)$ on $[0, 1]$, such that: * $B_H(0) = 0$ * $\mathbb{E}(B_H(t)) = 0, \quad \forall t \in [0, 1]$ * $\mathbb{E}(B_H(s)B_H(t)) = \frac{1}{2}\left(\lvert s\rvert^{2H} + \lvert t\rvert^{2H} - \lvert t - s\rvert^{2H}\right)$ where $H$ is a real number in $(0, 1)$, named Hurst parameter. ```{r load_brownian, warning=FALSE, message=FALSE} # Simulate some data set.seed(42) fractional_brownian <- generate_fractional_brownian(N = 100, M = 350, H = 0.5, sigma = 0.05) ``` ```{r smooth_data_brown} # Smooth the data smooth_data <- smooth_curves(fractional_brownian, t0_list = 0.5, k0_list = 14) ``` ```{r estimate_H_brow} # Estimation of the Hurst coefficient print(smooth_data$parameter$H0) ``` ```{r plot_brown, fig.height=4.35, fig.width=7} # Plot a particular observation obs <- tibble(t = fractional_brownian[[1]]$t, Noisy = fractional_brownian[[1]]$x, Truth = fractional_brownian[[1]]$x_true, Smooth = smooth_data$smooth[[1]]$x) %>% reshape2::melt(id = 't') ggplot(obs, aes(x = t, y = value, color = variable)) + geom_line() + labs(title = 'Fractional brownian motion', x = 'Normalized time', y = 'Value', color = '') + theme_minimal() ``` ```{r mean_frac_brown} # Compute the mean curve mean_curve <- estimate_mean(fractional_brownian, U = seq(0, 1, length.out = 100), b = smooth_data$parameter$b) ``` ```{r plot_mean_frac_brown, fig.height=4.35, fig.width=7} data_fd <- list2irregFunData(fractional_brownian) mean_curve_plot <- tibble(t = seq(0, 1, length.out = 100), x = mean_curve) autoplot(data_fd) + geom_line(data = mean_curve_plot, mapping = aes(x = t, y = x, group = NULL), col = 'red', size = 2) + labs(title = 'Fractional brownian motion', x = 'Normalized time', y = 'Value') + theme_minimal() ``` ```{r compute_covariance_frac_brown} # Compute the covariance surface U <- seq(0, 1, length.out = 101) cov_surface <- estimate_covariance(fractional_brownian, U = U, b = smooth_data$parameter$b, h = 0.05) ``` ```{r plot_covariance_frac_brown, fig.height=5, fig.width=5, fig.align='center'} # Show the covariance surface cov_surface_plot <- tibble(expand.grid(U, U), C = as.vector(cov_surface)) ggplot(cov_surface_plot) + geom_contour_filled(aes(x = Var1, y = Var2, z = C)) + labs(title = 'Covariance surface of fractional brownian motion', x = '', y = '', fill = 'Level') + theme_minimal() ``` ### On piecewise fractional brownian motion ```{r load_piecewise_brownian, warning=FALSE, message=FALSE} set.seed(42) piece_frac_brown <- generate_piecewise_fractional_brownian(N = 150, M = 350, H = c(0.2, 0.5, 0.8), sigma = 0.05) ``` ```{r smooth_data_piecebrown} # Smooth the data smooth_data <- smooth_curves(piece_frac_brown, t0_list = c(0.15, 0.5, 0.85), k0_list = c(14, 14, 14)) ``` ```{r estimate H_piecebrow} # Estimation of the Hurst coefficient print(smooth_data$parameter$H0) ``` ```{r plot_piece_brown, fig.height=4.35, fig.width=7} # Plot a particular observation obs <- tibble(t = piece_frac_brown[[1]]$t, Noisy = piece_frac_brown[[1]]$x, Truth = piece_frac_brown[[1]]$x_true, Smooth = smooth_data$smooth[[1]]$x) %>% reshape2::melt(id = 't') ggplot(obs, aes(x = t, y = value, color = variable)) + geom_line() + labs(title = 'Piecewise fractional brownian motion', x = 'Normalized time', y = 'Value', color = '') + theme_minimal() ``` ```{r mean_piece_frac_brown} # Compute the mean curve mean_curve <- estimate_mean(piece_frac_brown, U = seq(0, 1, length.out = 100), b = smooth_data$parameter$b, t0_list = c(0.15, 0.5, 0.85)) ``` ```{r plot_mean_piece_frac_brown, fig.height=4.35, fig.width=7} data_fd <- list2irregFunData(piece_frac_brown) mean_curve_plot <- tibble(t = seq(0, 1, length.out = 100), x = mean_curve) autoplot(data_fd) + geom_line(data = mean_curve_plot, mapping = aes(x = t, y = x, group = NULL), col = 'red', size = 2) + labs(title = 'Fractional brownian motion', x = 'Normalized time', y = 'Value') + theme_minimal() ``` ```{r compute_covariance_piece_frac_brown} # Compute the covariance surface U <- seq(0, 1, length.out = 101) cov_surface <- estimate_covariance(piece_frac_brown, U = U, b = smooth_data$parameter$b, h = 0.05, t0_list = c(0.15, 0.5, 0.85)) ``` ```{r plot_covariance_piece_frac_brown, fig.height=5, fig.width=5, fig.align='center'} # Show the covariance surface cov_surface_plot <- tibble(expand.grid(U, U), C = as.vector(cov_surface)) ggplot(cov_surface_plot) + geom_contour_filled(aes(x = Var1, y = Var2, z = C)) + labs(title = 'Covariance surface of \n piecewise fractional brownian motion', x = '', y = '', fill = 'Level') + theme_minimal() ``` ### On integrated fractional brownian motion ```{r load_inte_brownian, warning=FALSE, message=FALSE} # Simulate some data set.seed(42) inte_fractional_brownian <- generate_integrate_fractional_brownian(N = 100, M = 350, H = 0.5, sigma = 0.025) ``` ```{r smooth_data_inte_brown} # Smooth the data smooth_data <- smooth_curves_regularity(inte_fractional_brownian, t0 = 0.5, k0 = 14) ``` ```{r estimate_H_inte_brow} # Estimation of the Hurst coefficient print(smooth_data$parameter$H0) ``` ```{r plot_inte_brown, fig.height=4.35, fig.width=7} # Plot a particular observation obs <- tibble(t = inte_fractional_brownian[[1]]$t, Noisy = inte_fractional_brownian[[1]]$x, Truth = inte_fractional_brownian[[1]]$x_true, Smooth = smooth_data$smooth[[1]]$x) %>% reshape2::melt(id = 't') ggplot(obs, aes(x = t, y = value, color = variable)) + geom_line() + labs(title = 'Integreted Fractional brownian motion', x = 'Normalized time', y = 'Value', color = '') + theme_minimal() ``` ```{r mean_frac_inte_brown} # Compute the mean curve mean_curve <- estimate_mean(inte_fractional_brownian, U = seq(0, 1, length.out = 100), b = smooth_data$parameter$b) ``` ```{r plot_mean_inte_frac_brown, fig.height=4.35, fig.width=7} data_fd <- list2irregFunData(inte_fractional_brownian) mean_curve_plot <- tibble(t = seq(0, 1, length.out = 100), x = mean_curve) autoplot(data_fd) + geom_line(data = mean_curve_plot, mapping = aes(x = t, y = x, group = NULL), col = 'red', size = 2) + labs(title = 'Integrated fractional brownian motion', x = 'Normalized time', y = 'Value') + theme_minimal() ``` ```{r compute_covariance_inte_frac_brown} # Compute the covariance surface U <- seq(0, 1, length.out = 101) cov_surface <- estimate_covariance(inte_fractional_brownian, U = U, b = smooth_data$parameter$b, h = 0.05) ``` ```{r plot_covariance_inte_frac_brown, fig.height=5, fig.width=5, fig.align='center'} # Show the covariance surface cov_surface_plot <- tibble(expand.grid(U, U), C = as.vector(cov_surface)) ggplot(cov_surface_plot) + geom_contour_filled(aes(x = Var1, y = Var2, z = C)) + labs(title = 'Covariance surface of integrated fractional brownian motion', x = '', y = '', fill = 'Level') + theme_minimal() ``` <file_sep>################################################################################ # Functions for moments estimation # ################################################################################ #' Perform a leave-one-out mean curve #' #' This function performs the computation of a leave-one-out mean curve. #' #' @param curves A list, where each element represents a real curve. Each curve #' have to be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points #' } #' @param b A list of bandwidth #' @param n The curve to remove from the estimation #' @param t0_list A list of time at which the bandwidths have been estimated. #' (default = NULL) #' #' @return A vector representing the LOO mean curve. #' @export #' @examples #' df <- generate_fractional_brownian(N = 10, M = 300, H = 0.5, sigma = 0.05) #' estimate_LOO_mean(df, b = 0.01, n = 1) estimate_LOO_mean <- function(curves, b, n, t0_list = NULL){ U <- curves[[n]][['t']] if (length(b) == 1) { bandwidth <- purrr::rerun(length(curves), rep(b, length(U))) } else if ((length(b) == length(curves)) & (length(b[[1]]) == 1)) { bandwidth <- purrr::map(b, ~ rep(.x, length(U))) } else if ((length(b) == length(curves)) & length(b[[1]] > 1)) { idx <- U %>% purrr::map_dbl(~ order(abs(.x - t0_list))[1]) bandwidth <- b %>% purrr::map(~ .x[idx]) } else { stop("Issues with the bandwidth parameter.") } as.vector(LOOmean(curves, U, bandwidth, n - 1)) } #' Perform an estimation of the leave-one-out mean curve #' #' This function performs the estimation of the leave-one-out mean curve of a #' set of curves. #' #' @param curves A list, where each element represents a real curve. Each curve #' have to be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param U A vector of numerics, sampling points at which estimate the curve. #' @param b A list of bandwidth #' @param t0_list A list of time at which the bandwidths have been estimated. #' (default = NULL) #' #' @return A vector representing the mean curve. #' @export #' @examples #' df <- generate_fractional_brownian(N = 10, M = 300, H = 0.5, sigma = 0.05) #' estimate_mean(df, U = seq(0, 1, length.out = 101), b = 0.01) estimate_mean <- function(curves, U, b, t0_list = NULL){ if ((length(b[[1]]) > 1) & is.null(t0_list)){ stop(paste("If there are multiple bandwidths for each cuves,", "t0_list can not be NULL.")) } if (length(b) == 1) { bandwidth <- purrr::rerun(length(curves), rep(b, length(U))) } else if ((length(b) == length(curves)) & (length(b[[1]]) == 1)) { bandwidth <- purrr::map(b, ~ rep(.x, length(U))) } else if ((length(b) == length(curves)) & length(b[[1]] > 1)) { idx <- U %>% purrr::map_dbl(~ order(abs(.x - t0_list))[1]) bandwidth <- b %>% purrr::map(~ .x[idx]) } else { stop("Issues with the bandwidth parameter.") } as.vector(mean_cpp(curves, U, bandwidth)) } #' Perform an estimation of the covariancce #' #' This function performs the estimation of the covariance of a set of curves. #' #' @param curves A list, where each element represents a real curve. Each curve #' have to be defined as a list with two entries: #' \itemize{ #' \item \strong{$t} The sampling points #' \item \strong{$x} The observed points. #' } #' @param U A vector of numerics, sampling points at which estimate the curve. #' @param b A list of bandwidth for the first smoothing #' @param h A list of bandwidth for the second smoothing #' @param t0_list A list of time at which the bandwidths have been estimated. #' (default = NULL) #' #' @return A matrix of shape (length(U), length(U)) which is an estimation of #' the covariance matrix. #' @export #' @examples #' df <- generate_fractional_brownian(N = 10, M = 300, H = 0.5, sigma = 0.05) #' estimate_covariance(df, U = seq(0, 1, length.out = 11), b = 0.01, h = 0.05) estimate_covariance <- function(curves, U, b, h, t0_list = NULL){ if (length(b) == 1) { band_b <- curves %>% purrr::map(~ rep(b, length(.x$t))) } else if ((length(b) == length(curves)) & (length(b[[1]]) == 1)) { band_b <- purrr::map2(b, curves, ~ rep(.x, length(.y$t))) } else if ((length(b) == length(curves)) & length(b[[1]] > 1)) { idx <- curves %>% purrr::map(~ purrr::map_dbl(.x$t, ~ order(abs(.x - t0_list))[1])) band_b <- purrr::map2(b, idx, ~ .x[.y]) } else { stop("Issues with the bandwidth b parameter.") } if (length(h) == 1) { band_h <- purrr::rerun(length(curves), rep(h, length(U))) } else if ((length(h) == length(curves)) & (length(h[[1]]) == 1)) { band_h <- purrr::map(h, ~ rep(.x, length(U))) } else if ((length(h) == length(curves)) & length(h[[1]] > 1)) { idx <- U %>% purrr::map_dbl(~ order(abs(.x - t0_list))[1]) band_h <- h %>% purrr::map(~ .x[idx]) } else { stop("Issues with the bandwidth h parameter.") } LOOmean_list <- purrr::map(1:length(curves), ~ estimate_LOO_mean(curves, b, .x, t0_list)) covariance_cpp(curves, LOOmean_list, U, band_b, band_h) }
9c1b46aab66276c3e3146cee8583ca19395db275
[ "RMarkdown", "Markdown", "C", "R", "C++" ]
29
R
StevenGolovkine/SmoothCurves
8efbdb8eeb6cdd56e84e19340f28199a4ede088a
1f15aa79f2004416778805db78e074169c56259b
refs/heads/master
<repo_name>nfabacus/student-directory<file_sep>/csvTest.rb @students = [{name: "Jim", cohort: "July"}, {name: "Kate", cohort: "July"}, {name: "George", cohort: "July"}] require 'csv' CSV.foreach("students.csv") do |line| name, cohort, hobby1, hobby2, hobby3, country_of_birth, height, weight = line[0], line[1], line[2],line[3],line[4],line[5],line[6],line[7] hobbies =[] hobbies << hobby1 hobbies << hobby2 hobbies << hobby3 puts name+" "+cohort end CSV.open("studentsTest.csv", "wb") do |file| @students.each do |student| student = [student[:name], student[:cohort]] file << student end end <file_sep>/untilLoopTest.rb students = [ {name: "tony"},{name: "John"},{name: "Daisy"},{name: "Bob"} ] index = 0 until index > students.count-1 student = students[index] puts "index is #{index} name is #{student[:name]}" index +=1 end <file_sep>/directory.rb require 'csv' @students = [] @cohorts = [:January, :February, :March, :April, :May, :June, :July, :August, :September, :October, :November, :December] def add_student_to_array (name, cohort, hobbies, country_of_birth, height, weight) @students << {name: name, cohort: cohort.to_sym, hobbies:hobbies, country_of_birth: country_of_birth, height: height, weight: weight} end def save_students (filename="students.csv") #open the file for writing CSV.open(filename, "wb") do |file| #iterate over the array of students @students.each do |student| student = [student[:name], student[:cohort], student[:hobbies][0], student[:hobbies][1], student[:hobbies][2],student[:country_of_birth], student[:height], student[:weight]] file << student end end end def load_students(filename= "students.csv") @students=[] CSV.foreach(filename) do |line| name, cohort, hobby1, hobby2, hobby3, country_of_birth, height, weight = line[0], line[1], line[2],line[3],line[4],line[5],line[6],line[7] hobbies =[] hobbies << hobby1 hobbies << hobby2 hobbies << hobby3 add_student_to_array name, cohort, hobbies, country_of_birth, height, weight end end def input_students studentsAdded = 0 while true puts "Please enter the names of the students" puts "To finish, just hit return twice" name = STDIN.gets.gsub(/\n/,"") #Used gsub instead of chomp break if name.empty? if name.length >= 12 puts "Name has to be shorter than 12 characters. This name will not be added." puts "Please enter a name under 12 characters." next end cohort = nil until !@cohorts.select{|month| month == cohort}.empty? puts "Which cohort is the student in? (January to December)" cohort = STDIN.gets.gsub(/\n/,"") #Used gsub instead of chomp cohort = "July" if cohort.empty? cohort = cohort.gsub(/\s+/,+"_").capitalize.to_sym end hobbies = [] 3.times do |x| puts "What is the student's hobby(#{x+1})?" hobby = STDIN.gets.chomp hobbies << hobby end puts "Where is the student's country of birth?" country_of_birth = STDIN.gets.chomp puts "What is the height of the student?" height = STDIN.gets.chomp puts "What is the weight of the student?" weight = STDIN.gets.chomp # add the student hash to the array add_student_to_array name, cohort, hobbies, country_of_birth, height, weight studentsAdded +=1 end puts "#{studentsAdded} student(s) added." puts "Now we have #{@students.count} students" puts "Exiting to the main menu.." end def print_header puts " The students of Villains Academy ".center(120, "xxx") puts "-------------".center(120) end def print_students_list if @students.count == 0 puts "No list to print.".center(120) return end selectedStudents = [] puts "Student Search (Type 'quit' to quit)".center(120) while true puts "Please input the first letter of the students'name you want to search for:".center(120) firstLetter = STDIN.gets.chomp.downcase if firstLetter == "quit" puts "quitting.." exit elsif firstLetter.length >1 puts "Please type in only one letter." next end break end index = 0 until index > @students.count-1 student = @students[index] if student[:name][0].downcase==firstLetter || firstLetter.empty? selectedStudents.push(student) end puts index +=1 end for i in 0..@cohorts.length-1 selectedStudents.map do |student| if student[:cohort]==@cohorts[i] puts "#{student[:name]} (#{student[:cohort]} cohort)".center(120) puts "Hobbies: #{student[:hobbies].join(', ')}.".center(120) puts "Country of birth: #{student[:country_of_birth]}".center(120) puts " Height: #{student[:height]} Weight: #{student[:weight]}".center(120) puts end end end end def print_footer() @students.count == 1 ? (puts "Now we have #{@students.count} great student.".center(120)) : (puts "Overall, we have #{@students.count} great students.".center(120)) end def print_menu # 1. print the menu and ask the user what to do. puts "1. Input the students" puts "2. Show the students" puts "3. Save the list to students.csv" puts "4. Load the list from students.csv" puts "9. Exit" # 9 because we'll be adding more items. end def show_students print_header print_students_list print_footer end def process(selection) case selection when "1" input_students when "2" show_students puts "Displayed the student list successfully..back to the main menu.".center(120) puts when "3" filename = ask_filename "save" save_students(filename) puts "Saved students successfully..back to the main menu.".center(120) puts when "4" filename = ask_filename "load" load_students(filename) puts "Loaded students successfully..back to the main menu.".center(120) puts when "9" puts "Exiting the program...".center(120) puts exit # this will cause the program to terminate else puts "I don't know what you meant, try again.".center(120) end end def ask_filename param loop do puts "Please type in the CSV file name (e.g. students.csv) Type q to quit." filename = STDIN.gets.chomp if filename == "q" puts "Exiting the program..." puts exit end next if filename.empty? case param when "save" return filename when "load" if File.exists?(filename) return filename else puts "Sorry, #{filename} doesn't exist." end end end end def try_load_students filename = ARGV.first # first argument from the command line filename = "students.csv" if filename.nil? if File.exists?(filename) #if it exists load_students(filename) else #if it does not exist puts "Sorry, #{filename} doesn't exist." exit #quit the program end end def interactive_menu loop do print_menu process(STDIN.gets.chomp) end end try_load_students interactive_menu <file_sep>/mapByCohort.rb cohorts = [:January, :February, :March, :April, :May, :June, :July, :August, :September, :October, :November, :December] students = [ {name: "Dr. <NAME>", cohort: :november}, {name: "<NAME>", cohort: :december}, {name: "<NAME>", cohort: :november}, {name: "<NAME>", cohort: :january}, {name: "<NAME>", cohort: :november}, {name: "The Wicked Witch of the West", cohort: :march}, {name: "Terminator", cohort: :november}, {name: "<NAME>", cohort: :march}, {name: "<NAME>", cohort: :november}, {name: "<NAME>", cohort: :november}, {name: "<NAME>", cohort: :january} ] studentsByCohorts =[] for i in 0..cohorts.length-1 studentsByCohorts = students.map{|student| student if student[:cohort].capitalize==cohorts[i]} puts studentsByCohorts end <file_sep>/quine.rb filename = File.basename(__FILE__) puts File.read filename # Oy, this is my own source code!
77d918ec34c4b12a5e6109a783fb8027d1826f33
[ "Ruby" ]
5
Ruby
nfabacus/student-directory
ad333b3c2649cbd93a344ac6db6665f7acdf64cc
809036768f4343f38d4a976ce267fadd0a707375
refs/heads/master
<file_sep>from psychopy import visual, core, event, monitors import unittest class NewWindowTest(unittest.TestCase): #1 def setUp(self): #2 self.win = visual.Window(color='black') self.rect = visual.Rect(win, width=.5, height=.3, fillColor='red') def tearDown(self): #3 self.win.close() def test_can_start_a_list_and_retrieve_it_later(self): #4 # Edith has heard about a cool new online to-do app. She goes # to check out its homepage self.rect.draw() self.win.flip() # don't forget to flip when done with drawing all stimuli so that the stimuli become visible self.event.waitKeys() # She notices the page title and header mention to-do lists self.assertIn('To-Do', self.browser.title) #5 self.fail('Finish the test!') #6 # She is invited to enter a to-do item straight away if __name__ == '__main__': #7 TestCase.setUp() unittest.main() #8 unittest.tearDown() <file_sep>""" test for existance of psychopy @author: Neuromancer """ import unittest import numpy, psychopy if __name__ == '__main__': unittest.main() <file_sep># -*- coding: utf-8 -*- """ Created on Wed Oct 28 08:45:43 2015 @author: Neuromancer """ import numpy as np from psychopy import visual, core, event, monitors win = visual.Window(color='black') rect = visual.Rect(win, width =.5, height =.3, fillColor ='red') rect.draw() win.flip() # don't forget to flip when done with drawing all stimuli so that the stimuli become visible event.waitKeys() win.close()<file_sep># Psychopy Eye Tracking Psychopy experiment with Eyelink eyetracking with pylink library and Datapixx2 hardware.
9340c655287105c17efb456138e881a861dd4375
[ "Markdown", "Python" ]
4
Python
alistairwalsh/loquacious-octo-turtle
3fc9d5091896dfc2866f929a918498973da56731
d1d6fa00ab8a14e9a2777e22dcca57a6cc4adb0f
refs/heads/master
<file_sep><!DOCTYPE html PUBLIC "-//IETF//DTD HTML//EN"> <!-- saved from url=(0051)https://www.toothycat.net/wiki/wiki.pl?Binutils/bfd --> <html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"><title>ToothyWiki: Binutils/Bfd</title> <script language="javascript" src="./ToothyWiki_ Binutils_Bfd_files/rot13.js"></script> <link rel="icon" href="https://www.toothycat.net/favicon.ico"></head><body bgcolor="white"> <h1><a href="http://www.toothycat.net/"><img src="./ToothyWiki_ Binutils_Bfd_files/text_logo.jpg" alt="[Home]" border="0" align="right"></a><a href="https://www.toothycat.net/wiki/wiki.pl?search_bb=1&amp;search_ns=Binutils&amp;search=Bfd">Binutils/Bfd</a></h1>xxx.xxx.xxx.xxx | <a href="https://www.toothycat.net/wiki/wiki.pl?ToothyWiki">ToothyWiki</a> | <a href="https://www.toothycat.net/wiki/wiki.pl?Binutils">Binutils</a> | <a href="https://www.toothycat.net/wiki/wiki.pl?RecentChanges">RecentChanges</a> | <a href="https://www.toothycat.net/wiki/wiki.pl?action=login">Login</a> | <a href="https://www.toothycat.net/apoc/">Webcomic</a><br> <hr><a name="libbfd"></a><a name="libbfd"></a><a name="uid-0"></a><h3>libbfd</h3> <br>This library provides functions to read and write the contents of executable binaries and libraries.&nbsp; To use the library, simply include "bfd.h", and link your program against libbdf.so.&nbsp; <br><br>A binary file is represented by an instance of the "bfd" object.&nbsp; Each file is broken into sections represented by "struct bfd_section" objects.&nbsp; These can be retrieved by name.&nbsp; For example, ".text" and ".data" are the standard section names in ELF for the code and data segments.<br><br>Although it would be possible to access the linking information directly from the appropriate bfd_sections, libbfd abstracts this functionality to allow the API to work independently of the binary structure.&nbsp; To achieve this, bfd objects can be used to retrieve arrays of "struct bfd_symbol" that represent entries in the binary's linker tables.<br><br><a name="Primary_bfd_object_methods"></a><a name="Primary"></a><a name="uid-1"></a><h4>Primary bfd object methods</h4> <br>Class representing a Binary File Descriptor<br><pre>&nbsp; // Open and close binary files<br>&nbsp; bfd&nbsp; &nbsp; &nbsp; &nbsp; * bfd_openr( const char * filename, const char * target );<br>&nbsp; bfd_boolean&nbsp; bfd_close( bfd * );<br></pre> <br><pre>&nbsp; //&nbsp; Query file properties <br>&nbsp; char&nbsp; &nbsp; &nbsp; &nbsp; * bfd_get_filename( bfd * );<br>&nbsp; char&nbsp; &nbsp; &nbsp; &nbsp; * bfd_get_target( bfd * );<br>&nbsp; bfd_flavour&nbsp; bfd_get_flavour( bfd * );<br>&nbsp; flagword&nbsp; &nbsp; &nbsp; bfd_get_flags(&nbsp; bfd * );<br></pre> <br><pre>&nbsp; // Address of the start of executable code when loaded into memory (.text section in standard ELF)<br>&nbsp; bfd_vma&nbsp; &nbsp; &nbsp; bfd_get_start_address( bfd * );<br></pre> <br><pre>&nbsp; // Enumerate or retrieve file sections (for example ".text", ".data")<br>&nbsp; //<br>&nbsp; //&nbsp; Callback prototype is:<br>&nbsp; //&nbsp; void callback( bfd * bfdFile,<br>&nbsp; //&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; struct bfd_section * section,<br>&nbsp; //&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; void * user_data );<br>&nbsp; //<br>&nbsp; void bfd_map_over_sections( bfd *, &amp;callback, void * user_data );<br>&nbsp; struct bfd_section * get_section_by_name( bfd *, const char * name );<br></pre> <br><pre>&nbsp; // Symbol access<br>&nbsp; long bfd_get_symtab_upper_bound( bfd * );<br>&nbsp; long bfd_canonicalize_symtab( bfd *, struct bfd_symbol ** symbols );<br></pre> <br><pre>&nbsp; long bfd_get_dynamic_symtab_upper_bound( bfd * );<br>&nbsp; long bfd_canonicalize_dynamic_symtab( bfd *, struct bfd_symbol ** symbols );<br></pre> <br><a name="Primary_struct_bfd_sections_properties"></a><a name="Primary"></a><a name="uid-2"></a><h4>Primary struct bfd_sections properties</h4> <br>Class representing a section in an binary file<br><pre>&nbsp; // Section name<br>&nbsp; const char&nbsp; &nbsp; * name;<br></pre> <br><pre>&nbsp; //&nbsp; Address and size of section when loaded into memory<br>&nbsp; bfd_vma&nbsp; &nbsp; &nbsp; &nbsp; vma;<br>&nbsp; bfd_size_type&nbsp; size;<br></pre> <br><a name="Primary_"></a><a name="Primary"></a><a name="uid-3"></a><h4>Primary "struct bfd_symbol" properties</h4> <br>Class representing an entry in one of the binary's symbol table<br><pre>&nbsp; //&nbsp; The symbol name, the section it resides in, and standard symbol information structure<br>&nbsp; const char * name<br>&nbsp; struct bfd_section * section<br>&nbsp; void bfd_symbol_info( struct bfd_symbol *, symbol_info * info ); <br></pre> <br><a name="Example"></a><a name="Example"></a><a name="uid-4"></a><h4>Example: Opening an existing binary file</h4> <br>This code opens /bin/ls as an 64-bit x86 ELF binary.&nbsp; Note that it is necessary to call bfd_check_format() before using the bfd instance.<br><br><pre>&nbsp; bfd_init();<br></pre> <br><pre>&nbsp; bfd * bfdFile = bfd_openr( "/bin/ls", "elf64-x86-64" );<br>&nbsp; if ( bfdFile == NULL )<br>&nbsp; {<br>&nbsp; &nbsp; &nbsp; printf( "Error [%x]: %s\n", bfd_get_error(), bfd_errmsg(bfd_get_error()) );<br>&nbsp; &nbsp; &nbsp; return;<br>&nbsp; }<br></pre> <br><pre>&nbsp; if ( !bfd_check_format( bfdFile, bfd_object ))<br>&nbsp; {<br>&nbsp; &nbsp; &nbsp; printf( "Error [%x]: %s\n", bfd_get_error(), bfd_errmsg(bfd_get_error()) );<br>&nbsp; &nbsp; &nbsp; return;<br>&nbsp; }<br></pre> <br><pre>&nbsp; // Program goes here<br></pre> <br><pre>&nbsp; bfd_close( bfdFile );<br></pre> <br><a name="Reading_symbol_tables"></a><a name="Reading"></a><a name="uid-5"></a><h4>Reading symbol tables</h4> <br>Retrieving the symbols included in the bfd file is slightly more complicated (you need to pass in a buffer of appropriate size). The code below extracts the dynamic symbols from a bfd instance (static symbols are similar):<br><br><pre>&nbsp; &nbsp; struct bfd_symbol ** symbols;<br>&nbsp; &nbsp; long&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; symbolsSize;<br>&nbsp; &nbsp; long&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; symbolsCount;<br></pre> <br><pre>&nbsp; &nbsp; long i;<br></pre> <br><pre>&nbsp; &nbsp; // Calculate required buffer size<br>&nbsp; &nbsp; symbolsSize = bfd_get_dynamic_symtab_upper_bound( bfdFile );<br>&nbsp; &nbsp; if ( symbolsSize &lt; 0 )<br>&nbsp; &nbsp; {<br>&nbsp; &nbsp; &nbsp; printf( "Error [%x]: %s\n", bfd_get_error(), bfd_errmsg(bfd_get_error()) );<br>&nbsp; &nbsp; &nbsp; return;<br>&nbsp; &nbsp; }<br></pre> <br><pre>&nbsp; &nbsp; // Allocate buffer<br>&nbsp; &nbsp; symbols = malloc( symbolsSize );<br>&nbsp; &nbsp; if ( symbols == NULL )<br>&nbsp; &nbsp; {<br>&nbsp; &nbsp; &nbsp; printf( "Could not allocate memory\n" );<br>&nbsp; &nbsp; &nbsp; return;<br>&nbsp; &nbsp; }<br></pre> <br><pre>&nbsp; &nbsp; // Retrieve unpacked symbols<br>&nbsp; &nbsp; symbolsCount = bfd_canonicalize_dynamic_symtab( bfdFile, symbols );<br>&nbsp; &nbsp; if ( symbolsCount &lt; 0 )<br>&nbsp; &nbsp; {<br>&nbsp; &nbsp; &nbsp; printf( "Error [%x]: %s\n", bfd_get_error(), bfd_errmsg(bfd_get_error()) );<br>&nbsp; &nbsp; &nbsp; free( symbols );<br>&nbsp; &nbsp; &nbsp; return;<br>&nbsp; &nbsp; }<br></pre> <br><pre>&nbsp; &nbsp; // List symbols<br>&nbsp; &nbsp; for ( i = 0; i &lt; symbolsCount; i++ )<br>&nbsp; &nbsp; {<br>&nbsp; &nbsp; &nbsp; printf( "Symbol [flags %x][value %x] %s\n", symbols[i]-&gt;flags, symbols[i]-&gt;value, symbols[i]-&gt;name );<br>&nbsp; &nbsp; } <br></pre> <br><pre>&nbsp; &nbsp; free( symbols );<br></pre> <br><a name="Modifying_and_linking_binary_files"></a><a name="Modifying"></a><a name="uid-6"></a><h4>Modifying and linking binary files</h4> <br>In addition to examining existing files, libbfd also has functionality for creating and modifying them.&nbsp; The most advanced functionality is in the area of code disassemble/reassembly and linking.&nbsp; This can even support code compiled for different machine architectures.<br><hr> <table width="100%" cellpadding="0" cellspacing="0" border="0"><tbody><tr><td width="*"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tbody><tr><td width="100%">xxx.xxx.xxx.xxx | <a href="https://www.toothycat.net/wiki/wiki.pl?ToothyWiki">ToothyWiki</a> | <a href="https://www.toothycat.net/wiki/wiki.pl?Binutils">Binutils</a> | <a href="https://www.toothycat.net/wiki/wiki.pl?RecentChanges">RecentChanges</a> | <a href="https://www.toothycat.net/wiki/wiki.pl?action=login">Login</a> | <a href="https://www.toothycat.net/apoc/">Webcomic</a><br> This page is read-only | <a href="https://www.toothycat.net/wiki/wiki.pl?id=Binutils/Bfd&amp;action=history">View other revisions</a> | <a href="https://www.toothycat.net/cgi/log.pl?act=rrx&amp;n=/wiki/wiki.pl?Binutils/Bfd">Recently used referrers</a><br>Last edited January 12, 2009 11:10 pm (viewing revision 1, which is the newest) <a href="https://www.toothycat.net/wiki/wiki.pl?id=Binutils/Bfd&amp;action=browse&amp;diff=1">(diff)</a></td></tr></tbody></table><table width="100%" cellpadding="0" cellspacing="0" border="0"><tbody><tr><td width="70%" align="left"><form method="post" action="https://www.toothycat.net/wiki/wiki.pl" enctype="application/x-www-form-urlencoded"> <input type="hidden" name="ipmatch" value="xxx.xxx.xxx.xxx">Search: <input type="text" name="search" size="20"> <label><input type="checkbox" name="search_ww" value="1" checked="checked">Whole words</label> <label><input type="checkbox" name="search_all" value="1" checked="checked">Must contain all</label> <label><input type="checkbox" name="search_title" value="1">Page title search</label><input type="hidden" name="dosearch" value="1"><div><input type="hidden" name=".cgifields" value="search_ww"><input type="hidden" name=".cgifields" value="search_all"><input type="hidden" name=".cgifields" value="search_title"></div> </form></td><td width="30%" align="right"><form method="post" action="https://www.toothycat.net/wiki/wiki.pl" enctype="application/x-www-form-urlencoded"> <input type="hidden" name="ipmatch" value="xxx.xxx.xxx.xxx"><input type="submit" name="dorot13" value="Rot13:" onclick="return rot13(rot13text1)"> <input type="text" name="rot13text1" size="20"><input type="hidden" name="rot13tag" value="1"><input type="hidden" name="action" value="browse"><input type="hidden" name="id" value="Binutils/Bfd"></form></td></tr></tbody></table></td></tr></tbody></table> </body></html> <file_sep>// <NAME> <<EMAIL>> // binutils - mach.rs #![allow(dead_code)] #![allow(non_upper_case_globals)] #![allow(unknown_lints)] #![allow(clippy::all)] // Manually generate for binutils-2.29.1 pub const bfd_mach_m68000: u64 = 1; pub const bfd_mach_m68008: u64 = 2; pub const bfd_mach_m68010: u64 = 3; pub const bfd_mach_m68020: u64 = 4; pub const bfd_mach_m68030: u64 = 5; pub const bfd_mach_m68040: u64 = 6; pub const bfd_mach_m68060: u64 = 7; pub const bfd_mach_cpu64: u64 = 8; pub const bfd_mach_fido: u64 = 9; pub const bfd_mach_mcf_isa_a_nodiv: u64 = 10; pub const bfd_mach_mcf_isa_a: u64 = 11; pub const bfd_mach_mcf_isa_a_mac: u64 = 12; pub const bfd_mach_mcf_isa_a_emac: u64 = 13; pub const bfd_mach_mcf_isa_aplus: u64 = 14; pub const bfd_mach_mcf_isa_aplus_mac: u64 = 15; pub const bfd_mach_mcf_isa_aplus_emac: u64 = 16; pub const bfd_mach_mcf_isa_b_nousp: u64 = 17; pub const bfd_mach_mcf_isa_b_nousp_mac: u64 = 18; pub const bfd_mach_mcf_isa_b_nousp_emac: u64 = 19; pub const bfd_mach_mcf_isa_b: u64 = 20; pub const bfd_mach_mcf_isa_b_mac: u64 = 21; pub const bfd_mach_mcf_isa_b_emac: u64 = 22; pub const bfd_mach_mcf_isa_b_float: u64 = 23; pub const bfd_mach_mcf_isa_b_float_mac: u64 = 24; pub const bfd_mach_mcf_isa_b_float_emac: u64 = 25; pub const bfd_mach_mcf_isa_c: u64 = 26; pub const bfd_mach_mcf_isa_c_mac: u64 = 27; pub const bfd_mach_mcf_isa_c_emac: u64 = 28; pub const bfd_mach_mcf_isa_c_nodiv: u64 = 29; pub const bfd_mach_mcf_isa_c_nodiv_mac: u64 = 30; pub const bfd_mach_mcf_isa_c_nodiv_emac: u64 = 31; pub const bfd_mach_i960_core: u64 = 1; pub const bfd_mach_i960_ka_sa: u64 = 2; pub const bfd_mach_i960_kb_sb: u64 = 3; pub const bfd_mach_i960_mc: u64 = 4; pub const bfd_mach_i960_xa: u64 = 5; pub const bfd_mach_i960_ca: u64 = 6; pub const bfd_mach_i960_jx: u64 = 7; pub const bfd_mach_i960_hx: u64 = 8; pub const bfd_mach_or1k: u64 = 1; pub const bfd_mach_or1knd: u64 = 2; pub const bfd_mach_sparc: u64 = 1; pub const bfd_mach_sparc_sparclet: u64 = 2; pub const bfd_mach_sparc_sparclite: u64 = 3; pub const bfd_mach_sparc_v8plus: u64 = 4; pub const bfd_mach_sparc_v8plusa: u64 = 5 /* with ultrasparc add'ns. */; pub const bfd_mach_sparc_sparclite_le: u64 = 6; pub const bfd_mach_sparc_v9: u64 = 7; pub const bfd_mach_sparc_v9a: u64 = 8 /* with ultrasparc add'ns. */; pub const bfd_mach_sparc_v8plusb: u64 = 9 /* with cheetah add'ns. */; pub const bfd_mach_sparc_v9b: u64 = 10 /* with cheetah add'ns. */; pub const bfd_mach_sparc_v8plusc: u64 = 11 /* with UA2005 and T1 add'ns. */; pub const bfd_mach_sparc_v9c: u64 = 12 /* with UA2005 and T1 add'ns. */; pub const bfd_mach_sparc_v8plusd: u64 = 13 /* with UA2007 and T3 add'ns. */; pub const bfd_mach_sparc_v9d: u64 = 14 /* with UA2007 and T3 add'ns. */; pub const bfd_mach_sparc_v8pluse: u64 = 15 /* with OSA2001 and T4 add'ns (no IMA). */; pub const bfd_mach_sparc_v9e: u64 = 16 /* with OSA2001 and T4 add'ns (no IMA). */; pub const bfd_mach_sparc_v8plusv: u64 = 17 /* with OSA2011 and T4 and IMA and FJMAU add'ns. */; pub const bfd_mach_sparc_v9v: u64 = 18 /* with OSA2011 and T4 and IMA and FJMAU add'ns. */; pub const bfd_mach_sparc_v8plusm: u64 = 19 /* with OSA2015 and M7 add'ns. */; pub const bfd_mach_sparc_v9m: u64 = 20 /* with OSA2015 and M7 add'ns. */; pub const bfd_mach_sparc_v8plusm8: u64 = 21 /* with OSA2017 and M8 add'ns. */; pub const bfd_mach_sparc_v9m8: u64 = 22 /* with OSA2017 and M8 add'ns. */; pub const bfd_mach_spu: u64 = 256; pub const bfd_mach_mips3000: u64 = 3000; pub const bfd_mach_mips3900: u64 = 3900; pub const bfd_mach_mips4000: u64 = 4000; pub const bfd_mach_mips4010: u64 = 4010; pub const bfd_mach_mips4100: u64 = 4100; pub const bfd_mach_mips4111: u64 = 4111; pub const bfd_mach_mips4120: u64 = 4120; pub const bfd_mach_mips4300: u64 = 4300; pub const bfd_mach_mips4400: u64 = 4400; pub const bfd_mach_mips4600: u64 = 4600; pub const bfd_mach_mips4650: u64 = 4650; pub const bfd_mach_mips5000: u64 = 5000; pub const bfd_mach_mips5400: u64 = 5400; pub const bfd_mach_mips5500: u64 = 5500; pub const bfd_mach_mips5900: u64 = 5900; pub const bfd_mach_mips6000: u64 = 6000; pub const bfd_mach_mips7000: u64 = 7000; pub const bfd_mach_mips8000: u64 = 8000; pub const bfd_mach_mips9000: u64 = 9000; pub const bfd_mach_mips10000: u64 = 10000; pub const bfd_mach_mips12000: u64 = 12000; pub const bfd_mach_mips14000: u64 = 14000; pub const bfd_mach_mips16000: u64 = 16000; pub const bfd_mach_mips16: u64 = 16; pub const bfd_mach_mips5: u64 = 5; pub const bfd_mach_mips_loongson_2e: u64 = 3001; pub const bfd_mach_mips_loongson_2f: u64 = 3002; pub const bfd_mach_mips_loongson_3a: u64 = 3003; pub const bfd_mach_mips_sb1: u64 = 12310201 /* octal 'SB', 01 */; pub const bfd_mach_mips_octeon: u64 = 6501; pub const bfd_mach_mips_octeonp: u64 = 6601; pub const bfd_mach_mips_octeon2: u64 = 6502; pub const bfd_mach_mips_octeon3: u64 = 6503; pub const bfd_mach_mips_xlr: u64 = 887682 /* decimal 'XLR' */; pub const bfd_mach_mips_interaptiv_mr2: u64 = 736550 /* decimal 'IA2' */; pub const bfd_mach_mipsisa32: u64 = 32; pub const bfd_mach_mipsisa32r2: u64 = 33; pub const bfd_mach_mipsisa32r3: u64 = 34; pub const bfd_mach_mipsisa32r5: u64 = 36; pub const bfd_mach_mipsisa32r6: u64 = 37; pub const bfd_mach_mipsisa64: u64 = 64; pub const bfd_mach_mipsisa64r2: u64 = 65; pub const bfd_mach_mipsisa64r3: u64 = 66; pub const bfd_mach_mipsisa64r5: u64 = 68; pub const bfd_mach_mipsisa64r6: u64 = 69; pub const bfd_mach_mips_micromips: u64 = 96; pub const bfd_mach_i386_intel_syntax: u64 = (1 << 0); pub const bfd_mach_i386_i8086: u64 = (1 << 1); pub const bfd_mach_i386_i386: u64 = (1 << 2); pub const bfd_mach_x86_64: u64 = (1 << 3); pub const bfd_mach_x64_32: u64 = (1 << 4); pub const bfd_mach_i386_i386_intel_syntax: u64 = (bfd_mach_i386_i386 | bfd_mach_i386_intel_syntax); pub const bfd_mach_x86_64_intel_syntax: u64 = (bfd_mach_x86_64 | bfd_mach_i386_intel_syntax); pub const bfd_mach_x64_32_intel_syntax: u64 = (bfd_mach_x64_32 | bfd_mach_i386_intel_syntax); pub const bfd_mach_l1om: u64 = (1 << 5); pub const bfd_mach_l1om_intel_syntax: u64 = (bfd_mach_l1om | bfd_mach_i386_intel_syntax); pub const bfd_mach_k1om: u64 = (1 << 6); pub const bfd_mach_k1om_intel_syntax: u64 = (bfd_mach_k1om | bfd_mach_i386_intel_syntax); pub const bfd_mach_i386_nacl: u64 = (1 << 7); pub const bfd_mach_i386_i386_nacl: u64 = (bfd_mach_i386_i386 | bfd_mach_i386_nacl); pub const bfd_mach_x86_64_nacl: u64 = (bfd_mach_x86_64 | bfd_mach_i386_nacl); pub const bfd_mach_x64_32_nacl: u64 = (bfd_mach_x64_32 | bfd_mach_i386_nacl); pub const bfd_mach_iamcu: u64 = (1 << 8); pub const bfd_mach_i386_iamcu: u64 = (bfd_mach_i386_i386 | bfd_mach_iamcu); pub const bfd_mach_i386_iamcu_intel_syntax: u64 = (bfd_mach_i386_iamcu | bfd_mach_i386_intel_syntax); pub const bfd_mach_h8300: u64 = 1; pub const bfd_mach_h8300h: u64 = 2; pub const bfd_mach_h8300s: u64 = 3; pub const bfd_mach_h8300hn: u64 = 4; pub const bfd_mach_h8300sn: u64 = 5; pub const bfd_mach_h8300sx: u64 = 6; pub const bfd_mach_h8300sxn: u64 = 7; pub const bfd_mach_ppc: u64 = 32; pub const bfd_mach_ppc64: u64 = 64; pub const bfd_mach_ppc_403: u64 = 403; pub const bfd_mach_ppc_403gc: u64 = 4030; pub const bfd_mach_ppc_405: u64 = 405; pub const bfd_mach_ppc_505: u64 = 505; pub const bfd_mach_ppc_601: u64 = 601; pub const bfd_mach_ppc_602: u64 = 602; pub const bfd_mach_ppc_603: u64 = 603; pub const bfd_mach_ppc_ec603e: u64 = 6031; pub const bfd_mach_ppc_604: u64 = 604; pub const bfd_mach_ppc_620: u64 = 620; pub const bfd_mach_ppc_630: u64 = 630; pub const bfd_mach_ppc_750: u64 = 750; pub const bfd_mach_ppc_860: u64 = 860; pub const bfd_mach_ppc_a35: u64 = 35; pub const bfd_mach_ppc_rs64ii: u64 = 642; pub const bfd_mach_ppc_rs64iii: u64 = 643; pub const bfd_mach_ppc_7400: u64 = 7400; pub const bfd_mach_ppc_e500: u64 = 500; pub const bfd_mach_ppc_e500mc: u64 = 5001; pub const bfd_mach_ppc_e500mc64: u64 = 5005; pub const bfd_mach_ppc_e5500: u64 = 5006; pub const bfd_mach_ppc_e6500: u64 = 5007; pub const bfd_mach_ppc_titan: u64 = 83; pub const bfd_mach_ppc_vle: u64 = 84; pub const bfd_mach_rs6k: u64 = 6000; pub const bfd_mach_rs6k_rs1: u64 = 6001; pub const bfd_mach_rs6k_rsc: u64 = 6003; pub const bfd_mach_rs6k_rs2: u64 = 6002; pub const bfd_mach_hppa10: u64 = 10; pub const bfd_mach_hppa11: u64 = 11; pub const bfd_mach_hppa20: u64 = 20; pub const bfd_mach_hppa20w: u64 = 25; pub const bfd_mach_d10v: u64 = 1; pub const bfd_mach_d10v_ts2: u64 = 2; pub const bfd_mach_d10v_ts3: u64 = 3; pub const bfd_mach_m6812_default: u64 = 0; pub const bfd_mach_m6812: u64 = 1; pub const bfd_mach_m6812s: u64 = 2; pub const bfd_mach_z8001: u64 = 1; pub const bfd_mach_z8002: u64 = 2; pub const bfd_mach_sh: u64 = 1; pub const bfd_mach_sh2: u64 = 0x20; pub const bfd_mach_sh_dsp: u64 = 0x2d; pub const bfd_mach_sh2a: u64 = 0x2a; pub const bfd_mach_sh2a_nofpu: u64 = 0x2b; pub const bfd_mach_sh2a_nofpu_or_sh4_nommu_nofpu: u64 = 0x2a1; pub const bfd_mach_sh2a_nofpu_or_sh3_nommu: u64 = 0x2a2; pub const bfd_mach_sh2a_or_sh4: u64 = 0x2a3; pub const bfd_mach_sh2a_or_sh3e: u64 = 0x2a4; pub const bfd_mach_sh2e: u64 = 0x2e; pub const bfd_mach_sh3: u64 = 0x30; pub const bfd_mach_sh3_nommu: u64 = 0x31; pub const bfd_mach_sh3_dsp: u64 = 0x3d; pub const bfd_mach_sh3e: u64 = 0x3e; pub const bfd_mach_sh4: u64 = 0x40; pub const bfd_mach_sh4_nofpu: u64 = 0x41; pub const bfd_mach_sh4_nommu_nofpu: u64 = 0x42; pub const bfd_mach_sh4a: u64 = 0x4a; pub const bfd_mach_sh4a_nofpu: u64 = 0x4b; pub const bfd_mach_sh4al_dsp: u64 = 0x4d; pub const bfd_mach_sh5: u64 = 0x50; pub const bfd_mach_alpha_ev4: u64 = 0x10; pub const bfd_mach_alpha_ev5: u64 = 0x20; pub const bfd_mach_alpha_ev6: u64 = 0x30; pub const bfd_mach_arm_unknown: u64 = 0; pub const bfd_mach_arm_2: u64 = 1; pub const bfd_mach_arm_2a: u64 = 2; pub const bfd_mach_arm_3: u64 = 3; pub const bfd_mach_arm_3M: u64 = 4; pub const bfd_mach_arm_4: u64 = 5; pub const bfd_mach_arm_4T: u64 = 6; pub const bfd_mach_arm_5: u64 = 7; pub const bfd_mach_arm_5T: u64 = 8; pub const bfd_mach_arm_5TE: u64 = 9; pub const bfd_mach_arm_XScale: u64 = 10; pub const bfd_mach_arm_ep9312: u64 = 11; pub const bfd_mach_arm_iWMMXt: u64 = 12; pub const bfd_mach_arm_iWMMXt2: u64 = 13; pub const bfd_mach_n1: u64 = 1; pub const bfd_mach_n1h: u64 = 2; pub const bfd_mach_n1h_v2: u64 = 3; pub const bfd_mach_n1h_v3: u64 = 4; pub const bfd_mach_n1h_v3m: u64 = 5; pub const bfd_mach_tic3x: u64 = 30; pub const bfd_mach_tic4x: u64 = 40; pub const bfd_mach_v850: u64 = 1; pub const bfd_mach_v850e: u64 = 'E' as u64; pub const bfd_mach_v850e1: u64 = '1' as u64; pub const bfd_mach_v850e2: u64 = 0x4532; pub const bfd_mach_v850e2v3: u64 = 0x45325633; pub const bfd_mach_v850e3v5: u64 = 0x45335635 /* ('E'|'3'|'V'|'5') */; pub const bfd_mach_arc_a4: u64 = 0; pub const bfd_mach_arc_a5: u64 = 1; pub const bfd_mach_arc_arc600: u64 = 2; pub const bfd_mach_arc_arc601: u64 = 4; pub const bfd_mach_arc_arc700: u64 = 3; pub const bfd_mach_arc_arcv2: u64 = 5; pub const bfd_mach_m16c: u64 = 0x75; pub const bfd_mach_m32c: u64 = 0x78; pub const bfd_mach_m32r: u64 = 1 /* For backwards compatibility. */; pub const bfd_mach_m32rx: u64 = 'x' as u64; pub const bfd_mach_m32r2: u64 = '2' as u64; pub const bfd_mach_mn10300: u64 = 300; pub const bfd_mach_am33: u64 = 330; pub const bfd_mach_am33_2: u64 = 332; pub const bfd_mach_fr30: u64 = 0x46523330; pub const bfd_mach_frv: u64 = 1; pub const bfd_mach_frvsimple: u64 = 2; pub const bfd_mach_fr300: u64 = 300; pub const bfd_mach_fr400: u64 = 400; pub const bfd_mach_fr450: u64 = 450; pub const bfd_mach_frvtomcat: u64 = 499 /* fr500 prototype */; pub const bfd_mach_fr500: u64 = 500; pub const bfd_mach_fr550: u64 = 550; pub const bfd_mach_moxie: u64 = 1; pub const bfd_mach_ft32: u64 = 1; pub const bfd_mach_mep: u64 = 1; pub const bfd_mach_mep_h1: u64 = 0x6831; pub const bfd_mach_mep_c5: u64 = 0x6335; pub const bfd_mach_metag: u64 = 1; pub const bfd_mach_ia64_elf64: u64 = 64; pub const bfd_mach_ia64_elf32: u64 = 32; pub const bfd_mach_ip2022: u64 = 1; pub const bfd_mach_ip2022ext: u64 = 2; pub const bfd_mach_iq2000: u64 = 1; pub const bfd_mach_iq10: u64 = 2; pub const bfd_mach_epiphany16: u64 = 1; pub const bfd_mach_epiphany32: u64 = 2; pub const bfd_mach_ms1: u64 = 1; pub const bfd_mach_mrisc2: u64 = 2; pub const bfd_mach_ms2: u64 = 3; pub const bfd_mach_avr1: u64 = 1; pub const bfd_mach_avr2: u64 = 2; pub const bfd_mach_avr25: u64 = 25; pub const bfd_mach_avr3: u64 = 3; pub const bfd_mach_avr31: u64 = 31; pub const bfd_mach_avr35: u64 = 35; pub const bfd_mach_avr4: u64 = 4; pub const bfd_mach_avr5: u64 = 5; pub const bfd_mach_avr51: u64 = 51; pub const bfd_mach_avr6: u64 = 6; pub const bfd_mach_avrtiny: u64 = 100; pub const bfd_mach_avrxmega1: u64 = 101; pub const bfd_mach_avrxmega2: u64 = 102; pub const bfd_mach_avrxmega3: u64 = 103; pub const bfd_mach_avrxmega4: u64 = 104; pub const bfd_mach_avrxmega5: u64 = 105; pub const bfd_mach_avrxmega6: u64 = 106; pub const bfd_mach_avrxmega7: u64 = 107; pub const bfd_mach_bfin: u64 = 1; pub const bfd_mach_cr16: u64 = 1; pub const bfd_mach_cr16c: u64 = 1; pub const bfd_mach_crx: u64 = 1; pub const bfd_mach_cris_v0_v10: u64 = 255; pub const bfd_mach_cris_v32: u64 = 32; pub const bfd_mach_cris_v10_v32: u64 = 1032; pub const bfd_mach_riscv32: u64 = 132; pub const bfd_mach_riscv64: u64 = 164; pub const bfd_mach_rl78: u64 = 0x75; pub const bfd_mach_rx: u64 = 0x75; pub const bfd_mach_s390_31: u64 = 31; pub const bfd_mach_s390_64: u64 = 64; pub const bfd_mach_score3: u64 = 3; pub const bfd_mach_score7: u64 = 7; pub const bfd_mach_xstormy16: u64 = 1; pub const bfd_mach_msp11: u64 = 11; pub const bfd_mach_msp110: u64 = 110; pub const bfd_mach_msp12: u64 = 12; pub const bfd_mach_msp13: u64 = 13; pub const bfd_mach_msp14: u64 = 14; pub const bfd_mach_msp15: u64 = 15; pub const bfd_mach_msp16: u64 = 16; pub const bfd_mach_msp20: u64 = 20; pub const bfd_mach_msp21: u64 = 21; pub const bfd_mach_msp22: u64 = 22; pub const bfd_mach_msp23: u64 = 23; pub const bfd_mach_msp24: u64 = 24; pub const bfd_mach_msp26: u64 = 26; pub const bfd_mach_msp31: u64 = 31; pub const bfd_mach_msp32: u64 = 32; pub const bfd_mach_msp33: u64 = 33; pub const bfd_mach_msp41: u64 = 41; pub const bfd_mach_msp42: u64 = 42; pub const bfd_mach_msp43: u64 = 43; pub const bfd_mach_msp44: u64 = 44; pub const bfd_mach_msp430x: u64 = 45; pub const bfd_mach_msp46: u64 = 46; pub const bfd_mach_msp47: u64 = 47; pub const bfd_mach_msp54: u64 = 54; pub const bfd_mach_xc16x: u64 = 1; pub const bfd_mach_xc16xl: u64 = 2; pub const bfd_mach_xc16xs: u64 = 3; pub const bfd_mach_xgate: u64 = 1; pub const bfd_mach_xtensa: u64 = 1; pub const bfd_mach_z80strict: u64 = 1 /* No undocumented opcodes. */; pub const bfd_mach_z80: u64 = 3 /* With ixl, ixh, iyl, and iyh. */; pub const bfd_mach_z80full: u64 = 7 /* All undocumented instructions. */; pub const bfd_mach_r800: u64 = 11 /* R800: successor with multiplication. */; pub const bfd_mach_lm32: u64 = 1; pub const bfd_mach_tilepro: u64 = 1; pub const bfd_mach_tilegx: u64 = 1; pub const bfd_mach_tilegx32: u64 = 2; pub const bfd_mach_aarch64: u64 = 0; pub const bfd_mach_aarch64_ilp32: u64 = 32; pub const bfd_mach_nios2: u64 = 0; pub const bfd_mach_nios2r1: u64 = 1; pub const bfd_mach_nios2r2: u64 = 2; pub const bfd_mach_visium: u64 = 1; pub const bfd_mach_wasm32: u64 = 1; pub const bfd_mach_pru: u64 = 0; <file_sep>// <NAME> <<EMAIL>> // binutils - build.rs use std::env; use std::ffi; use std::fs::File; use std::io::Read; use std::path; use std::process; extern crate cc; extern crate sha2; use sha2::{Digest, Sha256}; fn execute_command(command: &str, arguments: Vec<&str>) { // Execute a command, and panic on any error let status = process::Command::new(command).args(arguments).status(); match status { Ok(exit) => match exit.success() { true => (), false => panic!( "\n\n \ Error '{}' exited with code {}\n\n", command, exit.code().unwrap() ), }, Err(e) => panic!( "\n\n \ Error with '{}': {}\n\n", command, e ), }; } fn change_dir(directory: &str) { // Go to another directory, and panic on error if !env::set_current_dir(directory).is_ok() { panic!( "\n\n \ Can't change dir to {}' !\n\n", directory ); } } fn hash_file(filename: &str, hash_value: &str) -> bool { // Compute a SHA256 and return true if correct let mut f = File::open(filename).expect("file not found"); let mut hasher = Sha256::new(); loop { let mut buffer = [0; 256]; let len = match f.read(&mut buffer[..]) { Err(_) => return false, Ok(len) => len, }; if len == 0 { break; } hasher.input(&buffer[0..len]); } return format!("{:x}", hasher.result()) == hash_value; } fn build_binutils(version: &str, sha256sum: &str, output_directory: &str, targets: &str) { // Build binutils from source let binutils_name = format!("binutils-{}", version); let filename = format!("{}.tar.gz", binutils_name); let directory_filename = format!("{}/{}", output_directory, filename); // Check if binutils is already built if path::Path::new(&format!("{}/built/", output_directory)).exists() { return; } // Check if the tarball exists, or download it if !path::Path::new(&filename).exists() { execute_command( "curl", vec![ format!("https://ftp.gnu.org/gnu/binutils/{}", filename).as_str(), "--output", &directory_filename, ], ); } // Verify the SHA256 hash if !hash_file(&directory_filename, sha256sum) { panic!( "\n\n \ Incorrect hash value for {} !\n\n", filename ); } // Check if the tarball exists after calling curl if !path::Path::new(&directory_filename).exists() { panic!( "\n\n \ Can't download {} to {} using curl!\n\n", filename, directory_filename ); } // Call tar change_dir(output_directory); if !path::Path::new(&binutils_name).exists() { execute_command("tar", vec!["xzf", &filename]); } // Calls commands to build binutils if path::Path::new(&binutils_name).exists() { change_dir(&binutils_name); let prefix_arg = format!("--prefix={}/built/", output_directory); execute_command( "./configure", vec![&prefix_arg, &format!("--enable-targets={}", targets)], ); execute_command("make", vec!["-j8"]); execute_command("make", vec!["install"]); // Copy useful files execute_command( "cp", vec![ "opcodes/config.h", &format!("{}/built/include/", output_directory), ], ); execute_command( "cp", vec![ "libiberty/libiberty.a", &format!("{}/built/lib/", output_directory), ], ); } } fn main() { let version = "2.29.1"; let sha256 = "0d9d2bbf71e17903f26a676e7fba7c200e581c84b8f2f43e72d875d0e638771c"; // Retrieve targets to build let targets_var = match env::var_os("TARGETS") { Some(dir) => dir, None => ffi::OsString::from("all"), }; let targets = targets_var .as_os_str() .to_str() .expect("Invalid TARGETS content!"); // Get the current working directory let current_dir = env::current_dir().unwrap(); // Where binutils will be built let out_directory = format!("{}/target", current_dir.to_str().unwrap()); // Build binutils build_binutils(version, sha256, &out_directory, targets); // Build our C helpers change_dir(current_dir.to_str().unwrap()); cc::Build::new() .file("src/helpers.c") .include(format!("{}/built/include/", out_directory)) .compile("helpers"); // Locally compiled binutils libraries path println!( "cargo:rustc-link-search=native={}", format!("{}/built/lib/", out_directory) ); println!("cargo:rustc-link-lib=static=bfd"); println!("cargo:rustc-link-lib=static=opcodes"); println!("cargo:rustc-link-lib=static=iberty"); // Link to zlib println!("cargo:rustc-link-search=native=/usr/lib/"); // Arch Linux println!("cargo:rustc-link-search=native=/usr/lib/x86_64-linux-gnu/"); // Debian based println!("cargo:rustc-link-lib=static=z"); } <file_sep>// <NAME> <<EMAIL>> // C based binutils and custom helpers #include <config.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <bfd.h> #include <dis-asm.h> void buffer_to_rust(char *buffer); // Silly macro that helps removing the unused warnings #define UNUSED_VARIABLE(id) id=id /*** Generic helpers ***/ #define BUFFER_SIZE 64 char buffer_asm[BUFFER_SIZE]; void copy_buffer(void* useless, const char* format, ...) { /* Construct the final opcode into buffer_asm */ UNUSED_VARIABLE(useless); va_list ap; va_start(ap, format); vsnprintf(buffer_asm, BUFFER_SIZE, format, ap); va_end(ap); buffer_to_rust(buffer_asm); } void show_buffer(struct disassemble_info *info) { printf("len=%d - vma=%lu\n", info->buffer_length, info->buffer_vma); printf("%p\n", info->buffer); printf("%x\n", info->buffer[0]); printf("%x\n", info->buffer[1]); printf("%x\n", info->buffer[2]); printf("%x\n", info->buffer[3]); } /*** disassemble_info structure helpers ***/ disassemble_info* new_disassemble_info() { /* Return a new structure */ struct disassemble_info *info = malloc (sizeof(struct disassemble_info)); return info; } bfd_boolean configure_disassemble_info(struct disassemble_info *info, asection *section, bfd *bfdFile) { /* Construct and configure the disassembler_info class using stdout */ init_disassemble_info (info, stdout, (fprintf_ftype) copy_buffer); info->arch = bfd_get_arch (bfdFile); info->mach = bfd_get_mach (bfdFile); info->section = section; info->buffer_vma = section->vma; info->buffer_length = section->size; return bfd_malloc_and_get_section (bfdFile, section, &info->buffer); } void configure_disassemble_info_buffer(struct disassemble_info *info, enum bfd_architecture arch, unsigned long mach) { /* A variant of configure_disassemble_info() for buffers */ init_disassemble_info (info, stdout, (fprintf_ftype) copy_buffer); info->arch = arch; info->mach = mach; info->read_memory_func = buffer_read_memory; } typedef void (*print_address_func) (bfd_vma addr, struct disassemble_info *dinfo); void set_print_address_func(struct disassemble_info *info, print_address_func print_function) { info->print_address_func = print_function; } asection* set_buffer(struct disassemble_info *info, bfd_byte* buffer, unsigned int length, bfd_vma vma) { /* Configure the buffet that will be disassembled */ info->buffer = buffer; info->buffer_length = length; info->buffer_vma = vma; asection *section = (asection*) malloc(sizeof(asection)); if (section) { info->section = section; info->section->vma = vma; } return (asection*) section; } asection* get_disassemble_info_section(struct disassemble_info *info) { return info->section; } unsigned long get_disassemble_info_section_vma(struct disassemble_info *info) { return info->section->vma; } void free_disassemble_info(struct disassemble_info *info, bool free_section) { /* Free the structure and allocated variable */ if (info) { if (free_section && info->section) free(info->section); free(info); } } /*** bfd structure helpers ***/ unsigned long get_start_address(bfd *bfdFile) { return bfdFile->start_address; } unsigned int macro_bfd_big_endian(bfd *bfdFile) { return bfd_big_endian(bfdFile); } /*** bfd_arch_info structure helpers ***/ enum bfd_architecture get_arch(struct bfd_arch_info *arch_info) { return arch_info->arch; } unsigned long get_mach(struct bfd_arch_info *arch_info) { return arch_info->mach; } /*** section structure helpers ***/ unsigned long get_section_size(asection *section) { return section->size; } <file_sep>extern crate binutils; use binutils::opcodes::DisassembleInfo; use binutils::utils::disassemble_buffer; #[test] fn compact_loop() { // Prepare the disassembler let mut info = disassemble_buffer("i386", &[0xc3, 0x90, 0x66, 0x90], 0x2800) .unwrap_or(DisassembleInfo::empty()); // Iterate over the instructions loop { match info .disassemble() .ok_or(2807) .map(|i| Some(i.unwrap())) .unwrap_or(None) { Some(instruction) => println!("{}", instruction), None => break, } } } <file_sep>// <NAME> <<EMAIL>> // binutils - instruction.rs use std::fmt; use bfd::Bfd; use helpers; use opcodes::DisassembleInfo; use Error; #[allow(dead_code)] pub struct Instruction<'a> { pub length: u64, pub offset: u64, pub opcode: String, info: Option<&'a mut DisassembleInfo>, pub error: Option<Error>, } impl<'a> fmt::Display for Instruction<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "0x{:X} {}", self.offset, self.opcode) } } pub(crate) fn get_opcode() -> Result<String, Error> { unsafe { let ret = match helpers::CURRENT_OPCODE { None => Err(Error::DisassembleInfoError("Empty opcode!".to_string())), Some(ref opcode) => Ok(opcode.clone()), }; helpers::CURRENT_OPCODE = None; ret } } pub fn get_instruction<'a>(offset: u64, length: u64) -> Result<Instruction<'a>, Error> { Ok(Instruction { offset, length, opcode: get_opcode()?, info: None, error: None, }) } impl<'a> Instruction<'a> { pub fn empty_with_error(error: Option<Error>) -> Instruction<'a> { Instruction { offset: 0, length: 0, opcode: String::new(), info: None, error, } } pub fn from_buffer( info: &'a mut DisassembleInfo, bfd: Bfd, buffer: &[u8], offset: u64, ) -> Instruction<'a> { match info.init_buffer(buffer, bfd, offset) { Ok(_) => (), Err(e) => return Instruction::empty_with_error(Some(e)), }; Instruction { offset: 0, length: 0, opcode: String::new(), info: Some(info), error: None, } } } impl<'a> Iterator for Instruction<'a> { type Item = Instruction<'a>; fn next(&mut self) -> Option<Self::Item> { // Temporarily remove info from the structure let info = match self.info.take() { Some(i) => i, None => { return Some(Instruction::empty_with_error(Some( Error::DisassembleInfoError("empty".to_string()), ))) } }; let i = info.disassemble(); match i { Some(r) => match r { Ok(i) => { self.info = Some(info); Some(i) } Err(_) => None, }, None => None, } } } #[cfg(test)] mod tests { #[test] fn test_no_init() { use instruction; assert!(instruction::get_opcode().is_err()); assert!(instruction::get_instruction(0, 0).is_err()); } #[test] fn test_iterator() { use bfd; use instruction; use opcodes; let mut bfd = bfd::Bfd::empty(); let _ = bfd.set_arch_mach("i386:x86-64"); let mut info = opcodes::DisassembleInfo::new().unwrap(); let buffer = vec![0x90]; let mut instruction = instruction::Instruction::from_buffer(&mut info, bfd, &buffer, 0); match instruction.next() { Some(i) => assert_eq!(i.opcode, "nop"), None => assert!(false), }; } } <file_sep>[package] name = "binutils" version = "0.1.1" build = "build.rs" authors = ["<NAME> <<EMAIL>>"] license = "MIT" readme = "README.md" repository = "https://github.com/guedou/binutils-rs/" description = "A Rust library that ease interacting with the binutils disassembly engine" keywords = ["ffi", "binutils", "disassemble", "reverse"] categories = ["api-bindings", "external-ffi-bindings"] exclude = ["resources/*"] [dependencies] libc = "0.2.40" [build-dependencies] cc = "1.0" sha2 = "0.7.1" <file_sep># Copyright (C) 2018 <NAME> <<EMAIL>> BINUTILS_BUILT_DIR=../../built/ CFLAG_INCLUDES=-I$(BINUTILS_BUILT_DIR)/include/ CFLAGS=-ggdb2 LDFLAGS=-L$(BINUTILS_BUILT_DIR)/lib/ -lbfd -lopcodes -Wl,-rpath,$(BINUTILS_BUILT_DIR)/lib/ TARGETS=test_binary test_buffer_mep test_buffer_x86_64 all: $(TARGETS) .IGNORE: clean clean: @rm $(TARGETS) %: src/%.c gcc -o $@ $^ $(CFLAG_INCLUDES) -ldl -lz $(CFLAGS) $(LDFLAGS) <file_sep># Playing with libfd and libopcodes This directory contains examples that show howto call `binutils` bfd and opcodes libraries from C: 1. [test_binary](examples/src/test_binary.c): this is the example from https://www.toothycat.net/wiki/wiki.pl?Binutils/libopcodes that was adapt to work with binutils 2.29.1 2. [test_buffer_x86_64](examples/src/test_buffer_x86_64.c): this example shows howto disassemble a buffer containing x86 instructions 3. [test_buffer_mep](examples/src/test_buffer_mep.c): similar to the second example with a more exotic architecture and binutils builtins For convenience, the [libbfd](http://htmlpreview.github.com/?https://github.com/guedou/binutils-rs/blob/master/resources/docs/ToothyWiki_%20Binutils_Bfd.html) and [libopcodes](http://htmlpreview.github.com/?https://github.com/guedou/binutils-rs/blob/master/resources/docs/ToothyWiki_%20Binutils_Libopcodes.html) documentation from toothycat.net is archived in this repository. ## Building examples The examples assume that binutils 2.29.1 is built at the root of this repostitory. They can be compiled by typing `make` in the `src/` directory. Here is how binutils dynamic libraries can be installed: ``` curl https://ftp.gnu.org/gnu/binutils/binutils-2.29.1.tar.gz -O tar xzvf binutils-2.29.1.tar.gz cd binutils-2.29.1/ ./configure --prefix=../built --enable-shared --enable-targets=all make -j8 ``` Note: by default binutils does not produce shared libraries. When enabling all targets, the resulting `objdump` binary is 61MB! <file_sep>// <NAME> <<EMAIL>> // binutils libopcodes bindings - opcodes.rs use libc::{c_uint, c_ulong, uintptr_t}; use std; use super::Error; use bfd::{Bfd, BfdRaw}; use helpers; use instruction::{get_instruction, Instruction}; use section::Section; use utils; extern "C" { pub(crate) fn disassembler( arc: c_uint, big_endian: bool, mach: c_ulong, bfd: *const BfdRaw, ) -> extern "C" fn(pc: c_ulong, info: *const DisassembleInfoRaw) -> c_ulong; fn disassemble_init_for_target(dinfo: *const DisassembleInfoRaw); } pub type DisassemblerFunction = dyn Fn(c_ulong, &DisassembleInfo) -> c_ulong; pub(crate) enum DisassembleInfoRaw {} pub struct DisassembleInfo { info: *const DisassembleInfoRaw, free_section: bool, disassembler: Option<Box<DisassemblerFunction>>, pc: u64, } impl DisassembleInfo { pub fn empty() -> DisassembleInfo { DisassembleInfo { info: std::ptr::null(), free_section: false, disassembler: None, pc: 0, } } pub fn new() -> Result<DisassembleInfo, Error> { let new_info = unsafe { helpers::new_disassemble_info() }; if new_info.is_null() { return Err(Error::DisassembleInfoError(String::from( "Error while getting disassemble_info!", ))); } Ok(DisassembleInfo { info: new_info, free_section: false, disassembler: None, pc: 0, }) } pub(crate) fn raw(&self) -> *const DisassembleInfoRaw { self.info } pub fn configure(&self, section: Section, bfd: Bfd) -> Result<(), Error> { utils::check_null_pointer(self.info, "info pointer is null!")?; utils::check_null_pointer(self.raw(), "section pointer is null!")?; utils::check_null_pointer(bfd.raw(), "bfd pointer is null!")?; if !unsafe { helpers::configure_disassemble_info(self.info, section.raw(), bfd.raw()) } { return Err(Error::DisassembleInfoError( "Error while calling configure_disassemble_info() !".to_string(), )); } Ok(()) } pub fn init_buffer(&mut self, buffer: &[u8], bfd: Bfd, offset: u64) -> Result<(), Error> { let disassemble_fn = match bfd.raw_disassembler(bfd.arch_mach.0, false, bfd.arch_mach.1) { Ok(f) => f, Err(e) => return Err(e), }; self.configure_buffer(bfd.arch_mach.0, bfd.arch_mach.1, buffer, offset)?; self.configure_disassembler(disassemble_fn)?; self.init()?; Ok(()) } pub fn configure_buffer( &mut self, arch: c_uint, mach: c_ulong, buffer: &[u8], offset: u64, ) -> Result<(), Error> { utils::check_null_pointer(self.info, "info pointer is null!")?; unsafe { let ptr = buffer.as_ptr(); utils::check_null_pointer(ptr, "buffer pointer is null!")?; let len = buffer.len(); if len == 0 { return Err(Error::DisassembleInfoError( "buffer length is 0!".to_string(), )); }; helpers::configure_disassemble_info_buffer(self.info, arch, mach); if helpers::set_buffer(self.info, ptr, len as u32, offset).is_null() { return Err(Error::DisassembleInfoError( "set_buffer() malloc error!".to_string(), )); } self.free_section = true; } Ok(()) } pub fn init(&self) -> Result<(), Error> { utils::check_null_pointer(self.info, "info pointer is null!")?; unsafe { disassemble_init_for_target(self.info) }; Ok(()) } pub fn set_print_address_func( &self, print_function: extern "C" fn(c_ulong, *const uintptr_t), ) -> Result<(), Error> { utils::check_null_pointer(self.info, "info pointer is null!")?; unsafe { helpers::set_print_address_func(self.info, print_function) } Ok(()) } pub fn configure_disassembler( &mut self, disassembler: Box<DisassemblerFunction>, ) -> Result<(), Error> { if self.info.is_null() { self.pc = 0; self.disassembler = None; return Err(Error::DisassembleInfoError( "info pointer is null!".to_string(), )); } let section_raw = unsafe { helpers::get_disassemble_info_section(self.info) }; utils::check_null_pointer(section_raw, "section pointer is null!")?; self.pc = unsafe { helpers::get_disassemble_info_section_vma(self.info) }; self.disassembler = Some(disassembler); Ok(()) } pub fn disassemble<'a>(&mut self) -> Option<Result<Instruction<'a>, Error>> { let f = match self.disassembler { Some(ref f) => f, None => { return Some(Err(Error::CommonError( "disassembler not configured!".to_string(), ))) } }; let count = f(self.pc, self); if count == 4_294_967_295 { return None; } let instruction = get_instruction(self.pc, count); self.pc += count; Some(instruction) } } impl Drop for DisassembleInfo { fn drop(&mut self) { if !self.info.is_null() { unsafe { helpers::free_disassemble_info(self.info, self.free_section); } self.info = std::ptr::null(); } } } #[cfg(test)] mod tests { #[test] fn test_di_empty() { use bfd; use opcodes; use std; let mut di = opcodes::DisassembleInfo::empty(); assert_eq!(di.info, std::ptr::null()); let mut bfd = bfd::Bfd::empty(); match di.init_buffer(&[0x90], bfd, 0) { Ok(_) => assert!(false), Err(_) => assert!(true), }; let _ = bfd.set_arch_mach("i386:x86-64"); let _ = di.configure_buffer(bfd.arch_mach.0, bfd.arch_mach.1, &[0x90], 1); let disassemble_fn = bfd .raw_disassembler(bfd.arch_mach.0, false, bfd.arch_mach.1) .unwrap(); let _ = di.configure_disassembler(disassemble_fn); } #[test] fn test_configure_null() { // Make sure that configure() test null pointers use bfd; use opcodes; use section; use std; let mut di = opcodes::DisassembleInfo::new().unwrap(); assert_ne!(di.info, std::ptr::null()); let section = section::Section::null(); match di.configure(section, bfd::Bfd::empty()) { Ok(_) => assert!(false), Err(_) => assert!(true), } let section = section::Section::from_raw(0x2807 as *const section::SectionRaw); match di.configure(section.unwrap(), bfd::Bfd::empty()) { Ok(_) => assert!(false), Err(_) => assert!(true), } let mut bfd = bfd::Bfd::empty(); let _ = bfd.set_arch_mach("i386:x86-64"); let _ = di.configure_buffer(bfd.arch_mach.0, bfd.arch_mach.1, &[], 0); } #[test] fn test_configure_disassembler() { use bfd; use opcodes; use std; let mut di = opcodes::DisassembleInfo::new().unwrap(); assert_ne!(di.info, std::ptr::null()); let mut bfd = bfd::Bfd::empty(); let _ = bfd.set_arch_mach("i386:x86-64"); let disassemble_fn = bfd .raw_disassembler(bfd.arch_mach.0, false, bfd.arch_mach.1) .unwrap(); let _ = di.configure_disassembler(disassemble_fn); } } <file_sep>// <NAME> <<EMAIL>> #include <config.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <bfd.h> #include <dis-asm.h> bfd_byte buffer[] = { 0xc3, 0x90, 0x66, 0x90 }; int buffer_len = 4; int buffer_ptr = 0; int copy_buffer(bfd_vma memaddr, bfd_byte *myaddr, unsigned int length, struct disassemble_info *dinfo) { // Copy our buffer to binutils if (length > buffer_len) return 1; memcpy (myaddr, &buffer[buffer_ptr], length); buffer_ptr += length; return 0; } int main(int argc, char** argv) { disassembler_ftype disassemble; struct disassemble_info info; unsigned long count, pc; /* Construct a specific disassembler */ enum bfd_architecture arch = bfd_arch_i386; bfd_boolean big_endian = FALSE; unsigned long mach = bfd_mach_x86_64; disassemble = disassembler (arch, big_endian, mach, NULL); if( disassemble == NULL) { printf ("Error creating disassembler\n"); return EXIT_FAILURE; } /* Construct and configure the disassembler_info structure */ init_disassemble_info (&info, stdout, (fprintf_ftype) fprintf); info.arch = arch; info.mach = mach; info.read_memory_func = copy_buffer; disassemble_init_for_target (&info); /* Disassemble instruction from the buffer */ pc = 0; for (int i=0; i < 3; i++) { printf ("Address: 0x%lx\n", pc); count = disassemble (pc, &info); pc += count; printf ("\nType: 0x%x\n", info.insn_type); printf ("====\n"); } return EXIT_SUCCESS; } <file_sep>// <NAME> <<EMAIL>> // binutils libbfd bindings - bfd.rs use libc::{c_char, c_uint, c_ulong, uintptr_t}; use std; use std::ffi::{CStr, CString}; use helpers::{get_arch, get_mach, get_start_address, macro_bfd_big_endian, CURRENT_OPCODE}; use opcodes::{disassembler, DisassembleInfo, DisassemblerFunction}; use section::{Section, SectionRaw}; use utils; use Error; extern "C" { fn bfd_init(); pub fn bfd_get_error() -> c_uint; pub fn bfd_errmsg(error_tag: c_uint) -> *const c_char; fn bfd_openr(filename: *const c_char, target: *const c_char) -> *const BfdRaw; fn bfd_check_format(bfd: *const BfdRaw, bfd_format: BfdFormat) -> bool; fn bfd_get_section_by_name(bfd: *const BfdRaw, name: *const c_char) -> *const SectionRaw; fn bfd_arch_list() -> *const uintptr_t; fn bfd_scan_arch(string: *const c_char) -> *const c_uint; fn bfd_get_arch(bfd: *const BfdRaw) -> c_uint; fn bfd_get_mach(bfd: *const BfdRaw) -> c_ulong; } // Rust bfd types // Note: - trick from https://doc.rust-lang.org/nomicon/ffi.html // - it allows to use the Rust type checker pub(crate) enum BfdRaw {} #[derive(Clone, Copy)] pub struct Bfd { bfd: *const BfdRaw, pub arch_mach: (u32, u64), } impl Bfd { pub(crate) fn raw(&self) -> *const BfdRaw { self.bfd } pub fn empty() -> Bfd { unsafe { bfd_init() }; Bfd { bfd: std::ptr::null(), arch_mach: (0, 0), } } pub fn openr(filename: &str, target: &str) -> Result<Bfd, Error> { unsafe { bfd_init() }; let filename_cstring = CString::new(filename)?; let target_cstring = CString::new(target)?; let bfd = unsafe { bfd_openr(filename_cstring.as_ptr(), target_cstring.as_ptr()) }; if bfd.is_null() { return Err(bfd_convert_error()); }; Ok(Bfd { bfd, arch_mach: (0, 0), }) } pub fn check_format(&self, format: BfdFormat) -> Result<(), Error> { utils::check_null_pointer(self.bfd, "bfd pointer is null!")?; if !unsafe { bfd_check_format(self.bfd, format) } { return Err(bfd_convert_error()); }; Ok(()) } pub fn get_section_by_name(&self, section_name: &str) -> Result<Section, Error> { utils::check_null_pointer(self.bfd, "bfd pointer is null!")?; let section_name_cstring = CString::new(section_name)?; let section = unsafe { bfd_get_section_by_name(self.bfd, section_name_cstring.as_ptr()) }; if section.is_null() { return Err(Error::SectionError(section_name.to_string())); }; Ok(Section::from_raw(section)?) } pub fn disassembler(&self) -> Result<Box<DisassemblerFunction>, Error> { utils::check_null_pointer(self.bfd, "bfd pointer is null!")?; let arch = unsafe { bfd_get_arch(self.bfd) }; let big_endian = match self.is_big_endian() { Ok(be) => be, Err(e) => return Err(e), }; let mach = unsafe { bfd_get_mach(self.bfd) }; self.raw_disassembler(arch, big_endian, mach) } pub fn raw_disassembler( &self, arch: c_uint, big_endian: bool, mach: c_ulong, ) -> Result<Box<DisassemblerFunction>, Error> { let disassemble = unsafe { disassembler(arch, big_endian, mach, self.bfd) }; if (disassemble as *const c_uint).is_null() { return Err(Error::BfdError( 0, String::from("Error creating disassembler!"), )); }; let disassemble_closure = move |p: c_ulong, di: &DisassembleInfo| -> c_ulong { // Reset the buffer pointer unsafe { CURRENT_OPCODE = None; } disassemble(p, di.raw()) }; Ok(Box::new(disassemble_closure)) } pub fn get_start_address(&self) -> Result<c_ulong, Error> { utils::check_null_pointer(self.bfd, "bfd pointer is null!")?; Ok(unsafe { get_start_address(self.bfd) }) } pub fn is_big_endian(&self) -> Result<bool, Error> { utils::check_null_pointer(self.bfd, "bfd pointer is null!")?; Ok(unsafe { macro_bfd_big_endian(self.bfd) }) } pub fn set_arch_mach(&mut self, arch: &str) -> Result<(u32, u64), Error> { let arch_cstring = CString::new(arch)?; let arch_info = unsafe { bfd_scan_arch(arch_cstring.as_ptr()) }; if arch_info.is_null() { return Err(Error::BfdError(0, "architecture not found!".to_string())); }; self.arch_mach = unsafe { (get_arch(arch_info), get_mach(arch_info)) }; Ok(self.arch_mach) } } pub fn arch_list() -> Vec<String> { let mut ret_vec = Vec::new(); let mut index = 0; let mut stop = false; let list = unsafe { bfd_arch_list() }; if list.is_null() { return ret_vec; } loop { let slice = unsafe { std::slice::from_raw_parts(list.offset(index), 32) }; for item in slice.iter().take(32) { if *item == 0 { stop = true; break; } let arch = unsafe { CStr::from_ptr(*item as *const i8).to_str() }; match arch { Ok(s) => ret_vec.push(s.to_string()), Err(_) => ret_vec.push("arch_list() - from_ptr() error !".to_string()), } } if stop { break; } else { index += 32; } } unsafe { libc::free(list as *mut libc::c_void); } ret_vec } fn bfd_convert_error() -> Error { let error = unsafe { bfd_get_error() }; let msg_char = unsafe { bfd_errmsg(error) }; let msg_str = match unsafe { CStr::from_ptr(msg_char).to_str() } { Ok(s) => s, Err(e) => return Error::Utf8Error(e), }; Error::BfdError(error, msg_str.to_string()) } #[allow(non_camel_case_types)] // use the same enum names as libbfd #[allow(dead_code)] // don't warn that some variants are not used #[repr(C)] pub enum BfdFormat { bfd_unknown = 0, bfd_object, bfd_archive, bfd_core, bfd_type_end, } #[cfg(test)] mod tests { #[test] fn test_bfd_empty() { use bfd; use std; let bfd = bfd::Bfd::empty(); assert_eq!(bfd.bfd, std::ptr::null()); assert_eq!(bfd.arch_mach, (0, 0)); match bfd.get_start_address() { Ok(_) => assert!(false), Err(_) => assert!(true), }; match bfd.is_big_endian() { Ok(_) => assert!(false), Err(_) => assert!(true), }; } #[test] fn test_bfd_openr() { use bfd; use std; use Error; let raw_binary_name = b"bin\0name".to_vec(); let binary_name = unsafe { std::str::from_utf8_unchecked(&raw_binary_name) }; match bfd::Bfd::openr(binary_name, "elf64-x86-64") { Ok(_) => assert!(false), Err(Error::NulError(_)) => assert!(true), Err(_) => assert!(false), }; match bfd::Bfd::openr("/bin/ls", "elf64-x86-64") { Ok(_) => assert!(true), Err(_) => assert!(false), }; match bfd::Bfd::openr("", "") { Ok(_) => assert!(false), Err(Error::BfdError(_, _)) => assert!(true), Err(_) => assert!(false), }; } #[test] fn test_bfd_get_section_bad() { use bfd; use std; use Error; let bfd = bfd::Bfd::openr("/bin/ls", "elf64-x86-64").unwrap(); let raw_section_name = b".\0text".to_vec(); let section_name = unsafe { std::str::from_utf8_unchecked(&raw_section_name) }; match bfd.get_section_by_name(section_name) { Ok(_) => assert!(false), Err(Error::NulError(_)) => assert!(true), Err(_) => assert!(false), } match bfd.get_section_by_name("unknown") { Ok(_) => assert!(false), Err(Error::SectionError(_)) => assert!(true), Err(_) => assert!(false), } } #[test] fn test_bfd_get_section_good() { use bfd; let bfd = bfd::Bfd::openr("/bin/ls", "elf64-x86-64").unwrap(); bfd.check_format(bfd::BfdFormat::bfd_object).unwrap(); match bfd.get_section_by_name(".text") { Ok(section) => { assert!(!section.raw().is_null()); assert!(section.get_size().unwrap() > 0); } Err(_) => assert!(false), }; assert!(bfd.get_start_address().is_ok()); assert!(!bfd.is_big_endian().unwrap_or(true)); } #[test] fn test_bfd_arch_list() { use bfd; assert_eq!(bfd::arch_list()[0..2].len(), 2); } #[test] fn test_bfd_disassemble() { use bfd; use opcodes; let bfd = bfd::Bfd::openr("/bin/ls", "elf64-x86-64").unwrap(); bfd.check_format(bfd::BfdFormat::bfd_object).unwrap(); let section = bfd.get_section_by_name(".text").unwrap(); let info = match opcodes::DisassembleInfo::new() { Ok(i) => i, Err(_) => { assert!(false); return; } }; match info.configure(section, bfd) { Ok(_) => assert!(true), Err(_) => assert!(false), }; } } <file_sep>// <NAME> <<EMAIL>> #include <config.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <bfd.h> #include <dis-asm.h> bfd_byte buffer[] = { 0x53, 0x53, 0x08, 0xd8, 0x01, 0x00, 0x53, 0x53, 0x30, 0xeb, 0x5b, 0x00 }; unsigned int buffer_len = 12; int main (int argc, char ** argv) { bfd *bfdFile; asection *section; disassembler_ftype disassemble; struct disassemble_info info; unsigned long count, pc; /* Open /dev/null as a binary target with libbfd */ bfdFile = bfd_openr ("/dev/null", "binary"); if (bfdFile == NULL) { printf ("Error [%x]: %s\n", bfd_get_error (), bfd_errmsg (bfd_get_error ())); return EXIT_FAILURE; } /* Check the file format */ if (!bfd_check_format (bfdFile, bfd_object)) { printf ("Error [%x]: %s\n", bfd_get_error (), bfd_errmsg (bfd_get_error ())); return EXIT_FAILURE; } /* Retrieve the ELF .data code section */ section = bfd_get_section_by_name (bfdFile, ".data"); if (section == NULL) { printf ("Error accessing .text section\n"); return EXIT_FAILURE; } /* Configure a MeP disassembler */ enum bfd_architecture arch = bfd_arch_mep; bfd_boolean big_endian = BFD_ENDIAN_BIG; unsigned long mach = bfd_mach_mep; bfd_default_set_arch_mach(bfdFile, arch, mach); disassemble = disassembler (bfd_get_arch (bfdFile), bfd_big_endian (bfdFile), bfd_get_mach (bfdFile), bfdFile); if( disassemble == NULL) { printf ("Error creating disassembler\n" ); return EXIT_FAILURE; } /* Construct and configure the disassembler_info structure */ init_disassemble_info (&info, stdout, (fprintf_ftype) fprintf); info.arch = bfd_get_arch (bfdFile); info.mach = bfd_get_mach (bfdFile); info.section = section; /* Configure buffer information */ section->vma = 0xC00000; // memory offset info.read_memory_func = buffer_read_memory; // builtin info.buffer_length = buffer_len; info.buffer = (bfd_byte*) &buffer; info.buffer_vma = section->vma; /* Initialize the disassembler_info structure */ disassemble_init_for_target (&info); /* Diassemble instructions */ pc = section->vma; for (int i=0; i < 4; i++) { printf ("Address: 0x%lx\n ", pc); count = disassemble (pc, &info); pc += count; printf ("\n====\n"); fflush (stdout); } return EXIT_SUCCESS; } <file_sep># binutils-rs A Rust library that ease interacting with the [binutils](https://www.gnu.org/software/binutils/) disassembly engine with a high-level API. Its main goal is to simplify disassembling raw buffers into instructions. [![crates.io badge](https://img.shields.io/crates/v/binutils.svg)](https://crates.io/crates/binutils/) [![doc.rs badge](https://docs.rs/binutils/badge.svg)](https://docs.rs/crate/binutils/) ## Usage You need to add the following lines to your `Cargo.toml`: ```toml [dependencies] binutils = "0.1.1" ``` and make sure that your are using it in your code: ```rust extern crate binutils; ``` > **Note:** By default, all architectures supported by binutils will be built by cargo. The resulting library will be over 60MB. When size is an issue, the `TARGETS` environment variable can be set to only build specific architectures (i.e. `TARGETS=arm-linux,mep`) as defined in `bfd/config.bfd`. > ## Examples Here is how to disassemble a buffer containing x86 instructions while being gentle with errors: ```rust extern crate binutils; use binutils::utils::disassemble_buffer; use binutils::opcodes::DisassembleInfo; // Prepare the disassembler let mut info = disassemble_buffer("i386", &[0xc3, 0x90, 0x66, 0x90], 0x2800) .unwrap_or(DisassembleInfo::empty()); // Iterate over the instructions loop { match info.disassemble() .ok_or(2807) .map(|i| Some(i.unwrap())) .unwrap_or(None) { Some(instruction) => println!("{}", instruction), None => break, } } ``` Other examples are located in the [examples/](examples) directory, and be used with `cargo run --example`. ## Resources Examples in C and archived documentations are available in the [resources/](resources/) directory. ## Roadmap - [ ] add Travis support: test and rustfmt - [ ] code coverage with tarpaulin - [ ] write more tests - [ ] investigate stripping libraries - [ ] convert check_null_pointer() to a macro to add file and line numbers to the Error - [ ] fuzz the disassembler - [ ] generate mach.rs with build.rs - [ ] generate documentation from comments - [ ] use the error_chain crate - [ ] investigate info->stop_vma - [ ] rewrite copy_buffer in Rust <file_sep>// <NAME> <<EMAIL>> // binutils - utils.rs use bfd::{arch_list, Bfd}; use helpers; use opcodes::DisassembleInfo; use Error; pub fn disassemble_buffer( arch_name: &str, buffer: &[u8], offset: u64, ) -> Result<DisassembleInfo, Error> { // Create a bfd structure let mut bfd = Bfd::empty(); // Check if the architecture is supported if !arch_list().iter().any(|arch| arch == arch_name) { let error = Error::CommonError(format!("Unsupported architecture ({})!", arch_name)); return Err(error); } // Set bfd_arch and bfd_mach from the architecture name let _ = bfd.set_arch_mach(arch_name); // Create a disassemble_info structure let mut info = DisassembleInfo::new()?; // Configure the disassemble_info structure info.init_buffer(buffer, bfd, offset)?; Ok(info) } pub(crate) fn check_null_pointer<T>(pointer: *const T, message: &str) -> Result<(), Error> { if pointer.is_null() { Err(Error::NullPointerError(message.to_string())) } else { Ok(()) } } pub fn opcode_buffer_append(string: &str) { unsafe { let tmp = match helpers::CURRENT_OPCODE { Some(ref o) => o, None => "", }; helpers::CURRENT_OPCODE = Some(format!("{}{}", tmp, string)); } } #[cfg(test)] mod tests { #[test] fn test_opcode_buffer_append() { use helpers; use utils; unsafe { helpers::CURRENT_OPCODE = None; utils::opcode_buffer_append("te"); assert_eq!(helpers::CURRENT_OPCODE, Some("te".to_string())); utils::opcode_buffer_append("st!"); assert_eq!(helpers::CURRENT_OPCODE, Some("test!".to_string())); helpers::CURRENT_OPCODE = None; } } } <file_sep>// <NAME> <<EMAIL>> // binutils bindings to helpers.c - helpers.rs #![doc(hidden)] use std::ffi::CStr; use libc::{c_char, c_uchar, c_uint, c_ulong, uintptr_t}; use bfd::BfdRaw; use opcodes::DisassembleInfoRaw; use section::SectionRaw; extern "C" { // libbfd helpers pub(crate) fn macro_bfd_big_endian(bfd: *const BfdRaw) -> bool; pub(crate) fn get_start_address(bfd: *const BfdRaw) -> c_ulong; pub(crate) fn get_arch(arch_info: *const c_uint) -> u32; pub(crate) fn get_mach(arch_info: *const c_uint) -> u64; // libopcodes helpers pub(crate) fn new_disassemble_info() -> *const DisassembleInfoRaw; pub(crate) fn configure_disassemble_info( info: *const DisassembleInfoRaw, section: *const SectionRaw, bfd: *const BfdRaw, ) -> bool; pub(crate) fn configure_disassemble_info_buffer( info: *const DisassembleInfoRaw, arch: c_uint, mach: c_ulong, ); pub(crate) fn set_print_address_func( info: *const DisassembleInfoRaw, print_function: extern "C" fn(c_ulong, *const uintptr_t), ); pub(crate) fn set_buffer( info: *const DisassembleInfoRaw, buffer: *const c_uchar, length: c_uint, vma: c_ulong, ) -> *const SectionRaw; pub(crate) fn free_disassemble_info(info: *const DisassembleInfoRaw, free_section: bool); pub(crate) fn get_disassemble_info_section( info: *const DisassembleInfoRaw, ) -> *const DisassembleInfoRaw; pub(crate) fn get_disassemble_info_section_vma(info: *const DisassembleInfoRaw) -> c_ulong; // Custom helpers #[allow(dead_code)] pub(crate) fn show_buffer(info: *const DisassembleInfoRaw); } pub(crate) static mut CURRENT_OPCODE: Option<String> = None; /// # Safety /// /// This function is used to copy the disassembly buffer to a static variable #[no_mangle] pub unsafe extern "C" fn buffer_to_rust(buffer: *const c_char) { let buffer_cstr = CStr::from_ptr(buffer); let current_string = match CURRENT_OPCODE { Some(ref o) => o, None => "", }; let new_string = match buffer_cstr.to_str() { Ok(s) => s.to_string(), Err(e) => format!("buffer_to_rust() - {}", e), }; CURRENT_OPCODE = Some(format!("{}{}", current_string, new_string)); } <file_sep>// <NAME> <<EMAIL>> #include <config.h> #include <stdlib.h> #include <string.h> #include <bfd.h> #include <dis-asm.h> void override_print_address(bfd_vma addr, struct disassemble_info *info) { // This function change how addresses are displayed printf ("0x%x", addr); } int main(int argc, char **argv) { bfd *bfdFile; asection *section; disassembler_ftype disassemble; struct disassemble_info info; unsigned long count, pc; /* Open an ELF binary with libbfd */ bfd_init (); bfdFile = bfd_openr ("/bin/ls", "elf64-x86-64"); if (bfdFile == NULL) { printf ("Error [%x]: %s\n", bfd_get_error (), bfd_errmsg (bfd_get_error ())); return EXIT_FAILURE; } if (!bfd_check_format( bfdFile, bfd_object)) { printf ("Error [%x]: %s\n", bfd_get_error (), bfd_errmsg (bfd_get_error ())); return EXIT_FAILURE; } /* Retrieve the ELF .text code section */ section = bfd_get_section_by_name (bfdFile, ".text"); if (section == NULL) { printf ("Error accessing .text section\n"); return EXIT_FAILURE; } /* Get a disassemble function pointer */ disassemble = disassembler (bfd_get_arch (bfdFile), bfd_big_endian (bfdFile), bfd_get_mach (bfdFile), bfdFile); if (disassemble == NULL) { printf ("Error creating disassembler\n"); return EXIT_FAILURE; } /* Construct and configure the disassembler_info class */ init_disassemble_info (&info, stdout, (fprintf_ftype) fprintf); info.print_address_func = override_print_address; info.arch = bfd_get_arch (bfdFile); info.mach = bfd_get_mach (bfdFile); info.buffer_vma = section->vma; info.buffer_length = section->size; info.section = section; bfd_malloc_and_get_section (bfdFile, section, &info.buffer); disassemble_init_for_target (&info); /* Start diassembling */ pc = bfd_get_start_address (bfdFile); do { printf ("0x%x ", pc); count = disassemble (pc, &info); pc += count; printf ("\n"); } while (count > 0 && pc <= section->size); return EXIT_SUCCESS; } <file_sep>// <NAME> <<EMAIL>> // binutils - section.rs use libc::c_ulong; use std::ptr; use utils; use Error; extern "C" { fn get_section_size(section: *const SectionRaw) -> c_ulong; } pub enum SectionRaw {} #[derive(Clone, Copy)] pub struct Section { pub section: *const SectionRaw, } impl Section { #[allow(dead_code)] pub(crate) fn null() -> Section { Section { section: ptr::null(), } } pub(crate) fn raw(self) -> *const SectionRaw { self.section } pub fn from_raw(section_raw: *const SectionRaw) -> Result<Section, Error> { utils::check_null_pointer(section_raw, "raw section pointer is null!")?; Ok(Section { section: section_raw, }) } pub fn get_size(self) -> Result<c_ulong, Error> { utils::check_null_pointer(self.section, "section pointer is null!")?; Ok(unsafe { get_section_size(self.section) }) } } <file_sep>// <NAME> <<EMAIL>> // binutils - test_binary.rs extern crate libc; use libc::{c_ulong, uintptr_t}; extern crate binutils; use binutils::bfd; use binutils::instruction; use binutils::opcodes::DisassembleInfo; use binutils::utils; extern "C" fn change_address(addr: c_ulong, _info: *const uintptr_t) { // Example of C callback that modifies an address used by an instruction // Format the address and copy it to the buffer utils::opcode_buffer_append(&format!("0x{:x}", addr)); } fn test_ls(max_instructions: Option<u8>) { println!("From an ELF"); let bfd = match bfd::Bfd::openr("/bin/ls", "elf64-x86-64") { Ok(b) => b, Err(e) => { println!("Error with openr() - {}", e); return; } }; match bfd.check_format(bfd::BfdFormat::bfd_object) { Ok(_) => (), Err(e) => { println!("Error with check_format() - {}", e); return; } }; // Retrieve the .text code section let section = match bfd.get_section_by_name(".text") { Ok(s) => s, Err(e) => { println!("Error with get_section_by_name() - {}", e); return; } }; // Construct disassembler_ftype class let disassemble = match bfd.disassembler() { Ok(d) => d, Err(e) => { println!("Error with disassembler() - {}", e); return; } }; // Create a disassemble_info structure let info = match DisassembleInfo::new() { Ok(i) => i, Err(e) => { println!("{}", e); return; } }; // Configure the disassemble_info structure match info.configure(section, bfd) { Ok(_) => (), Err(e) => { println!("Error configure() - {}", e); return; } }; match info.set_print_address_func(change_address) { Ok(_) => (), Err(e) => { println!("Error set_print_address_func() - {}", e); return; } }; match info.init() { Ok(_) => (), Err(e) => { println!("Error init() - {}", e); return; } }; // Disassemble the binary let mut pc = match bfd.get_start_address() { Ok(a) => a, Err(e) => { println!("Error with get_start_address() - {}", e); return; } }; let section_size = match section.get_size() { Ok(a) => a, Err(e) => { println!("Error with get_size() - {}", e); return; } }; let mut counter = 0; loop { let length = disassemble(pc, &info); let instruction = match instruction::get_instruction(pc, length) { Ok(i) => i, Err(e) => { println!("{}", e); return; } }; println!("{}", instruction); pc += length; counter += 1; if !(length > 0 && pc <= section_size) { break; } if !max_instructions.is_none() && max_instructions.unwrap() <= counter { break; } } } fn main() { test_ls(Some(12)); } <file_sep>// <NAME> <<EMAIL>> // binutils - test_buffer.rs extern crate binutils; use binutils::bfd; use binutils::instruction; use binutils::instruction::Instruction; use binutils::opcodes::DisassembleInfo; use binutils::utils; fn test_buffer_full(arch_name: &str, buffer: Vec<u8>, offset: u64) { println!("---"); println!("From a buffer (full API) - {}", arch_name); let mut bfd = bfd::Bfd::empty(); if !bfd::arch_list().iter().any(|arch| arch == arch_name) { println!("Unsuported architecture ({})!", arch_name); return; } // Retrieve bfd_arch and bfd_mach from the architecture name let bfd_arch_mach = match bfd.set_arch_mach(arch_name) { Ok(arch_mach) => arch_mach, Err(e) => { println!("Error with set_arch_mach() - {}", e); return; } }; // Construct disassembler_ftype class let disassemble = match bfd.raw_disassembler(bfd_arch_mach.0, false, bfd_arch_mach.1) { Ok(d) => d, Err(e) => { println!("Error with raw_disassembler() - {}", e); return; } }; // Create a disassemble_info structure let mut info = match DisassembleInfo::new() { Ok(i) => i, Err(e) => { println!("{}", e); return; } }; // Configure the disassemble_info structure match info.configure_buffer(bfd_arch_mach.0, bfd_arch_mach.1, &buffer, offset) { Ok(_) => (), Err(e) => { println!("configure_buffer() - {}", e); return; } }; match info.init() { Ok(_) => (), Err(e) => { println!("Error init() - {}", e); return; } }; // Disassemble the buffer let mut pc = offset; for _i in 0..3 { let length = disassemble(pc, &info); let instruction = match instruction::get_instruction(pc, length) { Ok(i) => i, Err(e) => { println!("{}", e); return; } }; println!("{}", instruction); pc += length; } } fn test_buffer_compact(arch_name: &str, buffer: Vec<u8>, offset: u64) { println!("---"); println!("From a buffer (compact API) - {}", arch_name); let mut bfd = bfd::Bfd::empty(); if !bfd::arch_list().iter().any(|arch| arch == arch_name) { println!("Unsuported architecture ({})!", arch_name); return; } // Set bfd_arch and bfd_mach from the architecture name let _ = bfd.set_arch_mach(arch_name); // Create a disassemble_info structure let mut info = match DisassembleInfo::new() { Ok(i) => i, Err(e) => { println!("{}", e); return; } }; // Configure the disassemble_info structure match info.init_buffer(&buffer, bfd, offset) { Ok(_) => (), Err(e) => { println!("init_buffer() - {}", e); return; } }; // Disassemble the buffer loop { let instruction = match info.disassemble() { None => break, Some(i) => match i { Ok(i) => i, Err(e) => { println!("disassemble() - {}", e); break; } }, }; println!("{}", instruction); } } fn test_buffer_utils(arch_name: &str, buffer: Vec<u8>, offset: u64) { println!("---"); println!("From a buffer (binutils::utils) - {}", arch_name); let mut info = match utils::disassemble_buffer(arch_name, &buffer, offset) { Ok(i) => i, Err(e) => { println!("{}", e); return; } }; // Disassemble the buffer loop { let instruction = match info.disassemble() { None => break, Some(i) => match i { Ok(i) => i, Err(e) => { println!("disassemble() - {}", e); break; } }, }; println!("{}", instruction); } } fn test_buffer_iter(arch_name: &str, buffer: Vec<u8>, offset: u64) { println!("---"); println!("From a buffer (iter) - {}", arch_name); let mut bfd = bfd::Bfd::empty(); if !bfd::arch_list().iter().any(|arch| arch == arch_name) { println!("Unsuported architecture ({})!", arch_name); return; } // Set bfd_arch and bfd_mach from the architecture name let _ = bfd.set_arch_mach(arch_name); // Create a disassemble_info structure let mut info = match DisassembleInfo::new() { Ok(i) => i, Err(e) => { println!("{}", e); return; } }; // Disassemble the buffer using an iterator for instruction in Instruction::from_buffer(&mut info, bfd, &buffer, offset) { println!("{}", instruction); } } fn main() { test_buffer_full("i386:x86-64", vec![0xc3, 0x90, 0x66, 0x90], 0xA00); test_buffer_compact( "mep", vec![ 0x53, 0x53, 0x08, 0xd8, 0x01, 0x00, 0x53, 0x53, 0x30, 0xeb, 0x5b, 0x00, ], 0xC00000, ); test_buffer_utils( "mep", vec![ 0x53, 0x53, 0x08, 0xd8, 0x01, 0x00, 0x53, 0x53, 0x30, 0xeb, 0x5b, 0x00, ], 0xC00000, ); test_buffer_iter( "mep", vec![ 0x53, 0x53, 0x08, 0xd8, 0x01, 0x00, 0x53, 0x53, 0x30, 0xeb, 0x5b, 0x00, ], 0xC00000, ); } <file_sep>// <NAME> <<EMAIL>> // binutils - lib.rs pub mod bfd; pub mod helpers; pub mod instruction; pub mod mach; pub mod opcodes; pub mod section; pub mod utils; extern crate libc; use std::fmt; // Specific errors #[derive(Debug)] pub enum Error { BfdError(u32, String), DisassembleInfoError(String), SectionError(String), CommonError(String), NulError(String), Utf8Error(std::str::Utf8Error), NullPointerError(String), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::BfdError(tag, ref msg) => write!(f, "{} ({})", msg, tag), Error::DisassembleInfoError(ref msg) => write!(f, "{}", msg), Error::SectionError(ref section) => write!(f, "Can't find '{}' section!", section), Error::CommonError(ref msg) => write!(f, "{}", msg), Error::NulError(ref error) => write!(f, "{}", error), Error::Utf8Error(ref error) => write!(f, "{}", error), Error::NullPointerError(ref error) => write!(f, "{}", error), } } } // Needed to use the ? operator on Cstring::new() impl From<std::ffi::NulError> for Error { fn from(error: std::ffi::NulError) -> Self { Error::NulError(format!("{}", error)) } } // Needed to use the ? operator on Cstring::from_bytes_with_nul() impl From<std::ffi::FromBytesWithNulError> for Error { fn from(error: std::ffi::FromBytesWithNulError) -> Self { Error::NulError(format!("{}", error)) } } // Needed to use the ? operator on Cstr.to_str() impl From<std::str::Utf8Error> for Error { fn from(error: std::str::Utf8Error) -> Self { Error::Utf8Error(error) } }
65192377ac21e3fef0fd472c0b9b5facbbab9bf5
[ "HTML", "TOML", "Markdown", "Makefile", "Rust", "C" ]
21
HTML
adomore/binutils-rs
01769254b92bbd3239fcdb61effdc8f9c4835829
068b03856fccc5f27b2be380ea97700d155d1106
refs/heads/master
<repo_name>rizbo-dev/todolist<file_sep>/src/app/ToDoClass.js import { v4 as uuidv4} from 'uuid'; import {showTodoItem} from './utils/domGeneratorUtil'; export class ToDoClass{ constructor(todoName) { this.id = uuidv4(); this.name = todoName; this.completed = false; } showTodo() { showTodoItem(this); } }<file_sep>/src/app/utils/domGeneratorUtil.js import { getTodosFromLocalStorage, removeTodoFromLocalStorage } from "./localStorageUtil"; export const showTodoItem = (newTodo) => { const todoDiv = document.createElement('div'); todoDiv.setAttribute('data-id',newTodo.id); todoDiv.classList.add('todo-item'); const todoName = document.createElement('div'); todoName.classList.add('item-name'); if (newTodo.completed) { todoName.classList.add('item-name-completed'); } todoName.innerText = newTodo.name; const todoControl = document.createElement('div'); todoControl.classList.add('item-control'); const completeButton = document.createElement('button'); completeButton.classList.add('btn-completed'); const deleteButton = document.createElement('button'); deleteButton.classList.add('btn-uncompleted'); completeButton.innerHTML = '<i class="fas fa-check"></i>'; deleteButton.innerHTML = '<i class="fas fa-times"></i>'; //buttons listeners completeButton.addEventListener('click', () => { if (newTodo.completed) { newTodo.completed = false; todoName.classList.remove('item-name-completed'); } else { newTodo.completed = true; todoName.classList.add('item-name-completed'); } let todosFromLocal = getTodosFromLocalStorage(); todosFromLocal.forEach((todo) => { if (todo.id === newTodo.id) { todo.completed = newTodo.completed; } }); localStorage.removeItem('todos'); localStorage.setItem("todos", JSON.stringify(todosFromLocal)); }); deleteButton.addEventListener('click', () => { let indexToBeRemoved; let todosFromLocal = getTodosFromLocalStorage(); todosFromLocal.forEach((todo,index) => { if (todo.id === newTodo.id) { indexToBeRemoved = index; } }); removeTodoFromLocalStorage(indexToBeRemoved); todoDiv.classList.add("removeTodo"); setTimeout(() => { todoDiv.remove(); },1000); // todoDiv.addEventListener('transitionend', (e) => { // todoDiv.remove(); // }) }); //append todoControl.appendChild(completeButton); todoControl.appendChild(deleteButton); todoDiv.appendChild(todoName); todoDiv.appendChild(todoControl); document.querySelector('.items').appendChild(todoDiv); } <file_sep>/README.md # Todolist ## Second project for Infostud internship ## Installation Todolist requires [Node.js](https://nodejs.org/) to run. Install the dependencies and devDependencies and start the server. ```sh npm install ``` ## Run server (development) ```sh npm start ``` Opens new window in browser at http://localhost:8080/ ## Create production code ```sh npm run build ``` Creates all needed files in dist folder. ```sh cd dist start index.html ``` Opens production code in browser.
d620fcf5e92de7c048e3820e6e62ddb8a8c308c4
[ "JavaScript", "Markdown" ]
3
JavaScript
rizbo-dev/todolist
22a60410dbf3c9a6b2e839e4ca5b68a77f05f1b5
b37dd5bd5e8a62307900f9f671f590e3eb6b649d
refs/heads/master
<repo_name>nyodas/yolo<file_sep>/main.go package main import ( "context" "encoding/json" "log" "net/url" "strings" "time" "cloud.google.com/go/storage" "github.com/spf13/cobra" "google.golang.org/api/iterator" "google.golang.org/api/option" "github.com/coreos/etcd/client" ) func listBucket() (remoteCmdSound []*cobra.Command) { bucketName := "yolo-sound" ctx := context.Background() query := &storage.Query{} client, err := storage.NewClient(ctx,option.WithoutAuthentication()) if err != nil { log.Fatal(err) } it := client.Bucket(bucketName).Objects(ctx,query) for { obj, err := it.Next() if err == iterator.Done { break } if err != nil { log.Printf("listBucket: unable to list bucket %q: %v", bucketName, err) return } if obj.Name == "favicon.ico" { continue } sndName := strings.TrimSuffix(obj.Name,".mp3") sndCmd := cobra.Command{ Use: sndName + "", Short: "Play " + sndName, Run: func(cmd *cobra.Command, args []string) { sound := snd{} sound.SmartUrl(sndName) sound.Play() }, } remoteCmdSound = append(remoteCmdSound, &sndCmd) } return } type snd struct { File string `json:"file"` } func (s *snd) toJson() (string){ jsonByte,err := json.Marshal(s) if err != nil { return "" } return string(jsonByte) } func (s *snd) SmartUrl(sndName string) { sndUrl ,_:= url.Parse(string("https://storage.googleapis.com/yolo-sound/"+ sndName + ".mp3")) s.File = sndUrl.String() } func (s *snd) Play(){ cfg := client.Config{ Endpoints: []string{"https://etcd.snd.wtf"}, Transport: client.DefaultTransport, // set timeout per request to fail fast when the target endpoint is unavailable HeaderTimeoutPerRequest: time.Second, } c, err := client.New(cfg) if err != nil { log.Fatal(err) } kapi := client.NewKeysAPI(c) _, err = kapi.Set(context.Background(), "/yolo_grafana", s.toJson(), nil) if err != nil { log.Fatal(err) } else { // print common key info log.Printf("Set is done, it should begin soon") } } func main() { sndSoundCmds := listBucket() var cmdPrint = &cobra.Command{ Use: "url [url to play]", Short: "Play a sound url on yolo", Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { sound := snd{ File: args[0], } sound.Play() }, } var rootCmd = &cobra.Command{Use: "app"} rootCmd.AddCommand(cmdPrint) for _,cmd := range sndSoundCmds { rootCmd.AddCommand(cmd) } rootCmd.Execute() }
dc331cb0207df490498baf86ece55719e577813b
[ "Go" ]
1
Go
nyodas/yolo
6f5f793c37aa19064010480d5470fcdbe99c7d53
b090f1dae82ce8a2a063f3c62c76c1b4877f5a12
refs/heads/master
<file_sep>#!/usr/bin/env Rscript # Required packages library(tm) library(wordcloud) # Locate and load the Corpus. cname <- file.path("~", "Desktop", "programming", "R", "texts") docs <- Corpus(DirSource(cname)) # Transforms toSpace <- content_transformer(function(x, pattern) gsub(pattern, " ", x)) docs <- tm_map(docs, toSpace, "/|@|\\|") docs <- tm_map(docs, content_transformer(tolower)) docs <- tm_map(docs, removeNumbers) docs <- tm_map(docs, removePunctuation) docs <- tm_map(docs, removeWords, stopwords("english")) docs <- tm_map(docs, stripWhitespace) docs <- tm_map(docs, stemDocument) # Document term matrix. dtm <- DocumentTermMatrix(docs) findFreqTerms(dtm, lowfreq=450) findAssocs(dtm, "data", corlimit=0.8) freq <- sort(colSums(as.matrix(dtm)), decreasing=TRUE) wf <- data.frame(word=names(freq), freq=freq) #set.seed(142) wordcloud(names(freq), freq, min.freq=500, scale=c(5, .1), colors=brewer.pal(6, "Dark2")) <file_sep>library(ggmap) corvallis <- c(lon = -123.2620, lat = 44.5646) # Get map at zoom level 5: map_5 map_5 <- get_map(location = corvallis, zoom = 5, scale = 1) # Plot map at zoom level 5 ggmap(map_5) # Get map at zoom level 13: corvallis_map corvallis_map <- get_map(location = corvallis, zoom = 13, scale = 1) # Plot map at zoom level 13 ggmap(corvallis_map) # Swap out call to ggplot() with call to ggmap() ggmap(corvallis_map) + geom_point(aes(lon, lat), data = sales) # Map color to year_built ggmap(corvallis_map) + geom_point(aes(lon, lat, color=year_built), data = sales) # Map size to bedrooms ggmap(corvallis_map) + geom_point(aes(lon, lat, size=bedrooms), data = sales) # Map color to price / finished_squarefeet ggmap(corvallis_map) + geom_point(aes(lon, lat, color=price/finished_squarefeet), data = sales) corvallis <- c(lon = -123.2620, lat = 44.5646) # Add a maptype argument to get a satellite map corvallis_map_sat <- get_map(corvallis, zoom = 13, maptype = "satellite") #get display satellite map ggmap(corvallis_map_sat) + geom_point(aes(lon, lat, color = year_built), data = sales) # Add source and maptype to get toner map from Stamen Maps corvallis_map_bw <- get_map(corvallis, zoom = 13, source = "stamen", maptype = "toner") # Edit to display toner map ggmap(corvallis_map_bw) + geom_point(aes(lon, lat, color = year_built), data = sales) <file_sep># learnR A repository to learn how to program in R
0a9e8c9160b5d51d08c1dc46387d5164ba3f2f5e
[ "Markdown", "R" ]
3
R
christopherdurr/learnR
47f4c6dfddbf86abbabc3f5b585844e6fed6747c
7c701867ae2d415418bf9f624127ef36734de75f
refs/heads/master
<file_sep># watsonnlu-bubblecloud Spring Boot app which allows user to upload a file and see Watson NLU results for that document in a bubble cloud. Configure your Watson NLU username and password in NLUCredentials.java. App uses Apache Tika to extract text from documents. https://tika.apache.org/1.16/formats.html Excellent resource on bubble cloud by <NAME> here: http://vallandingham.me/building_a_bubble_cloud.html <file_sep>spring.http.multipart.max-file-size=10000000KB spring.http.multipart.max-request-size=10000000KB <file_sep>package com.test.nluvisual.controller; class NLUCredentials { static String USER_NAME = "your-username-here"; static String PASSWORD ="<PASSWORD>"; }
1c013e412ab5d7e46de0d98954a7fb374a95fa7c
[ "Markdown", "Java", "INI" ]
3
Markdown
pavan-tummala/watsonnlu-bubblecloud
530b64137a22c9606ea002195df9e7c7c6b28517
6ecea09c129d900fd3993d0c831d62529f5163a4
refs/heads/master
<file_sep>from flask import Flask, render_template from flask_socketio import SocketIO app = Flask(__name__) app.config['SECRET_KEY'] = 'secret' socketio = SocketIO(app) @app.route('/') def chat(): return render_template('chat.html') def messageRecived(): print('message was received!') @socketio.on('my event') def handle_my_custom_event(json): socketio.emit('my response', json, callback=messageRecived) if __name__ == '__main__': socketio.run(app, debug=True) <file_sep>![language](https://img.shields.io/badge/language-Python-brightgreen.svg?style=flat-square) [![Build Status](https://img.shields.io/travis/enotcode/mypychat/master.svg?style=flat-square)](https://travis-ci.org/enotcode/mypychat) [![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/enotcode/mypychat.svg?style=flat-square)](https://scrutinizer-ci.com/g/enotcode/mypychat/?branch=master) [![License](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](/LICENSE/) # MyPyChat Very simple chat on Flask and Socket.IO # How to start? ``` git clone https://github.com/enotcode/mypychat.git cd mypychat pip install -r requirements.txt python3 server.py ``` # Want to contribute? Just fork and make a pull request – as easy as that ;) # License [MIT](/LICENSE/) <file_sep>from server import app import pytest class Test: def test_homepage(self): with app.test_request_context('/'): assert ("Home page")
4e3ca7b196dc08d15b46def485aeccd035445d78
[ "Markdown", "Python" ]
3
Python
VAFomin/mypychat
cce2c52e31ea4bd3ff16b98af5d33024773b985e
6cca8e0b18fcd6b9b911c3d4c0871624a38a210d
refs/heads/master
<file_sep><?php class Disciplina { /** * @var string */ public $nome; /** * @var string */ private $codigo; /** * @var int */ public $creditos; /** * @var static */ public static $ministrada; public static function ministrarDisciplina() { self::$ministrada++; } public function verDisciplina() { return "{$this->nome} ({$this->codigo}) - {$this->creditos} créditos - " . self::$ministrada; } /** * @return string */ public function getCodigo(): string { return $this->codigo; } /** * @param string $codigo * @return void */ public function setCodigo(string $codigo): void { $this->codigo = $codigo; } } <file_sep><?php declare(strict_types=1); error_reporting(E_ALL); ini_set('display_errors', 'true'); ?> <!doctype html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Sistema de gestão acadêmica</title> </head> <body> <h2>Estudante</h2> <?php require './Pessoa.php'; require './Estudante.php'; require './Professor.php'; require './Disciplina.php'; $estudante = new Estudante('<EMAIL>'); echo $estudante->disciplinasMatriculadas() . '<br>'; echo '<br><hr>'; $estudanteDados = $estudante->verEstudante(); echo "Nome estudante: {$estudanteDados->nome} <br>"; echo "Telefone: {$estudanteDados->telefone} <br>"; echo "Email: {$estudanteDados->email} <br>"; echo "Data nascimento: {$estudanteDados->data_nascimento} <br>"; echo "Idade: {$estudante->calculaIdade($estudanteDados->data_nascimento)} <br>"; echo "Matricula: {$estudanteDados->matricula} <br>"; echo "IRA: {$estudanteDados->ira} <br>"; echo utf8_decode("Avaliação do aluno: {$estudante->calculaAvaliacao()}") . '<br>'; ?> <br> <hr><br> <h2>Disciplinas</h2> <?php $disciplinaMatematica = new Disciplina(); $disciplinaMatematica->nome = 'Matematica'; $disciplinaMatematica->setCodigo('MAT'); $disciplinaMatematica->creditos = 4; Disciplina::ministrarDisciplina(); $matematica = $disciplinaMatematica->verDisciplina(); echo utf8_decode($matematica . PHP_EOL); ?> <br><br> <?php $disciplinaPortugues = new Disciplina(); $disciplinaPortugues->nome = 'Portugues'; $disciplinaPortugues->setCodigo('PORT'); $disciplinaPortugues->creditos = 4; Disciplina::ministrarDisciplina(); echo utf8_decode($disciplinaPortugues->verDisciplina()); ?> <br> <hr><br> <h2>Professor</h2> <?php $conexao = new Connection(); $professores = $conexao->listaProfessores(); foreach ($professores as $professor) { echo utf8_decode($professor['nome']) . " <a href='editarEstudante.php?email={$professor['email']}'>Editar</a><br>"; } ?> </body> </html><file_sep># LAMP Stack * PHP Version 7.3.8 * Apache Version 2.4 * MySQL version 8.0.17 * Redis Version latest ## Installation ```shell git clone https://github.com/cafe-chopp/php-docker-environment.git cd php-docker-environment docker-compose up -d ``` ## Ports from services Stack `Ports` `apache2:8080` `mysql:3306` ## User and password From Services users and passwords and the paths are within .env You can access it via `http://localhost`. ### caso ocorra erros ao conectar com banco de dados: ### entrar dentro do container do mysql e executar comandos $ mysql -u root -p ### digite a senha <PASSWORD> $ ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '<PASSWORD>'; $ ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'root'; ### depois verifique se a conexao ocorreu $ php -r "new PDO('mysql:host=mysql;dbname=api_base', 'root', 'root');" <file_sep><?php declare(strict_types=1); class Connection { private $dsn = 'mysql:unix_socket=/var/run/mysqld/mysqld.sock;host=mysql;port=3306;dbname=api_base'; private $username = 'root'; private $password = '<PASSWORD>'; public $connect = null; private $options = array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', ); public function connect() { try { $this->connect = new PDO($this->dsn, $this->username, $this->password, $this->options); return $this->connect; } catch (PDOException $e) { throw new PDOException($e->getMessage(), (int)$e->getCode()); } catch (Throwable $e) { throw $e; } } /** * @return array * @throws Throwable */ public function listaProfessores(): array { $sql = "SELECT nome, email, especialidade, salario, data_nascimento FROM professor p LEFT JOIN pessoa po on p.pessoa_id = po.ID"; $conectar = $this->connect(); $result = $conectar->prepare($sql); $result->execute(); return $result->fetchAll(); } } <file_sep><!doctype html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Editar Estudante</title> </head> <body> <h1>Edição de Estudante</h1> <?php require './Pessoa.php'; require './Estudante.php'; $estudante = new Estudante($_GET['email']); if (isset($_POST['editarEstudante'])) { $formData = filter_input_array(INPUT_POST, FILTER_DEFAULT); $estudante = new Estudante($formData['email']); $estudanteDados = $estudante->editarEstudante($formData); if ($estudanteDados) { echo "Estudante editado com sucesso!"; echo "<a href='index.php'><br>Voltar</a>"; } else { echo "Ocorreu um problema ao editar Estudante."; } } else { $estudanteDados = $estudante->verEstudante(); ?> <form name="EdicaoEstudante" action="" method="POST"> <input type="hidden" name="id" value="<?= $estudanteDados->ID ?>"> <p> <label>Nome</label> <input type="text" name="nome" required value="<?= $estudanteDados->nome ?>"> </p> <p> <label>Telefone</label> <input type="text" name="telefone" value="<?= $estudanteDados->telefone ?>"> </p> <p> <label>Email</label> <input type="text" name="email" value="<?= $estudanteDados->email ?>"> </p> <p> <label>Data Nascimento</label> <input type="text" name="data_nascimento" value="<?= $estudanteDados->data_nascimento ?>"> </p> <p> <label>Matrícula</label> <input type="text" name="matricula" value="<?= $estudanteDados->matricula ?>"> </p> <input type="submit" value="Editar Estudante" name="editarEstudante"> </form> <?php } ?> <br> </body> </html><file_sep><!doctype html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Cadastro Estudante</title> </head> <body> <h1>Cadastro de Estudante</h1> <?php require './Pessoa.php'; require './Estudante.php'; $formData = filter_input_array(INPUT_POST, FILTER_DEFAULT); if (!empty($formData)) { $estudante = new Estudante($formData['email']); $cadastro = $estudante->criarEstudante($formData); if ($cadastro) { echo "Estudante cadastrado com sucesso!"; } else { echo "Ocorreu um problema ao cadastrar Estudante."; } } ?> <form name="CadastroEstudante" action="" method="POST"> <p> <label>Nome</label> <input type="text" name="nome" required> </p> <p> <label>Telefone</label> <input type="text" name="telefone"> </p> <p> <label>Email</label> <input type="text" name="email"> </p> <p> <label>Data Nascimento</label> <input type="text" name="data_nascimento"> </p> <p> <label>Matrícula</label> <input type="text" name="matricula"> </p> <input type="submit" value="Cadastrar Estudante" name="CadastrarEstudante"> </body> </html><file_sep><?php declare(strict_types=1); class Estudante extends Pessoa { /** * @var string */ public $matricula; /** * @var string */ public $ira; /** * @return string */ public function disciplinasMatriculadas(): string { return "POO - PHP Orientado a Objetos"; } /** * @param int $nota * @return int */ public function atualizaIRA(int $nota): int { $this->ira += $nota; return $this->ira; } /** * @return object * @throws Throwable */ public function verEstudante(): object { $conn = new Connection(); $conectar = $conn->connect(); $sql = "SELECT ID, nome, telefone, email, data_nascimento, matricula, ira FROM api_base.estudante e LEFT JOIN api_base.pessoa p on e.pessoa_id = p.ID WHERE email = :email"; $result = $conectar->prepare($sql); $result->execute(array(':email' => $this->email)); return $result->fetchObject(); } /** * @return float */ public function calculaAvaliacao(): float { $ira = 50; $porcentagemPresenca = 80; return ($ira * $porcentagemPresenca); } public function criarEstudante(array $estudante): bool { $conn = new Connection(); $conexao = $conn->connect(); $sql = "INSERT INTO pessoa(nome, telefone, email, data_nascimento) VALUES(:nome, :telefone, :email, :data_nascimento)"; $result = $conexao->prepare($sql); $result->execute( array( ':nome' => $estudante['nome'], ':telefone' => $estudante['telefone'], ':email' => $estudante['email'], ':data_nascimento' => $estudante['data_nascimento'] ) ); $estudanteId = $conexao->lastInsertId(); if ($estudanteId) { $sql = "INSERT INTO estudante(pessoa_id, matricula) VALUES(:pessoa_id, :matricula)"; $result = $conexao->prepare($sql); $result->execute(array( ':pessoa_id' => $estudanteId, ':matricula' => $estudante['matricula'] )); if ($result->rowCount()) { return true; } else { return false; } } else { return false; } } public function editarEstudante(array $estudante): bool { $conn = new Connection(); $conexao = $conn->connect(); $sql = "UPDATE pessoa SET nome = :nome, telefone = :telefone, email = :email, data_nascimento = :data_nascimento WHERE ID = :id"; $result = $conexao->prepare($sql); $resultStatus = $result->execute(array( ':nome' => $estudante['nome'], ':telefone' => $estudante['telefone'], ':email' => $estudante['email'], ':data_nascimento' => $estudante['data_nascimento'], ':id' => $estudante['id'] )); if ($resultStatus) { $sql = "UPDATE estudante SET matricula = :matricula WHERE pessoa_id = :id"; $result = $conexao->prepare($sql); $resultStatus = $result->execute(array( ':matricula' => $estudante['matricula'], ':id' => $estudante['id'] )); if ($resultStatus) { return true; } else { return false; } } else { return false; } } } <file_sep><?php declare(strict_types=1); require './Connection.php'; abstract class Pessoa { /** * @var int */ public $id; /** * @var string */ public $nome; /** * @var string */ public $telefone; /** * @var string */ public $email; /** * @var string */ public $dataNascimento; public function __construct( string $email ) { $this->email = $email; } /** * @return object * @throws Throwable */ public function verDados(): object { $conn = new Connection(); $conectar = $conn->connect(); $sql = "SELECT nome, telefone, email FROM api_base.pessoa WHERE email = :email"; $result = $conectar->prepare($sql); $result->execute(array(':id' => $this->id)); return $result->fetchObject(); } public function calculaIdade(string $dataNascimento): int { $date = new DateTime($dataNascimento); $intervalo = $date->diff(new DateTime(date('Y-m-d'))); return intval($intervalo->format('%Y')); } abstract public function calculaAvaliacao(); } <file_sep><?php declare(strict_types=1); class Professor extends Pessoa { /** * @var string */ public $especialidade; /** * @var float */ public $salario; public function verProfessor(): object { $conn = new Connection(); $conectar = $conn->connect(); $sql = "SELECT nome, telefone, email, especialidade, salario, data_nascimento FROM api_base.professor pr LEFT JOIN api_base.pessoa pe on pr.pessoa_id = pe.ID WHERE email = :email"; $result = $conectar->prepare($sql); $result->execute(array(':email' => $this->email)); return $result->fetchObject(); } /** * @return float */ public function calculaAvaliacao(): float { $qtdDisciplinasMinistradas = 100; $qtdAnosInstituicao = 12; return ($qtdDisciplinasMinistradas * $qtdAnosInstituicao); } }
78f557aee3aabd0ffa74325255ac43c9c9392720
[ "Markdown", "PHP" ]
9
PHP
jeysonlr/aula-pos-PHPOO
c2c3e898995aa34ef48e7c293fb77e09429017a3
3e97b204fcc8f2beff384f84ee2f681af2a89c3c
refs/heads/master
<file_sep>package com.example.ex02; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { EditText text_year; TextView text_result; Button button_cal; String list_first[] = {"Canh", "Tân", "Nhâm", "Quý", "Giáp", "Ât", "Bính", "Đinh", "Mậu", "Kỷ"}; String list_last[] = {"Thân", "Dậu", "Tuất", "Hợi", "Tý", "Sửu", "Dần", "Mẹo", "Thìn", "Tỵ", "Ngọ", "Mùi"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text_year = findViewById(R.id.text_year); text_result = findViewById(R.id.text_result); button_cal = findViewById(R.id.button_cal); button_cal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { text_result.setText(""); if(text_year.getText().toString().trim().length()==0){ text_year.requestFocus(); return; } int last_num = Integer.parseInt(text_year.getText().toString().charAt(text_year.getText().toString().length()-1)+""); int year = Integer.valueOf(text_year.getText().toString().trim()); text_result.setText(list_first[last_num]+" "+ list_last[year%12]); } }); } } <file_sep>package com.example.ex05; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import android.widget.TextView; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainActivity extends AppCompatActivity { EditText editText_fullname; TextView textView_output; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText_fullname = findViewById(R.id.editText_fullname); textView_output = findViewById(R.id.textView_output); editText_fullname.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { String fullname = editText_fullname.getText().toString().trim(); String name[] = fullname.split(" "); String temp = ""; for (int i = 0; i < name.length; i++){ if(i!=0){ temp += name[i]+" "; } } textView_output.setText( " Họ : " +name[0] + "\nTên : " + temp); } }); } }
96d0c240e3a83343b388fa5d23e4e3e9e9d09c86
[ "Java" ]
2
Java
tgiabao1340/Android-Studio-26-08-2019
f13e2979ee8b708b6abe8604abcb7abcb8669a16
929f5076df7dccaf6e80dab2414529cf83886f90
refs/heads/master
<repo_name>yuxianda/phpweb<file_sep>/docs/x.da-build-sh.sh jekyll b -d ../public/phpweb echo '...done...' read -p "Press enter to continue! --Noticed by thianda"<file_sep>/application/trouble/controller/Common.php <?php namespace app\trouble\controller; use app\common\controller\Common as CCommon; use think\Controller; use think\Request; use think\Config; class Common extends CCommon{ /** * 判断是否已登录--(初始化函数 _initialize 优先于 $beforeActionList 配置) */ } <file_sep>/application/kxeams/controller/C.php <?php namespace app\kxeams\controller; use app\common\controller\Common; use think\Controller; use think\Request; use think\Db; class C extends Common { /** * 获取 todo main表的 detail 信息 * * @param unknown $main_id */ protected function todoDetail($main_id) { return Db::name ( "detail" )->where ( "main_id", $main_id )->alias ( "dd" )->join ( "__ITEM__ ii", "ii.id=dd.item_id" )->field ( "name,type,maker,units,count,dusage,dremarks" )->select (); } protected function storeCounts($types = []) { } } <file_sep>/application/index/controller/Index.php <?php namespace app\index\controller; use think\Controller; use PHPMailer\PHPMailer\PHPMailer; class Index extends Controller { public function index() { if (in_array ( substr ( request ()->ip (), 0, 8 ), [ '10.61.21', '0.0.0.0', '127.0.0.' ] )) { return $this->fetch ( 'indexs' ); } else { return $this->fetch (); } } public function testMail() { $mail = new PHPMailer(); $mail->isSMTP (); // Set mailer to use SMTP $mail->CharSet = "utf-8"; $mail->SetLanguage ( 'zh_cn' ); $mail->SMTPDebug = 1; $mail->Host = 'smtp.139.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = "<EMAIL>"; // SMTP username $mail->Password = '<PASSWORD>'; // SMTP password // $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 25; // TCP port to connect to $mail->setFrom ( '<EMAIL>', 'Excel服务器' ); $mail->addAddress ( '<EMAIL>' ); // Name is optional // $mail->addReplyTo ( '<EMAIL>', 'Information' ); // $mail->addCC ( '<EMAIL>' ); // $mail->addBCC ( '<EMAIL>' ); // $mail->addAttachment ( '/var/tmp/file.tar.gz' ); // Add attachments $mail->addAttachment ( '/aa.jpg', '附件new.jpg' ); // Optional name // 绝对路径从磁盘根目录算起,相对路径从public/idnex.php算起。 $mail->isHTML ( true ); // Set email format to HTML $mail->Subject = '测试邮件标题' . date ( "Y-m-d H:i:s" ); $mail->Body = 'This is the HTML message body <b>in bold!</b><hr>正文是Body'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; if (! $mail->send ()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent'; } exit ( 0 ); } public function _empty() { $dir = APP_PATH . request ()->module () . DS . "view" . DS . request ()->controller () . DS . request ()->action () . "." . config ( 'template.view_suffix' ); if (file_exists ( $dir )) return $this->fetch ( request ()->action () ); else { return $this->error ( "请求未找到(╯﹏╰)", null, null, 60 ); } } } <file_sep>/application/kxeams/model/Main.php <?php namespace app\kxeams\model; use think\Model; use traits\model\SoftDelete; class Main extends Model { use SoftDelete; protected $deleteTime = 'mdelete_time'; protected $autoWriteTimestamp = 'datetime'; protected $createTime = 'mcreate_time'; protected $updateTime = false; protected $type = [ 'id' => 'integer', 'mcreate_time' => 'datetime', 'mdelete_time' => 'datetime' ]; public function item() { return $this->belongsTo ( 'Item' ); } }<file_sep>/application/zx_apply/controller/Common.php <?php namespace app\zx_apply\controller; use app\common\controller\Common as CCommon; use think\Session; use app\zx_apply\model\Infotables; class Common extends CCommon { /** * 判断是否已登录--(初始化函数 _initialize 优先于 $beforeActionList 配置) */ public function _initialize() { $this->checkAuth(); parent::_initialize(); $this->assign("title", "数据专线开通-全流程辅助--X.Da"); } private function checkAuth() { $u = input('get.y'); $users = [ 'y' => 'xda', 'sjbz' => '数据班组' ]; foreach ($users as $k => $v) { if ($k == $u) { session("user", [ 'name' => $v, 'role' => 'manage' ]); } } } /** * 退出登录 */ public function loginout() { $this->log("注销登陆", [ "stauts" => "success", "name" => session("user.name") ]); Session::delete("user"); return $this->success("已注销登录", "index/index#logout", "", 1); } public function _empty() { $dir = APP_PATH . request()->module() . DS . "view" . DS . request()->controller() . DS . request()->action() . "." . config('template.view_suffix'); if (file_exists($dir)) return $this->fetch(request()->action()); else { return $this->error("页面不在了哦~你猜我给它弄到哪去了?→_→", null, null, 30); } } public function tt() { $data = null; $db = Infotables::find(2273); $values = array_values($db->toArray()); return dump($values); } } <file_sep>/docs/README.md # PHPWEB 文档库 请访问:<https://thianda.github.io/phpweb/> Github:<https://github.com/thianda/phpweb> [![](images/red_packet.jpg)](images/red_packet.jpg) 模板:[pixyll.com](http://www.pixyll.com) 中文版 <https://github.com/ee0703/pixyll-zh-cn>. <file_sep>/application/kxeams/model/Mylist.php <?php namespace app\kxeams\model; use think\Model; class Mylist extends Model { }<file_sep>/application/zx_apply/model/Vlantables.php <?php namespace app\zx_apply\model; use think\Model; use think\Db; use traits\model\SoftDelete; class Vlantables extends Model { use SoftDelete; protected $deleteTime = 'delete_time'; protected $autoWriteTimestamp = false; /** * 录入/更新/删除vlan * * @param string $aStation * @param string $vlan * @param string $description * @param unknown $infoId */ public static function createVlan($aStation = "", $vlan = "", $description = "", $infoId = null) { if (is_null($infoId)) { return; // 仅内部调用,infoId不会为空。 } $vlantables = new static(); $aStationConf = config("aStation"); if (array_key_exists($aStation, $aStationConf)) { // 根据a端匹配到9312名,则保存vlan $data = [ "deviceName" => $aStationConf[$aStation], "vlan" => $vlan == 0 ? null : $vlan, "description" => $description, "infoId" => $infoId ]; // 根据infoId,如果已存在则更新,否则新增。 $dbData = $vlantables->where(["infoId" => $infoId])->find(); if ($dbData) { $dbData->isUpdate(true)->save($data); } else { $vlantables->isUpdate(false)->save($data); } } } /** * 自动预分配vlan,返回预分配vlan * * @param string $device * @param string $cName * @param string $manual * 0 for write to db(default), 1 for pre-generate. * @return number|string */ public static function generateVlan($device = "", $cName = "", $manual = false) { $usedVlans = self::where("deviceName", $device)->distinct(true)->column("vlan"); for ($vlan = 2111; $vlan < 3071; $vlan++) { if (!in_array($vlan, $usedVlans)) { $preVlan = $vlan; break; } } if ($manual) { // 手动分类,推荐空闲vlan $result = [ "preVlan" => $preVlan, "usedVlans" => $usedVlans ]; } else { Db::name("vlantables")->insert([ "deviceName" => $device, "vlan" => $preVlan, "description" => $cName ]); $result = $preVlan; } return $result; } /** * 导入更新已使用vlan * * @param string $deviceName * @param string $str * @return void|string */ public static function importUsedVlan($deviceName = "", $str = "") { preg_match_all('/vlan batch ([\S ]+)/', $str, $str); // 匹配后结果输出到$str $str = implode(" ", $str[1]); // $str = str_replace ( 'vlan batch ', '', $str ); // $str = preg_replace ( '/[\r\n]/', '', $str ); $array = explode(" ", $str); $result = []; $count = count($array); for ($i = 0; $i < $count; $i++) { // 遍历数组,替换to,补充连续的vlan if ($array[$i] == "to") { array_splice($array, $i, 1); // 补充连续的vlan for ($j = $array[$i - 1] + 1; $j < $array[$i]; $j++) { $array[] = $j; } } } sort($array, SORT_NUMERIC); // 排序 $count = 0; $validation = 0; foreach ($array as $v) { if ($v > 2000 && $v < 3071) { // 范围之外的vlan,无操作 $count++; // 已有,则放弃 $vlanInfo = self::where([ "deviceName" => $deviceName, "vlan" => $v ])->select(); if (!$vlanInfo) { // 无信息,则insert $vlanInfo = self::create([ "deviceName" => $deviceName, "vlan" => $v, "description" => "手动导入-" . date("Y-m-d h:i:s", time()) ]); $validation++; } } } return [ "total" => count($array), "count" => $count, "validation" => $validation ]; } /** * 检查vlan是否已分配 * * @param string $zxType * @param string $aStation * @param number $vlan * @return array */ public static function check($zxType = "", $aStation = "", $vlan = 0) { $data = Infotables::where([ "zxType" => $zxType, "aStation" => $aStation, "vlan" => $vlan ])->field("id,cName")->find(); if (!$data) { $data = self::where("vlan", $vlan); $deviceConf = config("aStation"); if (array_key_exists($aStation, $deviceConf)) { $data = $data->where("deviceName", $deviceConf[$aStation]); $data = $data->field("id,description as cName")->find(); if ($data) { // 修改以区别,不同于要查询的数据 $data = $data->toArray(); // 随意设置个$data["id"],非null $data["id"] .= "_vlan"; $data["code"] = 0; } } else { // 此时情况为:vlan存在,aStation不在预设范围内(为空) $data = [ "id" => "", "code" => 2, "cName" => "请填写正确的<span style='color: red;'>A端基站</span>!" ]; } } else { $data["code"] = 0; } return $data; } }<file_sep>/application/trouble/config.php <?php return [ 'version' => "V1.0622-gz", ];<file_sep>/application/kxeams/model/Detail.php <?php namespace app\kxeams\model; use think\Model; class Detail extends Model { protected $type = [ 'id' => 'integer', 'main_id' => 'integer', 'item_id' => 'integer', 'count' => 'integer', ]; }<file_sep>/application/checkME60/controller/Index.php <?php namespace app\checkME60\controller; use app\common\controller\Common; class Index extends Common { public function index() { return $this->redirect ( "main" ); } } <file_sep>/docs/about.md --- layout: page title: 关于 permalink: about/ tags: about --- # 关于 phpweb文档 文档全部由[YuXianda](https://github.com/yuxianda)撰写。 > All the posts are written by [YuXianda](https://github.com/yuxianda). 此文档主题fork于[johnotander/pixyll](https://github.com/johnotander/pixyll)。 > This Jekyll theme was crafted with <3 by [<NAME>](http://johnotander.com) > ([@4lpine](https://twitter.com/4lpine)). Checkout the [Github repository](https://github.com/johnotander/pixyll) to download it, request a feature, report a bug, or contribute. It's free, and open source ([MIT](http://opensource.org/licenses/MIT)). [返回](../)<file_sep>/docs/_posts/2017-12-17-tl-esserver.md --- layout: post title: Excel服务器辅助 date: 2017-12-17 22:05:15 summary: 本模块可自助找回Excel服务器账号,需服务器连接带外网,需要一个邮箱账号。 categories: notes update_date: 2017-12-17 22:42:22 --- ### 链接 内网: <http://10.65.187.202/esserver/>;外网: <http://172.16.58.3:800/esserver/>。 ### 密码找回 输入用户名以及用户名对应的邮箱,验证成功,即可向该邮箱发送一封验证邮件,访问邮件里的密码重置链接,即可重新设置该账户的密码,非常简单。 > 获取重置密码的链接之前。需要验证登陆名以及邮箱地址。 > > 若邮箱验证失败或无邮箱,可填写包含登陆名字段的邮箱地址. > > 验证信息正确数大于2即可获取重置链接。 ### 密码重置 在执行了密码找回后,会在对应的邮箱中收到密码重置的链接,在有效期内访问,即可直接重置Excel服务器的密码。注意设置新密码的密码复杂度,以及不允许与最近2次的密码相同。 ### 系统设置 功能不对外开放^_^ ### 下载安装谷歌浏览器(chrome) [本模块](/esserver)在的IE9以下无法正常显示,推荐使用谷歌(chrome)或火狐(firefox)浏览器。 <file_sep>/application/trouble/database.php <?php return [ 'prefix' => 'trouble_', ]; <file_sep>/docs/_posts/2017-12-12-template.md --- layout: post title: new title date: 2017-12-12 22:22:22--0800 summary: the summarys of the post categories: notes update_date: 2017-12-17 22:22:22 --- ## 我是模板<file_sep>/application/zx_apply/database.php <?php return [ 'prefix' => 'zx_', ]; <file_sep>/application/zx_apply/controller/Index.php <?php namespace app\zx_apply\controller; use think\Controller; use think\Request; use think\Db; use think\Cache; use app\zx_apply\model\Infotables; use app\zx_apply\model\Vlantables; use Overtrue\Pinyin\Pinyin; class Index extends Common { public function ch2arr($str) { $length = mb_strlen($str, 'utf-8'); $array = []; for ($i = 0; $i < $length; $i++) $array[] = mb_substr($str, $i, 1, 'utf-8'); return $array; } /** * 首页-登录 * * @return mixed|string|void */ public function index() { if (request()->isGet()) { if (request()->url() != "/zx_apply/index/index.html") { return $this->redirect("index"); } return $this->fetch(); } if (request()->isPost()) { // post请求 验证登陆 $user = Db::table("phpweb_check")->where('email', input("post.email"))->order("time desc")->find(); $msg = ""; if (!$user) { return $this->result(["code" => 0], 0, "该邮箱还未申请验证码"); } if ($user["code"] != input("post.code")) { $msg = "验证码错误"; } else { // 验证码正确,继续验证申请人姓名 if ($user["name"] != input("post.name")) { $msg = "申请人姓名与申请时不一致<br />申请时为:<b>" . $user["name"] . "</b><br />申请时间:" . $user["time"]; } } if ($msg) { $this->writeLog("登陆", "failed", $msg); return $this->error($msg, null, input("post.")); } else if (time() - strtotime($user["time"]) > 3600 * 24 * 15) { // 15天内可直接登陆 $msg = "登陆超时,请重新获取验证码。"; $this->writeLog("登陆", "failed", $msg); unset($user["code"]); return $this->error($msg, "index", $user); } else { $e = explode("@", $user["email"]); // 附加role。 if ($e[1] == "ln.chinamobile.com" && in_array($e[0], config("manageEmails"))) { $user["role"] = "manage"; } else { $user["role"] = "index"; } session("user", $user); $msg = "欢迎回来," . $user["name"] . "。"; $this->writeLog("登陆", "success", $msg); $url = session("to_url") ? session("to_url") : session("user.role") . "/query"; session("to_url", null); return $this->success($msg, $url, $user); } } } protected function writeLog($k, $status, $msg) { $this->log($k, [ "status" => $status, "name" => input("post.name"), "email" => input("post.email"), "msg" => strip_tags($msg) ]); } /** * 数据专线申请开通 */ public function apply() { if (request()->isGet()) { return $this->fetch(); } else if (request()->isPost()) { $data = input("post."); $this->checkInstanceID(null, $data["instanceId"]); // 检查instanceId $extraHeader = config("extraInfo"); foreach ($extraHeader as $k => $v) { $data["extra"][$v] = $data[$v]; unset($data[$v]); } $result = Infotables::createInfo($data, "apply"); // 发邮件通知 $subject = "[待办]ip申请-" . ($data["ifOnu"] ? "onu" : "9312") . "-" . $data["cName"] . $data["instanceId"]; $body = "<p>请登陆系统及时处理:</p><br> 内网: <a href='http://10.65.187.202/zx_apply/index/index.html#Manage/todo'>http://10.65.187.202/zx_apply/index/index.html#Manage/todo</a><br>外网: <a href='http://172.16.31.10:800/zx_apply/index/index.html#Manage/todo'>http://172.16.31.10:800/zx_apply/index/index.html#Manage/todo</a>"; $this->sendManageNotice($subject, $body, true); $v = [ "username" => session("user.name"), "email" => session("user.email"), "cName" => $data["cName"], "instanceId" => $data["instanceId"] ]; $this->log("提交申请", $v); $redirectUrl = "../" . session("user.role") . "/query.html"; return $this->result(null, $result, $redirectUrl); // return json_encode ( $data, 256 ); } } /** * 修改提交 */ public function re_apply() { if (request()->isGet()) { return $this->error("Nothing here. Do not try again!"); } $data = input("post."); $oldData = Infotables::get(input("param.old"))->toArray(); $updates = []; // 记录有更新的字段 $change = ''; /* 不验证实例标识重复与否 */ $extraHeader = config("extraInfo"); foreach ($extraHeader as $k => $v) { $data["extra"][$v] = $data[$v]; unset($data[$v]); if ($data["extra"][$v] != $oldData["extra"][$v]) { $change .= $k . " => [" . $oldData["extra"][$v] . "] 改为 [" . $data["extra"][$v] . "]\r\n"; $updates[$k] = "[" . $oldData["extra"][$v] . "]=>[" . $data["extra"][$v] . "]"; } } // 不验证 instanceID $result = Infotables::createInfo($data, "apply"); $this->queryDelete(["id" => [input("param.old")]]); // 发邮件通知 $subject = "[待办]修改申请-" . $data["aPerson"] . "-" . $data["cName"]; $oldInfo = "<pre style='color:#088'>A端基站: " . $oldData["aStation"] . "\r\nip: " . $oldData["ip"] . "\r\nvlan: " . $oldData["vlan"] . "</pre>"; $body = "<p>原分配信息:</p>" . $oldInfo; $body .= "<p>修改内容:</p><pre style='color:#088bff'>"; foreach ($data as $k => $v) { if ($k = 'extra') { continue; } if ($v != $oldValue) { $change .= $k . " => [" . $oldValue . "] 改为 [" . $v . "]\r\n"; $updates[$k] = "[" . $oldValue . "]=>[" . $v . "]"; } } $change == '' && $change = "无"; $body .= $change; $body .= "</pre><p>请登陆系统及时处理:</p>" . config("systemURLString"); $this->sendManageNotice($subject, $body, true); $v = [ "username" => session("user.name"), "email" => session("user.email"), "cName" => $data["cName"], "instanceId" => $data["instanceId"], "oldInfo" => $oldInfo, "updates" => $updates ]; $this->log("修改申请", $v); $redirectUrl = "../" . session("user.role") . "/query.html"; return $this->result(null, $result, $redirectUrl); } /** * 根据label、order 获取表格的 header! * $v为false,获取option(default);为ture,获取value * * @param String $label * @param String $order * @param boolean $v * @return string */ public function getHeader($label = "label", $order = "order", $v = false) { if ($label === "label" || $order === "order") { return "{msg:\"你要搞什么?\"}"; // 未输入参数label或order } $_headerData = Db::table("phpweb_sysinfo")->field("value,option")->where(["label" => $label])->order("id")->select(); $orderArr = explode(",", $order); $headerArr = []; $sub = $v ? "value" : "option"; foreach ($orderArr as $o) { $headerArr[] = $_headerData[$o][$sub]; } return implode(",", $headerArr); } /** * 根据order获取handsontable组件的colWidth * * @param unknown $order * @return string|void */ protected function getColWidths($order = null) { if (!is_null($order)) { $orderArr = explode(",", $order); $result = []; foreach ($orderArr as $v) { $result[] = config("colWidth")[$v]; } return implode(",", $result); } return $this->result(null, 0, "~缺参数~"); } /** * 信息查询 */ public function query() { if (request()->isGet()) { // 访问 $aStation = array_keys(config("aStation")); $zxTitle = [ "label" => "zx_apply-new-rb", "order" => "24,1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,20,29,30,31,32,33,34,35,36,37,38,39,40,41,42,22,23,26" ]; $this->assign([ "aStationData" => implode(",", $aStation), "colHeaderData" => $this->getHeader($zxTitle["label"], $zxTitle["order"]), "colWidthsData" => $this->getColWidths($zxTitle["order"]), "data" => $this->getInfoData()->toJson() ]); return $this->fetch(); } if (request()->isPost()) { // 获取台账 input("post.r") == "info" && $data = $this->getInfoData(input("post.zxType"))->toArray(); input("post.r") == "search" && $data = $this->querySearch(input("post.")); input("post.r") == "brief" && $data = $this->querySearchBrief(input("post.")); input("get.r") == "update" && $data = $this->queryUpdateInfo(input("post.")); return $data; } if (request()->isPut()) { // 相关操作 input("post.r") == "copy_one_more" && $data = $this->queryCopyOne(input("post.")); input("post.r") == "export" && $data = $this->queryExport(); return $data; } } /** * 获取台账信息 * * @param string $zxType * @param number $limit * @return \think\model\Collection|\think\Collection */ protected function getInfoData($zxType = "互联网", $limit = 100) { $where = ""; if (session("user.role") != "manage") { $where = ["aEmail" => session("user.email")]; } return collection(Infotables::where("zxType", $zxType)->where($where)->order("status,ip desc,create_time desc")->limit($limit)->select()); } /** * 全局查询 * * @param unknown $data * @return array */ protected function querySearch($data) { $where = ""; if (session("user.role") != "manage") { $where = ["aEmail" => session("user.email")]; } return collection(Infotables::where("zxType", $data["zxType"])->where($where)->where($data["where"][0], "like", "%" . $data["where"][2] . "%")->order("ip desc")->select())->toArray(); } /** * 基本信息查询 * * @param unknown $data * @return array */ private function querySearchBrief($data) { if (!isset($data["where"][2]) || $data["where"][2] == "") { return; } $field = "create_time,instanceId,cName,cAddress,vlan,ip,aPerson,aEmail"; $result = collection(Infotables::where("zxType", $data["zxType"])->where($data["where"][0], "like", "%" . $data["where"][2] . "%")->field($field)->order("ip desc")->select())->toArray(); $v = $data; $v["resultLen"] = count($result); $v["user"] = session("user.name"); $v["url"] = request()->url(true); $this->log("基本信息查询", $v); if (Cache::get('querySearchBriefTimes')) { Cache::inc('querySearchBriefTimes'); } else { Cache::set('querySearchBriefTimes', 1, 600); } $querySearchBriefTimes = Cache::get('querySearchBriefTimes'); if ($querySearchBriefTimes > 12) { $address = config("manageEmails"); foreach ($address as $k => $v) { $address[$k] = $v . "@ln.chinamobile.com"; } if ($querySearchBriefTimes > 14) { session(null); $msg = session("user.name") . "已被系统强制登出,原因:查询频繁,单位时间内累计" . $querySearchBriefTimes . "次"; $this->log("强制登出", $msg); $this->noticeManage("[频繁查询]" . session("user.name") . "-10分钟内:" . $querySearchBriefTimes, null, $address); return $this->error("已退出登陆,请勿频繁查询!", "index"); } return $querySearchBriefTimes; } return $result; } /** * 从query.html更新台账 * * @param unknown $updateData * @return number|\think\false */ protected function queryUpdateInfo($updateData) { $result = 0; $dbNew = []; foreach ($updateData as $k => $v) { $infotables = new Infotables(); $line_and_id = explode("-", $k); $extraHeader = config("extraInfo"); foreach ($extraHeader as $e => $exH) { if (isset($v[$exH])) { // extra 部分有更新,需要先获取完整的 $v["extra"][$exH] = $v[$exH]; unset($v[$exH]); } } $result += $infotables->isUpdate(true)->allowField(true)->save($v, ["id" => $line_and_id[1]]); // 反查询刚才修改后的数据库里的值,用于前后端数据的一致性 $data = $infotables->where("id", $line_and_id[1])->find(); foreach ($v as $kk => $vv) { $dbNew[$k][$kk] = $data->$kk; } $infotables = null; } return $this->result($dbNew, 1, $result); } /** * 从query.html删除台账条目 * * @param unknown $input */ protected function queryDelete($input) { $result = Infotables::destroy($input["id"]); // 操作人记录到备注里 Infotables::where('id', 2684)->exp('marks', 'concat(marks,\'' . session("user.name") . "已删;" . "')")->update(); // 同步删除vlantables foreach ($input["id"] as $id) { Vlantables::destroy(["infoId" => $id]); } return $result; } /** * 额外再申请 IP 操作 * * @return void */ protected function queryCopyOne($input) { if (request()->isGet()) { return $this->error("Nothing here. Do not try again!"); } $id = $input["copyOne"]; /* 不验证实例标识重复与否 */ $data = Infotables::get($id)->getData(); // 获取原始数据,去除 id,直接保存 unset($data["id"]); $result = Infotables::createInfo($data, "apply"); // 发邮件通知 $subject = "[待办]额外申请-" . $data["aPerson"] . "-" . $data["cName"]; $oldInfo = "<pre>A端基站: " . $data["aStation"] . "\r\nip: " . $data["ip"] . "\r\nvlan: " . $data["vlan"] . "</pre>"; $body = "<p>原分配信息:</p>" . $oldInfo; $body .= "<p>现申请额外的IP,需要您核实。"; $body .= "</p><p>请登陆系统及时处理:</p>" . config("systemURLString"); $this->sendManageNotice($subject, $body); $v = [ "username" => session("user.name"), "email" => session("user.email"), "cName" => $data["cName"], "instanceId" => $data["instanceId"], "oldInfo" => $oldInfo ]; $this->log("额外申请", $v); $redirectUrl = "../" . session("user.role") . "/query.html"; return $this->result(null, $result, $redirectUrl); } /** * 导出全量台账-基于专线类型 * * @param string $zxType * @return string[]|array[] */ protected function queryExport($zxType = "互联网") { if ($zxType == "互联网") { $colHeader = "申请时间,产品实例标识,带宽,网元厂家,A端基站,客户名称,单位详细地址,客户需求说明(选填),VLAN,IP,联系人姓名(客户侧),联系电话(客户侧),联系人邮箱(客户侧)*,负责人姓名(移动侧)*,负责人电话(移动侧)*,负责人邮箱(移动侧)*,备注,是否ONU带\n(默认为否),单位性质*,单位分类*,行业分类*,使用单位证件类型*,使用单位证件号码*,单位所在省*,单位所在市*,单位所在县*,应用服务类型*,单位属性,网络安全责任人,责任人身份证号,责任人电话,责任人邮箱"; $colName = "create_time,instanceId,bandWidth,neFactory,aStation,cName,cAddress,cNeeds,vlan,ip,cPerson,cPhone,cEmail,mPerson,mPhone,mEmail,marks,ifOnu,extra.unitProperty,extra.unitCategory,extra.industryCategory,extra.credential,extra.credentialnum,extra.province,extra.city,extra.county,extra.appServType,extra.unitAttribute,extra.securityPerson,extra.securityPersonID,extra.securityPhone,extra.securityEmail"; $field = ""; } else if ($zxType == "营业厅") { $colHeader = "申请时间,产品实例标识,网元厂家,A端基站,客户名称,单位详细地址,VLAN,互联IP,业务IP,联系人姓名(客户侧),联系电话(客户侧)"; $colName = "create_time,instanceId,neFactory,aStation,cName,cAddress,,vlan,ip,ipB,cPerson,cPhone"; $field = $colName; } else if ($zxType == "卫生网") { $colHeader = "申请时间,产品实例标识,网元厂家,A端基站,客户名称,单位详细地址,VLAN,互联IP,业务IP,联系人姓名(客户侧),联系电话(客户侧)"; $colName = "create_time,instanceId,neFactory,aStation,cName,cAddress,vlan,ip,ipB,cPerson,cPhone"; $field = $colName; } else if ($zxType == "平安校园") { $colHeader = "申请时间,产品实例标识,客户名称,单位详细地址,VLAN,监控IP"; $colName = "create_time,instanceId,cName,cAddress,vlan,ip"; $field = $colName; } if (session("user.role") == "manage") { $data = collection(Infotables::field($field)->where("zxType", $zxType)->order("ip")->select())->toArray(); } else { $data = collection(Infotables::field($field)->where("aPerson", session("user.name"))->order("ip")->select())->toArray(); } $v = [ "dataNum" => count($data), "zxType" => $zxType, "username" => session("user.name"), "email" => session("user.email") ]; $this->log("导出全量数据", $v); return [ "data" => $data, "colHeader" => $colHeader, "colName" => $colName ]; } /** * 检查 instanceId 是否重复 * 可输入$data数组或instanceId * * @param unknown $info * @param unknown $data */ protected function checkInstanceID($info, $data) { if (null == $info) { $instanceId = $data; } else if ($info["id"] != $data["id"]) { $instanceId = $data["instanceId"]; } else { return; } $info = Infotables::get([ "instanceId" => $instanceId ]); if ($info) { return $this->error("实例标识重复,请重试", null, "该实例标识对应客户名为:<br>" . $info["cName"] . "<br>申请人:" . $info["aPerson"]); } } /** * 给管理员发送通知 * * @param string $subject * @param string $body * @param boolean $addCurrentUser */ protected function sendManageNotice($subject = '', $body = '', $addCurrentUser = false) { $address = config("manageEmails"); foreach ($address as $k => $v) { $address[$k] = $v . "@ln.chinamobile.com"; } $addCurrentUser && $address["CC1"] = session("user.email"); $this->sendEmail($address, $subject, $body); } }<file_sep>/application/esserver/model/Log.php <?php namespace app\esserver\model; use think\Model; class Log extends Model { // 未使用 protected $pk = 'id'; protected $type = [ 'v' => 'array' ]; /*protected $auto = [ 'value' ]; public function setValueAttr($value) { return json_encode ( $value, JSON_UNESCAPED_UNICODE ); }*/ }<file_sep>/docs/_posts/2018-01-25-redis-php-extension-installation.md --- layout: post title: 为php安装redis扩展-windows系统 date: 2018-01-25 11:21:32--0800 summary: 在windows中,不同的php版本对应不同的redis扩展版本,安装配置略繁琐,记录一下。 categories: notes update_date: 2018-07-12 17:27:55 --- ## 0. 安装redis 可以访问redis的[官网](https://redis.io/),但是官方只提供linux版本的redis。windows版本可以下载由Microsoft Open Tech group 编译好的版本 <https://github.com/MSOpenTech/redis>,不过现在貌似改名了,直接跳转到<https://github.com/MicrosoftArchive/redis/>,直接在[releases](https://github.com/MicrosoftArchive/redis/releases)页面下载即可。下载msi包,安装时可直接安装为windows服务并设置环境变量。很方便。 目前,最新版本一直是[3.2.100Pre-release](https://github.com/MicrosoftArchive/redis/releases/download/win-3.2.100/Redis-x64-3.2.100.msi)。最新稳定版是[3.0.504](https://github.com/MicrosoftArchive/redis/releases/download/win-3.0.504/Redis-x64-3.0.504.msi)。 在cmd执行测试,执行`redis-cli -v`查看版本。或: ```sh C:\Users\Administrator>redis-cli 127.0.0.1:6379> ping PONG ``` ### 1. 确认php版本 在php安装目录执行`php -v`。或者在php里执行`phpinfo()`。windows 版的php为Thread Safe(ts)。 ```sh C:\Users\Administrator>php -r "phpinfo();">c:\phpinfo.txt ``` 上面代码将phpinfo输出到`c:\phpinfo.txt`,可在不架设web的情况下快速查看phpinfo。 ### 2. 下载DLL(重点!) #### 2.1 php_igbinary.dll 访问:<http://windows.php.net/downloads/pecl/releases/igbinary/>,可看见不同的版本,依据版本优先选`a.b.c`中基于`a.b`,选`c`最大的文件夹进入。例如为选择`2.0.x`,当前最新的是`2.0.7`,进入后可看见支持从php5.6到7.2。下载对应版本即可。(选ts、线程安全版本) | php版本 | 文件夹 | 下载文件 | | ------- | ------ | ------------------------------------------------------------ | | 5.6 | 2.0.7 | [php_igbinary-2.0.7-5.6-ts-vc11-x86.zip](https://windows.php.net/downloads/pecl/releases/igbinary/2.0.7/php_igbinary-2.0.7-5.6-ts-vc11-x86.zip) | | 7.2 | 2.0.7 | [php_igbinary-2.0.7-7.2-ts-vc15-x86.zip](https://windows.php.net/downloads/pecl/releases/igbinary/2.0.7/php_igbinary-2.0.7-7.2-ts-vc15-x86.zip) | 下载的zip包里有俩文件是我们需要的:`php_igbinary.dll`、`php_igbinary.pdb`(可选)。将它们复制到php的ext目录下。 #### 2.2 php_redis.dll 访问:<http://pecl.php.net/package/redis>,可看见Downloads下面有DLL的下载链接,根据`Version`点击`DLL`查看支持的php版本,如点击`2.2.7`后面的DLL,可看见这个版本的DLL支持PHP5.3到PHP5.6。 | php版本 | Version | 下载文件 | | ------- | --------------- | ------------------------------------------------------------ | | 5.6 | 2.2.7 | [5.6 Thread Safe (TS) x86](https://windows.php.net/downloads/pecl/releases/redis/2.2.7/php_redis-2.2.7-5.6-ts-vc11-x86.zip) | | 7.2 | 4.1.0(当前最新) | [7.2 Thread Safe (TS) x86](https://windows.php.net/downloads/pecl/releases/redis/4.1.0/php_redis-4.1.0-7.2-ts-vc15-x86.zip) | 下载的zip包里有俩文件是我们需要的:`php_redis.dll`、`php_redis.pdb`(可选)。将它们复制到php的ext目录下。 ### 3. 配置php.ini 在php安装目录执行`php --ini`,可查看当前加载的php.ini所在位置。在php.ini中添加: ```ini extension=php_igbinary.dll extension=php_redis.dll ``` 注意`php_igbinary.dll`要放在`php_redis.dll`前面。 ### 4. 测试 重启apache。可以在`phpinfo()`中看见redis的配置。 ``` php -r "phpinfo();">c:\phpinfo.txt ``` 可在`c:\phpinfo.txt`看见如下字样:(用notepad++打开。自带的notepad无换行。) ``` redis Redis Support => enabled Redis Version => 2.2.7 ``` 或写段php代码测试 ```php <?php //连接本地的 Redis 服务 $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo "Connection to server sucessfully"; //设置 redis 字符串数据 $redis->set("tutorial-name", "Redis tutorial"); // 获取存储的数据并输出 echo "Stored string in redis:: " . $redis->get("tutorial-name"); ?> ``` <file_sep>/application/kxeams/model/TableAttr.php <?php namespace app\kxeams\model; use think\Model; class TableAttr extends Model { }<file_sep>/application/kxeams/controller/Manage.php <?php namespace app\kxeams\controller; use think\Controller; use think\Request; use think\Db; use app\kxeams\model\Main; use app\kxeams\model\Item; use app\kxeams\model\Detail; class Manage extends User { protected $beforeActionList = [ 'checkAuth' ]; public function checkAuth() { // if (strpos ( input ( 'session.user/a' )['role'], '管理员' ) === false) { if (strpos ( session ( 'user.role' ), '管理员' ) === false) { return $this->error ( "您的权限不足,无法访问。", "user/index" ); } } public function index() { if (Request::instance ()->isGet ()) { return $this->indexGet (); } else if (Request::instance ()->isPost ()) { return $this->indexPost (); } } /** * 物品总览 */ public function indexGet() { $fields = "id,name,type,maker,units,class"; $col_names = "序号,名称,类型,单位,物品大类"; $items = db ( "item" )->field ( $fields )->select (); $result = [ ]; for($i = 0; $i < count ( $items ); $i ++) { // 根据每一个id,分别查询main明细,并计算数量 $data = db ( "detail" )->alias ( "dd" )->join ( '__MAIN__ mm', 'dd.main_id = mm.id' )->where ( [ "item_id" => $items [$i] ['id'], "moffice" => session ( "user.office" ) ] )->field ( "count,form_type,progress,from_dept,from_store,to_dept,to_store" )->select (); $sum = 0; foreach ( $data as $d ) { if (in_array ( $d ["progress"], [ config ( "领用进度.2" ), config ( "发放进度.2" ), "-" ] )) { if ($d ["to_dept"] == session ( "user.dept" )) $sum += $d ["count"]; else if ($d ["from_dept"] == session ( "user.dept" )) { $sum -= $d ["count"]; } } } $items [$i] ['sum'] = $sum; // 把sum属性加到每个item里 } $items = $this->array_to_json ( $items ); $this->assign ( [ "Header" => $col_names . ",库存数量", "Widths" => "80,150,150,100,100,100,*", "ColSorting" => "int,str,str,str,str,str,int", "ColTypes" => "ro,ro,ro,ro,ro,ro,ro", /*"dd" => json_encode ( [ "data" => $items ] ) */ "dd" => $items ] ); // return dump ( $items ); return $this->fetch (); } public function indexPost() { $id = input ( "post.del_id" ); // return dump ( $id ); $data = Db::name ( "item" )->where ( "id", $id )->find (); return $data; } /** * 出入库查询明细 */ public function loglist() { $main = new Main (); $headers = "dd.id as ddid,name,type,maker,units,count,dusage,dremarks,mm.id as mmid,mcreate_time,form_type,username,usertel,location,owner,dept"; $data = $main->alias ( "mm" )->join ( '__DETAIL__ dd', 'mm.id = dd.main_id' )->join ( '__ITEM__ ii', 'ii.id = dd.item_id' )->field ( $headers )->order ( "mmid" )->select (); $res = [ ]; foreach ( $data as $k => $v ) { $res [] = $v->toArray (); } // return dump($res); // $csvstr = $this->array_to_json ( $res ); // return $csvstr; $this->assign ( "dd", $this->array_to_json ( $res ) ); return $this->fetch (); } public function loglist_v2() { // 测试用,不好用 $main = new Main (); $headers = "name,type,maker,units,class,count,location,mcreate_time,owner,musage,dept,username,usertel,form_type,progress,mremarks"; $data = $main->alias ( "mm" )->join ( '__DETAIL__ dd', 'mm.id = dd.main_id' )->join ( '__ITEM__ ii', 'ii.id = dd.item_id' )->field ( $headers )->order ( "name desc" )->select (); $res = [ ]; foreach ( $data as $k => $v ) { $res [] = $v->toArray (); } $this->assign ( "dd", json_encode ( $res, 256 ) ); return $this->fetch (); } /** * 新到入库 */ public function new_change() { if (Request::instance ()->isGet ()) { $attr = $this->getTableAttr ( 'asset_main_change' ); $this->assign ( [ 'fields' => $attr ['fields'], 'headers' => $attr ['headers'], 'defaultval' => $attr ['defaultval'], 'sortattr' => $attr ['sortattr'], 'edattr' => $attr ['edattr'], 'diswidth' => $attr ['diswidth'], 'validation' => $attr ['validation'] ] ); return $this->fetch ( "new_change" ); } else { $dataa = input ( 'post.data/a' ); // 获取post数据 $result = $this->csv_to_array ( explode ( ",", $dataa ['mygrid__ColNames'] ), $dataa ['data'] ); // return dump ( $dataa['table'] )."<br>".dump ( $result ); $main = new Main (); $main->allowField ( true )->data ( $dataa ['table'], true )->isUpdate ( false )->save (); $main_id = $main->id; $item = new Item (); $detail = new Detail (); // 多行数据逐行处理 foreach ( $result as $data ) { $field = [ 'name' => $data ['name'], 'type' => $data ['type'], 'maker' => $data ['maker'] ]; $iid = $item->where ( $field )->value ( 'id' ); // item 不存在则新增 if ($iid == null) { // $data ['icreate_time'] = date("Y-m-d H:i:s",time()); $item->allowField ( true )->data ( $data, true )->isUpdate ( false )->save (); $data ['item_id'] = $item->id; } else { $data ['item_id'] = $iid; } $data ['main_id'] = $main_id; $detail->allowField ( true )->data ( $data, true )->isUpdate ( false )->save (); } return $this->success ( "", url ( 'manage/index' ) ); } } public function setting() { return $this->fetch (); } /** * 获取表属性 * * @param string $table_name * @param unknown $uid */ private function getTableAttr($uid) { return Db::name ( 'table_attr' )->where ( 'uid', $uid )->find (); } }<file_sep>/application/othermode/controller/Index.php <?php namespace app\othermode\controller; class Index { public function index() { return "ordermode<br>复制本目录文件需要修改namespace为对应的新建模块名"; } } <file_sep>/README.md ## X.Da小项目:bow: [![GitHub license](https://img.shields.io/github/license/thianda/phpweb.svg)](https://github.com/thianda/phpweb/blob/master/LICENSE) [![Build Status](https://travis-ci.org/thianda/phpweb.svg?branch=master)](https://travis-ci.org/thianda/phpweb) [![HitCount](http://hits.dwyl.io/thianda/phpweb.svg)](http://hits.dwyl.io/thianda/phpweb) 基于ThinkPHP 5.0.x开发 更新log可查看 [CHANGELOG](CHANGELOG.md) 目前模块有: | 模块名 | 功能描述 | | --------- | ---------------------------------------- | | docs | 开发文档库( *beta*) :fire: | | checkME60 | 城域网BAS设备健康度检查(**done**) :heavy_check_mark: | | common | 公共库 | | esserver | excel服务器辅助(**done**) :heavy_check_mark: | | index | 首页 | | kxemas | 客响维材管理系统(*shutdown) :no_entry_sign: | | othermode | template模板 | | trouble | 办公终端报修流程(*pause) :wrench: | | zx_apply | 专线业务开通辅助(*alpha*) :fire: | 本地 clone 后需要在本目录下执行一次 `composer install` composer 的安装及使用请查看: [composer 中文网](http://www.phpcomposer.com/ ) > 另:`public/static/`内文件已打包,不保存在repo中。详见[release](https://github.com/thianda/phpweb/releases)。 > > `docs`需搭环境(*jekyll*)在`docs/`内执行`x.da-build-sh.sh`生成静态文档。 ### 生成docs步骤 以windows系统为例,安装git-for-windows后,使用 git-bash,切换到`/docs`目录 1. 安装 rubyinstaller [官网下载](https://rubyinstaller.org/downloads/)安装 2. 安装 jekyll ```sh gem install jekyll ``` 安装出错请参考[这里](https://thianda.github.io/notes/create-blog-by-using-jekyll.html#%E5%AE%89%E8%A3%85jekyll)。 3. 安装 bundler ```sh gem install bundler ``` 4. 安装依赖 ```sh bundle install ``` 5. 生成静态文档到`/public/phpweb` ```sh ./x.da-build-sh.sh ``` ### LICENSE MIT<file_sep>/application/kxeams/controller/User.php <?php namespace app\kxeams\controller; use think\Db; class User extends C { /** * 管理条例 * * {@inheritdoc} * * @see \app\controller\C::index() */ public function index() { $this->assign ( [ "laws" => $this->getSysInfo ( "laws" ) ] ); return $this->fetch (); } /** * 资产概况 */ public function main() { return $this->fetch (); } /** * 领用申请 */ public function apply() { if (request ()->isGet ()) { return $this->fetch ( "apply" ); } else { // 处理提交的数据 return dump ( input ()); $applyFormData = input ( "apply/a" ); $formAccount = $applyFormData [0] ['formAccount']; $applyFormData [0] ['progress'] = config ( "progress.0" ); $main = model ( "Main" ); if ($main->allowField ( true )->save ( $applyFormData [0] )) { // 保存 main (流水账) 返回的 id 用来保存到 detail 表 $main_id = $main->id; $formName = [ "item_id", "count", "dusage", "dremarks" ]; $list = [ ]; for($id = 1; $id <= $formAccount; $id ++) { // 遍历 领用物品的 Form $list [$id - 1] ["main_id"] = $main_id; for($i = 0; $i < count ( $formName ); $i ++) // 遍历 FormName 取值 $list [$id - 1] [$formName [$i]] = $applyFormData [$id] [$formName [$i]]; } $detail = model ( "detail" ); if ($detail->allowField ( true )->saveAll ( $list )) { return [ "state" => 1, "text" => "提交成功" ]; } else { // 保存 detail 数据表出错 return [ "state" => 0, "title" => "保存领用明细数据表出错", "type" => "alert-error", "text" => "请联系开发者处理。" ]; } } else { // 保存 main 数据表出错 return [ "state" => 0, "title" => "保存领用表单数据表出错", "type" => "alert-error", "text" => "请联系开发者处理。" ]; } } } public function todo() { if (request ()->isGet ()) { $this->assign ( "list", $this->refleshTodoList () ); return $this->fetch (); } else { $req = input ( "post.req" ); $main_id = input ( "post.main_id" ); if ($req == "getDetail") { return $this->todoDetail ( $main_id ); } $form_type = mb_substr ( input ( "post.form_type" ), 2 ); $from_store = input ( "post.from_store" ); $mlogs = strlen ( input ( "post.mlogs" ) ) == 0 ? "" : $mlogs . "\n"; if ($req == "yes") { Db::name ( "main" )->where ( "id", $main_id )->update ( [ "from_store" => $from_store, "progress" => config ( $form_type . "进度.2" ), "mlogs" => $mlogs . config ( $form_type . "进度.2" ) . "," . session ( ('user.name') ) . "," . date ( 'Y-m-d H:i:s' ) ] ); return $this->refleshTodoList (); } else if ($req == "no") { Db::name ( "main" )->where ( "id", $main_id )->update ( [ "from_store" => $from_store, "progress" => config ( $form_type . "进度.1" ), "mlogs" => $mlogs . config ( $form_type . "进度.1" ) . "," . session ( ('user.name') ) . "," . date ( 'Y-m-d H:i:s' ) ] ); return $this->refleshTodoList (); } else { return $this->error ( "无法执行您的请求。" ); } } } /** * 刷新 todoList 数据 * * @return string */ protected function refleshTodoList() { $where1 = "`progress` = '" . config ( "领用进度.0" ) . "' and `form_type` = '维材领用' and `from_dept` = '" . session ( "user.dept" ) . "'"; $where2 = "`progress` = '" . config ( "发放进度.0" ) . "' and `form_type` like '%发放' and `from_dept` = '" . session ( "user.dept" ) . "'"; $data = Db::name ( "main" )->where ( $where1 )->whereOr ( $where2 )->order ( "mcreate_time desc" )->select ( ); return json_encode ( $data, 256 ); } public function history() { $where = [ 'to_dept' => session ( "user.dept" ) ]; $list = $this->getMain ( $where ); $this->assign ( "list", $list ); return $this->fetch (); } protected function getMain($where = []) { $data = Db::name ( "main" )->where ( $where )->order ( "mcreate_time desc" )->select (); return json_encode ( $data, 256 ); } /** * 根据条件查询数据(无用) * * @param string $table * @param string $field * @param array $where */ public function match_item($field = '', $where = []) { if ($field == '') $field = input ( "post.field" ); if ($where == '') $where = input ( "post.where/a" ); return Db::name ( "item" )->where ( $where )->field ( $field )->select (); } public function t() { $a = [ ]; $a [0] ["name"] = "name0"; $a [0] ["type"] = "type0"; $a [1] ["name"] = "name1"; $a [1] ["type"] = "type1"; $b = [ [ "name" => "name0", "type" => "type0" ], [ "name" => "name1", "type" => "type1" ] ]; echo "a<br>" . dump ( $a ); echo "b<br>" . dump ( $b ); die (); // return dump(json_encode($b)); $field = "name,type,maker,units"; $where ["class"] = "备品"; $where ["units"] = "箱"; return dump ( $this->match_item ( $field, $where ) ); } }<file_sep>/application/kxeams/controller/Index.php <?php namespace app\kxeams\controller; use think\Controller; use think\Session; use think\Db; use think\Request; class Index extends Controller { protected function _initialize() { // $this->assign("version" , C::getSysInfo ( "version" )); $this->assign ( "version", config ( "version" ) ); } public function index() { return $this->redirect ( 'default' ); } public function t() { return $this->replace ( "aaa'aa" ); // return $this->fetch("t",[],Config::get('view_replace_str')); // return $this->fetch ( "t" ); } public function login() { $info ["txtUser"] = input ( "post.txtUser" ); $info ["txtPwd"] = input ( "post.txtPwd" ); $info ["txtUser"] = $this->replace ( $info ["txtUser"] ); $info ["txtPwd"] = $this->replace ( $info ["txtPwd"] ); if ($info ['txtUser'] == null || $info ['txtPwd'] == null) { return $this->redirect ( 'default' ); } // 首先验证kxeam用户 $user = Db::query ( "select `name`,`role`,`dept`,`office`,`tel`,`v_no` from asset_user where `loginname`=? and password=?", [ $info ["txtUser"], $info ["txtPwd"] ] ); if (null == $user) { // 若kxeam验证失败,验证ESserver用户 $sql = "select UserLogin,UserName from [ESApp1].[dbo].[ES_User] where UserLogin = '" . $info ["txtUser"] . "' and UserPwd = '" . $info ["txtPwd"] . "'"; $ESuser = $this->query ( $sql ); if (null == $ESuser) { return $this->error ( "账号或密码错误,请重试!", "index", "", 10 ); } else { $user = Db::query ( "select `name`,`role`,`dept`,`office`,`tel`,`v_no` from asset_user where `loginname`=?", [ $ESuser [0] ['UserLogin'] ] ); } } if ($user != [ ]) { $user = $user [0]; // 同步一下密码 db ( "user" )->where ( 'loginname', $info ["txtUser"] )->setField ( 'password', $info ["txtPwd"] ); foreach ( $user as $k => $u ) { Session::set ( "user." . $k, $u ); } if (strpos ( $user ['role'], "管理员" ) !== false) { return $this->success ( "登录成功," . $user ['name'] . ",正在跳转", "Manage/index", "", 1 ); } else if (strpos ( $user ['role'], "用户" ) !== false) { return $this->success ( "登录成功," . $user ['name'] . ",正在跳转", "User/index", "", 1 ); } else { // return dump ( $user ); return $this->error ( "权限获取异常,请联系管理员!", "", "", 10 ); } // return dump ( Session::get ( 'user' ) ); } else { return $this->error ( "您无权登陆维材管理,请联系管理员!", "index", "", 10 ); } // 默认 密码 _<PASSWORD> md5: 65<PASSWORD>54e3e3051651cb7<PASSWORD>4db2 // 123456 md5: e10adc3949ba59abbe56e057f20f883e // $this->success ( "登录成功,正在跳转...", "Manage/index" ); } /** * 执行Sql语句,$encoding 为 true,将执行结果的数组key转换为UTF-8(处理sqlServer表列名为中文时乱码的情况) * * @param unknown $sql * @param string $encoding * @return mixed|NULL */ protected function query($sql, $encoding = false) { $res = Db::connect ( "db_esserver" )->query ( $sql ); if ($encoding) { $ans = [ ]; for($i = 0; $i < count ( $res ); $i ++) { foreach ( $res [$i] as $k => $v ) { $ans [$i] [iconv ( "GB2312", "UTF-8//IGNORE", $k )] = $v; } } $res = null; return $ans; } else { return $res; } } protected function replace($str) { return preg_replace ( "/\'/", "", $str ); } public function _empty() { $request = Request::instance (); $dir = APP_PATH . $request->module () . DS . "view" . DS . $request->controller () . DS . $request->action () . "." . config ( 'template.view_suffix' ); if (file_exists ( $dir )) return $this->fetch ( $request->action () ); else { return $this->error ( "请求未找到,将返回上一页...(kxeams/controller/Index.php->_empty())" ); } } } <file_sep>/application/zx_apply/model/Infotables.php <?php namespace app\zx_apply\model; use think\Model; use traits\model\SoftDelete; class Infotables extends Model { use SoftDelete; protected $deleteTime = 'delete_time'; protected $autoWriteTimestamp = true; protected $dateFormat = 'Y-m-d'; protected $type = [ // "aDate" => "date", "extra" => "array" ]; public function setIpAttr($value) { if (is_int($value)) { return $value; } else { return Iptables::ip_parse($value)[2]; } } public function getIpAttr($value, $data) { return Iptables::ip_export($value, isset($data["ipMask"]) ? $data["ipMask"] : -1); return $value ? long2ip($value) : null; } public function setIpBAttr($value) { if (is_int($value) || "" == $value) { return $value; } else { return Iptables::ip_parse($value)[2]; } } public function getIpBAttr($value, $data) { return Iptables::ip_export($value, isset($data["ipBMask"]) ? $data["ipBMask"] : -4); } public function setNeFactoryAttr($value) { // if (preg_match_all ( "/[0-9]/", $tt ) == strlen ( $tt )) { if (is_numeric($value) && floor($value) == $value) { // 是数字,且是整数 return $value; } else { $ne = array_search($value, [ "华为", "中兴", "ONU" ]); return is_int($ne) ? $ne : null; } } public function getNeFactoryAttr($value) { $zx_nefactory = [ 0 => "华为", 1 => "中兴", 2 => "ONU", 3 => null ]; return is_null($value) ? null : $zx_nefactory[$value]; } // public function getStatusAttr($value) { // $statusArr = [ // 0 => "申请", // 1 => "预分配", // 2 => "已流程", // 3 => "已备ip", // 4 => "已做数据", // 9 => "历史导入" // ]; // return array_key_exists ( $value, $statusArr ) ? $statusArr [$value] : ""; // } /** * 新增Info,type可选导入、申请 * * @param string $data * @param string $type * @return number[]|\think\false[] */ public static function createInfo($data = "", $type = "") { $result = []; if ($type == "import") { foreach ($data as $k => $d) { $infotables = new static(); $data[$k] = array_merge([ "tags" => "导入", "status" => 9 ], $data[$k]); // 清除空元素 $data[$k] = array_filter($data[$k]); $infotables->isUpdate(false)->allowField(true)->save($data[$k], []); $result[$k] = $infotables->id; if (isset($data[$k]["vlan"]) && isset($data[$k]["aStation"])) { // 如果vlan不为空,则记录vlan表 Vlantables::createVlan($data[$k]["aStation"], $data[$k]["vlan"], $data[$k]["cName"], $result[$k]); } } } if ($type == "apply") { $infotables = new static(); $data["tags"] = "申请"; $data["status"] = 0; $result = $infotables->isUpdate(false)->allowField(true)->save($data, []); } return $result; } }<file_sep>/application/trouble/controller/Index.php <?php namespace app\trouble\controller; use app\trouble\controller\Common; use think\Db; use app\trouble\model\Forms; use think\Validate; use think\Session; class Index extends Common { public function t() { return base64_decode ( input ( "t" ) ); } /** * 登陆 * * @return mixed|string */ public function index() { if (input ( "?param.u" ) && input ( "?param.p" )) { return $this->loginIn ( input ( "param.u" ), input ( "param.p" ), input ( "param.e/d" ), input ( "param.m/d" ) ); } else { if (request ()->isMobile ()) { return $this->redirect ( "main" ); } else { return $this->fetch ( "main_pc" ); } } } private function loginIn($userLogin = null, $userPwd = null, $encrypt, $email = false) { if (preg_match ( "/[^A-Za-z0-9=]+/", $userLogin )) { return $this->error ( "参数格式错误" ); } // 获取用户名 $u = base64_decode ( $userLogin ); if (! Validate::max ( $u, 20 )) { return $this->error ( "输入参数异常:Too many..." ); } // 根据登录方式登录 if ($email) { return $this->loginEmail ( $u, base64_decode ( $userPwd ) ); } else { // 根据密码格式获取密码 if ($encrypt) { // $encrypt大于 1 表示账号登录提交的base64_decode『基于window.btoa的 utf8_to_b64()』。 // $encrypt等于 1 表示明文提交(测试用) // $encrypt等于 false 表示提交的MD5(书签访问) $userPwd = $encrypt > 1 ? base64_decode ( $userPwd ) : $this->pwd ( $userPwd ); } return $this->loginES ( $u, $userPwd ); } } private function pwd($p = '') { return strtoupper ( md5 ( $p ) ); } private function loginEmail($email, $vcode) { $info = Db::name ( "check" )->where ( "loginName", $email )->order ( "time desc" )->limit ( 1 )->find (); if ($info) { if (sprintf ( "%04s", $info ['code'] ) == $vcode) { if (time () - strtotime ( $info ['time'] ) < 1800) { // 30分钟之内 $user = $this->getLocalinfo ( null, $email ); foreach ( $user as $k => $u ) { Session::set ( "user." . $k, $u ); } return $this->success ( "登录成功", "view", null, 1 ); } else { return $this->error ( "验证码已过期,请重新获取" ); } } else { return $this->error ( "验证码错误" ); } } else { return $this->error ( "请先获取验证码" ); } } private function loginES($u, $userPwd) { $field = 'UserLogin,UserName,UserPwd,Email,MobilePhone'; $user = Db::connect ( config ( "db_esserver" ) )->name ( "User" )->field ( $field )->where ( "UserLogin", $u )->find (); if (empty ( $user )) { return $this->error ( '用户[' . $u . ']不存在<br>请重试' ); } if ($user ['UserPwd'] == $userPwd) { $user = $this->getLocalinfo ( $user ); foreach ( $user as $k => $u ) { if ($k != 'UserPwd') { Session::set ( "user." . $k, $u ); } } if (! request ()->isMobile () && ! request ()->isAjax ()) { return $this->display ( "<h1>登陆成功,<a href='view.html'>跳转</a></h1>" ); } return $this->success ( "登录成功", "view", null, 1 ); } else { return $this->error ( "密码错误" ); } } private function getLocalinfo($u, $e = null) { $field = 'UserName,UserDept,UserDept2,UserRole'; if ($u) { $where = [ "UserLogin" => $u ['UserLogin'] ]; } else { $u = [ 'Email' => $e ]; $where = $u; } $info = Db::name ( "user" )->field ( $field )->where ( $where )->find (); if ($info) { foreach ( $info as $k => $i ) { $u [$k] = $i; } } return $u; } protected function sendEmail($address = '', $subject = '', $body = '', $url = "") { $mail = new \PHPMailer (); $mail->isSMTP (); // Set mailer to use SMTP $mail->CharSet = "utf-8"; $mail->SetLanguage ( 'zh_cn' ); // $mail->SMTPDebug = 1; $mail->Host = 'smtp.139.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = "<EMAIL>"; // SMTP username $mail->Password = '<PASSWORD>'; // SMTP password // $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 25; // TCP port to connect to $mail->setFrom ( '<EMAIL>', '终端故障报修' ); $mail->addAddress ( $address ); // Name is optional // $mail->addReplyTo ( '<EMAIL>', 'Information' ); // $mail->addCC ( '<EMAIL>' ); // $mail->addBCC ( '<EMAIL>' ); // $mail->addAttachment ( '/var/tmp/file.tar.gz' ); // Add attachments // $mail->addAttachment ( '/aa.jpg', '附件new.jpg' ); // Optional name // 绝对路径从磁盘根目录算起,相对路径从public/idnex.php算起。 $mail->isHTML ( true ); // Set email format to HTML $mail->Subject = $subject; $mail->Body = $body; $mail->AltBody = '您的邮件客户端不支持查看HTML格式的邮件正文。请换个方式查看此邮件'; if (! $mail->send ()) { return $mail->ErrorInfo; } else { return true; } } /** * 获取邮件验证码 * * @param string $e * @return void|string */ public function getVcode($e = '', $ttl = 120) { if (preg_match ( '/[^A-Za-z._]+/', $e )) { return $this->error ( '非法邮箱地址哦' ); } else { $e = strtolower ( $e ); } // 检查30分钟内是否已申请 $data = Db::name ( "check" )->whereTime ( 'time', '-31 min' )->where ( "loginName", $e )->order ( "time desc" )->find (); if ($data) { // if (time () - strtotime ( $data ['time'] ) < 1800) { return $this->success ( "距离上一次申请间隔小于30分钟,请勿重复操作。" ); // } } else { // 检查生成的验证码是否与生效中的其他用户的相同 $data = Db::name ( "check" )->field ( "code" )->whereTime ( 'time', '-31 min' )->select (); $codes = [ ]; foreach ( $data as $d ) { $codes [] .= $d ['code']; } $vcode = rand ( 0, 9999 ); while ( in_array ( $vcode, $codes ) ) { $vcode = rand ( 0, 9999 ); } // 存入数据库 $insertData = [ 'code' => $vcode, 'loginName' => $e ]; Db::name ( "check" )->insert ( $insertData ); } $address = $e . '@ln.chinamobile.com'; $subject = '-终端故障报修-您的登录验证码为:【' . sprintf ( "%04s", $vcode ) . '】请在30分钟内使用。'; $body = '<p>您申请了邮箱登录的验证码,若本次非本人操作,请忽略本邮件</p><hr><br> <p style="text-align:right;">Powered by <a href="")">Thianda</a></p>'; // $sendEmail = $this->sendEmail ( $address, $subject, $body ); $sendEmail = true; if (is_bool ( $sendEmail )) { $msg = "验证码已通过邮件发送,请到邮箱内查收来自<b><EMAIL></b>的邮件。"; return $this->success ( $msg, null, 2 * $vcode ); } else { Db::name ( "check" )->where ( 'code', $vcode )->delete (); return $this->error ( '邮件发送未成功:' . $sendEmail ); } } /** * 首页 查看所有历史申请单 * * @param number $page * @return mixed|string */ public function view() { return $this->fetch (); } public function getView($page = 1, $listRows = 3) { $field = "id,applicant,createTime,troubleDescrition,status"; $data = Db::name ( "forms" )->field ( $field )->order ( 'createTime desc' )->page ( $page, $listRows )->select (); $data = Forms::beautify ( $data ); return json ( $data ); } public function detail($id = 0) { $data = Db::name ( "forms" )->find ( $id ); $data = Forms::beautify ( $data, true ); $this->assign ( "data", $data ); return $this->fetch (); } public function more($id = 0) { return $this->detail ( $id ); } public function sendList() { $list = db ( "user" )->field ( [ 'concat(UserName," ",MobilePhone)' => "UserName" ] )->where ( "UserRole", 4 )->select (); return json ( $list ); } public function getDetail($id = 0) { // $fieldMode = [ // // 流水查看 // 'flow' => "id,applicant,createTime,troubleDescrition,status", // // 部门审批详细页 // 'deptA' => "id,applicant,emailAddr,createTime,dept2,dept,troubleType,troubleDescrition,logs,status", // // 客响审批详细页 // 'kxA' => "id,applicant,emailAddr,createTime,dept2,dept,troubleType,troubleDescrition,applicationApproval,applicationApprovalTime,logs,status", // // 受理派单详细页 // 'receive' => "id,applicant,emailAddr,createTime,dept2,dept,troubleType,troubleDescrition,applicationApproval,applicationApprovalTime,approvalOpinion,approvalTime,logs,status", // // 代维受理详细页 // 'accept' => "id,applicant,emailAddr,createTime,dept2,dept,troubleType,troubleDescrition,applicationApproval,applicationApprovalTime,approvalOpinion,approvalTime,receiver,dispatchTime,logs,status", // // 申请人确认详细页 // 'confirm' => "id,applicant,emailAddr,createTime,dept2,dept,troubleType,troubleDescrition,applicationApproval,applicationApprovalTime,approvalOpinion,approvalTime,receiver,dispatchTime,acceptanceTime,results,logs,status" // ]; $field = ""; $data = Db::name ( "forms" )->field ( $field )->find ( $id ); $data = Forms::beautify ( $data, true ); return json ( $data ); session ( "user.UserRole" ); } // 修改报修单信息(无安全验证) public function handle() { $data = input (); if (! empty ( $data ) && ! empty ( $data ['id'] )) { Forms::update ( $data, [ "id" => $data ['id'] ], true ); return $this->getDetail ( $data ['id'] ); } else { return $this->display ( "<h1>传入为空</h1>" ); } } // 修改报修单信息(验证权限) public function handlec() { $field = 'logs,status'; $fieldAttr = [ 0 => 'marks', 1 => 'applicationApproval,applicationApprovalTime', 2 => 'approvalOpinion,approvalTime', 3 => 'receiver,dispatchTime,managerConfirm', 4 => 'acceptanceTime,results' ]; $userRole = session ( "user.UserRole" ) ? session ( "user.UserRole" ) : 0; $field .= $fieldAttr [$userRole]; $data = input (); if (! empty ( $data ) && ! empty ( $data ['id'] )) { Forms::update ( $data, [ "id" => $data ['id'] ], $field ); return $this->getDetail ( $data ['id'] ); } else { return $this->display ( "<h1>传入为空</h1>" ); } } public function todo() { $d = Db::name ( "check" )->find ( [ "code" => "0123" ] ); return dump ( time () - strtotime ( $d ['time'] ) ); } public function getUser() { } /** * 填写申请单 * * return mixed|string */ public function apply() { return $this->fetch (); } /** * 我的 * * @return mixed|string */ public function my() { return $this->display ( implode ( session ( "user" ), "," ) ); } /** * 我的申请单 * * @return mixed|string */ public function mine() { return $this->fetch (); } } <file_sep>/docs/404.md --- layout: center permalink: 404.html --- ``` 404 (_) | | __ __ _ __ _ _ __ __| | __ _ \ \/ /| | / _` || '_ \ / _` | / _` | > < | || (_| || | | || (_| || (_| | /_/\_\|_| \__,_||_| |_| \__,_| \__,_| \_' o __ __ __| __ / \ | (__( | ) (__| (__( ``` Sorry, we can't seem to find this page's pixylls. <div class="mt3"> <a href="{{ site.baseurl }}/" class="button button-blue button-big">Home</a> <a href="{{ site.baseurl }}/contact/" class="button button-blue button-big">Contact</a> </div> <file_sep>/application/kxeams/config.php <?php return [ 'version'=>"V1.0417-kx", '领用进度'=>[ 0=>"待审批", 1=>"审批未通过", 2=>"审批通过", ], '发放进度'=>[ 0=>"待知晓", 1=>"拒绝接收", 2=>"同意接收", ], ];<file_sep>/docs/_posts/2017-12-17-zx-apply.md --- layout: post title: 专线开通全流程辅助工具 date: 2017-12-17 20:24:02 summary: 记录需求,开发思路等 categories: notes update_date: 2018-05-18 16:15:34 --- ## 工作流程 ```flow st=>start: 0.申请 e=>end: 结束 op1=>operation: 1.审核并分配ip、vlan op2=>operation: 2.发起资管流程 op3=>operation: 3.资管录ip等客户信息 op4=>operation: 4.工信部、集团ip备案 op5=>operation: 5.数据制作 op6=>operation: 6.资管录vlan信息 st->op1->op2->op3->op4->op5->op6->e ``` ## 一、功能模块 ### 首页登录 用户无需注册,在首页使用邮箱加验证码登录。登录后默认为前台用户。后台权限账号需修改配置预设,无法在前台系统中设置。 > 为防止滥发邮件验证码,可限制登录邮箱的域名,限制发送验证码频率。单位时间内超过预设频次可触发相应操作,如记录系统日志并发送告警邮件。 用户获取验证码操作和登录操作会记录系统日志。 ### IP/VLAN 申请 前台用户根据预设的表单填写客户信息。提交后,可触发相关操作,如记录系统日志,给后台账号发送待办邮件通知等。 表单数据可按专线类别区分。不同类别的专线可设置不同的填写字段, IP 地址彼此不冲突,可独立分配,计算。 ### IP/VLAN 查询 前台用户可查询并导出自己申请过的客户信息为 excel。不可以直接修改,右键可以修改后重新提交申请,可以相同客户信息再申请多个 ip。 > `当前页搜索`和`全局搜索`可查询当前用户申请过的所有信息,`历史信息查询`可查询所有信息,但仅显示部分非敏感信息,每次`历史信息查询`均记录到系统日志。`历史信息查询`限制查询频率,单位时间内查询次数超过预设频次会触发发送告警邮件,并强制将前台用户踢下线。 ### 待办 前台提交申请后,管理员可在待办中查看申请信息,审核后可参考预分配信息分配 ip、vlan,提交时会可触发相关操作,如输出某种格式的模板数据(excel 文件)并以邮件附件发送。 ### 台账导入 历史数据可按模板修改为符合录入的格式,导入到系统。 > 导入操作无数据验证,需谨慎操作 > > - 无有效性验证,即:不会验证 ip、vlan、实例标识等是否与已有数据冲突。 > - 无合法性验证,即:A 端基站等字段若不是枚举值,依然可录入系统。 ### 数据查询 使用类 excel 的界面展示,每行一条数据。前台用户不可直接修改,但可以修改后重新申请。后台账号可查询、修改,删除,导出 excel 等其他操作。 附加功能不限于下列内容 - 可根据某字段设置不同行的背景色 - 可根据不同预设格式导出不同格式的 excel - 可根据数据制作的逻辑生成脚本(客户名转拼音生成`description`) - 导出全量台账,格式兼容旧台账。信息较全。 ### 系统设置 设置最后一次分配的 ip,用于预分配推荐。 查看/补充 vlan 使用情况,可手动补充新增已使用 vlan,但不可删除。 ## 二、使用帮助 > todo ## 三、数据结构 根据实际需求,数据产生的先后顺序,设计如下几张数据表: ### IP 模型 无对应数据表。模型内函数仅在处理时调用。 > IP地址存储类型:int > 1. 利用 MySQL 函数进行处理。可以采用 INET_ATON,INET_NTOA 函数进行转换。 > 2. 利用开发语言的函数进行处理,以 php 进行举例。可以采用 ip2long,long2ip 函数进行转换。 ```php # PHP存入时: $ip = ip2long($ip); # MySQLl取出时: SELECT INET_ATON(ip) FROM table # PHP取出时,多一步: $ip = long2ip($ip); ``` **主要函数功能** 预分配推荐、设置最后已分配 ip、检查 ip / ipB 是否冲突、ip 是否可用、ip 的字符串格式与 int 格式的相互转换。 ### vlan 模型 同一台交换机内 vlan 不可重复 **主要函数功能** 录入 vlan、自动预分配、导入已使用 vlan、检查 vlan 是否冲突。 ### 申请信息表模型 申请开通时提供的信息,基于模板 excel 表格,都是必填项。 除 `extra`字段均为普通字段,大部分与表单的字段对应。个别字段为系统生成,用于逻辑判断与数据计算。 extra 字段为附加字段,json 格式,可根据实际需求拓展。 ### 系统日志模型 保存系统日志,任意操作可触发记录日志。 ### 邮件验证码模型 记录发送的邮件验证码,验证时使用。 ### 系统参数模型 预设某些系统参数。 ## 四、功能逻辑 ### 首页登陆 <https://exceltl.tk/zx_apply/> - 根据邮箱验证码登录,基于 localStorage 保存会话。有效期15天。 - 有效期内免验证登陆。通过 URL 访问会直接跳回登陆页面并自动登录。 - 登陆后判断权限,跳转至对应页面 - 域名已启用 TLS_AES 加密。已申请 https 证书 - 为防止滥发邮件验证码,可限制登录邮箱的域名,限制发送验证码频率。 - 单位时间内超过预设频次记录可触发响应操作,如记录系统日志并发送告警邮件。 ### 用户-申请 - 填写信息,数据校验后可提交。并发送待办邮件给后台用户。 ### 用户-信息查询 - 基于邮箱筛选,仅可查看/修改自己邮箱申请过的信息。查询结果使用 ajax 返回,并在前端重新渲染。 - 重新申请 - 同客户信息申请多个 ip - 导出为 excel ### 管理-待办 - 显示申请后未自动分配的列表。点击显示详细信息,内容均可修改,填写 ip、vlan 后可提交 - ip 录入格式:`xxx.xxx.xxx.xxx[/mask]`,如:`172.16.17.32`或`172.16.32.24/30` - 提交时更新数据表`infotables`。并返回提交结果和最新的待办列表 - 提交时自动判断录入的 ip、vlan 是否重复,重复则返回失败的提示,并自动关联`vlantables` ### 管理-导入历史数据 - 导入历史数据 (强校验) - 根据模板复制粘贴(可多条) - 单条填表录入(暂不支持,可使用`用户-申请 ip、vlan`代替) ### 管理-查询 - 展示台账,可全局按列模糊搜索 > 仅`客户名`、`产品示例标识`、`vlan`列 - 点击单条台账,显示详细信息 - 直接编辑台账信息,提示是否同步至服务器的确认对话框,此设置当前回话内有效 > 此处修改时不做数据冲突验证,需注意 - 部分字段涉及数据校验,当前页不可编辑,需在详细信息窗口标记为`刚申请`,然后回到待办页修改并提交 - 右键点击台账,发现更多操作 ### 管理-设置 - 更新最后一次分配的 ip - 更新录入 sw 交换机的已分配 vlan,如已存在则忽略,并给出执行结果。 ## 五、需求分析 - 不需要显示所有信息,查询可由服务器完成。全局查询或导出全部台账为 excel 下载后手动查询。 - 数据呈现与数据存储格式不一致,存储格式可扩展,前后端数据同步操作需**额外开销**。 - 显示带有不同**标签**的数据的数量,点击显示详细条目信息。 - 需一眼看出分配到哪个 ip 了 - 独立的 vlan 预分配记录表 - 数据表设计字段类型需考虑历史数据迁移问题 方案 1:数据表字段类型不严格限制,均为 varchar。 方案 2:设计两张数据表,保存旧数据的采用方案1设计,新数据符合规范,严格设置字段类型及大小。 方案 3:按照新数据严格限制,历史数据迁移前整改历史数据的数据规范,直至符合数据规范。 若方案 1,查询搜索方便,但性能有损。前端严格验证,数据格式、数据安全不可控。 若方案 2,新数据格式规范无隐患,且便于将来大数据分析。 但查询需指定数据表,设计复杂, 若方案 3,最优方案,整改耗时耗力。 ## 六、使用场景涉及的操作备忘录 ### 预分配ip、vlan--manage/todo ``` Manage/todo() checkInstanceId() checkAndSetIp() checkAndSetVlan()->Vlantables::createVlan() updateInfo()->Iptables::setLastIp() refleshTodoList() ``` ### 查询页面生成制作脚本--manage/query ``` Tool/_script.html Magage/_getDevice9312Info() ``` ### 查询页面修改/导出信息--manage/query ``` Manage/query() getInfoData() queryDelete() Index/querySearch() Index/queryUpdateInfo() queryExport() ``` ### 管理-导入历史数据--manage/import ``` Manage/import() checkDateIsValid() _ht_apply()->Infotables::createInfo()->->Vlantables::createVlan() ``` ### 管理-设置-manage/settings ``` Manage/settings() ->Iptables::setLastIp() ->Vlantables::importUsedVlan() ``` <file_sep>/application/zx_apply/controller/Manage.php <?php namespace app\zx_apply\controller; use think\Controller; use think\Db; use app\zx_apply\model\Vlantables; use app\zx_apply\model\Infotables; use app\zx_apply\model\Iptables; use Overtrue\Pinyin\Pinyin; class Manage extends Index { protected $beforeActionList = [ 'checkAuth' ]; protected function checkAuth() { if (session("user.role") != "manage") { return $this->redirect("index/query"); } } public function index() { return $this->redirect("todo"); } /** * 待办 * * @param boolean $ignoreCheck * @return void */ public function todo($ignoreCheck = false) { if (request()->isGet()) { $this->assign("list", $this->refleshTodoList()); return $this->fetch(); } if (request()->isPost()) { $req = input("get.req"); // $infotables = new Infotables (); // 无论是什么请求,先获取数据库的 info $info = Infotables::get(input("post.id")); // 获取器数据 $data = input("post."); if ($info) { // 设置不需要输出的字段 $detail = $info->hidden([ 'aDate', 'tags', 'ipMask', 'ipBMask', 'create_time', 'update_time', 'delete_time' ])->toArray(); } else { return $this->success("这条待办找不到啦!"); } $extra = $detail["extra"]; if (is_array($extra)) { foreach ($extra as $k => $v) { $detail[$k] = $v; } } unset($detail["extra"]); $detail["ip"] = $info->ip; // 更正ip为 str 形式 $detail["ipB"] = $info->ipB; // 更正ipB if ($req == "getDetail") { // 返回单条数据及同客户名的信息摘要 $cName = mb_substr($info->cName, 2, 10, "utf-8"); $field = "id,instanceId,cName,create_time,neFactory,vlan,aStation,ip,aPerson,aEmail,delete_time"; $relative = collection(Infotables::withTrashed()->where("cName", "like", "%" . $cName . "%")->where("id", "<>", $info->id)->field($field)->select())->toArray(); $result = [ "related" => $relative, "detail" => $detail, "string" => $cName ]; return json($result); } else if ($req == "auto_pre") { // 若已有ip则不再分配ip if ($detail["ip"] == "") { $genIp = Iptables::generateIP($data["zxType"]); } else { $genIp = $detail["ip"]; } // 若无A端基站则不分配vlan if ($data["aStation"] == "") { return [ "genIp" => $genIp, "device" => null ]; } else { $device = config("aStation")[$data["aStation"]]; $genVlan = Vlantables::generateVlan($device, null, 1); return [ "genIp" => $genIp, "preVlan" => $genVlan["preVlan"], "usedVlans" => $genVlan["usedVlans"], "device" => $device ]; } } else if ($req == "distribution") { // 判断是否有变化 $ifChanged = false; foreach ($detail as $k => $v) { if ($v != $data[$k]) { $ifChanged = true; break; } } if ($ifChanged) { $this->checkInstanceID($info, $data); $data = $this->checkAndSetIp($info, $data); $data = $this->checkAndSetVlan($data, $ignoreCheck); $this->updateInfo($data); // vlan 不为空,且 status 为 0 或者 3,则 status +1 if (isset($data["vlan"]) && ($info->status == 0 || $info->status == 3)) { Infotables::where("id", $data["id"])->setInc("status"); } return $this->result($this->refleshTodoList(), 1, "操作成功。<br>是否发送邮件通知给申请人?"); } else { return $this->result(null, 2, "本次提交无修改"); } } } } public function generateVlan() { $aStation = ""; $aStationConf = config("aStation"); if (array_key_exists(input("get.d"), $aStationConf)) { $device = $aStationConf[input("get.d")]; return Vlantables::generateVlan($device, "预分配", 1); } } protected function updateInfo($data) { $extraHeader = config("extraInfo"); foreach ($extraHeader as $k => $v) { $data["extra"][$v] = $data[$v]; unset($data[$v]); } // unset ( $data ["delete_time"] ); $infotables = new Infotables(); // 更新单条数据 $result = $infotables->isUpdate(true)->save($data, [ "id" => $data["id"] ]); // 更新最后分配的IP isset($data["ip"]) && Iptables::setLastIp($data["ip"]); $infotables->find($data["id"]); return $result; } protected function refleshTodoList() { $where = ["neFactory" => 2, "vlan" => null]; $whereor = ["status" => 0]; $field = "id,cName,create_time,aPerson,ifOnu,instanceId,zxType,aStation"; // 显示 ONU 业务 vlan 为空的,和状态为 0 的 $data = Infotables::where($where)->whereOr($whereor)->field($field)->order("create_time desc")->select(); return json_encode($data, 256); } /** * 发邮件告知申请已处理,并发送 IDC 备案信息给厂家联系人 */ public function sendResultEmail() { if (request()->isGet() || !input("?post.id")) { return $this->result("Wrong Req", 0); } $address = []; // 忽略送来的参数,从数据库获取 $order = "1,2,3,6,4,5,9,10,17,23,19"; // instanceId,zxType,bandWidth,cName,vlan,ip,ipB,mEmail,aEmail $field = $this->getHeader("zx_apply-new-rb", $order, true); $items = explode(",", $this->getHeader("zx_apply-new-rb", $order)); array_pop($items); $db = Infotables::field($field)->find(input("post.id")); $values = array_values($db->toArray()); // $title = '[ip已分配]-' . $db->bandWidth . "M-" . $db->cName; $title = '铁岭IDC.ISP-' . $db->ip . "-" . $db->cName; $contact = base64_decode('a2FuZ2xpQGV2ZXJzZWMuY24='); $body = ""; // $body .= "<p>请根据下面的ip字段,填写IDC/ISP备案信息,最新的要求和模板可在内网访问: <a href='http://10.65.187.202/i/isp'>http://10.65.187.202/i/isp</a> 查看和下载。</p>"; // $body .= "<pre style='color:#000;background-color:#ccc;padding:15px;'><p style='color:red'>目前已实现自动生成 idc.isp 备案信息。若本邮件存在附件,"; // $body .= "请<span style='color:blue'>客户经理</span>检查附件的内容是否准确、完整。<br>补充修改后请直接发送给厂家:</p>" . $contact . "<p style='color:red'>并抄送给:</p>" . $CC . "</pre>"; $body .= "<br><table style='border-collapse:collapse;border:none;'>"; for ($i = 0; $i < count($items); $i++) { $body .= "<tr>"; $body .= "<th style='width:200px;border:solid #666 1px;'>" . $items[$i] . "</th><td style='width:500px;border:solid #666 1px;'>" . $values[$i] . "</td>"; $body .= "</tr>"; } $body .= "</table>"; $address['Addr1'] = $contact; $address['CCm'] = $db->mEmail; $address['CCa'] = $db->aEmail; if($db->ifOnu){ $CCs= config("manageEmails"); foreach ($CCs as $k => $v) { $address['CC'.$k] = $v . "@ln.chinamobile.com"; } }else{ $address['CCu'] = session("user.email"); } $attachment = Generator::generateIDCinfoFiles(input("post.id")); $result = $this->sendEmail($address, $title, $body, $attachment); unlink($attachment); return $this->result($result, is_bool($result) ? 1 : 0); } /** * 信息查询 */ public function query() { if (request()->isGet()) { // 访问 $aStation = array_keys(config("aStation")); $zxTitle = [ "label" => "zx_apply-new-rb", "order" => "24,1,4,5,6,9,10,19,22,23,26" ]; $this->assign([ "aStationData" => implode(",", $aStation), "colHeaderData" => $this->getHeader($zxTitle["label"], $zxTitle["order"]), "colWidthsData" => $this->getColWidths($zxTitle["order"]), "data" => $this->getInfoData()->toJson() ]); return $this->fetch(); } if (request()->isPost()) { // 获取台账 // return $this->getInfoData(); input("post.r") == "info" && $data = $this->getInfoData(input("post.zxType"))->toArray(); input("post.r") == "detail" && $data = Infotables::get(input("post.id"))->toJson(); input("post.r") == "search" && $data = $this->querySearch(input("post.")); input("get.r") == "update" && $data = $this->queryUpdateInfo(input("post.")); input("post.r") == "delete" && $data = $this->queryDelete(input("post.")); return $data; } if (request()->isPut()) { // 相关操作 input("post.r") == "script" && $data = Generator::generateScript(input("post.id/a")[0]); input("post.r") == "export_zg" && $data = Generator::generateZgWorkflow(input("post.id")); input("post.r") == "export_jtip" && $data = Generator::generateJtIp(explode(",", input("post.id"))); input("post.r") == "export_gxbip" && $data = Generator::generateGxbIp(explode(",", input("post.id"))); input("post.r") == "export" && $data = $this->queryExport(input("post.zxType")); return $data; } } public function _getDevice9312Info() { return base64_decode(config("device9312")); } /** * get:加载数据到handsontable并验证, * post:上传,后台处理入库 * 1.默认post为新申请,移除ip、vlan信息再保存, * 严格验证,不合规不许提交,标记status:0 * 2.带post参数type=import,视为旧信息导入, * 生成ip表(全)和vlan表信息(不全)。直接入库,并标记tags:导入 * 3.为了新增字段不修改数据库,将新增字段用json保存到一列。 * 在csv_to_array时,需要获取额外的字段 * * @return void|string|mixed|string */ public function _ht_apply() { $zxInfoTitle = [ "label" => "zx_apply-new-rb", "order" => "0,1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,29,30,31,32,33,34,35,36,37" ]; if (request()->isPost()) { $postData = input("post.data"); $type = input("post.type"); $dataHeader = $this->getHeader($zxInfoTitle["label"], $zxInfoTitle["order"], true); // 获取数据库的列名 $dataHeader = explode(",", $dataHeader); // 根据列名和数据转成php数组 // $postData = substr ( $postData, 3 ); // 莫名奇妙的前三个字节是垃圾数据。3天才研究出来,只能这样解决!!!(目前已在前端解决) $data = $this->csv_to_array($dataHeader, $postData); // return dump($data); // 获取额外的字段 $extraHeader = config("extraInfo"); foreach ($data as $k => $v) { // 清除空元素 $data[$k] = array_filter($v); $temp = []; foreach ($extraHeader as $kk => $vv) { if (isset($data[$k][$vv])) { $data[$k]["extra"][$vv] = $data[$k][$vv]; unset($data[$k][$vv]); } } if (isset($v["aStation"]) && $v["aStation"] == "柴河局") { $data[$k]["neFactory"] = isset($data[$k]["neFactory"]) ? $data[$k]["neFactory"] : ""; $data[$k]["aStation"] .= "-" . $data[$k]["neFactory"]; } $data[$k]["aDate"] = isset($data[$k]["aDate"]) ? $data[$k]["aDate"] : ""; if ($this->checkDateIsValid($data[$k]["aDate"])) { // 申请时间转存到 create_time $data[$k]["create_time"] = strtotime($data[$k]["aDate"]); } } // 若导入,ip/vlan信息要单独存储。 $result = Infotables::createInfo($data, $type); // $result = $info->save($data[0]); return dump($result); } if (request()->isGet()) { if (input('?get.t')) { $aStation = array_keys(config("aStation")); $this->assign([ "aStation" => implode(",", $aStation), 'colHeaderData' => $this->getHeader($zxInfoTitle["label"], $zxInfoTitle["order"]), "colWidthsData" => $this->getColWidths($zxInfoTitle["order"]) ]); return $this->fetch("_ht_apply"); } } } /** * ip、vlan申请 * * @return mixed|string */ public function import() { // post数据传给 _ht_apply() return $this->fetch(); } /** * 系统设置 * * @return mixed|string */ public function settings() { if (request()->isGet()) { if (!strpos(request()->header("referer"), request()->action())) { session("settings_back_url", request()->header("referer")); } $lastIp = Iptables::ip_export(Db::table("phpweb_sysinfo")->where("label", "zx_apply-lastIP")->value("value")); $this->assign([ "lastIp" => $lastIp ]); return $this->fetch(); } else if (request()->isPost()) { if (input("post.exec") == "ok_ip") { return Iptables::setLastIp(input("post.lastIpStr")); } if (input("post.exec") == "cal_ip") { $unusedIps = []; // todo return $this->result($unusedIps, 1); } if (input("post.exec") == "ok_vlan") { return Vlantables::importUsedVlan(input("post.device"), input("post.vlanImport")); } } } /** * todo预分配时检查获取的数据与数据库中的ip/ipB是否重复 * * @param unknown $info * @param unknown $data * @return void|NULL|unknown */ protected function checkAndSetIp($info, $data) { if ($info["ip"] != $data["ip"]) { // 获取的ip有变化,则检查是否冲突 $ip = Iptables::check($data["ip"], "ip", $data["zxType"]); if ($ip) return $this->error("互联ip冲突,", null, $ip["cName"]); } // 设置ipMask $ip_array = Iptables::ip_parse($data["ip"]); $data["ip"] = $ip_array[2]; $data["ipMask"] = $ip_array[1]; if ($data["ipB"] == "") { // 设置 ipB为null $data["ipB"] = null; $data["ipBMask"] = null; return $data; } if ($info["ipB"] != $data["ipB"]) { $ipB = Iptables::check($data["ipB"], "ipB", $data["zxType"]); if ($ipB) return $this->error("业务ip冲突,", null, $ipB["cName"]); } // 设置ipBMask $ipB_array = Iptables::ip_parse($data["ipB"]); /* 若未提供ipBMask,默认强制设置ipBMask为-8 */ $ipB_array[1] == -1 && $ipB_array = Iptables::ip_parse(Iptables::ip_export($ipB_array[0], -8)); /* 修正ip为ip_start */ $data["ipB"] = $ipB_array[2]; $data["ipBMask"] = $ipB_array[1]; return $data; } /** * todo预分配时检查获取的vlan是否已分配,并记录/更新 * * @param Infotables $data * @param boolean $check * @return Infotables $data */ protected function checkAndSetVlan($data, $ignoreCheck) { if ($data["vlan"] == "") { $data["vlan"] = null; Vlantables::createVlan($data["aStation"], $data["vlan"], $data["cName"], $data["id"]); return $data; } if ($ignoreCheck == false) { // default : $ignoreCheck = false $vlan = Vlantables::check($data["zxType"], $data["aStation"], $data["vlan"]); if ($vlan && $vlan["id"] != $data["id"]) { if ($vlan["code"]) { // (code = 2) vlan 存在但 aStation 不在预设范围内(为空) return $this->result(null, $vlan["code"], $vlan["cName"]); } else { // (code = 0) 找到 vlan 且 vlan 的 id 与自己的id不同 return $this->result("是否强制分配?", $vlan["code"], $vlan["cName"]); } } else { // vlan 不存在或 vlan id 与自己的 id 相同,则返回执行 infotables 的更新 } } else { // 基于 Id 更新,若更新 0 条,则新增 } Vlantables::createVlan($data["aStation"], $data["vlan"], $data["cName"], $data["id"]); return $data; } /** * 校验日期格式是否正确 * * @param string $date * 日期 * @param string $formats * 需要检验的格式数组 * @return boolean */ protected function checkDateIsValid($date, $formats = array("Y-m-d", "Y/m/d")) { $unixTime = strtotime($date); if (!$unixTime) { // strtotime转换不对,日期格式显然不对。 return false; } // 校验日期的有效性,只要满足其中一个格式就OK foreach ($formats as $format) { if (date($format, $unixTime) == $date) { return true; } } return false; } }<file_sep>/application/esserver/controller/Index.php <?php namespace app\esserver\controller; use app\common\controller\Common; use think\Db; class Index extends Common { public function index() { return $this->redirect ( "main" ); } public function main() { if (request ()->isGet ()) { return $this->fetch (); } else { // 密码重置申请 $input = input ( "post." ) ['data']; // return dump($input); $sql = "select * from [ESApp1].[dbo].[ES_User] where UserLogin = '" . $input ["UserLogin"] . "'"; $res = $this->query ( $sql ); if ($res == null) { $v = array_merge ( [ "status" => "failed" ], $input ); $this->log ( "Excel密码重置", $v ); // 账户不存在 return [ "auth" => [ "vUserLogin" => false ] ]; } else { // 登录名存在 $res = $res [0]; $auth = [ "vUserLogin" => true, "vUserName" => $res ['UserName'] == $input ['UserName'], "vMobilePhone" => $res ['MobilePhone'] == $input ['MobilePhone'] // "newEmail" => false ]; $auth ["EmptyMsg"] = ''; if ($res ['MobilePhone'] == '') { // 预留电话为空 $auth ["vMobilePhone"] = false; $auth ["EmptyMsg"] .= "预留MobilePhone为空<br>"; } $mail = $input ['Email'] . $input ['Email2']; if ($res ['Email'] == '') { // Email 为空 $auth ["vEmail"] = false; $auth ["EmptyMsg"] .= "预留Email为空"; } else if ($res ['Email'] == $mail) { // Email 相等 $auth ["vEmail"] = true; $auth ["newEmail"] = "完全匹配"; } else if (strpos ( $mail, $input ['UserLogin'] ) !== false) { // Email 包含 UserLogin 字段 $auth ["vEmail"] = true; $auth ["newEmail"] = "与登陆名符合"; } else { $auth ["vEmail"] = false; } $flag = ''; $e = ''; $num = 0; $aInfo = null; if ($auth ["vEmail"] == true) { $num ++; $flag = 'email'; $e = $res ['Email']; } if ($auth ["vMobilePhone"] == true) $num ++; if ($flag == '') $e = $res ['MobilePhone'] . "@139.com"; if ($num > 0) { $aInfo = base64_encode ( json_encode ( [ "u" => $res ['UserLogin'], "p" => $res ['UserPwd'], "e" => $e ] ) ); } return [ "auth" => $auth, "e" => $e, "num" => $num, "aInfo" => $aInfo ]; } } } public function resetpwd() { // 通过邮件链接访问 if (request ()->isGet ()) { $r = input ( "param.r" ); if ($r == null) { return $this->error ( "访问无效。", "main" ); } $r = json_decode ( base64_decode ( $r ), true ); // 若获取的 base64 编码不合法,则解析为null,计算的时间差为1900年到发信时间的时间差。 if (time () - $r ["t"] > 86400) { $msg = "此链接已过期,您可重新申请找回。"; return $this->error ( $msg, "main", '', 10 ); } $sql = "select UserLogin,UserName from [ESApp1].[dbo].[ES_User] where UserLogin = '" . $r ["u"] . "' and UserPwd = '" . $r ["p"] . "'"; $res = $this->query ( $sql ); $flag = $res == null; if ($flag) { $status = "failed"; $msg = "参数不对,请检查是否已通过其他途径修改过密码,并重新申请找回。"; } else { $this->assign ( [ 'UserLogin' => $r ["u"], 'UserPwd' => base64_encode ( $r ["p"] ) ] ); $status = "success"; $msg = "通过邮件链接访问"; } // 记录log $v = [ "status" => $status, "UserLogin" => $r ["u"], "e" => $r ["e"], "msg" => $msg ]; $this->writeLog ( "Excel密码重置申请", $v ); return $flag ? $this->error ( $msg, "main", null, 10 ) : $this->fetch (); } // main页面点击发送邮件按钮 if (request ()->isPost ()) { $input = input ( 'post.excel_data_for_resetpwd' ); if ($input == null) { // 若没有传值,则直接访问。 return $this->fetch (); } $info = json_decode ( base64_decode ( $input ), true ); $info ['t'] = time (); $r = base64_encode ( json_encode ( $info ) ); // return dump ( $r ); $subject = "【ESWeb】您刚刚申请Excel服务器账号" . $info ['u'] . "找回密码服务,请按正文操作。"; $url ['out'] = "http://172.16.58.3:800/esserver/index/resetpwd.html?r=" . $r; $url ['in'] = "http://10.65.187.202/esserver/index/resetpwd.html?r=" . $r; $body = "<p>如果您未自己进行申请重置,请忽略此邮件。</p><hr>"; $body .= "<p style='color: blue;'>请访问下面的链接进行重置密码(此链接有效期24小时):</p>"; $body .= "<p>内网>>><br><span style='font-size:10px;'><a href='" . $url ['in'] . "'>" . $url ['in'] . "</a>" . "</span></p>"; $body .= "<p>外网>>><br><span style='font-size:10px;'><a href='" . $url ['out'] . "'>" . $url ['out'] . "</a></span></p>"; $sendEmail = $this->sendEmail ( $info ['e'], $subject, $body ); if (is_bool ( $sendEmail )) { $re = [ 'status' => true, 'msg' => '相关邮件已发送,请到邮箱内查收主题包含<b>【ESWeb】</b>的邮件。' ]; } else { $re = [ 'status' => false, 'msg' => '邮件发送未成功:' . $sendEmail ]; } $v = array_merge ( [ "status" => is_bool ( $sendEmail ) ? "success" : "failed", "msg" => $re ["msg"] ], $info ); $this->log ( "Excel密码重置发邮件", $v ); return $re; } // 重置密码操作,保存新密码 if (request ()->isPut ()) { $input = input ( "post." ); if ($input ["UserPwd"] != $input ["UserPwd2"]) { return $this->error ( "两次密码不一致" ); } else { $cipherPwd = strtoupper ( md5 ( $input ["UserPwd"] ) ); if (! $this->validPwd ( $input ["UserPwd"] )) { return $this->error ( "必须包含大写字母、小写字母、数字三种组合在一起,且长度最少为8。请重试。", null, "密码复杂度不符合要求" ); } else if ($this->validPwdHis ( $input ["UserLogin"], $cipherPwd )) { return $this->error ( "密码不能与最近2次历史密码重复,请重试。", null, "新密码不符合要求" ); } else { // 更新密码操作。 $p = base64_decode ( $input ["p"] ); $sql = "update [ESApp1].[dbo].[ES_User] set UserPwd = '" . $cipherPwd . "',LstLoginTime = GETDATE(),PwdDate = GETDATE(),AccState = 0 where UserLogin = '" . $input ["UserLogin"] . "' and UserPwd = '" . $p . "'"; $res = Db::execute ( $sql ); $sql2 = "insert into [ESApp1].[dbo].[ES_UserPwdHis] values ((select UserId from [ESApp1].[dbo].[ES_User] where UserLogin = '" . $input ["UserLogin"] . "'), GETDATE(), '" . $cipherPwd . "')"; Db::execute ( $sql2 ); // $sql = "select * from [ESApp1].[dbo].[ES_User] where UserLogin = '" . $input ["UserLogin"]. "' and UserPwd = '" . $p. "'"; // $res = $this->query ( $sql ); // return dump($sql); if ($res > 0) { $msg = "密码重置成功。"; $this->writeLog ( "Excel密码重置操作", [ "status" => "success", "msg" => $msg, "name" => $input ["UserLogin"] ] ); $this->success ( $msg, "main" ); } else { $msg = "请检查是否已通过其他途径修改过密码或重试。"; $this->writeLog ( "Excel密码重置操作", [ "status" => "failed", "msg" => $msg, "name" => $input ["UserLogin"] ] ); $this->error ( $msg, null, "未能重置密码" ); } } } } } protected function query($sql, $encoding = false) { $res = Db::query ( $sql ); if ($encoding) { $ans = [ ]; for($i = 0; $i < count ( $res ); $i ++) { foreach ( $res [$i] as $k => $v ) { $ans [$i] [iconv ( "GB2312", "UTF-8//IGNORE", $k )] = $v; } } $res = null; return $ans; } else { return $res; } } protected function validPwd($pwd) { if (preg_match_all ( '/[A-Z]/', $pwd ) < 1) return false; else if (preg_match_all ( '/[a-z]/', $pwd ) < 1) return false; else if (preg_match_all ( '/[0-9]/', $pwd ) < 1) return false; else if (strlen ( $pwd ) < 7) return false; else return true; } /** * 检查是否与近N此密码相同。 * * @param unknown $u * @param unknown $p * @return boolean */ public function validPwdHis($u, $p, $t = 2) { $sql = "select top " . $t . " Pwd from [ESApp1].[dbo].[ES_UserPwdHis] where UserId = (select UserId from [ESApp1].[dbo].[ES_User] where UserLogin = '" . $u . "') order by CreTime desc"; $PwdHis = Db::query ( $sql ); $PwdHisArray = [ ]; foreach ( $PwdHis as $v ) { $PwdHisArray [] = $v ['Pwd']; } return in_array ( $p, $PwdHisArray ); } /** * 反馈-密码找回 */ public function reportLog() { if (request ()->isPost ()) { // return dump(input("param.UserLogin")); if (! input ( "?param.UserLogin" ) || ! input ( "?param.str" )) { return $this->error ( "参数无效。" ); } $where = '{"UserLogin":"' . input ( "param.UserLogin" ) . '"%'; $log = db ( "log", 'logDatabase', false )->where ( "v", "like", $where )->find (); if ($log == null) { // 不存在记录(从未反馈过) $logData = json_decode ( htmlspecialchars_decode ( input ( "param.str" ) ), 256 ); $this->writeLog ( "找回密码一键反馈", $logData ); $sendEmail = $this->sendEmail ( "<EMAIL>", "Excel服务器账户重置密码反馈-" . input ( "param.UserLogin" ), "提交信息如下:<br>" . dump ( $logData ) ); if (is_bool ( $sendEmail )) { $re = [ 'type' => 'alert', 'title' => '已成功反馈', 'msg' => '有进展会通过邮件回复你。感谢配合。' ]; } else { $re = [ 'type' => 'alert-error', 'title' => '反馈操作异常,请通过其他方式反馈', 'msg' => '通知邮件自动发送未成功:' . $sendEmail ]; } } else { // 已有记录(点击过一键反馈按钮) $time = $log ["time"]; // $time = json_decode ( $log ['v'], true ) ['time']; $re = [ 'type' => 'alert-warning', 'title' => '不要重复反馈', 'msg' => '之前反馈过下面账户的找回密码的情况<br><b>' . input ( "param.UserLogin" ) . "</b><br>反馈时间:" . $time . '<br>请勿重复操作。' ]; } return $re; } else { // 默认get请求,测试用 $logData = [ 'k' => "找回密码一键反馈-" . input ( "param.UserLogin" ), 'v' => input ( "param.str" ) ]; $log = db ( "log", 'logDatabase', false )->where ( "k", $logData ['k'] )->find (); $logArray = explode ( "\n", $log ['v'] ); return dump ( $logArray ); // return $this->error ( "不能如此访问" ); } } /** * 系统设置,基于IP限制访问 * * @return mixed|string|void */ public function setting() { return $this->error ( "您无权访问哦。", null, null, 10 ); } /** * 记录log * * @param string $k * @param array $v */ private function writeLog($k = "", $v = []) { $logData = [ "k" => $k, "v" => json_encode ( $v, 256 ), 'module' => request ()->module (), 'ip' => request ()->ip ( 1 ) ]; db ( "log", 'logDatabase', false )->insert ( $logData ); } /** * 强制重置密码 * * @param string $UserLogin */ private function fourceReset($UserLogin = "") { if ($UserLogin) { // 设置密码为姓名首拼大小写加123456 // 清空历史密码 return $this->success ( "密码强制重置完毕" ); } return $this->error ( "UserLogin为空" ); } /** * $md5 为 true 则不转为MD5(默认为false) * * @param string $name * @param string $pwd * @param string $md5 * @return void|string */ protected function SignIn($name = '', $pwd = '', $md5 = false) { if (! $md5) $pwd = strtoupper ( md5 ( $pwd ) ); $sql = "select * from [ESApp1].[dbo].[ES_User] where UserLogin = '" . $name . "' and UserPwd = '" . $pwd . "'"; $res = $this->query ( $sql ); return dump ( $res ); } }<file_sep>/docs/_posts/2017-12-21-handsontable-usage-notes.md --- layout: post title: handsontable 用法笔记 date: 2017-12-21 20:56:07--0800 summary: 开发中用到了handsontable,官网的demos、usage和api查阅起来不是很方便,在学习过程中自己整理了一下。官方版本目前已更新到5.0。 categories: notes update_date: 2018-07-27 18:15:44 --- {:TOC} ## 简介 handsontable-JavaScript Spreadsheet Component For Web Apps,这是官网的title。它是一个component。作为JavaScript组件,handsontable的特点是大数据高性能,样式与Excel非常相似。可以在web中呈现和Excel里一样的表格数据。并可在前端完成一系列复杂的数据分析及操作功能。 版本发布: - Handsontable Community Edition(Open Source) - Handsontable Pro(commercial license) 两个版本均托管在[github](https://github.com/handsontable/)。pro版在使用时会在html中以及console中添加显示如下内容:(v1.15.0) > Evaluation version of Handsontable Pro. Not licensed for use in a production environment 如使用pro版建议购买license尊重作者的劳动成果。 {% if site.url=="https://{{ site.github_username }}.github.io" %} <link rel="STYLESHEET" type="text/css" href="https://docs.handsontable.com/bower_components/handsontable-pro/dist/handsontable.min.css"> <script src="https://docs.handsontable.com/bower_components/handsontable-pro/dist/handsontable.min.js"></script> {% else %} <link rel="STYLESHEET" type="text/css" href="/static/handsontable-pro/handsontable.full.min.css"> <script src="/static/handsontable-pro/handsontable.full.min.js"></script> {% endif %} ## 干货写前面 ### 方法调用 先构造一个handsontable,然后直接使用,或者使用jQuery的封装形式。 ```javascript // all following examples assume that you constructed Handsontable like this var ht = new Handsontable(document.getElementById('example1'), options); // now, to use setDataAtCell method, you can either: ht.setDataAtCell(0, 0, 'new value'); $('#example1').handsontable('setDataAtCell', 0, 0, 'new value'); ``` ### 构造函数的options参数 ``` javascript data: # 数据源(二维数组、对象) startRows: # 初始行数 startCols: # 初始列数 rowHeaders: true # 行标 [] colHeaders: true # 列名 可以设置为自定义数组 [] colWidths: # 列宽度 integer:均等 or [] autoColumnSize:true # 列宽自适应 filters: # 过滤 dropdownMenu:true # 下拉菜单 minSpareRows: # 最小多余的行数 minSpareCols: # 最小多余的列数 afterChange: function () {}, # 修改显示后的回调函数 manualColumnMove: # 列移动 manualRowMove: true # 行移动 manualColMove: true # 列移动 true // https://docs.handsontable.com/demo-moving.html stretchH: # 拉伸高度 默认:"none" 可选 "last" "all" 用于父级不可滚动时 // https://docs.handsontable.com/demo-stretching.html copyPaste: # 复制粘贴选项 search: # 启动搜索插件 contextMenu: true # 右键菜单 可以自定义数组 [] selectionMode: # 选择模式 可选 range(默认) single multiple ``` # 基本用法 ## 快速开始 1. 在网页中引入`js`和`css`文件。推荐引入`handsontable.full.min.js`和`handsontable.full.min.css`。 2. 在html中添加容器`<div id="example"></div>`。 3. 用`JavaScript`初始化 ```javascript var data = [ ["", "Ford", "Tesla", "Toyota", "Honda"], ["2017", 10, 11, 12, 13], ["2018", 20, 11, 14, 13], ["2019", 30, 15, 12, 13] ]; var container = document.getElementById('example'); var hot = new Handsontable(container, { data: data, rowHeaders: true, colHeaders: true, filters: true, dropdownMenu: true }); ``` 浏览器打开即可查看效果: <div id="example"></div> <style> table.htCore{font-size:12px;font-family: Verdana, Helvetica, Arial, FreeSans, sans-serif;} table.htCore input[type="text"]{height:15px;font-size:12px;margin-bottom:0;} table.htCore a{background-image: none;} table.htCore label{font-size:15px;} // 调整css防blog样式污染。 </style> <script> var data = [ ["", "Ford", "Tesla", "Toyota", "Honda"], ["2017", 10, 11, 12, 13], ["2018", 20, 11, 14, 13], ["2019", 30, 15, 12, 13] ]; var container = document.getElementById('example'); var hot = new Handsontable(container, { data: data, rowHeaders: true, colHeaders: true, filters: true, dropdownMenu: true }); </script> ## 数据绑定 ### 理解作为引用的绑定 Handsontable通过引用与你的数据源(数组或对象)绑定。因此,特点有二: - 在网格中输入的所有数据都将改变原始数据源。 - 从Handsontable外部更改数据源。除非在屏幕上使用呈现方法`render()`刷新网格,否则将不会在屏幕上显示更改。 ```javascript var data1 = [ ['', 'Tesla', 'Nissan', 'Toyota', 'Honda', 'Mazda', 'Ford'], ['2017', 10, 11, 12, 13, 15, 16], ['2018', 10, 11, 12, 13, 15, 16], ['2019', 10, 11, 12, 13, 15, 16], ['2020', 10, 11, 12, 13, 15, 16], ['2021', 10, 11, 12, 13, 15, 16] ], container1 = document.getElementById('example1'), settings1 = { data: data1 }, hot1; hot1 = new Handsontable(container1, settings1); data1[0][1] = 'Ford'; // change "Kia" to "Ford" programmatically hot1.render(); ``` ### 更改数据源而不更改显示 可以在引用数据时,引用数据源的一个单独的副本。这样数据源变化就不会影响数据显示了。 ```javascript ... hot2 = new Handsontable(container2, { data: JSON.parse(JSON.stringify(data2)) }); ``` ### 更改显示而不更改数据源 保存之前先克隆,`tmpData`即是显示修改之前的数据副本。 ```javascript ... hot3 = new Handsontable(container3, { data: data3, afterChange: function () { var tmpData = JSON.parse(JSON.stringify(data3)); // now tmpData has a copy of data3 that can be manipulated // without breaking the Handsontable data source object } }); ``` ## 数据来源 Handsontable是如何使用各种数据源的? ### 数组类型数据源 ```javascript var data = [ ['', 'Tesla', 'Nissan', 'Toyota', 'Honda', 'Mazda', 'Ford'], ['2017', 10, 11, 12, 13, 15, 16], ['2018', 10, 11, 12, 13, 15, 16], ['2019', 10, 11, 12, 13, 15, 16], ['2020', 10, 11, 12, 13, 15, 16], ['2021', 10, 11, 12, 13, 15, 16] ], container1 = document.getElementById('example1'), hot1; hot1 = new Handsontable(container1, { data: data, startRows: 5, startCols: 5, colHeaders: true, minSpareRows: 1 }); ``` ### 含隐藏列的数组类型数据源 ```javascript var hiddenData = [ ['', 'Tesla', 'Nissan', 'Toyota', 'Honda', 'Mazda', 'Ford'], ['2017', 10, 11, 12, 13, 15, 16], ['2018', 10, 11, 12, 13, 15, 16], ['2019', 10, 11, 12, 13, 15, 16], ['2020', 10, 11, 12, 13, 15, 16], ['2021', 10, 11, 12, 13, 15, 16] ], container = document.getElementById('example2'), hot2; hot2 = new Handsontable(container, { data: hiddenData, colHeaders: true, minSpareRows: 1, columns: [ {data: 0}, {data: 2}, {data: 3}, {data: 4}, {data: 5}, {data: 6} ] }); ``` ### 对象数据源 ```javascript var objectData = [ {id: 1, name: '<NAME>', address: ''}, {id: 2, name: '<NAME>', address: ''}, {id: 3, name: '<NAME>', address: ''}, {id: 4, name: '<NAME>', address: ''}, {id: 5, name: '<NAME>', address: ''}, ], container3 = document.getElementById('example3'), hot3; hot3 = new Handsontable(container3, { data: objectData, colHeaders: true, minSpareRows: 1 }); ``` ### 用列做函数的对象数据源 ```javascript var nestedObjects = [ {id: 1, name: {first: "Ted", last: "Right"}, address: ""}, {id: 2, address: ""}, // HOT will create missing properties on demand {id: 3, name: {first: "Joan", last: "Well"}, address: ""} ], container4 = document.getElementById('example4'), hot4; hot4 = new Handsontable(container4, { data: nestedObjects, colHeaders: true, columns: function(column) { var columnMeta = {}; if (column === 0) { columnMeta.data = 'id'; } else if (column === 1) { columnMeta.data = 'name.first'; } else if (column === 2) { columnMeta.data = 'name.last'; } else if (column === 3) { columnMeta.data = 'address'; } else { columnMeta = null; } return columnMeta; }, minSpareRows: 1 }); ``` 其实上面的闭包也可以写成这样: ```javascript columns: [ {data: 'id'}, {data: 'name.first'}, {data: 'name.last'}, {data: 'address'} ], ``` ### 自定义数据结构及列名的对象数据源 ```javascript dataSchema: {id: null, name: {first: null, last: null}, address: null}, colHeaders: ['ID', 'First Name', 'Last Name', 'Address'], ``` > 官网有个高级用法,感兴趣可自己阅读理解一下: > > <https://docs.handsontable.com/tutorial-data-sources.html#page-property-schema> ## 数据的加载与保存 ### 使用onChange回调保存数据 定义在初始化Handsontable时`option`选项参数:`afterChange` ```javascript afterChange: function (change, source) { if (source === 'loadData') { return; //don't save this change } if (!autosave.checked) { return; } clearTimeout(autosaveNotification); ajax('scripts/json/save.json', 'GET', JSON.stringify({data: change}), function (data) { exampleConsole.innerText = 'Autosaved (' + change.length + ' ' + 'cell' + (change.length > 1 ? 's' : '') + ')'; autosaveNotification = setTimeout(function() { exampleConsole.innerText ='Changes will be autosaved'; }, 1000); }); } }); Handsontable.dom.addEvent(load, 'click', function() { ajax('scripts/json/load.json', 'GET', '', function(res) { var data = JSON.parse(res.response); hot.loadData(data.data); exampleConsole.innerText = 'Data loaded'; }); }); Handsontable.dom.addEvent(save, 'click', function() { // save all cell's data ajax('scripts/json/save.json', 'GET', JSON.stringify({data: hot.getData()}), function (res) { var response = JSON.parse(res.response); if (response.result === 'ok') { exampleConsole.innerText = 'Data saved'; } else { exampleConsole.innerText = 'Save error'; } }); }); Handsontable.dom.addEvent(autosave, 'click', function() { if (autosave.checked) { exampleConsole.innerText = 'Changes will be autosaved'; } else { exampleConsole.innerText ='Changes will not be autosaved'; } }); ``` ### 本地保存 启用数据存储机制,可在初始化时设置`persistentState`参数为`true`,或者使用`updateSettings `方法。 ```javascript persistentStateSave (key: String, value: Mixed) # 在浏览器本地存储保存给定键的值 persistentStateLoad (key: String, valuePlaceholder: Object) # 根据已知键读取值,值被保存valuePlaceholder.value persistentStateReset (key: String) # 清除保存的值,无指定key则清除所有 ``` 使用这三个钩子的api,是为了防止同页面有2个以上实例,数据只能保存一份的尴尬。 ## 设置选项 单元格选项,在构造时定义配置 ```javascript var hot = new Handsontable(document.getElementById('example'), { cell: [ {row: 0, col: 0, readOnly: true} ] }); ``` 或者定义函数属性 ```javascript var hot = new Handsontable(document.getElementById('example'), { cells: function (row, col, prop) { var cellProperties = {} if (row === 0 && col === 0) { cellProperties.readOnly = true; } return cellProperties; } }) ``` 级联的配置模型,在构造函数使用第一级提供的配置选项或者`updateSettings`方法,使用二级对象提供的配置选项,具体阅读官方版:<https://docs.handsontable.com/tutorial-setting-options.html>,关键部分已摘抄至下面。 ### How does the Cascading Configuration work? Since Handsontable 0.9 we use Cascading Configuration, which is a fast way to provide configuration options for the whole table, along with its columns and particular cells. Consider the following example: ```javascript var hot = new Handsontable(document.getElementById('example'), { readOnly: true, columns: [ {readOnly: false}, {}, {} ], cells: function (row, col, prop) { var cellProperties = {} if (row === 0 && col === 0) { cellProperties.readOnly = true; } return cellProperties; } }); ``` The above notation will result in all TDs being read only, except for first column TDs which will be editable, except for the TD in top left corner which will still be read only. ### The cascading configuration model The Cascading Configuration model is based on prototypal inheritance. It is much faster and memory efficient compared to the previous model that used jQuery extend. See it yourself: <http://jsperf.com/extending-settings> - **Constructor** Configuration options that are provided using first-level ```javascript new Handsontable(document.getElementById('example'), { option: 'value' }); ``` and `updateSettings` method. - **Columns** Configuration options that are provided using second-level object ```javascript new Handsontable(document.getElementById('example'), { columns: { option: 'value' } }); ``` - **Cells** Configuration options that are provided using second-level function ```javascript new Handsontable(document.getElementById('example'), { cells: function(row, col, prop) { } }); ``` ## Using callbacks Please visit:<https://docs.handsontable.com/tutorial-using-callbacks.html> ## Styling > <https://docs.handsontable.com/tutorial-styling.html> Commonly used styles: ​ There is very little you can't do with Handsontable. As it doesn't impose any specific theme, you can play with CSS however you like. Keep in mind that Handsontable needs to calculate the width and height of elements inside it to control the scrollbar, so the complex styling rules may affect the performance. ​ Some of the recipes listed below need an additional parent class/id or other modifications to override the default values. Also, the styles might slightly vary depending on your configuration. The below examples were tested with a 10x10 grid with both row and column headers turned on. ### Table ​ **Background** ```css .ht_master tr td { background-color: #F00; } ``` ### Headers ​ **Background** ```css /* All headers */ .handsontable th { background-color: #F00; } /* Row headers */ .ht_clone_left th { background-color: #F00; } /* Column headers */ .ht_clone_top th { background-color: #F00; } ``` ​ **Borders** ```css /* Row headers */ /* Bottom */ .ht_clone_top_left_corner th { border-bottom: 1px solid #F00; } /* Left and right */ .ht_clone_left th { border-right: 1px solid #F00; border-left: 1px solid #F00; } /* Column headers */ /* Top, bottom and right */ .ht_clone_top th { border-top: 1px solid #F00; border-right: 1px solid #F00; border-bottom: 1px solid #F00; } /* Left */ .ht_clone_top_left_corner th { border-right: 1px solid #F00; } ``` ### Corner ​ **Background** ```css .ht_clone_top_left_corner th { background-color: #F00; } ``` ​ **Borders** ```css .ht_clone_top_left_corner th { border: 1px solid #F00; } ``` ### Rows ​ **Background** ```css /* Every odd row */ .ht_master tr:nth-of-type(odd) > td { background-color: #f00; } /* Every even row */ .ht_master tr:nth-of-type(even) > td { background-color: #f00; } /* Selected row */ /* Add a custom class name in the configuration: currentRowClassName: "foo"; */ .ht_master tr.foo > td { background-color: #f00; } /* Specific row (2) */ .ht_master tr:nth-child(2) > td { background-color: #f00; } ``` ​ **Borders** ```css /* Bottom */ .ht_master tr > td { border-bottom: 1px solid #F00; } /* Right */ .ht_master tr > td { border-right: 1px solid #F00; } ``` ### Columns ​ **Background** ```css /* Every odd column */ .ht_master tr > td:nth-of-type(odd) { background-color: #f00; } /* Every even column */ .ht_master tr > td:nth-of-type(even) { background-color: #f00; } /* Selected column */ /* Add a custom class name in the configuration: currentColClassName: "foo"; */ .ht_master tr > td.foo { background-color: #f00; } /* Specific column (B) */ .ht_master tr > td:nth-child(3) { background-color: #f00; } ``` ### Cell ​ **Background** ```css /* Selected cell */ .ht_master tr > td.current { background-color: #F00; } /* Specific cell (B2) */ .ht_master tr:nth-child(2) > td:nth-child(3) { background-color: #F00; } /* Edit mode */ .handsontableInput { background-color: #F00!important; } ``` ### Selection ​ **Background** ```css .handsontable td.area { background-color: #F00; } ``` ### Notice ​ Be careful when using Handsontable with popular CSS frameworks. They not only modify the style of all DOM elements, including textareas and inputs, but also add some transition properties which may negatively affect the performance. Make sure you add styles carefully and selectively or use the official Bootstrap integration. ​ The selection border color has been hard-coded. It can be changed using JavaScript, or alternatively you can postscript your CSS values with an (ugly) "!important" rule. ​ **JavaScript** ```css var borders = document.querySelectorAll('.handsontable .wtBorder'); for (var i = 0; i < borders.length; i++) { borders[i].style.backgroundColor = 'red'; } ``` ​ **CSS** ``` .wtBorder { background-color: #F00!important; } ``` # 开发者指南 ## 搜索 初始化时在`option`里可以配置`search: true`开启。 v4.0版本开始需要使用插件形式。原有项目升级增加下面第一句即可。 ```javascript hot.search = hot.getPlugin('search'); var queryResult = hot.search.query(value); ``` queryResult 格式: ```javascript { {row: 0, col:0, data: "xxxxx"}, {row: x, col:y, data: "xxxxx"}, length: n } ``` ## 单元格数据类型 默认定义了9种类型: - `autocomplete` for `Handsontable.cellTypes.autocomplete` - `checkbox` for `Handsontable.cellTypes.checkbox` - `date` for `Handsontable.cellTypes.date` - `dropdown` for `Handsontable.cellTypes.dropdown` - `handsontable` for `Handsontable.cellTypes.handsontable` - `numeric` for `Handsontable.cellTypes.numeric` - `password` for `Handsontable.cellTypes.password` - `text` for `Handsontable.cellTypes.text` - `time` for `Handsontable.cellTypes.time` 更多直接查看官方:<https://docs.handsontable.com/tutorial-cell-types.html> `columns`参数详解 ```javascript hot = new Handsontable(, { columns: [ xxx: yyy ] }); ///////////////////// data // 在获取hot数据时,作为数据的下角标 type // 数据类型 // 其他使用详见下面例子 ``` 初始化的`options`中配置举例 [autocomplete](https://docs.handsontable.com/0.35.0/demo-autocomplete.html) ```javascript hot = new Handsontable(container, { columns: [ { type: 'numeric', numericFormat: { pattern: '$0,0.00', culture: 'en-US' // this is the default culture, set up for USD # zh-CN }, allowEmpty: false }, { type: 'date', dateFormat: 'MM/DD/YYYY', correctFormat: true, defaultDate: '01/01/1900', }, ``` > 时间格式列的数据可能不合法,记得在初始化后调用`hot.validateCells()`方法。 ```javascript { type: 'time', timeFormat: 'h:mm:ss a', correctFormat: true }, { type: 'checkbox' }, { editer: 'select', selectOptions:['互联网','IMS'], }, { type: 'dropdown', source: ['yellow', 'red', 'orange', 'green'] }, ``` > Internally, cell `{type: "dropdown"}` is equivalent to cell` {type: "autocomplete", strict: true, filter: false}`. Therefore you can think of `dropdown` as a searchable `<select>`. ``` javascript { type: 'autocomplete', source: ['yellow', 'red', 'orange and another color', 'green', 'blue', 'gray', 'black', 'white', 'purple', 'lime', 'olive', 'cyan'], visibleRows: 4, // 下拉菜单可见列数 strict: false, // 是否严格模式(是否验证) trimDropdown: false, // 宽度自适应下拉内容 allowInvalid: true // 严格模式开启时,是否允许存在非法值 }, { type: 'handsontable', handsontable: { colHeaders: ['Marque', 'Country', 'Parent company'], autoColumnSize: true, data: manufacturerData, getValue: function() { var selection = this.getSelected(); // Get always manufacture name of clicked row return this.getSourceDataAtRow(selection[0]).name; }, } }, ] }); hot.validateCells(); ``` ## 右键菜单 初始化时在`option`里可以配置`contextMenu:true`开启,或者配置为如下选项: 如:`contextMenu:[row_above,row_below,undo,redo]` - row_above - row_below - hsep1 - col_left - col_right - hsep2 - remove_row - remove_col - hsep3 - undo - redo - make_read_only - alignment - borders (with Custom Borders turned on) - commentsAddEdit, commentsRemove (with Comments turned on) [自定义菜单](https://docs.handsontable.com/demo-context-menu.html#page-custom): ``` javascript var example3 = document.getElementById('example3'), settings3, hot3; settings3 = { data: getData(), rowHeaders: true, colHeaders: true }; hot3 = new Handsontable(example3, settings3); hot3.updateSettings({ contextMenu: { callback: function (key, options) { if (key === 'about') { setTimeout(function () { // timeout is used to make sure the menu collapsed before alert is shown alert("This is a context menu with default and custom options mixed"); }, 100); } }, items: { "row_above": { disabled: function () { // if first row, disable this option return hot3.getSelected()[0] === 0; } }, "row_below": {}, "hsep1": "---------", "remove_row": { name: 'Remove this row, ok?', disabled: function () { // if first row, disable this option return hot3.getSelected()[0] === 0 } }, "hsep2": "---------", "about": {name: 'About this menu'} } } }) ``` # API参考 ``` hot.loadData() hot.getData() // 数组格式 got.getSourceData() // JSON格式(columns里配置data) hot.search.query() // 全局搜索并高亮,返回 [{row,col,data},...] ``` 调用方法 ```javascript // all following examples assume that you constructed Handsontable like this var ht = new Handsontable(document.getElementById('example1'), options); // now, to use setDataAtCell method, you can either: ht.setDataAtCell(0, 0, 'new value'); # Alternatively, you can call the method using jQuery wrapper (obsolete, requires initialization using our jQuery guide $('#example1').handsontable('setDataAtCell', 0, 0, 'new value'); ``` ## 核心 ### 核心方法 #### updateSettings 在初始化之后,更新handsontable的设置 ```javascript var hot = new Handsontable(example, settings); hot.updateSettings(Settings); // Settings 是 json 结构 {} 如: hot.updateSettings({ contextMenu: { callback: function (key, options){ xxxxxx }, items:{ xxx:{}, yyy:{} } } }); ``` ### 钩子事件 #### afterChange Parameters: | Name | Type | Description | | --------- | ------ | ---------------------------------------- | | `changes` | Array | 2D array containing information about each of the edited cells `[[row, prop, oldVal, newVal], ...]`. | | `source` | String | optionalString that identifies source of hook call([list of all available sources](http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition)). | #### afterValidate 如果定义了validator函数,执行之后会触发该事件。并执行响应函数,函数的第一个参数是验证结果,用来确定是否验证通过。 Parameters: | Name | Type | Description | | --------- | --------------- | ------------------------------------------------------------ | | `isValid` | Boolean | `true` if valid, `false` if not. | | `value` | * | The value in question. | | `row` | Number | Row index. | | `prop` | String \|Number | Property name / column index. | | `source` | String | optionalString that identifies source of hook call([list of all available sources](http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition)). | #### afterSelectionEndByProp 表格单元数据被选择后触发。 Parameters: | Name | Type | Description | | --------------------- | ------ | ------------------------------------------------------------ | | `r` | Number | Selection start visual row index. | | `p` | String | Selection start data source object property index. | | `r2` | Number | Selection end visual row index. | | `p2` | String | Selection end data source object property index. | | `selectionLayerLevel` | Number | The number which indicates what selection layer is currently modified. | #### afterOnCellMouseOver 鼠标在单元格上移动时触发。 > 另有`afterOnCellMouseDown`:鼠标按下时触发(不区分单击 右击) > > `afterOnCellMouseOut`:鼠标移出单元格时触发 Parameters: | Name | Type | Description | | -------- | ------- | ---------------------------------------- | | `event` | Object | `mouseover` event object. | | `coords` | Object | Hovered cell's visual coordinate object. | | `TD` | Element | Cell's TD (or TH) element. | #### afterScrollVertically 垂直滚动后触发。无参数。 #### afterRender Callback fired after the Handsontable table is rendered. (滚动后均会触发) Parameters: | Name | Type | Description | | ---------- | ------- | ------------------------------------------------------------ | | `isForced` | Boolean | Is `true` if rendering was triggered by a change of settings or data; or `false` ifrendering was triggered by scrolling or moving selection. | ### 选项可选成员 这里介绍构造时,`var hot = new Handsontable(container, settings);`settings的选项的成员。 #### columns 官网例子: <https://docs.handsontable.com/Options.html#columns> 数据类型例子: > 具体数据类型可参见 [Developer guide/Cell types](https://docs.handsontable.com/tutorial-cell-types.html) ```javascript columns : [ { editor : 'select', selectOptions : [array], }, { strict : true, type : 'autocomplete', source : [array], },{ data: 'name.first' } ``` 数据加载例子(json): <https://docs.handsontable.com/tutorial-data-sources.html#page-nested> #### validator 使用时可以是函数、正则表达式、字符串。提供的可选字符串有 - autocomplete, - date, - numeric, - time. 可以自己[注册](http://docs.handsontable.com/demo-data-validation.html)一个验证器。 ```javascript Handsontable.validators.registerValidator('my.credit-card', creditCardValidator); ``` 注册时最好使用别名: ```javascript (function(Handsontable){ function customValidator(query, callback) { // ...your custom logic of the validator callback(/* Pass `true` or `false` based on your logic */); } // Register an alias Handsontable.validators.registerValidator('my.custom', customValidator); })(Handsontable); ``` 这样就可以像下面一样使用 `customValidator` 了: ```javascript var hot = new Handsontable(document.getElementById('container'), { data: someData, columns: [ { validator: 'my.custom' } ] }); ``` 下面是例子 ```javascript // as a function columns: [ { validator: function(value, callback) { // validation rules } }, // as a regexp { validator: /^[0-9]$/ // regular expression }, // as a string { validator: 'numeric' } ] ``` ## 插件 ### 获取自动调整的宽度 ```javascript // ... hot.updateSettings({autoColumnSize:true}); // ... // Access to plugin instance: var colSizePlugin = hot.getPlugin('autoColumnSize'); var result=""; for(var ii=0;ii<30;ii++){ result+=colSizePlugin.getColumnWidth(ii)+","; } console.info(result); ``` ### 导出到文件 ```javascript var exportPlugin = hot.getPlugin('exportFile'); // Export as a string: exportPlugin.exportAsString('csv'); // Export as a Blob object: exportPlugin.exportAsBlob('csv'); // Export to downloadable file (MyFile.csv): exportPlugin.downloadFile('csv', {filename: 'MyFile'}); ``` <file_sep>/application/kxeams/model/Item.php <?php namespace app\kxeams\model; use think\Model; use traits\model\SoftDelete; class Item extends Model { use SoftDelete; protected $deleteTime = 'idelete_time'; protected $autoWriteTimestamp = 'datetime'; protected $createTime = 'icreate_time'; protected $updateTime = false; protected $type = [ 'id' => 'integer', 'icreate_time' => 'datetime', 'idelete_time' => 'datetime' ]; }<file_sep>/application/zx_apply/config.php <?php return [ 'version' => "V0.7.19-zx", // 'aStation' => '{"柴河局09":"CHJ-09","西丰新局":"XF-10","昌图新局":"CT-11","昌图老局":"CT-12","西丰老局":"XF-13","开原老局":"KY-14","铁岭县":"TLX-15","清河局":"QH-16","新台子":"XTZ-17","调兵山新局":"DBS-18","调兵山老局":"DBS-19","开原新局":"KY-20","柴河局-华为":"CHJ-21","柴河局-中兴":"CHJ-22","银州区":"YZL-23"}', 'systemURLString' => "<br> 内网: <a href='http://10.65.178.202/zx_apply/index/index.html#Manage/todo'>http://10.65.178.202/zx_apply/index/index.html#Manage/todo</a><br>外网: <a href='http://172.16.58.3:800/zx_apply/index/index.html#Manage/todo'>http://172.16.58.3:800/zx_apply/index/index.html#Manage/todo</a>", 'aStation' => [ "请选择" => null, "柴河局09" => "CHJ-09", "西丰新局" => "XF-10", "昌图新局" => "CT-11", "昌图老局" => "CT-12", "西丰老局" => "XF-13", "开原老局" => "KY-14", "铁岭县" => "TLX-15", "清河" => "QH-16", "新台子" => "XTZ-17", "调兵山新局" => "DBS-18", "调兵山老局" => "DBS-19", "开原新局" => "KY-20", "柴河局-华为" => "CHJ-21", "柴河局-中兴" => "CHJ-22", "银州区" => "YZL-23", "其他" => null ], 'device9312' => '<KEY>', // 额外信息,用于IP备案 'extraInfo' => [ "单位性质" => "unitProperty", "单位分类" => "unitCategory", "行业分类" => "industryCategory", "单位证件类型" => "credential", "单位证件号" => "credentialnum", "所在省" => "province", "所在市" => "city", "所在县区" => "county", "应用服务类型" => "appServType", "单位属性" => "unitAttribute", "网络安全责任人" => "securityPerson", "责任人身份证号" => "securityPersonID", "责任人电话" => "securityPhone", "责任人邮箱" => "securityEmail", "邮政编码" => "zipCode", ], // 登陆后跳转到manage模块的账号 'manageEmails' => [ "yuxianda.tl", "buyu.tl", "liuyutl.tl" ], // 列宽度 'colWidth' => [ 0 => 98, 1 => 96, 2 => 65, 3 => 50, 4 => 65, 5 => 100, 6 => 240, 7 => 220, 8 => 450, 9 => 50, 10 => 116, 11 => 116, 12 => 107, 13 => 107, 14 => 164, 15 => 93, 16 => 96, 17 => 164, 18 => 200, 19 => 75, 20 => 200, 21 => 60, 22 => 107, 23 => 164, 24 => 98, 25 => 98, 26 => 50, 27 => 80, 28 => 0, 29 => 76, 30 => 76, 31 => 76, 32 => 132, 33 => 107, 34 => 62, 35 => 62, 36 => 76, 37 => 104, 38 => 90, 39 => 90, 40 => 107, 41 => 96, 42 => 164, 43 => 62, ], /* 生成IDC备案信息使用(与 index/apply.html 里定义的一致)*/ // 单位性质 'unitProperty' => [ 1 => '军队', 2 => '政府机关', 3 => '事业单位', 4 => '企业', 5 => '个人', 6 => '社会团体', 7 => '国瑞', 8 => '个体工商户', 9 => '民办非企业', 10 => '基金会', 11 => '律师事务所', 12 => '外国文化中心', 99 => '未知' ], // 单位分类 'unitCategory' => [ 1 => 'ISP', 2 => 'IDC', 3 => 'ISP和IDC', 4 => '公益性互联网络单位', 5 => '其他', 11 => '电信业务经营者', 12 => '公益性互联网络单位', 14 => '管局单位', 15 => '前置单位', 999 => '未知' ], // 行业分类 'industryCategory' => [ 1 => '农、林、牧、渔业', 2 => '采矿业', 3 => '制造业', 4 => '电力、燃气及水的生产和供应业', 5 => '建筑业', 6 => '交通运输、仓储和邮政业', 7 => '信息传输、计算机服务和软件业', 8 => '批发和零售业', 9 => '住宿和餐饮业', 10 => '金融业', 11 => '房地产业', 12 => '租赁和商务服务业', 13 => '科学研究、技术服务和地质勘查业', 14 => '水利、环境和公共设施管理业', 15 => '居民服务和其他服务业', 16 => '教育', 17 => '卫生、社会保障和社会福利业', 18 => '文化、体育和娱乐业', 19 => '公共管理与社会组织', 20 => '国际组织', 21 => 'example', 999 => '未知' ], // 使用单位证件类型 'credential' => [ 1 => '工商营业执照', 2 => '身份证', 3 => '组织机构代码证书', 4 => '事业法人证书', 5 => '军队代号', 6 => '社团法人证书', 7 => '护照', 8 => '军官证', 11 => '台胞证', 13 => '统一社会信用代码证书', 14 => '港澳居民来往内地通行证', 17 => '民办非企业单位登记证书', 19 => '基金会法人登记证书', 21 => '律师事务所执业许可证', ], 'province' => [ 210000 => '辽宁省' ], 'city' => [ 211200 => '铁岭市' ], 'county' => [ 211201 => '市辖区', 211202 => '银州区', 211204 => '清河区', 211221 => '铁岭县', 211223 => '西丰县', 211224 => '昌图县', 211281 => '调兵山市', 211282 => '开原市' ], 'appServType' => [ 1 => '企事业单位专线接入', 2 => '个人专线接入', 3 => '固定宽带接入', 4 => '移动网接入', 5 => '网络设备', 6 => '网站专线接入', 7 => 'IDC服务类', 8 => '物联网' ], ];<file_sep>/CHANGELOG.md ## 更新日志 #### v0.7.17(2018-09-10) [zx_apply]模块修复 bug - 更新 docs - 修复`修改申请`报错 bug - 修复`todo.html`分配后`vlan`无记录的 bug - 修复其他若干 bugs #### v0.7.12(2018-08-27) [zx_apply]模块修复 bug - `todo.html`和`index/query.html`编辑旧数据时自动修补新增的额外字段信息 - 修改自动修补新增的额外字段的 bugs #### v0.7.11(2018-08-23) [zx_apply]模块更新 - 自动生成 idc.isp 模板数据,并做为邮件附件发送 - 导出 excel 功能可选择使用前端或者后端 - 调整 LECENSE - fix [#3](https://github.com/thianda/phpweb/issues/3), fix [#4](https://github.com/thianda/phpweb/issues/4) - 修改若干 bugs - `index/query.html`右键新增`额外再申请1个IP`功能 - 同 vlan 提醒后确认,可强制录入 - ONU 业务在`todo.html`可显示当前所处状态(在 vlan 字段上方) #### v0.7.3(2018-08-05) [zx_apply]模块更新 - 完善前端导出 excel 功能 - 分离部分`Manage.php`的操作到`Generator.php` - `Infotables`新增 5 个额外字段(extra) - 调整`apply.html`表单字段位置,新增字段 4 个,隐藏无需编辑的字段 4 个 ### v0.7.0(2018-08-03) [zx_apply]模块更新 - 导出 excel 功能全部迁移到前端 TODO - php 文件读写,发邮件带附件 - 同 vlan 强制录入 #### v0.6.7(2018-08-03) [zx_apply]模块更新 - todo提交后发送邮件给客户经理和申请人 - close [#6](https://github.com/thianda/phpweb/issues/6) #### v0.6.6(2018-08-01) [zx_apply]模块更新 - 代码仓库脱敏处理,永久删除敏感信息 - 细节调整 #### v0.6.2(2018-07-27) [zx_apply]模块更新 - 修复搜索bug [#5](https://github.com/thianda/phpweb/issues/5). ### v0.6.0(2018-07-13) [zx_apply]模块更新 - 实现ONU业务申请时无需`A端基站`,先预分配ip不分配vlan,待做ONU上线数据时再选择`A端基站`并分配`vlan`。 - apply.html申请、query.html修改申请、todo代办页面同步修改表单动态逻辑 - 修改`Vlantables::check()`逻辑,优化存在`vlan`但不存在`aStation`时的结果 #### v0.5.5(2018-07-13) [zx_apply]模块更新 - 调整:申请时若为ONU业务则不需要填写`A端基站`,此规则在`修改申请`时亦生效 - 修复`manage/query.html`。在此之前,批量删除时前端显示与实际不符 - 完善vlan删除与修改功能:修改状态`[0]申请`,到待办里直接修改提交即可,若不填vlan即为删除 - 修复其他若干bug #### v0.5.1(2018-07-12) [zx_apply]模块代码格式化 - 格式化`zx_apply`模块的代码(php、html),遵循PSR-2 - 未知原因导致部分代码丢失,已补回 ### v0.5.0(2018-07-11) [zx_apply]模块部分重构 - 前端部分重构 - 修复申请填表单的bug - 需进一步调整 #### v0.4.18(2018-07-11) [zx_apply]模块更新 - 更新资管导入模板 - 优化`XLSX`组件的加载逻辑 - 计划将`导出excel操作`移至前端,加速导出速度,兼容性更强 - 修复细节bug #### v0.4.16(2018-07-05) [zx_apply]模块更新 - 修改`index/query.html`中`afterChange`事件的bug - 新增ip列表生成:`tool/swscript.html` #### V0.4.13(2018-06-28) [zx_apply]模块更新 - `manage/query.html`新增批量已完成功能,批量选取设置状态为[4]:已完成 - 导出资管模板数据时提示批量修改状态为[2]:已录资管等待IP备案 TODO:`更多操作`页面新功能:统计空闲ip > 需基于专线类型,细节有待研究 #### V0.4.12(2018-06-26) [zx_apply]模块修复若干bug - 完善细节功能,修复大量bug - 支持按照`专线类型`进行`全局搜索`以及`基本信息查询` #### v0.4.9(2018-06-12) - 用户可右键选择`修改申请`,修改个别字段信息后重新提交 - 用户申请提交前自动清除每个字段里的空格并给出提示 #### v0.4.8(2018-06-06) [zx_apply]模块bug修复 - 累计优化多处UI布局 - `todo`页提示同客户名的台账信息 - `apply`页提交前过滤空格符 - 模板导出时文件名的时间字段放后面 #### v0.4.6(2018-05-29) [zx_apply]模块更新 - 视图显示优化、安全事件逻辑优化 - 显示和导出全量数据可基于专线类别筛选,申请与待办暂未实现 - 查询、导出操作均记录log #### V0.4.5(2018-05-24) [zx_apply]模块bug修复 - 修复ip分配时的小bug - 调整查询页面排序为`status,create_time desc` - 更新资管系统导出模板 - 调整各种模板导出时文件名的命名规则 #### v0.4.4(2018-05-18) [zx_apply]模块大量更新。 - 待办页`vlan`字段不再是必填 - 待办页“自动预分配”结果显示由`alert`改为`window` - 查询页显示详细信息布局优化 - 查询页取消显示备注列 - 调整待办通知的邮件内容 - 申请人查询页可查询历史数据的基本信息(去除客户联系方式等敏感信息,并限制查询次数) #### v0.4.3(2018-05-16) - [zx_apply]模块预分配ip后给申请人自动发送邮件提醒(手动判断是否发送) #### v0.4.2(2018-05-11) #### v0.4.1(2018-05-04) [zx_apply]模块开始公测使用 - 添加`jsSheet`组件,用于zx_apply前端导出全量台账的xlsx文件 - 敏感配置信息独立存储 ### v0.4.0(2018-04-02) [zx_apply]模块大量更新。 - `Infotables`增加 ip掩码和ipB掩码,互联网ip掩码默认32,其他默认30,所有ipB掩码默认29 - 取消`Iptables`数据表,保留其model类及方法 - 定位为辅助平台,提供有限的台账维护功能。主要功能为限制数据录入的规范性。导出为各项工作所需的数据。包含但不限于: - 台账格式 - 资管流程模板格式 - 做数据脚本 - ip备案模板格式(2种) - 管理员查询页面可右键调用数据制作脚本生成、资管系统录入模板、集团IP备案导入模板、工信部IP备案导入模板功能。 - 更新`handsontable`组件到v1.18.1/v0.38.1 ### v0.3.2(2018-01-31) - 更新`dhtmlx`组件到5.1.0 - 修复esserver的bug - 添加系统log记录功能 - 添加zx_apply模块的登陆控制 #### v0.2.2.0108(2018-01-08) - 更新`/docs/_posts/2017-12-21-handsontable-usage-notes.md`内容 > 总结的自己脑袋都乱了。官网这个[docs](https://docs.handsontable.com)真的一点也不友好。 - 更新zx_apply核心代码 #### v0.2.2.0107(2018-01-07) - 更新`/docs/_posts/2017-12-21-handsontable-usage-notes.md`内容 - 添加`handsontable`作为grid组件。与`dhtmlXGrid`相比的优点: - 有配置默认值,上手更简单 - UI更接近Excel,功能也更近似Excel - 可全局搜索,性能良好 #### v0.2.2(2017-12-22) - 更新docs入口为项目名,可在github pages自动发布 - 添加静态资源handsontable - 更新docs开发文档样式,修复几处bug ### v0.2.0(2017-12-18) - 添加docs,记录开发文档 - 大量微调整 ### v0.1.0(2017-11-16) 开始托管于github,整合多个小项目(checkME60、esserver、kxeams、trouble、zx_apply)为本项目的子模块。 - initial release<file_sep>/application/zx_apply/model/Iptables.php <?php namespace app\zx_apply\model; use think\Model; use think\Db; class Iptables extends Model { /** * 自动预分配ip,并确保未使用 * * @param string $zxType * @return number|string */ public static function generateIP($zxType = "互联网") { // $lastIp = Db::name ( "infotables" )->where ( "zxType", $zxType )->where ( "ip", "NOT NULL" )->order ( "create_time desc" )->limit ( 1 )->value ( "ip" ); $lastIp = Db::table("phpweb_sysinfo")->where("label", "zx_apply-lastIP")->value("value"); if ($lastIp) { // lastIp检测是否已使用,已使用则自增,直至返回未使用的ip,并记录 do { $nextIpStr = self::ip_export($lastIp++); $valid = self::check($nextIpStr, "ip", $zxType); } while ($valid); // 有返回则表示冲突或不可用 self::setLastIp($nextIpStr); return $nextIpStr; } else { return "暂无参考,请在系统设置中设置或手动分配"; } } /** * 设置最后分配的ip * * @param string $ipStr * @return number */ public static function setLastIp($ipStr = "") { if (is_numeric($ipStr)) { $ip = $ipStr; } else { $ip = self::ip_parse($ipStr)[2]; } if (!strlen($ip)) { return; } // 已存在则更新,不存在则新增 if (Db::table("phpweb_sysinfo")->where("label", "zx_apply-lastIP")->find()) { $result = Db::table("phpweb_sysinfo")->where("label", "zx_apply-lastIP")->setField("value", $ip); } else { $data = [ "label" => "zx_apply-lastIP", "value" => $ip ]; $result = Db::table("phpweb_sysinfo")->insert($data); } return $result; } /** * 是否已分配 * * @param unknown $zxType * @param string $ip_str * @param string $filed * ip (defalut) or ipB * @return array|\think\db\false|PDOStatement|string|\think\Model */ public static function check($ip_str = "", $filed = "ip", $zxType = "互联网") { if ($ip_str == "") { return; } list($ip, $mask, $ip_start, $ip_end) = self::ip_parse($ip_str); if (!self::ifCanUse($zxType, $ip_start)) { return "no"; } $infotables = new Infotables(); $data = $infotables->where([ "zxType" => $zxType, $filed => $ip_start // $filed . "Mask" => $mask ])->field("id,cName")->find(); return $data; } /** * 判断ip是否可用 * * @param unknown $zxType * @param unknown $long * @param unknown $mask * @return boolean */ public static function ifCanUse($zxType = '互联网', $long, $mask = -1) { if ($long < 0) { // 2^31-(-x) 设计负数如何转化并计算。 $array = explode(",", "-255,0,-1"); } else { $array = explode(",", "0,1,255"); } return !in_array($long % 256, $array); } /** * ip转换 * ip字符串10.10.10.10/32转成ip2long形式的数组:ip/mask/ip_start/ip_end * * @param unknown $ip_str * @return boolean[]|number[] */ public static function ip_parse($ip_str = "") { if ($ip_str == "") { return [ null, null, null, null ]; } $mask_len = 32; if (strpos($ip_str, "/") > 0) { list($ip_str, $mask_len) = explode("/", $ip_str); } $ip = ip2long($ip_str); $mask = 0xFFFFFFFF << (32 - $mask_len) & 0xFFFFFFFF; $ip_start = $ip & $mask; $ip_end = $ip | (~$mask) & 0xFFFFFFFF; return array( $ip, $mask, $ip_start, $ip_end ); } /** * ip、掩码转换成ip字符串10.10.10.10/32 * * @param long $long * @param long $subnet_mask * @return string */ public static function ip_export($long, $subnet_mask = "") { if (!$long) { return null; } if ($subnet_mask == -1 | $subnet_mask == "") { return long2ip($long); } else { $suffix = strlen(preg_replace("/0/", "", decbin($subnet_mask))); // 十进制转二进制 统计32-bits的二进制中1的个数 return long2ip($long) . "/" . $suffix; } } }<file_sep>/application/checkME60/config.php <?php return [ 'version' => "V1.0426-ck60" ];<file_sep>/application/zx_apply/controller/Tool.php <?php namespace app\zx_apply\controller; class Tool extends Common { public function _initialize() { if (input("get.uu") == "y") { session("user", [ "name" => "{Test}" ]); } parent::_initialize(); } public function index() { // 暂未配置登录页面 return $this->redirect("main"); } }<file_sep>/application/common/controller/Common.php <?php namespace app\common\controller; use think\Controller; use think\Request; use think\Config; use think\Db; use think\Session; use think\Cache; use PHPMailer\PHPMailer\PHPMailer; class Common extends Controller { /** * 判断是否已登录--(初始化函数 _initialize 优先于 $beforeActionList 配置) */ public function _initialize() { $request = Request::instance(); if ($request->controller() == 'common') { return $this->error("非法访问!你很6啊。然而我会带你回去。"); } // url : index.php/【MODULE】/【CONTROLLER】/【ACTION】.html $permitModule = [ "esserver" ]; $permitController = [ // "Tool" ]; $permitActions = [ "index", "main", "getvcode" ]; // 判断是否从localhost 访问, url 是否允许 未登录访问。否则跳转 if (substr($request->domain(), -9) == "localhost" || in_array($request->module(), $permitModule) || in_array($request->controller(), $permitController) || in_array($request->action(), $permitActions) || input('session.user/a')) { $this->assign("version", config("version")); } else { // session 保存 to_url session("to_url", request()->baseUrl()); return $this->error('您未登录或登录超时,请先登录!', 'index/index#' . $request->controller() . "/" . $request->action()); } } public function index() { return "当前执行的是:common/index"; } /** * 退出登录 */ public function loginout() { $this->log("注销登陆", [ "stauts" => "success", "name" => session("user.name") ]); Session::delete("user"); return $this->success("已注销登录", "index#logout", "", 1); } /** * php 数组 转成 Grid 组件需要的 json 格式 * * @param array $array * @param string $header * @return string */ public static function array_to_json($array = [], $header = '') { $data_arr = []; if ($header == '') { foreach ($array as $val) { $id = null; $theData = []; foreach ($val as $k => $v) { if ($id == null || $k == 'id') // 让 id 为 第一个值,或者为id值 $id = $v; $theData[] = $v; } $data_arr[] = [ "id" => $theData[0], "data" => $theData ]; } } else { } return json_encode([ "rows" => $data_arr ], JSON_UNESCAPED_UNICODE); } /** * php 数组根据 header 转成 csv 字符串 * * @param array $array * @param string $header * @return string */ public static function array_to_csv($array = [], $header = '') { $csvstr = ''; if ($header == '') { foreach ($array as $val) { $i = 1; foreach ($val as $v) { if ($i < count($val)) $csvstr .= $v . ','; else $csvstr .= $v . "\n"; $i++; } } } else { $headers = explode(",", $header); foreach ($array as $val) { for ($i = 0; $i < count($headers); $i++) { if ($i < count($headers)) $csvstr .= $val[$headers[$i]] . ','; else $csvstr .= $val[$headers[$i]] . "\n"; } } } $csvstr = substr($csvstr, 0, strlen($csvstr) - 1); return $csvstr; } function zz() { return dump($this->csv_to_array([ "a", "b", "c" ], "1,2,3")); } /** * csv 转 php数组 * * @param array $header * @param string $csvstr * @return array */ public static function csv_to_array($header = [], $csvstr = '') { trim($csvstr); $data = explode("\n", $csvstr); $result = []; // 初始化结果数据 for ($i = 0; $i < count($data); $i++) { // 将多条原始数据分别分割为数组 $result[] = array_combine($header, explode(",", trim($data[$i]))); } return $result; } /** * 根据列名、表名查询非重复数据 * * @param string $table * @param array $field * @param array $where * @param string $distinct * @param string $order * @return string|\think\Collection|\think\db\false|PDOStatement|string */ public static function get_combo_options($table = '', $field = [], $where = [], $distinct = true, $order = "id") { $table = input("param.table"); $field = input("param.field/a"); $where = input("param.where/a"); $distinct = input("?param.distinct") ? input("param.distinct/b") : true; $order = input("param.order"); if ($table == '') return "传值为空"; foreach ($field as $k => $f) { $field_arr[] = $f . " as " . $k; } $field_str = implode(",", $field_arr); $result = Db::name($table)->distinct($distinct)->where($where)->field($field_str)->order($order)->select(); return $result; // 自动处理成 json() // return json_encode($result, 256);//Content-Type:text/html // return json ( $result ); // 返回 Content-Type : application/json } public static function get_combo_options2($column = '', $table = '') { $table = input("param.table"); $column = input("param.column"); if ($table == '' || $column == '') return "传值为空,需要_table和_column参数"; $result = Db::name($table)->distinct(true)->field($column . " as value")->select(); for ($i = 0; $i < count($result); $i++) { $result[$i]['text'] = $result[$i]['value']; } $result = [ 'options' => $result ]; return $result; } /** * 获取邮件验证码 * * @param string $e * @param number $ttl */ public function getVcode($e = '', $ttl = '120') { if (preg_match('/[^A-Za-z0-9.@_]+/', $e)) { return $this->error('非法邮箱地址哦'); } else { $e = strtolower($e); } // 限制系统每2小时最多发送12个验证码。(超2小时code可重复) $data = Db::table("phpweb_check")->whereTime('time', '-2 hours')->select(); if (count($data) > 12) { return $this->success("单位时间发送验证码过多。请根据页面下方信息与管理员联系。"); } // 检查$ttl分钟内是否已申请 // $data = Db::table ( "phpweb_check" )->whereTime ( 'time', '-31 min' )->where ( "loginName", $e )->order ( "time desc" )->find (); $codes = []; foreach ($data as $v) { if ($v['email'] == $e) { if (time() - strtotime($v['time']) < $ttl * 60) { return $this->success("距离上一次申请间隔小于" . $ttl . "分钟,请勿重复操作。<br><br>如未收到请稍等3分钟并检查是否在垃圾邮件中。"); } } $codes[] = $v['code']; } // 检查是否与生效中的其他用户的相同 do { $vcode = rand(0, 9999); } while (in_array($vcode, $codes)); $address = $e; $subject = '[ESWeb]验证码:' . sprintf("%04s", $vcode) . ',可在30分钟内使用。'; $body = '<p style="color:#088bff;">请确认是您申请了邮箱登录的验证码。若非本人操作,请忽略本邮件。</p><hr /><br /><br /><br /><br /> <div style="width:500px;padding:30px;background-color:#000;color:#bbb;"><p>Powered by <a style="color:#eee;font-weight:bold;" href="https://github.com/thianda/")">X.Da</a></p> <p><a style="color:#eee;font-weight:bold;" href="mailto:<EMAIL>")">Connect me</a>: <EMAIL></p> <p>Read <a style="color:#eee;font-weight:bold;" href="https://thianda.github.io/phpweb/notes/zx-apply.html">this</a> to find more</p></div>'; $sendEmail = $this->sendEmail($address, $subject, $body); // $sendEmail = true; // 测试用例 if (is_bool($sendEmail)) { $msg = "验证码已通过邮件发送,请到邮箱内查收主题包含[ESWeb]的邮件。"; // 新用户,通知管理员 if (Db::table("phpweb_check")->where("email", $e)->find()) { } else { $title = "[新用户]" . $e; $msg = "来自IP: " . request()->ip() . ",第一次获取了验证码。"; $this->noticeXianda($title, $msg); } // 存入数据库 $insertData = [ 'code' => $vcode, 'email' => $e, 'name' => input("param.name"), 'module' => request()->module() ]; Db::table("phpweb_check")->insert($insertData); $this->log("获取验证码", [ "status" => "success", "name" => input("param.name"), "email" => $e, "msg" => $msg ]); return $this->success($msg, null, 2 * $vcode); } else { $msg = "邮件发送未成功:" . $sendEmail; $this->log("获取验证码", [ "status" => "failed", "name" => input("param.name"), "email" => $e, "msg" => $msg ]); return $this->error($msg); } } /** * 获取参数 * * @param string $table * @param array $where * @return string 参数值 */ public static function getSysInfo($label = '') { return Db::table("phpweb_sysinfo")->where("label", $label)->value("value"); } public function bugReport() { if (Request::instance()->isGet()) { return $this->display("<h3>??????</h3>"); } else { $data = input("post."); // return dump($data); return Db::name('bugreport')->insert($data); // return $this->success(""); } } /** * 通知管理员 * * @param unknown $title * @param unknown $msg */ protected function noticeManage($title = "", $msg = "", $address = []) { $number = 20; $logs = Db::table("phpweb_log")->field("id,k,v,ip,module,time")->order("time desc")->limit($number)->select(); $tableStr = '<table class="_xda-resultTable" style="font-size:14px;border-collapse:collapse;border:none;">'; $tableStr .= '<tr bgcolor="#dddddd" style="font-size:18px;">'; $tableStr .= '<th>编号</th><th>键</th><th>值</th><th>ip</th><th>模块</th><th>时间</th>'; $tableStr .= '</tr>'; foreach ($logs as $key => $value) { $tableStr .= '<tr><td style="width:50px;">' . $value["id"] . '</td>'; $tableStr .= '<td style="width:90px;">' . $value["k"] . '</td>'; $v = str_replace(",", "\n", $value["v"]); $v = str_replace("{", "<pre style='width:500px;overflow:auto;'>", $v); $v = str_replace("}", "</pre>", $v); $v = str_replace("\":\"", ":\t\t", $v); $v = str_replace("\"", "", $v); $tableStr .= '<td style="width:500px;">' . $v . '</td>'; $tableStr .= '<td style="width:130px;">' . long2ip($value['ip']) . '</td>'; $tableStr .= '<td style="width:65px;">' . $value["module"] . '</td>'; $tableStr .= '<td style="width:150px;">' . $value["time"] . '</td></tr>'; } $tableStr .= '</table>'; $tableStr .= '<style>._xda-resultTable th, ._xda-resultTable td{border:solid #000 1px;}</style>'; // 下面是旧版php的字符串拼接变量的方法。 $msg = "<p>{$msg}</p><hr><p>以下是最近" . $number . "条系统log日志:</p>{$tableStr}"; // return $msg; $result = $this->sendEmail($address, $title, $msg); return $result; } protected function noticeXianda($title = "", $msg = "") { $this->noticeManage($title, $msg, "<EMAIL>"); } /** * 记录系统log * * @param unknown $k * @param unknown $v * @param unknown $time */ protected function log($k = "", $v = []) { Db::table("phpweb_log")->insert([ "k" => $k, "v" => json_encode($v, JSON_UNESCAPED_UNICODE), "module" => Request::instance()->module(), "ip" => ip2long(request()->ip()) ]); } protected function sendEmail($address = [], $subject = '', $body = '', $attachments = null) { try { $mail = new PHPMailer(); $mail->isSMTP(); // Set mailer to use SMTP $mail->CharSet = "utf-8"; $mail->SetLanguage('zh_cn'); // $mail->SMTPDebug = 1; $account = config("email"); $account['Username'] = Cache::remember("email_username", function () { Config::parse("static/email_config", "ini"); return Config::get("email_account.Username"); }); $account['Password'] = Cache::remember("email_password", function () { Config::parse("static/email_config", "ini"); return Config::get("email_account.Password"); }); $mail->Host = $account['SMTP']; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = $account['Username']; // SMTP username $mail->Password = $account['<PASSWORD>']; // SMTP password $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted $mail->Port = $account['Port']; // TCP port to connect to $mail->setFrom($account['Username'], '专线开通辅助'); if (is_string($address)) { $mail->addAddress($address); } else { foreach ($address as $key => $addr) { if (substr($key, 0, 2) === 'CC') $mail->addCC($addr); else $mail->addAddress($addr); } } // Name is optional // $mail->addReplyTo ( '<EMAIL>', 'Information' ); // $mail->addCC ( '<EMAIL>' ); // $mail->addBCC ( '<EMAIL>' ); if (!is_null($attachments)) { if (is_array($attachments)) { foreach ($attachments as $attachment) { $mail->addAttachment($attachment); } } else { $mail->addAttachment($attachments); } } // $mail->addAttachment ( '/var/tmp/file.tar.gz' ); // Add attachments // $mail->addAttachment ( '/aa.jpg', '附件new.jpg' ); // Optional name // 绝对路径从磁盘根目录算起,相对路径从public/index.php算起。 $mail->isHTML(true); // Set email format to HTML $mail->Subject = $subject; //$body .= '<br><br><br><p style="float:right;color:red;font-size:10px;">'+config('version')+'</p>'; $mail->Body = $body; $mail->AltBody = '您的邮件客户端不支持查看HTML格式的邮件正文。'; if ($mail->send()) { return true; } else { return $mail->ErrorInfo; } } catch (Exception $e) { return $mail->ErrorInfo; } } public function _empty() { $request = Request::instance(); $dir = APP_PATH . $request->module() . DS . "view" . DS . $request->controller() . DS . $request->action() . "." . config('template.view_suffix'); if (file_exists($dir)) return $this->fetch($request->action()); else { return $this->error("请求未找到,将返回上一页...(common/controller/Common.php->_empty())"); } } } <file_sep>/application/zx_apply/controller/Generator.php <?php namespace app\zx_apply\controller; use app\zx_apply\model\Infotables; use Overtrue\Pinyin\Pinyin; use app\zx_apply\model\Iptables; class Generator extends Common { /* 各系统的【单位属性】默认固定为“企业” */ /* 应该根据字段 unitProperty 来填写 */ /* 应删除字段 unitAttribute,或在 apply.html 中隐藏该字段,已精简页面显示 */ public static function generateIDCinfoFiles($ids = null, $type = 2) { if (!is_array($ids)) { $ids = explode(",", $ids); } $row = 3; $cellValues = []; $sheets = [ 2 => ["表4", "表5", "表8", "表10", "表11"] ]; $colNames = "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"; $theCompany = base64_decode("5Lit5Zu956e75Yqo6YCa5L+h6ZuG5Zui6L695a6B5pyJ6ZmQ5YWs5Y+4"); $engineRoom = base64_decode("6L695a6B56e75Yqo6ZOB5bKt5biCSURD5LiT57q/5py65oi/"); $structure = [ "表4" => [ "title" => "IP地址段信息", "header" => "起始IP地址,终止IP地址,IP地址使用方式,使用人,使用人的证件类型,对应证件号码,来源单位,分配单位,分配使用时间,机房名称", "default" => [ "C" => "专线", "G" => $theCompany, "H" => $theCompany, "J" => $engineRoom, ], ], "表5" => [ "title" => "用户信息", "header" => "用户属性,单位名称,单位属性,证件类型,证件号码,单位地址,邮政编码,服务开通时间,注册时间,网络安全责任人(名称),网络安全责任人(证件号码)", "default" => [ "A" => "其他用户", //"G" => 112000, ] ], "表8" => [ "title" => "占用机房信息(其他用户)", "header" => "机房名称,资源分配时间,网络带宽(Mbps),用户信息(单位名称)", "default" => [ "A" => $engineRoom, ] ], "表10" => [ "title" => "其他用户IP地址段信息", "header" => "机房名称,资源分配时间,网络带宽,用户信息(单位名称),起始IP地址,终止IP地址", "default" => [ "A" => $engineRoom, ] ], "表11" => [ "title" => "网络安全责任人", "header" => "姓名,证件类型,证件号码,固定电话,移动电话,email地址", "default" => [ "B" => "身份证", "D" => "无", ] ], ]; /* start creating cellValues */ foreach ($sheets[$type] as $sheet) { /* build headers */ $header = []; $keys = explode(" ", $colNames); $values = explode(",", $structure[$sheet]["header"]); foreach ($values as $k => $v) { $header[$keys[$k] . 2] = $v; } $cellValues[$sheet] = array_merge(["A1" => $structure[$sheet]["title"]], $header); /* add default values */ foreach ($structure[$sheet]["default"] as $k => $v) { $cellValues[$sheet][$k . $row] = $v; } } function getArrayValue($arr = [], $k = "0") { return array_key_exists($k, $arr) ? $arr[$k] : null; } foreach ($ids as $id) { /* add dynamic values */ $data = Infotables::get($id)->toArray(); $extra = getArrayValue($data, "extra"); $nullVal = null; $credential = $extra ? getArrayValue($extra, "credential") ? config("credential")[getArrayValue($extra, "credential")] : $nullVal : $nullVal; $unitProperty = $extra ? getArrayValue($extra, "unitProperty") ? config("unitProperty")[getArrayValue($extra, "unitProperty")] : $nullVal : $nullVal; if (in_array("表4", $sheets[$type])) { $cellValues["表4"]["A" . $row] = $data["ip"]; // ip $cellValues["表4"]["B" . $row] = $data["ip"]; // ip $cellValues["表4"]["D" . $row] = $data["cName"]; // 客户名 $cellValues["表4"]["E" . $row] = $credential; // 证件类型 $cellValues["表4"]["F" . $row] = getArrayValue($extra, "credentialnum"); // 证件号码 $cellValues["表4"]["I" . $row] = $data["create_time"]; // 分配时间 } if (in_array("表5", $sheets[$type])) { $cellValues["表5"]["B" . $row] = $data["cName"]; // 客户名 $cellValues["表5"]["C" . $row] = $unitProperty; // 单位属性 $cellValues["表5"]["D" . $row] = $credential; // 证件类型 $cellValues["表5"]["E" . $row] = getArrayValue($extra, "credentialnum"); // 证件号码 $cellValues["表5"]["F" . $row] = $data["cAddress"]; // 客户地址 $cellValues["表5"]["G" . $row] = $data["extra"]["zipCode"]; // 邮政编码 $cellValues["表5"]["H" . $row] = $data["create_time"]; // 服务开通时间 $cellValues["表5"]["I" . $row] = $data["create_time"]; // 注册时间 $cellValues["表5"]["J" . $row] = getArrayValue($extra, "securityPerson"); // 网络安全责任人 $cellValues["表5"]["K" . $row] = getArrayValue($extra, "securityPersonID"); // 责任人身份证号 } if (in_array("表8", $sheets[$type])) { $cellValues["表8"]["B" . $row] = $data["create_time"]; // 分配时间 $cellValues["表8"]["C" . $row] = $data["bandWidth"] + 0; // 带宽 $cellValues["表8"]["D" . $row] = $data["cName"]; // 客户名 } if (in_array("表10", $sheets[$type])) { $cellValues["表10"]["B" . $row] = $data["create_time"]; // 分配时间 $cellValues["表10"]["C" . $row] = $data["bandWidth"] + 0; // 带宽 $cellValues["表10"]["D" . $row] = $data["cName"]; // 客户名 $cellValues["表10"]["E" . $row] = $data["ip"]; // ip $cellValues["表10"]["F" . $row] = $data["ip"]; // ip } if (in_array("表11", $sheets[$type])) { $cellValues["表11"]["A" . $row] = getArrayValue($extra, "securityPerson"); $cellValues["表11"]["C" . $row] = getArrayValue($extra, "securityPersonID"); // 责任人身份证号 $cellValues["表11"]["E" . $row] = $data["cPhone"] + 0; // 客户电话 $cellValues["表11"]["F" . $row] = $data["cEmail"]; // 客户邮箱 $row++; } } //return $cellValues; $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); $index = 1; // 编辑worksheet foreach ($cellValues as $ws => $_sheet) { $worksheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, $ws); $spreadsheet->addSheet($worksheet, $index++); foreach ($_sheet as $k => $v) { $worksheet->setCellValue($k, $v); // $worksheet->getCell ( $k )->setValue ( $v ); } } $spreadsheet->removeSheetByIndex(0); $spreadsheet->getProperties()->setCreator("X.Da"); $spreadsheet->getProperties()->setLastModifiedBy('X.Da'); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx"); // header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); // 告诉浏览器数据excel07文件 // header('Content-Disposition: attachment;filename="' . $fileName . '"'); // 告诉浏览器将输出文件的名称 // header('Cache-Control: max-age=0'); // 禁止缓存 // $writer->save("php://output"); $dir = "../runtime/temp/"; $fileName = '铁岭IDC.ISP-' . $data["ip"] . "-" . $data["cName"] . '.xlsx'; // $tmp = time(). '.xlsx'; // $writer->save($dir . $tmp); $writer->save($dir . $fileName); $spreadsheet->disconnectWorksheets(); unset($spreadsheet); unset($writer); // if (file_exists($dir . $fileName) || !file_exists($dir . $tmp)) { // return -1; // idc.isp附件生成失败 // } else { // return rename($dir . $fileName, $dir . $tmp) ? $dir . $fileName : 0; // } return $dir . $fileName; } public static function generateZgWorkflow($ids = null) { if (is_string($ids)) { $ids = explode(",", $ids); } $row = 5; $cellValues = []; $principal = base64_decode("5Y2c546J"); $tel = base64_decode("MTg4NDEwNTA4MTU=") + 0; $dept = base64_decode("5a6i5oi35ZON5bqU5Lit5b+D"); $email = base64_decode("YnV5dS50bEBsbi5jaGluYW1vYmlsZS5jb20"); $engineRoom = base64_decode("<KEY>"); $default = [ "B" => "铁岭", "D" => "占用", "E" => "192.168.127.12/20", "F" => "集客专线", "G" => "互联网专线", "H" => "LNTIL-MA-CMNET-BAS02-YZME60X", "L" => $principal, "M" => $tel, "N" => "Auto import! --X.Da", "O" => "铁岭", "P" => $principal, "R" => "其他", //"S" => "企业", "T" => "辽宁", "W" => $dept, "X" => $email, "AD" => "静态", "AH" => "已启用", "AI" => $engineRoom, ]; foreach ($ids as $id) { foreach ($default as $k => $v) { $cellValues[$k . $row] = $v; } $data = Infotables::get($id)->toArray(); $cellValues["C" . $row] = $data["ip"] . "/32"; // ip $cellValues["K" . $row] = $data["create_time"]; // 分配时间 $cellValues["Q" . $row] = $data["cName"]; // 客户名 $cellValues["S" . $row] = $data["extra"]["unitAttribute"]; // 企业属性 /* 以下为选填 */ $cellValues["I" . $row] = $data["cPerson"]; // 客户联系人 $cellValues["J" . $row] = $data["cPhone"] + 0; // 客户电话 $cellValues["U" . $row] = $data["cAddress"]; // 客户地址 $cellValues["V" . $row] = $data["cEmail"]; // 客户邮箱 $cellValues["AG" . $row] = $data["instanceId"] + 0; // 政企专线计费代号 $row++; } $pFilename = './static/sampleData/zg_import.xls'; return self::exportExcelFile($pFilename, 0, $cellValues, 'Xls', '资管流程-' . $data["cName"] . '.xls'); } public static function generateJtIp($ids = null) { $row = 4; $cellValues = []; $dept = base64_decode("6ZOB5bKt56e75Yqo5a6i5oi35ZON5bqU5Lit5b+D"); $principal = base64_decode("5Y2c546J"); $tel = base64_decode("MTg4NDEwNTA4MTU=") + 0; $email = base64_decode("YnV5dS50bEBsbi5jaGluYW1vYmlsZS5jb20"); $default = [ "D" => "其他", //"F" => "企业", "G" => "辽宁", "H" => "铁岭", "Q" => "静态", "T" => "互联网专线", "U" => "占用", "V" => "已启用", "AA" => $dept, "AB" => $principal, "AC" => $tel, "AD" => $email ]; foreach ($ids as $id) { foreach ($default as $k => $v) { $cellValues[$k . $row] = $v; } $data = Infotables::get($id)->toArray(); $cellValues["B" . $row] = $data["ip"] . "/32"; // ip $cellValues["C" . $row] = $data["cName"]; // 客户名 $cellValues["F" . $row] = $data["extra"]["unitAttribute"]; // 企业属性 $cellValues["L" . $row] = $data["cAddress"]; // 客户地址 $cellValues["M" . $row] = $data["cPerson"]; // 客户联系人 $cellValues["N" . $row] = $data["cPhone"] + 0; // 客户电话 $cellValues["O" . $row] = $data["cEmail"]; // 客户邮箱 $cellValues["R" . $row] = $data["create_time"]; // 分配时间 $row++; } $pFilename = './static/sampleData/ip_jt.xlsx'; return self::exportExcelFile($pFilename, 0, $cellValues, 'Xlsx', '集团IP备案-' . $data["cName"] . '.xlsx'); } public static function generateGxbIp($ids = null) { $row = 2; $cellValues = []; $default = [ "D" => "其他", //"F" => "企业", "Q" => "静态" ]; foreach ($ids as $id) { foreach ($default as $k => $v) { $cellValues[$k . $row] = $v; } $data = Infotables::get($id)->toArray(); $cellValues["A" . $row] = $data["ip"]; // ip $cellValues["B" . $row] = $data["ip"]; // ip $cellValues["C" . $row] = $data["cName"]; // 客户名 $cellValues["F" . $row] = $data["extra"]["unitAttribute"]; // 企业属性 $cellValues["L" . $row] = $data["cAddress"]; // 客户地址 $cellValues["M" . $row] = $data["cPerson"]; // 客户联系人 $cellValues["N" . $row] = $data["cPhone"] + 0; // 客户电话 $cellValues["O" . $row] = $data["cEmail"]; // 客户邮箱 $cellValues["R" . $row] = $data["create_time"]; // 分配时间 $cellValues["F" . $row] = "企业"; $cellValues["G" . $row] = isset($data["extra"]["province"]) ? $data["extra"]["province"] : ""; $cellValues["H" . $row] = isset($data["extra"]["city"]) ? $data["extra"]["city"] : ""; $row++; } $pFilename = './static/sampleData/ip_gxb.xls'; return self::exportExcelFile($pFilename, 4, $cellValues, 'Xls', '工信部IP备案-' . $data["cName"] . '.xls'); } /** * 导出到excel * * @param unknown $pFilename 模板文件地址 * @param unknown $workSheetIndex 工作表索引 * @param unknown $cellValues 数据 * @param unknown $writerType 输出类型 Xls or Xlsx * @param unknown $fileName 输出文件名 * @param String $writerMethod 写入$cellValues使用的phpsSpreadsheet 方法名 * @param boolval $unusePHP 是否用 PHP 导出 excel 文件 */ private static function exportExcelFile($pFilename, $workSheetIndex, $cellValues, $writerType, $fileName, $writerMethod = "setCellValue") { if (!input("post.php/b")) { return [ "fileName" => $fileName, "cellValues" => $cellValues ]; } $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($pFilename); $worksheet = $spreadsheet->getSheet($workSheetIndex); // 编辑worksheet foreach ($cellValues as $d => $v) { $worksheet->$writerMethod($d, $v); // $worksheet->getCell ( $d )->setValue ( $v ); } // 定义spreadsheet参数并输出到浏览器 $spreadsheet->getProperties()->setCreator("X.Da"); $spreadsheet->getProperties()->setLastModifiedBy('X.Da'); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, $writerType); if ($writerType == "Xls") { header('Content-Type: application/vnd.ms-excel'); // 告诉浏览器将要输出excel03文件 } else { header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); // 告诉浏览器数据excel07文件 } header('Content-Disposition: attachment;filename="' . $fileName . '"'); // 告诉浏览器将输出文件的名称 header('Cache-Control: max-age=0'); // 禁止缓存 $writer->save("php://output"); $spreadsheet->disconnectWorksheets(); unset($spreadsheet); unset($writer); } public static function generateScript($id = null) { $data = Infotables::get($id); if ($data["zxType"] == "互联网") { if ($data['neFactory'] == 'ONU') { return self::error("ONU业务暂不支持数据制作脚本"); } return self::generateScriptNet($data); } if ($data["zxType"] == "卫生网") { return self::generateScriptWsw($data); } } /** * 数据制作脚本生成-互联网 * * @param unknown $data * @return string|NULL[]|string[] */ private static function generateScriptNet($data) { $data["domain"] = 'tlyd-rb'; // 1. domain $aStation = config("aStation"); $data["sw93"] = $aStation[$data["aStation"]]; // 2. 9312名 $pinyin = new Pinyin(); $desc = substr($data["sw93"], 0, stripos($data["sw93"], "-") + 1); $desc = str_replace("CHJ", "TL", $desc); $_desc = $pinyin->convert(preg_replace("/[^\x{4e00}-\x{9fa5}A-Za-z0-9-]/u", "", $data["cName"])); foreach ($_desc as $v) { $desc .= ucfirst($v); } $data["desc"] = $desc . "_NET"; // 3. 描述 $device9312 = json_decode(base64_decode(config("device9312")), true)[$data["sw93"]]; function bas($bas, $device9312, $data) { $trunk = $device9312['bas' . $bas . '_down_port']; $rbp = $device9312['rbp_name']; $_bas_name = [ "01" => "01-CHJ", "02" => "02-YZL" ]; if (strlen($data["domain"]) > 4) { // tlyd-rb $rbp = "\n remote-backup-profile " . $rbp; } else { $rbp = null; } $script = "interface " . $trunk . "." . $data["vlan"]; $script .= "\ndis th\n "; $script .= "\n description [LNTIL-MA-CMNET-BAS" . $_bas_name[$bas] . "ME60X]" . $trunk . "." . $data["vlan"] . "-[" . $data["desc"] . "]"; $script .= "\n user-vlan " . $data["vlan"] . $rbp; $script .= "\n bas\n #\n access-type layer2-subscriber default-domain authentication " . $data["domain"]; $script .= "\n authentication-method bind\n"; $script .= "static-user " . $data["ip"] . " " . $data["ip"] . " gateway " . substr($data["ip"], 0, strripos($data["ip"], ".") + 1) . "1 " . "interface " . $trunk . "." . $data["vlan"] . " vlan " . $data["vlan"] . " domain-name " . $data["domain"] . " detect\r\n"; return $script; } function the93($device9312, $data) { if ($data["neFactory"]) { $data["neFactory"] === '华为' && $down = "port_hw"; $data["neFactory"] === '中兴' && $down = "port_zte"; } else { return "网元厂家未定义"; } $script = "vlan " . $data["vlan"] . "\ndis th\n \n"; $script .= "description to-[" . $data["desc"] . "]\nq"; $script .= "\ninterface " . $device9312["up_port_yz"]; // 上行银州 bas02 $script .= "\nport trunk allow-pass vlan " . $data["vlan"]; if (strlen($data["domain"]) > 4) { // 上行柴河 bas01 $script .= "\ninterface " . $device9312["up_port_ch"] . "\nport trunk allow-pass vlan " . $data["vlan"]; } $script .= "\ninterface " . $device9312[$down]; // 下行 $script .= "\nport trunk allow-pass vlan " . $data["vlan"]; $script .= "\nq\r\n"; return $script; } $result = [ "bas01" => bas("01", $device9312, $data), "bas02" => bas("02", $device9312, $data), "the93" => [ $data["sw93"], the93($device9312, $data) ] ]; return $result; } /** * 数据制作脚本生成-卫生网 * * @param unknown $data * @return string|NULL[]|string[] */ private static function generateScriptWsw($data) { $aStation = config("aStation"); $data["sw93"] = $aStation[$data["aStation"]]; // 2. 9312名 $pinyin = new Pinyin(); $desc = substr($data["sw93"], 0, stripos($data["sw93"], "-") + 1); // 3. 描述 $desc = str_replace("CHJ", "TL", $desc); $_desc = $pinyin->convert(preg_replace("/[^\x{4e00}-\x{9fa5}A-Za-z0-9-]/u", "", $data["cName"])); foreach ($_desc as $v) { $desc .= ucfirst($v); } $device9312 = json_decode(config("device9312"), true)[$data["sw93"]]; $trunk = $device9312['bas02_down_port']; $ip = Iptables::ip_parse($data["ip"]); $ipB = Iptables::ip_parse($data["ipB"]); $script = "interface " . $trunk . "." . $data["vlan"] . "\ndis th\n"; $script .= "\n vlan-type dot1q " . $data["vlan"]; $script .= "\n description [LNTIL-MA-CMNET-BAS02-YZLME60X]" . $trunk . "." . $data["vlan"] . "-[" . $desc . "]"; $script .= "\n ip binding vpn-instance tlwsw"; $script .= "\n ip address " . long2ip($ipB[2] + 1) . " " . long2ip($ipB[1]); $script .= "\n traffic-policy remarkdscp inbound"; $script .= "\n statistic enable"; $script .= "\nip route-static vpn-instance tlwsw " . long2ip($ip[2]) . " " . long2ip($ip[1]) . " " . long2ip($ipB[2] + 2) . "\r\n"; /* the9312 */ if ($data["neFactory"]) { $data["neFactory"] === '华为' && $down = "port_hw"; $data["neFactory"] === '中兴' && $down = "port_zte"; } else { return [ "the93" => [ "网元厂家未定义", "" ] ]; } $the9312 = "vlan " . $data["vlan"] . "\ndis th\n\n"; $the9312 .= "description to-[" . $desc . "]\nq"; $the9312 .= "\ninterface " . $device9312["up_port_yz"] . "\nport trunk allow-pass vlan " . $data["vlan"]; $the9312 .= "\ninterface " . $device9312[$down] . "\nport trunk allow-pass vlan " . $data["vlan"] . "\nq\r\n"; return [ "bas02" => $script, "the93" => [ $data["sw93"], $the9312 ] ]; } /** * 修复历史数据新增 6 个 extra 字段为空的问题 * * @return void */ public function fix6newExtraFields() { $data = Infotables::all(); foreach ($data as $k => $v) { $unitProperty = config("unitProperty"); $extra = $v->extra; if (is_null($extra)) { continue; } if (!isset($extra['unitAttribute'])) $extra['unitAttribute'] = is_null($extra['unitProperty']) ? "" : $unitProperty[$extra['unitProperty']]; if (!isset($extra['securityPerson'])) $extra['securityPerson'] = is_null($v->cPerson) ? "" : $v->cPerson; if (!isset($extra['securityPersonID'])) $extra['securityPersonID'] = '0'; if (!isset($extra['securityPhone'])) $extra['securityPhone'] = is_null($v->cPhone) ? "" : $v->cPhone; if (!isset($extra['securityEmail'])) $extra['securityEmail'] = is_null($v->cEmail) ? "" : $v->cEmail; if (!isset($extra['zipCode'])) $extra['zipCode'] = "112000"; $data[$k]->extra = $extra; $data[$k]->save(); } return dump("ok"); } private function cacheSettings() { $client = new \Redis(); $client->connect('127.0.0.1', 6379); $pool = new \Cache\Adapter\Redis\RedisCachePool($client); $simpleCache = new \Cache\Bridge\SimpleCache\SimpleCacheBridge($pool); \PhpOffice\PhpSpreadsheet\Settings::setCache($simpleCache); } }<file_sep>/application/trouble/model/Forms.php <?php namespace app\trouble\model; use think\Model; class Forms extends Model { protected $type = [ 'id' => 'integer', 'createTime' => 'datetime', 'applicationApprovalTime' => 'datetime', 'approvalTime' => 'datetime', 'dispatchTime' => 'datetime', 'acceptanceTime' => 'datetime', 'marks' => 'integer', 'status' => 'integer' ]; public static function beautify($data, $single = false) { $status = [ 0 => '等待部门审批', 1 => '部门不同意', 2 => '等待处理', 3 => '客响不同意', 4 => '等待处理', 5 => '已撤销', 6 => '已派单,待受理', 7 => '处理中', 8 => '待申请人确认', 9 => '待派单人归档', - 1 => '已归档' ]; if (empty ( $data )) { return null; } else { if ($single) { $data ['statusText'] = $status [$data ['status']]; $data ['logs'] = strtr ( $data ['logs'], [ ";" => ";<br>" ] ); } else { foreach ( $data as $k => $v ) { $data [$k] ['statusText'] = $status [$v ['status']]; } } return $data; } } }
be96c54fdebd58d68bd58c5910e29361fb35100e
[ "Markdown", "PHP", "Shell" ]
43
Shell
yuxianda/phpweb
bbe816cb270f0854ce00091c8a729dc4ee5e6d10
aa5a84a43b193643f6469aa336395d5253fe3128
refs/heads/master
<file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <?php include "style.php"; ?> <link rel="stylesheet" href="css/index.css"> <title>Home</title> </head> <body> <div id="main-content"> <?php include 'header-sidebar.php';?> <div id="isi"> <h1><NAME></h1> <p style="text-align: justify;">Lorem Ipsum is simply dummy text of the printing and typesetting industry.when an unknown printer took a galley of type and scrambled it to make a type specimen book..</p> <h1>Galeri</h1> <p style="text-align: right; margin-top: -30px;"><a href="galeri.php" style="text-decoration: none; color: #29aae3">Lihat lainnya...</a></p> <div class="galeri"> <img src="gambar/book1.jpg" alt=""> <p><a href="galeri.php"><button class="button">Lihat lebih lanjut</button></a></p> </div> <div class="galeri"> <img src="gambar/book2.jpg" alt=""> <p><a href="galeri.php"><button class="button">Lihat lebih lanjut</button></a></p> </div> <div class="galeri"> <img src="gambar/book3.jpg" alt=""> <p><a href="galeri.php"><button class="button">Lihat lebih lanjut</button></a></p> </div> </div> <div id="clear"></div> </div> </body> </html> <file_sep><?php session_start(); if(isset($_SESSION['level'])){ if($_SESSION['level'] != 'pegawai'){ header('Location: ../admin/galeri.php'); } } else{ header('Location: ../index.php'); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="../css/style.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <body> <div id="batas"> <div id="atas"> <img src="../img/banner.jpg" alt=""> <p>Perpustakaan Universitas Udayana</p> </div> <div id="sidebar"> <img src="../img/logo.png" alt=""> <div class="populer"> <p>Artikel Populer</p> </div> <ul> <li><a href="index.php">HOME</a></li> <li><a href="tentang.php">TENTANG</a></li> <li><a href="galeri.php">GALERI</a></li> <li><a href="kontak.php">KONTAK</a></li> <li><a href="logout.php">Logout</a></li> </ul> </div> <div id="menu"> <ul> <li><a href="index.php">HOME</a></li> <li><a href="tentang.php">TENTANG</a></li> <li><a href="galeri.php">GALERI</a></li> <li><a href="kontak.php">KONTAK</a></li> <li><a href="logout.php">Logout</a></li> </ul> </div> <div id="isi"> <h1>Galeri</h1> <form class="example" action="#"> <input type="text" placeholder="Cari Buku..." name="search"> <button type="submit"><i class="fa fa-search"></i></button> </form> <div class="daftar-buku"> <div class="deskripsi"> <p>Shadow of the Conqueror</p> <p><NAME></p> <nav> <ul> <li>Jumlah Halaman</li> <li>Tanggal Terbit</li> <li>ISBN</li> <li>Bahasa</li> <li>Penerbit</li> <li>Berat</li> <li>Lebar</li> <li>Panjang</li> </ul> <ul> <li>504.0</li> <li>1 Juli 2019</li> <li>0648572919</li> <li>English</li> <li>Shadiversity Pty Ltd</li> <li>0.6 kg</li> <li>12.7 cm</li> <li>20.32 cm</li> </ul> <button class="button">Pinjam</button> </nav> </div> <img src="../img/book1.jpg" alt=""> </div> <div class="daftar-buku"> <div class="deskripsi"> <p>Can Openers</p> <p><NAME></p> <nav> <ul> <li>Jumlah Halaman</li> <li>Tanggal Terbit</li> <li>ISBN</li> <li>Bahasa</li> <li>Penerbit</li> <li>Berat</li> <li>Lebar</li> <li>Panjang</li> </ul> <ul> <li>240.0</li> <li>24 Nov 2017</li> <li>1635618592</li> <li>English</li> <li>Echo Point </li> <li>1.45 kg</li> <li>34.29 cm</li> <li>24.13 cm</li> </ul> <button class="button">Pinjam</button> </nav> </div> <img src="../img/book2.jpg" alt=""> </div> <div class="daftar-buku"> <div class="deskripsi"> <p>Geografi Pariwisata Jawa Bali</p> <p><NAME></p> <nav> <ul> <li>Jumlah Halaman</li> <li>Tanggal Terbit</li> <li>ISBN</li> <li>Bahasa</li> <li>Penerbit</li> <li>Berat</li> <li>Lebar</li> <li>Panjang</li> </ul> <ul> <li>308.0</li> <li>Mar 2014</li> <li>9786027757110</li> <li>Indonesia</li> <li>Media Bangsa </li> <li>0.5 kg</li> <li>- cm</li> <li>- cm</li> </ul> <button class="button">Pinjam</button> </nav> </div> <img src="../img/book3.jpg" alt=""> </div> <div><center><button class="button">Tampilkan Lebih Banyak</button></center></div> <br> </div> <div id="clear"></div> <div id="footer"> <p>©2020 Benedict</p> </div> </div> </body> </html> <file_sep>-- phpMyAdmin SQL Dump -- version 4.9.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: May 06, 2020 at 11:16 AM -- Server version: 10.4.10-MariaDB -- PHP Version: 7.1.33 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: `perpustakaan` -- -- -------------------------------------------------------- -- -- Table structure for table `buku` -- CREATE TABLE `buku` ( `id` int(11) NOT NULL, `judul_buku` varchar(100) NOT NULL, `penulis_buku` varchar(100) NOT NULL, `penerbit_buku` varchar(100) NOT NULL, `tahun_terbit` char(4) NOT NULL, `stok` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `buku` -- INSERT INTO `buku` (`id`, `judul_buku`, `penulis_buku`, `penerbit_buku`, `tahun_terbit`, `stok`) VALUES (1, 'Judul Buku', 'Penulis Buku', 'Penerbit Buku', '2018', 12), (2, 'Shadow of the Conqueror (Chronicles of Everfall) ', '<NAME>', 'Shadiversity Pty Ltd', '2019', 12), (3, 'Can Openers', '<NAME>', 'Echo Point Books & Media', '2020', 15); -- -- Indexes for dumped tables -- -- -- Indexes for table `buku` -- ALTER TABLE `buku` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `buku` -- ALTER TABLE `buku` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>-- phpMyAdmin SQL Dump -- version 4.9.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: May 28, 2020 at 04:24 PM -- Server version: 10.4.10-MariaDB -- PHP Version: 7.1.33 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: `perpustakaan` -- -- -------------------------------------------------------- -- -- Table structure for table `buku` -- CREATE TABLE `buku` ( `id_buku` int(11) NOT NULL, `judul` varchar(100) NOT NULL, `tahun` int(11) NOT NULL, `penulis` varchar(100) NOT NULL, `ISBN` varchar(13) NOT NULL, `pic` varchar(100) NOT NULL, `kategori` varchar(32) NOT NULL, `rak` int(11) NOT NULL, `stok` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `buku` -- INSERT INTO `buku` (`id_buku`, `judul`, `tahun`, `penulis`, `ISBN`, `pic`, `kategori`, `rak`, `stok`) VALUES (1, 'Shadow of The Conqueror', 2019, '<NAME>', '0648572919', 'book1.jpg', 'Fiksi', 1, 5), (2, 'Can Openers', 2017, '<NAME>', '1635618592', 'book2.jpg', 'Non-Fiksi', 2, 1), (3, 'Geografi Pariwisata Jawa Bali', 2014, '<NAME>', '9786027757110', 'book3.jpg', 'Pariwisata', 3, 1), (6, 'Dummy', 2018, 'dummeh', '0100010101001', 'dummy.jpg', 'dummy', 3, 1); -- -------------------------------------------------------- -- -- Table structure for table `pinjaman` -- CREATE TABLE `pinjaman` ( `id_pinjam` int(11) NOT NULL, `id_buku` int(11) NOT NULL, `id_user` int(11) NOT NULL, `tgl_ambil` date NOT NULL, `tgl_kembali` date NOT NULL, `status` enum('mohon','dipinjam','dikembalikan','batal') NOT NULL DEFAULT 'mohon' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `pinjaman` -- INSERT INTO `pinjaman` (`id_pinjam`, `id_buku`, `id_user`, `tgl_ambil`, `tgl_kembali`, `status`) VALUES (4, 1, 8, '2020-07-06', '2030-07-16', 'batal'), (5, 1, 8, '2020-05-28', '2020-06-17', 'mohon'); -- -------------------------------------------------------- -- -- Table structure for table `user` -- CREATE TABLE `user` ( `id_user` int(11) NOT NULL, `user_name` varchar(100) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(256) NOT NULL, `role` enum('suadmin','user','admin','nonaktif') NOT NULL, `picture` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `user` -- INSERT INTO `user` (`id_user`, `user_name`, `email`, `password`, `role`, `picture`) VALUES (1, 'admin', '<EMAIL>', '<PASSWORD>', '<PASSWORD>', ''), (2, 'petugas', '<EMAIL>', '12345', 'nonaktif', ''), (7, 'benadmin', '<EMAIL>', 'liklik', 'admin', ''), (8, 'ben', '<EMAIL>', 'ben', 'user', 'proxy.duckduckgo.com.jpg'); -- -- Indexes for dumped tables -- -- -- Indexes for table `buku` -- ALTER TABLE `buku` ADD PRIMARY KEY (`id_buku`); -- -- Indexes for table `pinjaman` -- ALTER TABLE `pinjaman` ADD PRIMARY KEY (`id_pinjam`), ADD KEY `id_buku` (`id_buku`), ADD KEY `id_user` (`id_user`); -- -- Indexes for table `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`id_user`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `buku` -- ALTER TABLE `buku` MODIFY `id_buku` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- AUTO_INCREMENT for table `pinjaman` -- ALTER TABLE `pinjaman` MODIFY `id_pinjam` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `user` -- ALTER TABLE `user` MODIFY `id_user` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- Constraints for dumped tables -- -- -- Constraints for table `pinjaman` -- ALTER TABLE `pinjaman` ADD CONSTRAINT `pinjaman_ibfk_1` FOREIGN KEY (`id_buku`) REFERENCES `buku` (`id_buku`), ADD CONSTRAINT `pinjaman_ibfk_2` FOREIGN KEY (`id_user`) REFERENCES `user` (`id_user`); 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 */;
59b39e75ffee8baa98ac085170f3a656fe685464
[ "SQL", "PHP" ]
4
PHP
nutman451/PraktikumWebA
e758acf5f17551f2a782033220d8a9b0b230d4de
2d7bf3623f5e076fa1aa675b4b292c42b947511b
refs/heads/master
<repo_name>vchennepalli/hello-world<file_sep>/build.py #!/usr/bin/env python import sys import os import subprocess class CiBuild(object): def __init__(self): self._root_dir = os.getcwd() print('Root directory %s' % self._root_dir) self._unit_test_dir = os.path.normpath('%s/unit_test' % self._root_dir) print('Unit test script location %s' % self._unit_test_dir) def run_unit_tests(self): scriptToRun = 'python ' + self._unit_test_dir + "/unit_test_script.py" subprocess.Popen(scriptToRun, cwd=self._root_dir, shell=True) print('Unit test script completed successfully') cibuild = CiBuild() cibuild.run_unit_tests() <file_sep>/unit_test/unit_test_script.py import sys import os path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) if not path in sys.path: sys.path.insert(1, path) del path from hello_world import sum print "############# Unit Test Script" print "############# Test case 1" total = sum(3, 4) print "Total:", total print "############# Test case 2" total = sum(10, 4) print "Total:", total <file_sep>/hello_world.py print ("Hello World!!!") def hello() : print ("My first github repository") def sum(a, b) : return a+b; hello()
43886d6d6987a1285aa84c5bafff91152c9125c4
[ "Python" ]
3
Python
vchennepalli/hello-world
27dd52af23e3fb398c083df206fe2961ab9a3b4c
1dd3ce9a797b3cee9ae92875ddf9dcecdfc734f9
refs/heads/master
<repo_name>longyt/Maven_Projects<file_sep>/BackStage/src/com/shadow/Utils/ExcelUtils.java package com.shadow.Utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; import com.shadow.Utils.Entity.BaseEntity; import com.shadow.Utils.Entity.Contain; public class ExcelUtils { private static Short red=(Short) HSSFColorPredefined.RED.getIndex(); private static Short green=(Short) HSSFColorPredefined.GREEN.getIndex(); private static Short blur=(Short) HSSFColorPredefined.BLUE.getIndex(); private static Short white=(Short) HSSFColorPredefined.WHITE.getIndex(); /** * 导出数据 * @throws Exception */ public static void Export(List<BaseEntity> list,HttpServletRequest resuest,Class clazz) throws Exception{ Class.forName("com.shadow.Utils.Entity.Contain"); HSSFWorkbook hssfWorkbook= new HSSFWorkbook(); HSSFSheet hssfSheet = hssfWorkbook.createSheet();//拿到第一幅 HSSFRow OneRow = hssfSheet.createRow(0);//拿到第一行 HSSFCell OneCell= OneRow.createCell(0, CellType.STRING); CustomFontAndBackgroundColor(hssfWorkbook,OneCell,blur,(short) 30);//设置字体颜色 OneCell.setCellValue("导出"+clazz.getSimpleName()+"表中的数据"); //拿到标题 HSSFRow TitleRow = hssfSheet.createRow(1); int TitleRowIndex=0; for (int i = 0; i < Contain.list.size(); i++) { HSSFCell TitleCell = TitleRow.createCell(TitleRowIndex, CellType.STRING); TitleCell.setCellValue((String) Contain.list.get(i).get("title"+(i+1))); TitleRowIndex++; } //拿到标题下的数据 int RowIndex=2; for (BaseEntity entity : list) { HSSFRow DataRow = hssfSheet.createRow(RowIndex); int CellIndex=0; Class clabb = entity.getClass(); Field [] fields = clabb.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); if(field.getType().getSimpleName().equals("Integer")){ Integer Tempvalue = (Integer) field.get(entity); DataRow.createCell(CellIndex, CellType.NUMERIC).setCellValue(Tempvalue); }else{ String Tempvalue = (String) field.get(entity); DataRow.createCell(CellIndex, CellType.STRING).setCellValue(Tempvalue); } CellIndex++; } RowIndex++; } String ExportPath = resuest.getServletContext().getRealPath("//export"); File file=new File(ExportPath); if(!file.exists()){ file.mkdirs(); } Contain.ExportResurcePath=ExportPath; System.out.println(ExportPath); File ExportFile = new File(Contain.ExportResurcePath+"//"+clazz.getSimpleName()+".xls"); OutputStream fos=new FileOutputStream(ExportFile); hssfWorkbook.write(fos); if(!ExportFile.exists()){ ExportFile.createNewFile(); } fos.flush(); fos.close(); hssfWorkbook.close(); } public static List<BaseEntity> Import(String ImportFileName,Class clazz) throws Exception{ /** * 定义一个list */ List<BaseEntity> list=new ArrayList<>(); File file=new File(ImportFileName); InputStream in=new FileInputStream(file); HSSFWorkbook hssfWorkbook=new HSSFWorkbook(in);//拿到xls文件 int sheets = hssfWorkbook.getNumberOfSheets(); for (int i = 0; i < sheets; i++) { HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(i); HSSFRow OneRow = hssfSheet.createRow(0); int OneRowCells = OneRow.getLastCellNum(); if(OneRowCells>1){ System.out.println("格式错误"); }else{ HSSFRow TwoRow = hssfSheet.getRow(1); int TwoRowCells = TwoRow.getLastCellNum(); for (int j = 0; j < TwoRowCells; j++) { String TitleName = TwoRow.getCell(j).getStringCellValue(); if(TitleName.equals(Contain.list.get(j).get("title"+(j+1)))){ //System.out.println("模板正确"); }else{ System.out.println("模板错误"); } } } /** * 遍历有多少行遍历所有数据放入list中返回 */ int AllRows = hssfSheet.getLastRowNum(); for (int j = 2; j <= AllRows; j++) { if(j%3==0){ Thread.sleep(1000); } HSSFRow Row = hssfSheet.getRow(j); int Allcells = Row.getLastCellNum(); BaseEntity entity2 = (BaseEntity) clazz.newInstance(); for (int k = 0; k < Allcells; k++) { HSSFCell cell = Row.getCell(k); String FieldName = (String) Contain.list.get(k).get("name"+(k+1)); Field field = clazz.getDeclaredField(FieldName); field.setAccessible(true); if(cell.getCellTypeEnum()==CellType.NUMERIC){ Integer Tempvalue = (int) cell.getNumericCellValue(); if(field.getType().getSimpleName().equals("Integer")){ field.set(entity2, Tempvalue); }else if(field.getType().getSimpleName().equals("String")){ field.set(entity2, Tempvalue.toString()); } }else if(cell.getCellTypeEnum()==CellType.STRING){ String Tempvalue = (String)cell.getStringCellValue(); if(field.getType().getSimpleName().equals("Integer")){ field.set(entity2, Tempvalue); }else if(field.getType().getSimpleName().equals("String")){ field.set(entity2, Tempvalue.toString()); } } } Contain.percent=((j*1.0)/(AllRows*1.0))*100; list.add(entity2); }//遍历数据for循环结束 }//遍历sheet循环结束 return list; } //字体颜色大小设置 public static void CustomFontAndBackgroundColor(HSSFWorkbook hssfWorkbook,HSSFCell hssfCell,Short color,Short fontsize){ //设置背景颜色 CellStyle cellStyle = hssfWorkbook.createCellStyle(); //cellStyle.setFillBackgroundColor(HSSFColorPredefined.RED.getIndex()); short alignCenter = CellStyle.VERTICAL_TOP; cellStyle.setAlignment(alignCenter); hssfCell.setCellStyle(cellStyle); //设置字体颜色和大小 HSSFFont hssfFont = hssfWorkbook.createFont(); hssfFont.setColor(color); hssfFont.setFontHeightInPoints(fontsize); cellStyle.setFont(hssfFont); } } <file_sep>/BackStage/src/com/shadow/Utils/Servlet/UploadServlet.java package com.shadow.Utils.Servlet; import java.io.DataInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.shadow.Utils.Entity.Data; @WebServlet("/upload.do") public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Data data=new Data(); request.setCharacterEncoding("utf-8"); String boundary=request.getContentType(); boundary ="--"+boundary.substring(boundary.indexOf("=")+1, boundary.length())+"--"; int boundaryLen = boundary.getBytes("iso-8859-1").length; int contentLength=request.getContentLength(); DataInputStream di =new DataInputStream(request.getInputStream()); FileOutputStream fos =null; byte[] body = new byte[5000]; int totalReadSize =0; String filePath =""; String suffix=""; String fileName=""; String oldfilename=""; String fullfilename=""; int k =0; while(totalReadSize<contentLength){ //读取 int readSize=di.read(body, 0, 5000); totalReadSize+=readSize; String content = new String(body,"iso-8859-1"); int contentTypeIndex = content.indexOf("Content-Type"); int flag =0; //写入文件 if(k==0){//第一次读 //把读取到的内容转换成为字符串 //因为读取到的内容本身为字节 //因为内容的头部包含了各种文件的信息(包括文件名和文件后缀) int fileNameIndex = content.indexOf("filename"); //获取contentTypeIndex的位置是为了方便找出文件的后缀 //suffixContet,整个文件名 String suffixContet = content.substring(fileNameIndex, contentTypeIndex); data.setFullSongName(suffixContet); fullfilename=suffixContet; //截取出文件后缀 int pointerIndex = suffixContet.lastIndexOf("."); suffix = suffixContet.substring(pointerIndex, suffixContet.length()-3); //拿到点之前的内容 oldfilename = suffixContet.substring(0,pointerIndex); data.setSongName(oldfilename); //通过系统当前时间生成一个唯一的文件名 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss"); fileName =sdf.format(new Date())+suffix; //找出头部的无用内容 //并且计算出这个无用内容的长度(字节的长度); int pos = content.indexOf("\n", contentTypeIndex); pos = content.indexOf("\n", pos+1); String disableContent = content.substring(0, pos); int start = disableContent.getBytes("iso-8859-1").length; //request.getSession().getServletContext() web的上下文(webroot的路径) filePath = request.getSession().getServletContext().getRealPath("/resource")+"\\"+fileName; File file = new File(filePath); file.createNewFile(); flag=content.indexOf(boundary, contentTypeIndex); fos = new FileOutputStream(file); if(flag>0){//一次性读完了 fos.write(body, start+1, readSize-(start+boundaryLen+4)); }else{ fos.write(body, start+1, readSize-(start+1)); fos.flush(); body = new byte[5000]; } }else{ flag = content.indexOf(boundary, contentTypeIndex); if(flag<0){ fos.write(body, 0, readSize); fos.flush(); body = new byte[5000]; }else{ fos.write(body, 0, readSize-(boundaryLen+4)); } } k++; } fos.flush(); fos.close(); di.close(); //,\"oldfilename\":\""+oldfilename+"\",\"suffixContet\":\""+fullfilename+"\" response.getWriter().write("{\"success\":\"success\",\"path\":\""+fileName+"\"}"); } }
173749ed607f0d6a8f89593fb7dc11571328ef5e
[ "Java" ]
2
Java
longyt/Maven_Projects
7ca892365d607735444ffd1e5b22973d2d2fb841
2e40cf0ab3cf82190b9b3dc3a555a3d3c72bda9c